prepare-send.ts (18282B)
1 import { 2 identityMessagingOwnership, 3 subscribeIdentityInvalidation, 4 type IdentitySession 5 } from '../runtime/identity-session.ts'; 6 import { 7 reservedSendSnapshot, 8 type ReservedSendIdentity 9 } from './send-identity.ts'; 10 import type { VerifiedOutboundEnvelope } from '../nostr/verify-outbound-envelope.ts'; 11 import { 12 captureEnvelopePreparation, 13 prepareEnvelopeRole, 14 preparedEnvelopeProof, 15 envelopePreparationSnapshot, 16 closeEnvelopePreparation, 17 type EnvelopePreparation 18 } from './envelope-preparation.ts'; 19 import { privateRecordSnapshot } from '../persistence/private-records.ts'; 20 import { 21 inboxRoutePlanSnapshot, 22 recheckInboxRoutePlan, 23 type InboxRoutePlan 24 } from './inbox-routing.ts'; 25 import type { InboxResolver } from './resolve-inbox.ts'; 26 import type { RelayPolicy } from '../config/relays.ts'; 27 import { 28 type PrivateStorageRepository, 29 type PrivateStorageFailure 30 } from '../persistence/private-storage.ts'; 31 import { 32 readSelfRecoveryBase, 33 commitSelfRecovery, 34 selfRecoveryAcknowledgementSnapshot, 35 verifySelfRecoveryAcknowledgement, 36 commitPairedDelivery, 37 pairedDeliveryAcknowledgementSnapshot, 38 verifyPairedDeliveryAcknowledgement, 39 type SelfRecoveryAcknowledgement, 40 type PairedDeliveryAcknowledgement 41 } from '../persistence/private-sends.ts'; 42 43 declare const preparationBrand: unique symbol; 44 export type SelfRecoveryPreparation = Readonly<{ [preparationBrand]: true }>; 45 export type SelfRecoveryPreparationResult = Readonly<{ 46 status: 47 | PrivateStorageFailure 48 | 'invalid' 49 | 'stopped' 50 | 'busy' 51 | 'saved' 52 | 'existing' 53 | 'reconciled' 54 | 'recovery_required' 55 | 'refused' 56 | 'mismatch' 57 | 'out_of_order'; 58 }>; 59 export type PairedDeliveryContext = Readonly<{ 60 plan: InboxRoutePlan; 61 policy: RelayPolicy; 62 own: InboxResolver; 63 other: InboxResolver; 64 }>; 65 export type PairedDeliveryPreparationResult = Readonly<{ 66 status: 67 | SelfRecoveryPreparationResult['status'] 68 | 'self_required' 69 | 'review_required' 70 | 'prepared'; 71 }>; 72 type Phase = 73 'unsaved' | 'preparing' | 'saved' | 'unknown_completion' | 'needs_action'; 74 type PairPhase = 75 | 'unprepared' 76 | 'preparing' 77 | 'prepared' 78 | 'unknown_completion' 79 | 'needs_action'; 80 type Snapshot = Readonly<{ 81 state: Phase; 82 busy: boolean; 83 owner: string; 84 command: string; 85 copy: string; 86 pairState: PairPhase; 87 pairCopy: string; 88 }>; 89 type Controller = { 90 run(review: unknown): Promise<SelfRecoveryPreparationResult>; 91 runPair( 92 context: PairedDeliveryContext, 93 review: unknown 94 ): Promise<PairedDeliveryPreparationResult>; 95 pairReceipt(): PairedDeliveryAcknowledgement | undefined; 96 snapshot(): Snapshot | undefined; 97 receipt(): SelfRecoveryAcknowledgement | undefined; 98 peer( 99 receipt: SelfRecoveryAcknowledgement 100 ): Promise<EnvelopePreparation | undefined>; 101 stop(): void; 102 }; 103 const preparations = new WeakMap<SelfRecoveryPreparation, Controller>(); 104 105 // This workflow owns durable self-first admission. Lower crypto factories stay 106 // memory-only foundations; their output alone cannot advance this workflow. 107 export function captureSelfRecoveryPreparation( 108 repository: PrivateStorageRepository, 109 session: IdentitySession, 110 reserved: ReservedSendIdentity, 111 review: unknown, 112 recoveredSelf?: VerifiedOutboundEnvelope 113 ): SelfRecoveryPreparation | undefined { 114 if (typeof window === 'undefined' || review !== 'reviewed_self_recovery') 115 return undefined; 116 const recordInput = reservedSendSnapshot(reserved), 117 ownershipInput = identityMessagingOwnership(session); 118 if ( 119 !recordInput || 120 !ownershipInput?.current() || 121 ownershipInput.owner !== recordInput.owner 122 ) 123 return undefined; 124 const pairInput = captureEnvelopePreparation( 125 session, 126 reserved, 127 'reviewed_envelope_pair', 128 recoveredSelf 129 ); 130 if (!pairInput) return undefined; 131 const record = recordInput, 132 ownership = ownershipInput, 133 pair = pairInput; 134 let active = true, 135 generation = 0, 136 busy = false, 137 phase: Phase = 'unsaved', 138 pairPhase: PairPhase = 'unprepared', 139 acknowledgement: SelfRecoveryAcknowledgement | undefined, 140 pairedAcknowledgement: PairedDeliveryAcknowledgement | undefined, 141 unsubscribe = () => {}; 142 function stop() { 143 if (!active) return; 144 active = false; 145 generation++; 146 acknowledgement = undefined; 147 pairedAcknowledgement = undefined; 148 closeEnvelopePreparation(pair); 149 unsubscribe(); 150 unsubscribe = () => {}; 151 } 152 function current() { 153 const observed = reservedSendSnapshot(reserved); 154 if ( 155 !active || 156 !ownership.current() || 157 !envelopePreparationSnapshot(pair) || 158 !observed || 159 observed.owner !== record.owner || 160 observed.id !== record.id || 161 observed.peer !== record.peer || 162 observed.rumorHash !== record.rumorHash || 163 observed.createdAt !== record.createdAt 164 ) { 165 stop(); 166 return false; 167 } 168 return true; 169 } 170 function receipt() { 171 return current() && 172 acknowledgement && 173 selfRecoveryAcknowledgementSnapshot(acknowledgement) 174 ? acknowledgement 175 : undefined; 176 } 177 function snapshot(): Snapshot | undefined { 178 if (!current()) return undefined; 179 return { 180 state: phase, 181 busy, 182 owner: record.owner, 183 command: record.id, 184 pairState: pairPhase, 185 pairCopy: 186 pairPhase === 'prepared' 187 ? 'Both encrypted artifacts and their delivery plan are saved locally. No recipient delivery is claimed.' 188 : pairPhase === 'unknown_completion' 189 ? 'Paired encrypted preparation could not be confirmed. Review the existing preparation before continuing.' 190 : pairPhase === 'preparing' 191 ? 'Preparing the missing peer envelope. No recipient delivery is claimed.' 192 : pairPhase === 'needs_action' 193 ? 'Paired delivery preparation needs review. The acknowledged self copy is a local recovery fact only.' 194 : 'No paired delivery preparation is acknowledged.', 195 copy: 196 phase === 'saved' && receipt() 197 ? 'Saved encrypted in this browser' 198 : phase === 'preparing' 199 ? 'Preparing encryption' 200 : phase === 'unknown_completion' 201 ? 'Encrypted save could not be confirmed. Review before continuing.' 202 : phase === 'needs_action' 203 ? 'Private text has no acknowledged encrypted save in this browser.' 204 : 'Private text is unsaved memory.' 205 }; 206 } 207 async function peer(expected: SelfRecoveryAcknowledgement) { 208 if (!current() || busy || acknowledgement !== expected || !receipt()) 209 return undefined; 210 const attempt = generation; 211 const verified = await verifySelfRecoveryAcknowledgement( 212 repository, 213 expected 214 ); 215 return verified && 216 current() && 217 generation === attempt && 218 acknowledgement === expected 219 ? pair 220 : undefined; 221 } 222 async function run( 223 reviewed: unknown 224 ): Promise<SelfRecoveryPreparationResult> { 225 if (reviewed !== 'reviewed_self_recovery') return { status: 'invalid' }; 226 if (!current()) return { status: 'stopped' }; 227 if (busy) return { status: 'busy' }; 228 if (typeof window === 'undefined' || !navigator.locks?.request) 229 return { status: 'unavailable' }; 230 busy = true; 231 const attempt = generation, 232 admitted = () => current() && attempt === generation; 233 try { 234 return await (async (): Promise<SelfRecoveryPreparationResult> => { 235 if (!admitted()) return { status: 'stopped' }; 236 const base = await readSelfRecoveryBase(repository, reserved); 237 if (!admitted()) return { status: 'stopped' }; 238 if (!base.ok) { 239 phase = 'needs_action'; 240 return { status: base.reason }; 241 } 242 if (acknowledgement) { 243 // A genuine committed pair is the exact legitimate successor to our 244 // self-only record. Reconcile through that receipt's full wire, never 245 // treat arbitrary edits to a self record as acknowledged advancement. 246 if (pairedAcknowledgement) { 247 const paired = pairedDeliveryAcknowledgementSnapshot( 248 pairedAcknowledgement 249 ), 250 originalSelf = 251 selfRecoveryAcknowledgementSnapshot(acknowledgement); 252 const matches = 253 paired && 254 originalSelf && 255 paired.owner === record.owner && 256 paired.id === record.id && 257 paired.peer === record.peer && 258 paired.rumorHash === record.rumorHash && 259 paired.createdAt === record.createdAt && 260 paired.self.eventId === originalSelf.self.eventId && 261 paired.self.wire === originalSelf.self.wire; 262 const valid = 263 matches && 264 (await verifyPairedDeliveryAcknowledgement( 265 repository, 266 pairedAcknowledgement 267 )); 268 if (!admitted()) return { status: 'stopped' }; 269 if (valid) { 270 phase = 'saved'; 271 return { status: 'saved' }; 272 } 273 pairedAcknowledgement = undefined; 274 acknowledgement = undefined; 275 phase = 'needs_action'; 276 return { status: 'conflict' }; 277 } 278 const valid = await verifySelfRecoveryAcknowledgement( 279 repository, 280 acknowledgement 281 ); 282 if (!admitted()) return { status: 'stopped' }; 283 if (valid) { 284 phase = 'saved'; 285 return { status: 'saved' }; 286 } 287 acknowledgement = undefined; 288 phase = 'needs_action'; 289 return { status: 'conflict' }; 290 } 291 const stored = privateRecordSnapshot( 292 base.value, 293 record.owner, 294 record.id 295 ); 296 if (!stored) return { status: 'invalid_record' }; 297 if ( 298 stored.family === 'private_send_operation' && 299 !preparedEnvelopeProof(pair, 'self') 300 ) { 301 phase = 'needs_action'; 302 return { status: 'recovery_required' }; 303 } 304 phase = 'preparing'; 305 const prepared = await prepareEnvelopeRole( 306 pair, 307 'self', 308 'reviewed_pair_role' 309 ); 310 if (!admitted()) return { status: 'stopped' }; 311 if (prepared.status !== 'prepared' && prepared.status !== 'complete') { 312 phase = 'needs_action'; 313 return { status: prepared.status }; 314 } 315 const proof = preparedEnvelopeProof(pair, 'self'); 316 if (!proof) { 317 phase = 'needs_action'; 318 return { status: 'mismatch' }; 319 } 320 // The lower crypto owner acquires this lock itself. Acquire it again 321 // only after crypto settles, then revalidate and CAS the stored base. 322 const saved = await navigator.locks.request( 323 'harvestcircle:owner:' + record.owner, 324 { mode: 'exclusive', ifAvailable: true }, 325 async (lock) => { 326 if (!lock) return { status: 'busy' as const }; 327 if (!admitted()) return { status: 'stopped' as const }; 328 return await commitSelfRecovery( 329 repository, 330 session, 331 reserved, 332 proof, 333 'reviewed_self_commit' 334 ); 335 } 336 ); 337 if (!admitted()) return { status: 'stopped' }; 338 if ('receipt' in saved) { 339 acknowledgement = saved.receipt; 340 phase = 'saved'; 341 } else 342 phase = 343 saved.status === 'unknown_completion' 344 ? 'unknown_completion' 345 : 'needs_action'; 346 return { status: saved.status }; 347 })(); 348 } catch { 349 phase = 'needs_action'; 350 return { status: admitted() ? 'unavailable' : 'stopped' }; 351 } finally { 352 busy = false; 353 } 354 } 355 function pairReceipt() { 356 return current() && 357 pairedAcknowledgement && 358 pairedDeliveryAcknowledgementSnapshot(pairedAcknowledgement) 359 ? pairedAcknowledgement 360 : undefined; 361 } 362 async function runPair( 363 context: PairedDeliveryContext, 364 reviewed: unknown 365 ): Promise<PairedDeliveryPreparationResult> { 366 if (reviewed !== 'reviewed_pair_preparation') return { status: 'invalid' }; 367 if (!current()) return { status: 'stopped' }; 368 if (busy) return { status: 'busy' }; 369 const self = receipt(); 370 if (!self) return { status: 'self_required' }; 371 busy = true; 372 const attempt = generation; 373 function finishPair( 374 result: PairedDeliveryPreparationResult 375 ): PairedDeliveryPreparationResult { 376 if (current() && attempt === generation) 377 pairPhase = 378 result.status === 'unknown_completion' 379 ? 'unknown_completion' 380 : (result.status === 'prepared' || 381 result.status === 'existing' || 382 result.status === 'reconciled') && 383 pairedAcknowledgement && 384 pairedDeliveryAcknowledgementSnapshot(pairedAcknowledgement) 385 ? 'prepared' 386 : 'needs_action'; 387 return result; 388 } 389 try { 390 const { plan, policy, own, other } = context, 391 routes = inboxRoutePlanSnapshot(plan); 392 if ( 393 !routes || 394 routes.peer.author !== record.peer || 395 routes.archive.author !== record.owner 396 ) 397 return finishPair({ status: 'invalid' }); 398 const routeWire = JSON.stringify(routes); 399 const routesCurrent = () => 400 recheckInboxRoutePlan(plan, policy, own, other) === 'unchanged' && 401 JSON.stringify(inboxRoutePlanSnapshot(plan)) === routeWire; 402 const admitted = () => current() && attempt === generation; 403 if (!routesCurrent()) return finishPair({ status: 'review_required' }); 404 if (!admitted()) return finishPair({ status: 'stopped' }); 405 if (pairedAcknowledgement) { 406 const valid = await verifyPairedDeliveryAcknowledgement( 407 repository, 408 pairedAcknowledgement 409 ); 410 if (!admitted()) return finishPair({ status: 'stopped' }); 411 if (!routesCurrent()) return finishPair({ status: 'review_required' }); 412 const saved = pairedDeliveryAcknowledgementSnapshot( 413 pairedAcknowledgement 414 ); 415 return finishPair( 416 valid && 417 saved && 418 JSON.stringify(saved.deliveryPlan.routes) === routeWire 419 ? { status: 'prepared' } 420 : { status: 'conflict' } 421 ); 422 } 423 const durableSelf = await verifySelfRecoveryAcknowledgement( 424 repository, 425 self 426 ); 427 if (!admitted()) return finishPair({ status: 'stopped' }); 428 if (!routesCurrent()) return finishPair({ status: 'review_required' }); 429 if (!admitted()) return finishPair({ status: 'stopped' }); 430 if (!durableSelf) return finishPair({ status: 'conflict' }); 431 phase = 'preparing'; 432 pairPhase = 'preparing'; 433 // The existing lower crypto factory owns the owner lock during SDK work. 434 const prepared = await prepareEnvelopeRole( 435 pair, 436 'peer', 437 'reviewed_pair_role' 438 ); 439 if (!admitted()) return finishPair({ status: 'stopped' }); 440 if (!routesCurrent()) return finishPair({ status: 'review_required' }); 441 if (!admitted()) return finishPair({ status: 'stopped' }); 442 if (prepared.status !== 'complete') 443 return finishPair({ status: prepared.status }); 444 const proof = preparedEnvelopeProof(pair, 'peer'); 445 if (!proof) return finishPair({ status: 'mismatch' }); 446 const saved = await navigator.locks.request( 447 'harvestcircle:owner:' + record.owner, 448 { mode: 'exclusive', ifAvailable: true }, 449 async (lock) => { 450 if (!lock) return { status: 'busy' as const }; 451 if (!routesCurrent()) return { status: 'review_required' as const }; 452 if (!admitted()) return { status: 'stopped' as const }; 453 return await commitPairedDelivery( 454 repository, 455 session, 456 reserved, 457 self, 458 proof, 459 plan, 460 'reviewed_pair_commit' 461 ); 462 } 463 ); 464 if (!admitted()) return finishPair({ status: 'stopped' }); 465 if (!routesCurrent()) return finishPair({ status: 'review_required' }); 466 if (!admitted()) return finishPair({ status: 'stopped' }); 467 if ('receipt' in saved) pairedAcknowledgement = saved.receipt; 468 phase = 'saved'; 469 return finishPair({ status: saved.status }); 470 } catch { 471 return finishPair({ status: current() ? 'unavailable' : 'stopped' }); 472 } finally { 473 busy = false; 474 if (current()) phase = 'saved'; 475 } 476 } 477 const token = Object.freeze({}) as SelfRecoveryPreparation; 478 preparations.set(token, { 479 run, 480 runPair, 481 pairReceipt, 482 snapshot, 483 receipt, 484 peer, 485 stop 486 }); 487 unsubscribe = subscribeIdentityInvalidation(session, () => { 488 if (!ownership.current()) stop(); 489 }); 490 return current() ? token : undefined; 491 } 492 export function prepareSelfRecovery( 493 token: SelfRecoveryPreparation, 494 review: unknown 495 ): Promise<SelfRecoveryPreparationResult> { 496 return ( 497 preparations.get(token)?.run(review) ?? 498 Promise.resolve({ status: 'invalid' }) 499 ); 500 } 501 export function selfRecoveryPreparationSnapshot( 502 token: SelfRecoveryPreparation 503 ) { 504 return preparations.get(token)?.snapshot(); 505 } 506 export function preparedSelfRecovery(token: SelfRecoveryPreparation) { 507 return preparations.get(token)?.receipt(); 508 } 509 export function selfRecoveryPeerPreparation( 510 token: SelfRecoveryPreparation, 511 receipt: SelfRecoveryAcknowledgement 512 ): Promise<EnvelopePreparation | undefined> { 513 return preparations.get(token)?.peer(receipt) ?? Promise.resolve(undefined); 514 } 515 export function stopSelfRecoveryPreparation( 516 token: SelfRecoveryPreparation 517 ): void { 518 preparations.get(token)?.stop(); 519 } 520 export function preparePairedDelivery( 521 token: SelfRecoveryPreparation, 522 context: PairedDeliveryContext, 523 review: unknown 524 ): Promise<PairedDeliveryPreparationResult> { 525 return ( 526 preparations.get(token)?.runPair(context, review) ?? 527 Promise.resolve({ status: 'invalid' }) 528 ); 529 } 530 export function preparedPairedDelivery(token: SelfRecoveryPreparation) { 531 return preparations.get(token)?.pairReceipt(); 532 }