seal-builder.ts (15310B)
1 import { 2 inboxProbeSnapshot, 3 inboxProbeRumorWire, 4 stopInboxProbeIdentity, 5 type InboxProbeIdentity 6 } from './inbox-access.ts'; 7 import { 8 privateSessionOwnership, 9 invalidatePrivateSessionGeneration, 10 type PrivateSession 11 } from '../runtime/private-session.ts'; 12 import { ExtensionSigner } from 'applesauce-signers'; 13 import type { UnsignedEvent } from 'applesauce-core/helpers'; 14 import { 15 reservedSendSnapshot, 16 reservedSendRumorWire, 17 type ReservedSendIdentity 18 } from '../messaging/send-identity.ts'; 19 import { 20 identityMessagingOwnership, 21 disconnectIdentity, 22 type IdentitySession 23 } from '../runtime/identity-session.ts'; 24 import { 25 browserExtensionScheduler, 26 runExtensionAction, 27 callExtension, 28 stopExtensionAction, 29 markExtensionWaitExpired, 30 type ExtensionAction 31 } from './extension-scheduler.ts'; 32 import { safeUnsignedInteger } from './envelope-bounds.ts'; 33 import { 34 sealCiphertextV2, 35 captureSealTemplate, 36 bindSealResponse 37 } from './seal-template.ts'; 38 declare const probeOperationBrand: unique symbol; 39 declare const probeSealBrand: unique symbol; 40 declare const operationBrand: unique symbol; 41 declare const sealBrand: unique symbol; 42 export type PrivateSealOperation = Readonly<{ [operationBrand]: true }>; 43 export type PrivateRecipientSeal = Readonly<{ [sealBrand]: true }>; 44 export type InboxProbeSealOperation = Readonly<{ [probeOperationBrand]: true }>; 45 export type InboxProbeRecipientSeal = Readonly<{ [probeSealBrand]: true }>; 46 export type PrivateSealResult = SealResult<PrivateRecipientSeal>; 47 export type InboxProbeSealResult = SealResult<InboxProbeRecipientSeal>; 48 type SealResult<T> = 49 | Readonly<{ status: 'sealed'; seal: T }> 50 | Readonly<{ 51 status: 52 'invalid' | 'busy' | 'unavailable' | 'refused' | 'stopped' | 'mismatch'; 53 }>; 54 type State<T> = { 55 run(): Promise<SealResult<T>>; 56 stop(expired: boolean): void; 57 }; 58 type SavedSeal = Readonly<{ 59 owner: string; 60 peer: string; 61 destination: string; 62 role: 'peer' | 'self'; 63 command: string; 64 rumorHash: string; 65 wire: string; 66 reserved: ReservedSendIdentity; 67 current(): boolean; 68 }>; 69 const operations = new WeakMap< 70 PrivateSealOperation, 71 State<PrivateRecipientSeal> 72 >(); 73 const seals = new WeakMap<PrivateRecipientSeal, SavedSeal>(); 74 type SavedProbeSeal = Readonly<{ 75 owner: string; 76 destination: string; 77 command: string; 78 rumorHash: string; 79 createdAt: number; 80 wire: string; 81 identity: InboxProbeIdentity; 82 current(): boolean; 83 }>; 84 const probeOperations = new WeakMap< 85 InboxProbeSealOperation, 86 State<InboxProbeRecipientSeal> 87 >(); 88 const probeSeals = new WeakMap<InboxProbeRecipientSeal, SavedProbeSeal>(); 89 const originalProbeOperations = new WeakMap< 90 InboxProbeIdentity, 91 InboxProbeSealOperation 92 >(); 93 type SealSource<T> = Readonly<{ 94 owner: string; 95 destination: string; 96 session: symbol; 97 current(): boolean; 98 rumorWire(): string | undefined; 99 invalidate(): void; 100 retire?(): void; 101 accept(wire: string, current: () => boolean): T; 102 }>; 103 // Module-private construction port. Only the two genuine capability factories 104 // below can supply it; callers cannot pass a signer, plaintext or current flag. 105 function createSealOperation<T>(source: SealSource<T>): State<T> { 106 let stopped = false, 107 started = false, 108 active: ExtensionAction | undefined; 109 const current = () => !stopped && source.current(); 110 function stop(expired: boolean) { 111 stopped = true; 112 source.retire?.(); 113 if (active) { 114 if (expired) markExtensionWaitExpired(active); 115 else stopExtensionAction(active); 116 } 117 } 118 function cipherPort() { 119 try { 120 if (!current()) return undefined; 121 const cipher = new ExtensionSigner().nip44; 122 if (!current() || !cipher) return undefined; 123 const encryptMethod = cipher.encrypt; 124 if (!current()) return undefined; 125 const decryptMethod = cipher.decrypt; 126 if ( 127 !current() || 128 typeof encryptMethod !== 'function' || 129 typeof decryptMethod !== 'function' 130 ) 131 return undefined; 132 const encrypt = encryptMethod.bind(cipher); 133 if (!current()) return undefined; 134 const decrypt = decryptMethod.bind(cipher); 135 if (!current()) return undefined; 136 // Owned plain port: the provider's getters are never re-read inside a 137 // scheduled invocation with the captured private rumor. 138 return { encrypt, decrypt }; 139 } catch { 140 return undefined; 141 } 142 } 143 async function fresh(action: ExtensionAction): Promise<boolean> { 144 if (!current()) return false; 145 const result = await callExtension(action, 'key', () => 146 new ExtensionSigner().getPublicKey() 147 ); 148 if (!current()) return false; 149 if ( 150 result.status !== 'settled' || 151 !result.current || 152 result.value !== source.owner 153 ) { 154 source.invalidate(); 155 return false; 156 } 157 const cipher = cipherPort(); 158 if (!current()) return false; 159 if (!cipher) { 160 source.invalidate(); 161 return false; 162 } 163 return current(); 164 } 165 async function work(action: ExtensionAction): Promise<SealResult<T>> { 166 active = action; 167 const initial = cipherPort(); 168 if (!current()) return { status: 'stopped' }; 169 if (!initial) { 170 source.invalidate(); 171 return { status: 'unavailable' }; 172 } 173 if (!(await fresh(action))) return { status: 'stopped' }; 174 const wire = source.rumorWire(), 175 cipher = cipherPort(); 176 if (!cipher && current()) source.invalidate(); 177 if (!wire || !cipher || !current()) return { status: 'stopped' }; 178 const encrypted = await callExtension(action, 'encrypt', () => 179 cipher.encrypt(source.destination, wire) 180 ); 181 if (!current()) return { status: 'stopped' }; 182 if (encrypted.status !== 'settled' || !encrypted.current) 183 return { status: encrypted.status === 'denied' ? 'refused' : 'stopped' }; 184 if (!sealCiphertextV2(encrypted.value)) return { status: 'mismatch' }; 185 if (!(await fresh(action))) return { status: 'stopped' }; 186 const decryptPort = cipherPort(); 187 if (!decryptPort || !current()) return { status: 'stopped' }; 188 const decrypted = await callExtension(action, 'decrypt', () => 189 decryptPort.decrypt(source.destination, encrypted.value) 190 ); 191 if (!current()) return { status: 'stopped' }; 192 if (decrypted.status !== 'settled' || !decrypted.current) 193 return { status: decrypted.status === 'denied' ? 'refused' : 'stopped' }; 194 if (decrypted.value !== wire || source.rumorWire() !== wire) 195 return { status: 'mismatch' }; 196 if (!(await fresh(action))) return { status: 'stopped' }; 197 const milliseconds = safeUnsignedInteger(Date.now()); 198 if (milliseconds === undefined || !current()) return { status: 'stopped' }; 199 // Public randomized timing metadata only. Never change the reserved inner 200 // timestamp. No identity key, crypto implementation or future time created. 201 const random = crypto.getRandomValues(new Uint32Array(1))[0], 202 now = Math.floor(milliseconds / 1000), 203 time = Math.max(0, now - (random % 3600)); 204 const captured = captureSealTemplate(source.owner, encrypted.value, time); 205 if (!captured || !current()) return { status: 'mismatch' }; 206 const response = await callExtension(action, 'sign', () => 207 new ExtensionSigner().signEvent(JSON.parse(captured) as UnsignedEvent) 208 ); 209 if (!current()) return { status: 'stopped' }; 210 if (response.status !== 'settled' || !response.current) 211 return { status: response.status === 'denied' ? 'refused' : 'stopped' }; 212 const signed = bindSealResponse(captured, response.value); 213 if (!signed) return { status: 'mismatch' }; 214 if (!(await fresh(action))) return { status: 'stopped' }; 215 if (!current()) return { status: 'stopped' }; 216 const seal = source.accept(signed, current); 217 return { status: 'sealed', seal }; 218 } 219 async function run(): Promise<SealResult<T>> { 220 if (started || !current()) return { status: 'stopped' }; 221 started = true; 222 if (typeof window === 'undefined' || !navigator.locks?.request) 223 return { status: 'unavailable' }; 224 try { 225 return await navigator.locks.request( 226 'harvestcircle:owner:' + source.owner, 227 { mode: 'exclusive', ifAvailable: true }, 228 async (lock): Promise<SealResult<T>> => { 229 if (!lock) return { status: 'busy' }; 230 if (!current()) return { status: 'stopped' }; 231 const scheduler = browserExtensionScheduler(); 232 if (!scheduler) return { status: 'unavailable' }; 233 const result = await runExtensionAction( 234 scheduler, 235 { 236 owner: source.owner, 237 session: source.session, 238 operation: Symbol() 239 }, 240 current, 241 work 242 ); 243 if (!current()) return { status: 'stopped' }; 244 if (result.status === 'busy') return { status: 'busy' }; 245 return result.status === 'completed' && 246 'value' in result && 247 result.value 248 ? result.value 249 : { status: result.status === 'denied' ? 'refused' : 'stopped' }; 250 } 251 ); 252 } catch { 253 return { status: current() ? 'refused' : 'stopped' }; 254 } finally { 255 active = undefined; 256 } 257 } 258 return { run, stop }; 259 } 260 // Explicit ordinary preparation; probe identities never enter this factory. 261 export function capturePrivateSealOperation( 262 session: IdentitySession, 263 reserved: ReservedSendIdentity, 264 role: unknown, 265 review: unknown 266 ): PrivateSealOperation | undefined { 267 if ( 268 review !== 'reviewed_private_seal' || 269 (role !== 'peer' && role !== 'self') 270 ) 271 return undefined; 272 const record = reservedSendSnapshot(reserved), 273 ownership = identityMessagingOwnership(session); 274 if (!record || !ownership?.current() || record.owner !== ownership.owner) 275 return undefined; 276 const current = () => { 277 const observed = reservedSendSnapshot(reserved); 278 return ( 279 ownership.current() && 280 observed?.owner === record.owner && 281 observed.id === record.id && 282 observed.peer === record.peer && 283 observed.rumorHash === record.rumorHash 284 ); 285 }; 286 const destination = role === 'self' ? record.owner : record.peer; 287 const state = createSealOperation({ 288 owner: record.owner, 289 destination, 290 session: ownership.session, 291 current, 292 rumorWire: () => reservedSendRumorWire(reserved), 293 invalidate: () => disconnectIdentity(session), 294 accept(wire, available) { 295 const seal = Object.freeze({}) as PrivateRecipientSeal; 296 seals.set(seal, { 297 owner: record.owner, 298 peer: record.peer, 299 destination, 300 role, 301 command: record.id, 302 rumorHash: record.rumorHash, 303 wire, 304 reserved, 305 current: available 306 }); 307 return seal; 308 } 309 }); 310 const operation = Object.freeze({}) as PrivateSealOperation; 311 operations.set(operation, state); 312 return operation; 313 } 314 315 // Distinct self-only diagnostic construction. An ordinary identity or copied 316 // snapshot cannot enter; one original crypto operation belongs to this issuer. 317 export function captureInboxProbeSealOperation( 318 session: PrivateSession, 319 identity: InboxProbeIdentity, 320 review: unknown 321 ): InboxProbeSealOperation | undefined { 322 if (review !== 'reviewed_inbox_probe_seal') return undefined; 323 const record = inboxProbeSnapshot(identity), 324 ownership = privateSessionOwnership(session); 325 if ( 326 !record || 327 !ownership?.current() || 328 record.owner !== ownership.owner || 329 !inboxProbeRumorWire(identity, session) 330 ) 331 return undefined; 332 const prior = originalProbeOperations.get(identity); 333 if (prior) return prior; 334 const current = () => { 335 const observed = inboxProbeSnapshot(identity); 336 return ( 337 ownership.current() && 338 !!inboxProbeRumorWire(identity, session) && 339 observed?.owner === record.owner && 340 observed.id === record.id && 341 observed.rumorHash === record.rumorHash && 342 observed.createdAt === record.createdAt 343 ); 344 }; 345 const state = createSealOperation({ 346 owner: record.owner, 347 destination: record.owner, 348 session: ownership.session, 349 current, 350 rumorWire: () => inboxProbeRumorWire(identity, session), 351 invalidate: () => { 352 invalidatePrivateSessionGeneration(session); 353 }, 354 retire: () => stopInboxProbeIdentity(identity), 355 accept(wire, available) { 356 const seal = Object.freeze({}) as InboxProbeRecipientSeal; 357 probeSeals.set(seal, { 358 owner: record.owner, 359 destination: record.owner, 360 command: record.id, 361 rumorHash: record.rumorHash, 362 createdAt: record.createdAt, 363 wire, 364 identity, 365 current: available 366 }); 367 return seal; 368 } 369 }); 370 const operation = Object.freeze({}) as InboxProbeSealOperation; 371 probeOperations.set(operation, state); 372 originalProbeOperations.set(identity, operation); 373 return operation; 374 } 375 export function buildInboxProbeSeal( 376 operation: InboxProbeSealOperation 377 ): Promise<InboxProbeSealResult> { 378 return ( 379 probeOperations.get(operation)?.run() ?? 380 Promise.resolve({ status: 'invalid' }) 381 ); 382 } 383 export function stopInboxProbeSeal(operation: InboxProbeSealOperation): void { 384 probeOperations.get(operation)?.stop(false); 385 } 386 export function expireInboxProbeSealWait( 387 operation: InboxProbeSealOperation 388 ): void { 389 probeOperations.get(operation)?.stop(true); 390 } 391 export function inboxProbeSealSnapshot( 392 seal: InboxProbeRecipientSeal 393 ): Readonly<Omit<SavedProbeSeal, 'current' | 'identity'>> | undefined { 394 const saved = probeSeals.get(seal); 395 return saved?.current() 396 ? { 397 owner: saved.owner, 398 destination: saved.destination, 399 command: saved.command, 400 rumorHash: saved.rumorHash, 401 createdAt: saved.createdAt, 402 wire: saved.wire 403 } 404 : undefined; 405 } 406 export function inboxProbeSealIdentity( 407 seal: InboxProbeRecipientSeal 408 ): InboxProbeIdentity | undefined { 409 const saved = probeSeals.get(seal); 410 return saved?.current() ? saved.identity : undefined; 411 } 412 export function buildPrivateSeal( 413 operation: PrivateSealOperation 414 ): Promise<PrivateSealResult> { 415 return ( 416 operations.get(operation)?.run() ?? Promise.resolve({ status: 'invalid' }) 417 ); 418 } 419 export function stopPrivateSeal(operation: PrivateSealOperation): void { 420 operations.get(operation)?.stop(false); 421 } 422 export function expirePrivateSealWait(operation: PrivateSealOperation): void { 423 operations.get(operation)?.stop(true); 424 } 425 // Detached signed ciphertext only; a cast/copy is not a private seal token. 426 // Future wrapper/nested owners must retain exact original operation binding. 427 export function privateSealSnapshot( 428 seal: PrivateRecipientSeal 429 ): Readonly<Omit<SavedSeal, 'current' | 'reserved'>> | undefined { 430 const saved = seals.get(seal); 431 return saved?.current() 432 ? { 433 owner: saved.owner, 434 peer: saved.peer, 435 destination: saved.destination, 436 role: saved.role, 437 command: saved.command, 438 rumorHash: saved.rumorHash, 439 wire: saved.wire 440 } 441 : undefined; 442 } 443 // Genuine association only; detached snapshots cannot recreate this identity. 444 export function privateSealReservation( 445 seal: PrivateRecipientSeal 446 ): ReservedSendIdentity | undefined { 447 const saved = seals.get(seal); 448 return saved?.current() ? saved.reserved : undefined; 449 }