sign-listing.ts (15735B)
1 import { 2 listingReviewOwnership, 3 type ListingReview 4 } from './prepare-listing.ts'; 5 import { 6 publicPublicationQuotaRepository, 7 readPublicListingIntent 8 } from '../persistence/public-publications.ts'; 9 import { 10 decodePublicRecord, 11 publicRecordSnapshot, 12 publicRecordWire, 13 type PublicRecordHandle 14 } from '../persistence/records.ts'; 15 import { 16 preparePublicListingSigningTransition, 17 preparePublicArtifactTransition, 18 publicTransitionSnapshot, 19 type CapturedArtifact 20 } from '../persistence/artifact-records.ts'; 21 import { 22 commitPublicOperationTransition, 23 observePublicOperationTransition 24 } from '../persistence/quota.ts'; 25 import { 26 captureIdentityPublicOperation, 27 identityPublicOperationOwnership, 28 identityPublicOperationSnapshot, 29 recheckIdentityOwner, 30 signIdentityPublicOperation, 31 stopIdentityPublicOperation, 32 type IdentityPublicOperation 33 } from '../runtime/identity-session.ts'; 34 import { runCapturedPublicEffect } from '../runtime/effect-ownership.ts'; 35 36 declare const signingBrand: unique symbol; 37 declare const publicationBrand: unique symbol; 38 export type ListingSigning = Readonly<{ [signingBrand]: true }>; 39 export type ListingPublication = Readonly<{ [publicationBrand]: true }>; 40 type Ownership = NonNullable<ReturnType<typeof listingReviewOwnership>>; 41 type Model = Readonly<{ 42 original: Ownership; 43 getOperation(): IdentityPublicOperation | undefined; 44 setOperation(value: IdentityPublicOperation): void; 45 getAttempted(): boolean; 46 setAttempted(): void; 47 getStopped(): boolean; 48 stop(): void; 49 getSigning(): boolean; 50 startSigning(): void; 51 finishSigning(): void; 52 subscribe(listener: () => void): () => void; 53 getMarked(): PublicRecordHandle | undefined; 54 setMarked(value: PublicRecordHandle): void; 55 getArtifact(): CapturedArtifact | undefined; 56 setArtifact(value: CapturedArtifact): void; 57 getPublication(): ListingPublication | undefined; 58 setPublication(value: ListingPublication): void; 59 }>; 60 function createModel(original: Ownership): Model { 61 let operation: IdentityPublicOperation | undefined; 62 let signing = false; 63 let attempted = false, 64 stopped = false; 65 let marked: PublicRecordHandle | undefined; 66 let artifact: CapturedArtifact | undefined; 67 let publication: ListingPublication | undefined; 68 const listeners = new Map<symbol, () => void>(); 69 let notifying = false; 70 function notify() { 71 if (notifying) return; 72 notifying = true; 73 try { 74 const callbacks = Array.from(listeners.entries()); 75 for (const [key, listener] of callbacks) { 76 if (listeners.get(key) !== listener) continue; 77 try { 78 listener(); 79 } catch { 80 /* Disclosure observers never control signing. */ 81 } 82 } 83 } finally { 84 notifying = false; 85 } 86 } 87 return { 88 original, 89 subscribe(listener) { 90 const key = Symbol(); 91 listeners.set(key, listener); 92 return () => { 93 listeners.delete(key); 94 }; 95 }, 96 getOperation: () => operation, 97 setOperation: (value) => { 98 operation = value; 99 }, 100 getAttempted: () => attempted, 101 setAttempted: () => { 102 attempted = true; 103 }, 104 getStopped: () => stopped, 105 stop: () => { 106 if (stopped) return; 107 stopped = true; 108 notify(); 109 }, 110 getSigning: () => signing, 111 startSigning: () => { 112 if (signing) return; 113 signing = true; 114 notify(); 115 }, 116 finishSigning: () => { 117 if (!signing) return; 118 signing = false; 119 notify(); 120 }, 121 getMarked: () => marked, 122 setMarked: (value) => { 123 marked = value; 124 }, 125 getArtifact: () => artifact, 126 setArtifact: (value) => { 127 artifact = value; 128 }, 129 getPublication: () => publication, 130 setPublication: (value) => { 131 publication = value; 132 } 133 }; 134 } 135 type Publication = Readonly<{ 136 model: Model; 137 recordWire: string; 138 wire: string; 139 owner: string; 140 command: string; 141 hash: string; 142 targets: readonly string[]; 143 policyFingerprint: string; 144 }>; 145 const signings = new WeakMap<ListingSigning, Model>(); 146 const commands = new WeakMap<ListingReview, ListingSigning>(); 147 const pending = new WeakMap<ListingSigning, Promise<ListingSigningResult>>(); 148 const publications = new WeakMap<ListingPublication, Publication>(); 149 export type ListingSigningResult = 150 | Readonly<{ status: 'prepared'; publication: ListingPublication }> 151 | Readonly<{ 152 status: 153 'invalid' | 'unavailable' | 'conflict' | 'unknown' | 'busy' | 'stopped'; 154 }>; 155 156 function current(model: Model): boolean { 157 const operation = model.getOperation(); 158 return ( 159 !model.getStopped() && 160 (model.getSigning() 161 ? model.original.readiness.signingCurrent() && 162 !!publicPublicationQuotaRepository(model.original.repository) 163 : model.original.current()) && 164 (!operation || 165 !!identityPublicOperationOwnership( 166 model.original.readiness.identity, 167 operation 168 )) 169 ); 170 } 171 export function beginListingSigning( 172 review: ListingReview, 173 consent: unknown 174 ): ListingSigning | undefined { 175 if (consent !== 'sign_reviewed_listing') return; 176 const original = listingReviewOwnership(review); 177 if (!original || !publicPublicationQuotaRepository(original.repository)) 178 return; 179 const existing = commands.get(review); 180 if (existing) return existing; 181 const token = Object.freeze({}) as ListingSigning; 182 signings.set(token, createModel(original)); 183 commands.set(review, token); 184 return token; 185 } 186 export function listingSigningSnapshot(token: ListingSigning) { 187 const model = signings.get(token); 188 if (!model) return; 189 const original = model.original; 190 const row = publicRecordSnapshot( 191 original.record, 192 original.readiness.owner, 193 original.command 194 ); 195 if (!row || row.family !== 'public_operation') return; 196 const heldOperation = model.getOperation(); 197 const operation = 198 heldOperation && 199 identityPublicOperationSnapshot(original.readiness.identity, heldOperation); 200 return { 201 owner: row.owner, 202 command: row.id, 203 hash: row.capture.hash, 204 stopped: model.getStopped(), 205 attempted: model.getAttempted(), 206 signing: model.getSigning() && current(model), 207 lateAvailable: operation?.lateAvailable ?? false 208 }; 209 } 210 // Original-token lifecycle observation only; no sign, retry or send authority. 211 export function subscribeListingSigning( 212 token: ListingSigning, 213 listener: () => void 214 ): () => void { 215 return signings.get(token)?.subscribe(listener) ?? (() => {}); 216 } 217 // Detached disclosure is never a send capability. HCP112 must independently 218 // admit the original plan, reread storage and obtain final network ownership. 219 export function listingPublicationSnapshot(token: ListingPublication) { 220 const value = publications.get(token); 221 if (!value || !current(value.model)) return; 222 return { 223 owner: value.owner, 224 command: value.command, 225 hash: value.hash, 226 wire: value.wire, 227 targets: value.targets.slice(), 228 policyFingerprint: value.policyFingerprint 229 }; 230 } 231 // Original custody only. This port grants no raw event or network effect; the 232 // typed publisher must obtain its own current lock and reread durable storage. 233 export function listingPublicationOwnership(token: ListingPublication) { 234 const value = publications.get(token); 235 if (!value || !current(value.model)) return; 236 const operation = value.model.getOperation(); 237 if (!operation) return; 238 return { 239 repository: value.model.original.repository, 240 identity: value.model.original.readiness.identity, 241 policy: value.model.original.readiness.policy, 242 operation, 243 owner: value.owner, 244 command: value.command, 245 recordWire: value.recordWire, 246 current: () => current(value.model) 247 }; 248 } 249 async function exactStored( 250 model: Model, 251 expected: PublicRecordHandle 252 ): Promise<boolean> { 253 const original = model.original, 254 owner = original.readiness.owner; 255 const read = await readPublicListingIntent( 256 original.repository, 257 original.command 258 ); 259 return ( 260 current(model) && 261 read.status === 'found' && 262 publicRecordWire(read.record, owner, original.command) === 263 publicRecordWire(expected, owner, original.command) 264 ); 265 } 266 async function persist(model: Model): Promise<ListingSigningResult> { 267 const original = model.original, 268 owner = original.readiness.owner; 269 const quota = publicPublicationQuotaRepository(original.repository); 270 const marked = model.getMarked(), 271 artifact = model.getArtifact(); 272 if (!quota || !marked || !artifact || !current(model)) 273 return { status: 'unavailable' }; 274 const transition = preparePublicArtifactTransition( 275 marked, 276 owner, 277 original.command, 278 artifact 279 ); 280 if (!transition.ok) return { status: 'conflict' }; 281 const proposed = publicTransitionSnapshot( 282 transition.value, 283 owner, 284 original.command 285 ); 286 if (!proposed) return { status: 'invalid' }; 287 const decoded = decodePublicRecord( 288 proposed.nextWire, 289 owner, 290 original.command 291 ); 292 if (!decoded.ok) return { status: 'invalid' }; 293 if (!current(model)) return { status: 'stopped' }; 294 const saved = await commitPublicOperationTransition(quota, transition.value); 295 if (!current(model)) return { status: 'unknown' }; 296 if (!saved.ok) { 297 if (saved.reason !== 'unknown_completion') 298 return { 299 status: saved.reason === 'conflict' ? 'conflict' : 'unavailable' 300 }; 301 const observed = await observePublicOperationTransition( 302 quota, 303 transition.value 304 ); 305 if (observed.state !== 'committed' || !current(model)) 306 return { status: observed.state === 'conflict' ? 'conflict' : 'unknown' }; 307 } 308 if (!(await exactStored(model, decoded.value))) return { status: 'unknown' }; 309 const row = publicRecordSnapshot(decoded.value, owner, original.command); 310 if (!row || row.family !== 'public_operation' || !row.artifact) 311 return { status: 'invalid' }; 312 const token = Object.freeze({}) as ListingPublication; 313 publications.set(token, { 314 model, 315 recordWire: proposed.nextWire, 316 wire: row.artifact.wire, 317 owner, 318 command: row.id, 319 hash: row.artifact.eventId, 320 targets: row.capture.targets.slice(), 321 policyFingerprint: row.capture.policyFingerprint 322 }); 323 model.setPublication(token); 324 return { status: 'prepared', publication: token }; 325 } 326 async function execute(model: Model): Promise<ListingSigningResult> { 327 try { 328 const original = model.original, 329 identity = original.readiness.identity, 330 owner = original.readiness.owner; 331 const quota = publicPublicationQuotaRepository(original.repository); 332 if ( 333 !quota || 334 !current(model) || 335 typeof window === 'undefined' || 336 !navigator.locks?.request 337 ) 338 return { status: 'unavailable' }; 339 const publication = model.getPublication(); 340 if (publication) { 341 const value = publications.get(publication); 342 if (!value) return { status: 'invalid' }; 343 const rechecked = await recheckIdentityOwner(identity); 344 if (!current(model) || rechecked.state === 'guest') 345 return { status: 'unavailable' }; 346 const read = await readPublicListingIntent( 347 original.repository, 348 original.command 349 ); 350 if ( 351 !current(model) || 352 read.status !== 'found' || 353 publicRecordWire(read.record, owner, original.command) !== 354 value.recordWire 355 ) 356 return { status: 'conflict' }; 357 return { status: 'prepared', publication }; 358 } 359 if (model.getArtifact()) { 360 await recheckIdentityOwner(identity); 361 if (!current(model)) return { status: 'unavailable' }; 362 // Retained exact verified artifact retry is storage-only; never a prompt. 363 return await navigator.locks.request( 364 'harvestcircle:owner:' + owner, 365 { mode: 'exclusive', ifAvailable: true }, 366 (lock) => 367 lock ? persist(model) : Promise.resolve({ status: 'busy' as const }) 368 ); 369 } 370 if (model.getAttempted()) return { status: 'unknown' }; 371 if (!(await exactStored(model, original.record))) 372 return { status: 'conflict' }; 373 const operation = captureIdentityPublicOperation( 374 identity, 375 original.record, 376 original.command, 377 'reviewed_captured_operation' 378 ); 379 if (!operation) return { status: 'unavailable' }; 380 model.setOperation(operation); 381 const ownership = identityPublicOperationOwnership(identity, operation); 382 if (!ownership || !current(model)) return { status: 'unavailable' }; 383 const captured = publicRecordSnapshot( 384 original.record, 385 owner, 386 original.command 387 ); 388 if (captured?.family !== 'public_operation') return { status: 'invalid' }; 389 const result = await runCapturedPublicEffect( 390 quota, 391 original.record, 392 original.command, 393 { ...ownership, current: () => current(model) && ownership.current() }, 394 captured.capture.kind === 5 && captured.source.type === 'public_head' 395 ? 'reviewed_prepared_withdrawal_operation' 396 : 'reviewed_prepared_listing_operation', 397 async (lease): Promise<ListingSigningResult> => { 398 const marker = preparePublicListingSigningTransition( 399 original.record, 400 owner, 401 original.command 402 ); 403 if (!marker.ok || !current(model)) return { status: 'invalid' }; 404 const next = publicTransitionSnapshot( 405 marker.value, 406 owner, 407 original.command 408 ); 409 if (!next) return { status: 'invalid' }; 410 model.setAttempted(); 411 const saved = await commitPublicOperationTransition( 412 quota, 413 marker.value 414 ); 415 if (!saved.ok || !current(model)) 416 return { 417 status: 418 saved.ok || saved.reason === 'unknown_completion' 419 ? 'unknown' 420 : 'unavailable' 421 }; 422 const decoded = decodePublicRecord( 423 next.nextWire, 424 owner, 425 original.command 426 ); 427 if (!decoded.ok || !(await exactStored(model, decoded.value))) 428 return { status: 'unknown' }; 429 model.setMarked(decoded.value); 430 model.startSigning(); 431 let signed; 432 try { 433 signed = await signIdentityPublicOperation( 434 identity, 435 operation, 436 lease 437 ); 438 } finally { 439 model.finishSigning(); 440 } 441 if (signed.status !== 'signed' || !current(model)) 442 return { 443 status: 444 signed.status === 'unknown' || !current(model) 445 ? 'unknown' 446 : 'invalid' 447 }; 448 model.setArtifact(signed.artifact); 449 return await persist(model); 450 } 451 ); 452 return result.status === 'completed' 453 ? result.value 454 : { 455 status: 456 result.status === 'busy' 457 ? 'busy' 458 : result.status === 'unknown' || result.status === 'retained' 459 ? 'unknown' 460 : 'unavailable' 461 }; 462 } catch { 463 return { status: 'unknown' }; 464 } 465 } 466 export function runListingSigning( 467 token: ListingSigning, 468 consent: unknown 469 ): Promise<ListingSigningResult> { 470 const model = signings.get(token); 471 if (!model || consent !== 'sign_reviewed_listing') 472 return Promise.resolve({ status: 'invalid' }); 473 const active = pending.get(token); 474 if (active) return active; 475 const work = execute(model).finally(() => { 476 if (pending.get(token) === work) pending.delete(token); 477 }); 478 pending.set(token, work); 479 return work; 480 } 481 export function stopListingSigning(token: ListingSigning): void { 482 const model = signings.get(token); 483 if (!model) return; 484 model.stop(); 485 const operation = model.getOperation(); 486 if (operation) 487 stopIdentityPublicOperation(model.original.readiness.identity, operation); 488 }