inbox-access-qualification.ts (15626B)
1 import type { RelayPolicy } from '../config/relays.ts'; 2 import { 3 inboxOperatorQualificationSnapshot, 4 inboxOperatorQualificationWire, 5 type InboxOperatorQualification 6 } from '../config/inbox-operators.ts'; 7 import { 8 inboxAccessConstructionBinding, 9 inboxAccessControllerSourceSnapshot, 10 subscribeInboxAccessControllerClose, 11 type InboxAccessController 12 } from './inbox-access-controller.ts'; 13 import type { OwnInboxAccessContext, ObserveInboxAccess } from './readiness.ts'; 14 import { 15 captureInboxProbeCleanupSelection, 16 inboxProbeCleanupSelectionBinding, 17 type InboxProbeNonceAcknowledgement 18 } from '../persistence/inbox-probes.ts'; 19 import { 20 inboxProbeRemovalAcknowledgementBinding, 21 type InboxProbeRemovalAcknowledgement 22 } from '../persistence/inbox-probe-cleanup.ts'; 23 import { 24 captureInboxProbeQualificationFence, 25 inboxProbeQualificationFenceCurrent, 26 inboxProbeCleanupReady 27 } from '../nostr/private-publisher.ts'; 28 import { 29 privateSessionOwnership, 30 recheckPrivateSession, 31 subscribePrivateSessionClose, 32 withIdlePrivateLocalStorage, 33 type PrivateSession 34 } from '../runtime/private-session.ts'; 35 import { 36 observePrivateRecord, 37 privateStorageOwner, 38 type PrivateStorageRepository, 39 type PrivateStorageFailure 40 } from '../persistence/private-storage.ts'; 41 import { privateRecordWire } from '../persistence/private-records.ts'; 42 43 declare const qualificationBrand: unique symbol; 44 export type InboxAccessQualification = Readonly<{ [qualificationBrand]: true }>; 45 export type InboxAccessQualificationResult = Readonly<{ 46 status: 'qualified' | 'invalid' | 'busy' | 'stopped' | PrivateStorageFailure; 47 qualification?: InboxAccessQualification; 48 }>; 49 type Metadata = Readonly<{ 50 owner: string; 51 command: string; 52 eventId: string; 53 preferenceId: string; 54 readTargets: readonly string[]; 55 archiveTargets: readonly string[]; 56 operatorWire: string; 57 }>; 58 type Scope = Metadata & 59 Readonly<{ 60 repository: PrivateStorageRepository; 61 session: PrivateSession; 62 policy: RelayPolicy; 63 access: InboxAccessController; 64 operator: InboxOperatorQualification; 65 identitySession: symbol; 66 authority: 'source_fixture' | 'operator'; 67 current(): boolean; 68 }>; 69 type Action = Readonly<{ 70 scope: Scope; 71 current(): boolean; 72 pending(): boolean; 73 result(): InboxAccessQualification | undefined; 74 begin(): boolean; 75 finish(): void; 76 stop(): void; 77 issue(): InboxAccessQualification; 78 }>; 79 const actions = new WeakMap<object, Action>(); 80 const qualifications = new WeakMap<InboxAccessQualification, Action>(); 81 function same(a: readonly string[], b: readonly string[]) { 82 return a.length === b.length && a.every((value, index) => value === b[index]); 83 } 84 function makeScope( 85 repository: PrivateStorageRepository, 86 session: PrivateSession, 87 policy: RelayPolicy, 88 access: InboxAccessController, 89 operator: InboxOperatorQualification, 90 metadata: Metadata 91 ): Scope | undefined { 92 const actual = inboxAccessConstructionBinding(access, session, policy), 93 owner = privateSessionOwnership(session), 94 declaration = inboxOperatorQualificationSnapshot(operator); 95 if ( 96 !actual || 97 !owner || 98 !declaration || 99 declaration.authority === 'unconfigured' || 100 privateStorageOwner(repository) !== metadata.owner || 101 owner.owner !== metadata.owner || 102 actual.owner !== metadata.owner || 103 actual.session !== owner.session || 104 actual.preferenceId !== metadata.preferenceId || 105 !same(actual.readTargets, metadata.readTargets) || 106 !same(actual.archiveTargets, metadata.archiveTargets) || 107 inboxOperatorQualificationWire(operator, policy) !== metadata.operatorWire 108 ) 109 return undefined; 110 const targets = Array.from( 111 new Set([...actual.readTargets, ...actual.archiveTargets]) 112 ); 113 if ( 114 !targets.every((origin) => { 115 const row = declaration.relays.find((value) => value.origin === origin); 116 return ( 117 row && 118 row.auth !== 'unsupported' && 119 row.recipientRead === 'supported' && 120 row.namedArchiveAck === 'supported' && 121 row.exactReadback === 'supported' && 122 row.retention === 'operator_defined' 123 ); 124 }) 125 ) 126 return undefined; 127 function current() { 128 const snapshot = inboxAccessControllerSourceSnapshot(access); 129 return ( 130 actual!.current() && 131 owner!.current() && 132 inboxOperatorQualificationWire(operator, policy) === 133 metadata.operatorWire && 134 !!snapshot && 135 !snapshot.busy && 136 !snapshot.cleanupRequired && 137 snapshot.state !== 'stopped' && 138 targets.every((origin) => { 139 const required = declaration!.relays.find( 140 (value) => value.origin === origin 141 )!, 142 auth = snapshot.auth.find((value) => value.origin === origin); 143 return required.auth === 'explicit_required' 144 ? auth?.state === 'accepted' 145 : !auth || auth.state === 'accepted'; 146 }) && 147 actual!.current() && 148 owner!.current() 149 ); 150 } 151 return current() 152 ? { 153 ...metadata, 154 readTargets: metadata.readTargets.slice(), 155 archiveTargets: metadata.archiveTargets.slice(), 156 repository, 157 session, 158 policy, 159 access, 160 operator, 161 identitySession: owner.session, 162 authority: declaration.authority, 163 current 164 } 165 : undefined; 166 } 167 function compatible(action: Action, scope: Scope) { 168 const saved = action.scope; 169 return ( 170 saved.repository === scope.repository && 171 saved.session === scope.session && 172 saved.policy === scope.policy && 173 saved.access === scope.access && 174 saved.operator === scope.operator && 175 saved.command === scope.command && 176 saved.eventId === scope.eventId && 177 saved.operatorWire === scope.operatorWire 178 ); 179 } 180 // The currentness port is created only by the two authenticated factories below; 181 // no caller currentness, epoch or coverage callback enters this private owner. 182 function createAction(scope: Scope, sourceCurrent: () => boolean): Action { 183 let stopped = false, 184 pending = false, 185 token: InboxAccessQualification | undefined; 186 const listeners = new Map<symbol, () => void>(); 187 function current() { 188 return !stopped && scope.current() && sourceCurrent(); 189 } 190 function stop() { 191 stopped = true; 192 for (const [id, off] of listeners) { 193 off(); 194 listeners.delete(id); 195 } 196 } 197 const saved: Action = { 198 scope, 199 current, 200 pending: () => pending, 201 result: () => token, 202 begin() { 203 if (pending || !current()) return false; 204 pending = true; 205 return true; 206 }, 207 finish() { 208 pending = false; 209 }, 210 stop, 211 issue() { 212 token ??= Object.freeze({}) as InboxAccessQualification; 213 qualifications.set(token, saved); 214 return token; 215 } 216 }; 217 listeners.set(Symbol(), subscribePrivateSessionClose(scope.session, stop)); 218 listeners.set( 219 Symbol(), 220 subscribeInboxAccessControllerClose(scope.access, stop) 221 ); 222 if (!current()) stop(); 223 return saved; 224 } 225 function result(action: Action): InboxAccessQualificationResult | undefined { 226 const token = action.result(); 227 if (!action.current()) return { status: 'stopped' }; 228 if (token) return { status: 'qualified', qualification: token }; 229 if (action.pending()) return { status: 'busy' }; 230 return undefined; 231 } 232 233 // Explicit qualification, without a new probe, network attempt or native write. 234 export async function qualifyInboxAccess( 235 repository: PrivateStorageRepository, 236 session: PrivateSession, 237 policy: RelayPolicy, 238 access: InboxAccessController, 239 operator: InboxOperatorQualification, 240 nonce: InboxProbeNonceAcknowledgement, 241 observations: unknown, 242 review: unknown 243 ): Promise<InboxAccessQualificationResult> { 244 if ( 245 typeof window === 'undefined' || 246 review !== 'reviewed_qualify_inbox_access' 247 ) 248 return { status: 'invalid' }; 249 try { 250 const selection = captureInboxProbeCleanupSelection( 251 repository, 252 session, 253 policy, 254 nonce, 255 observations, 256 'reviewed_inbox_probe_cleanup_selection' 257 ), 258 binding = 259 selection && 260 inboxProbeCleanupSelectionBinding( 261 selection, 262 repository, 263 session, 264 policy 265 ); 266 if ( 267 !selection || 268 !binding || 269 binding.access !== access || 270 binding.operator !== operator 271 ) 272 return { status: 'invalid_scope' }; 273 const scope = makeScope(repository, session, policy, access, operator, { 274 owner: binding.record.owner, 275 command: binding.record.id, 276 eventId: binding.record.self!.eventId, 277 preferenceId: binding.record.binding.preferenceId, 278 readTargets: binding.record.binding.readTargets, 279 archiveTargets: binding.record.binding.archiveTargets, 280 operatorWire: binding.record.binding.operatorWire 281 }); 282 if (!scope) return { status: 'invalid_scope' }; 283 let action = actions.get(nonce); 284 if (action && !compatible(action, scope)) 285 return { status: 'invalid_scope' }; 286 if (!action) { 287 const fence = captureInboxProbeQualificationFence( 288 repository, 289 session, 290 policy, 291 selection 292 ); 293 if (!fence) { 294 // A later append must not let this same old nonce resample authority. 295 actions.set( 296 nonce, 297 createAction(scope, () => false) 298 ); 299 return { status: 'stopped' }; 300 } 301 action = createAction(scope, () => 302 inboxProbeQualificationFenceCurrent(fence) 303 ); 304 actions.set(nonce, action); 305 } 306 const cached = result(action); 307 if (cached) return cached; 308 const saved = action; 309 if (!saved.begin()) return { status: saved.current() ? 'busy' : 'stopped' }; 310 try { 311 if (!navigator.locks?.request) return { status: 'unavailable' }; 312 return await navigator.locks.request( 313 'harvestcircle:owner:' + scope.owner, 314 { mode: 'exclusive', ifAvailable: true }, 315 async (lock): Promise<InboxAccessQualificationResult> => { 316 if (!lock) return { status: 'busy' }; 317 if (!saved.current()) return { status: 'stopped' }; 318 if (!inboxProbeCleanupReady(repository, session, policy, selection)) 319 return { status: saved.current() ? 'busy' : 'stopped' }; 320 if (!(await recheckPrivateSession(session)) || !saved.current()) 321 return { status: saved.current() ? 'busy' : 'stopped' }; 322 const job = 323 await withIdlePrivateLocalStorage<InboxAccessQualificationResult>( 324 session, 325 async () => { 326 if (!saved.current()) return { status: 'stopped' }; 327 if (!binding.begin()) return { status: 'busy' }; 328 try { 329 const native = await observePrivateRecord( 330 repository, 331 'private_sends', 332 scope.command 333 ); 334 if (!native.ok) return { status: native.reason }; 335 if (!saved.current()) return { status: 'stopped' }; 336 if ( 337 native.value.wire !== binding.wire || 338 privateRecordWire( 339 native.value.handle, 340 scope.owner, 341 scope.command 342 ) !== binding.wire 343 ) 344 return { status: 'conflict' }; 345 if (!saved.current()) return { status: 'stopped' }; 346 return { status: 'qualified', qualification: saved.issue() }; 347 } finally { 348 binding.finish(); 349 } 350 } 351 ); 352 if (!saved.current()) return { status: 'stopped' }; 353 return job.ok ? job.value : { status: 'busy' }; 354 } 355 ); 356 } finally { 357 saved.finish(); 358 } 359 } catch { 360 return { status: 'unknown_completion' }; 361 } 362 } 363 364 // This path consumes source-authenticated pre-disposal admission coverage as 365 // well as actual successful native removal. Mere genuine cleanup is insufficient. 366 export function qualifyRemovedInboxAccess( 367 repository: PrivateStorageRepository, 368 session: PrivateSession, 369 policy: RelayPolicy, 370 access: InboxAccessController, 371 operator: InboxOperatorQualification, 372 removal: InboxProbeRemovalAcknowledgement, 373 review: unknown 374 ): InboxAccessQualificationResult { 375 if ( 376 typeof window === 'undefined' || 377 review !== 'reviewed_qualify_inbox_access' 378 ) 379 return { status: 'invalid' }; 380 try { 381 const binding = inboxProbeRemovalAcknowledgementBinding( 382 removal, 383 repository, 384 session, 385 policy 386 ), 387 coverage = binding?.qualification; 388 if ( 389 !binding || 390 !coverage || 391 binding.access !== access || 392 binding.operator !== operator || 393 coverage.access !== access || 394 coverage.operator !== operator || 395 !coverage.current() 396 ) 397 return { status: 'invalid_scope' }; 398 const scope = makeScope( 399 repository, 400 session, 401 policy, 402 access, 403 operator, 404 binding 405 ); 406 if (!scope) return { status: 'invalid_scope' }; 407 let action = actions.get(removal); 408 if (action && !compatible(action, scope)) 409 return { status: 'invalid_scope' }; 410 if (!action) { 411 action = createAction(scope, () => { 412 const fresh = inboxProbeRemovalAcknowledgementBinding( 413 removal, 414 repository, 415 session, 416 policy 417 ); 418 return ( 419 !!fresh?.qualification && 420 fresh.access === access && 421 fresh.operator === operator && 422 fresh.qualification.current() && 423 fresh.current() 424 ); 425 }); 426 actions.set(removal, action); 427 } 428 const cached = result(action); 429 if (cached) return cached; 430 return action.current() 431 ? { status: 'qualified', qualification: action.issue() } 432 : { status: 'stopped' }; 433 } catch { 434 return { status: 'invalid' }; 435 } 436 } 437 438 export function inboxAccessQualificationSnapshot( 439 token: InboxAccessQualification 440 ) { 441 const saved = qualifications.get(token); 442 return saved?.current() 443 ? { 444 owner: saved.scope.owner, 445 command: saved.scope.command, 446 preferenceId: saved.scope.preferenceId, 447 authority: saved.scope.authority, 448 sourceOnly: true 449 } 450 : undefined; 451 } 452 export function stopInboxAccessQualification( 453 token: InboxAccessQualification 454 ): void { 455 qualifications.get(token)?.stop(); 456 } 457 // Existing projections receive only an informational view of a genuine proof. 458 // No public object or caller current callback can enter the qualification map. 459 export function observeQualifiedInboxAccess( 460 token: InboxAccessQualification 461 ): ObserveInboxAccess { 462 return (context: OwnInboxAccessContext) => { 463 try { 464 const saved = qualifications.get(token); 465 if (!saved?.current()) return undefined; 466 const scope = saved.scope; 467 if ( 468 context.owner !== scope.owner || 469 context.session !== scope.identitySession || 470 context.preferenceId !== scope.preferenceId || 471 !same(scope.readTargets, context.readTargets) || 472 !same(scope.archiveTargets, context.archiveTargets) || 473 !saved.current() 474 ) 475 return undefined; 476 return { 477 owner: scope.owner, 478 session: scope.identitySession, 479 preferenceId: scope.preferenceId, 480 readTargets: scope.readTargets.slice(), 481 archiveTargets: scope.archiveTargets.slice(), 482 receive: 'qualified_exercised', 483 archive: 'qualified_exercised', 484 current: saved.current 485 }; 486 } catch { 487 return undefined; 488 } 489 }; 490 }