send-identity.ts (7949B)
1 import { canonicalLocalId } from '../private-handles.ts'; 2 import { safeUnsignedInteger } from '../nostr/envelope-bounds.ts'; 3 import { 4 identityMessagingOwnership, 5 type IdentitySession 6 } from '../runtime/identity-session.ts'; 7 import { 8 bindFirstRumorReservation, 9 rumorReservationCommand, 10 rumorPlanSnapshot, 11 type RumorPlan 12 } from './rumor-plan.ts'; 13 import { 14 recoveredSelfEnvelopeSnapshot, 15 type RecoveredSelfEnvelope 16 } from '../nostr/self-recovery-reader.ts'; 17 import { 18 privateSendReservationOwner, 19 reservePrivateSendReservation, 20 type PrivateSendReservationRepository, 21 type PrivateSendReservation, 22 type ReservationFailure 23 } from '../persistence/private-send-reservations.ts'; 24 declare const reservedBrand: unique symbol; 25 export type ReservedSendIdentity = Readonly<{ [reservedBrand]: true }>; 26 export type SendIdentityResult = 27 | Readonly<{ 28 status: 'reserved' | 'existing'; 29 identity: ReservedSendIdentity; 30 disposition: 'stored_original'; 31 }> 32 | Readonly<{ 33 status: ReservationFailure | 'busy'; 34 disposition: 'not_created' | 'may_exist'; 35 }>; 36 type Controller = { 37 record: PrivateSendReservation; 38 plan: RumorPlan; 39 current(): boolean; 40 }; 41 const identities = new WeakMap<ReservedSendIdentity, Controller>(); 42 // Metadata only, shared by every call using the same genuine plan. Retain the 43 // last actual storage disposition even when its plaintext capability is stopped. 44 const possibleOriginals = new WeakMap<RumorPlan, boolean>(); 45 function originalMayExist(plan: RumorPlan): boolean { 46 return ( 47 possibleOriginals.get(plan) ?? 48 (!rumorPlanSnapshot(plan) || rumorReservationCommand(plan) !== undefined) 49 ); 50 } 51 // Explicit reviewed local reservation only. No plaintext persistence or SDK 52 // effect; later owners revalidate this identity before encryption/preparation. 53 export async function reserveSendIdentity( 54 repository: PrivateSendReservationRepository, 55 session: IdentitySession, 56 commandId: unknown, 57 plan: RumorPlan, 58 review: unknown 59 ): Promise<SendIdentityResult> { 60 const id = canonicalLocalId(commandId), 61 ownership = identityMessagingOwnership(session), 62 snapshot = rumorPlanSnapshot(plan); 63 if ( 64 snapshot && 65 rumorReservationCommand(plan) === undefined && 66 !possibleOriginals.has(plan) 67 ) 68 possibleOriginals.set(plan, false); 69 // A previous owner-locked binding may already have reached storage. Early 70 // failure during its explicit reconciliation cannot certify a new draft. 71 const failure = ( 72 status: ReservationFailure | 'busy' 73 ): SendIdentityResult => ({ 74 status, 75 disposition: originalMayExist(plan) ? 'may_exist' : 'not_created' 76 }); 77 if (review !== 'reviewed_private_intent' || !id) return failure('invalid'); 78 if (!ownership?.current() || !snapshot) return failure('stopped'); 79 if ( 80 snapshot.owner !== ownership.owner || 81 privateSendReservationOwner(repository) !== ownership.owner 82 ) 83 return failure('invalid_scope'); 84 const actor = ownership; 85 try { 86 if (typeof window === 'undefined' || !navigator.locks?.request) 87 return failure('unavailable'); 88 return await navigator.locks.request( 89 'harvestcircle:owner:' + snapshot.owner, 90 { mode: 'exclusive', ifAvailable: true }, 91 async (lock): Promise<SendIdentityResult> => { 92 if (!lock) return failure('busy'); 93 if (!actor.current()) return failure('stopped'); 94 if (!rumorPlanSnapshot(plan)) return failure('stopped'); 95 const milliseconds = safeUnsignedInteger(Date.now()); 96 if (milliseconds === undefined) return failure('clock_conflict'); 97 const seconds = Math.floor(milliseconds / 1000); 98 const previouslyPossible = originalMayExist(plan); 99 const bound = bindFirstRumorReservation(plan, id, seconds); 100 if (!bound) 101 return failure(previouslyPossible ? 'conflict' : 'clock_conflict'); 102 const captured: PrivateSendReservation = { 103 schema: 1, 104 family: 'private_send_reservation', 105 owner: bound.owner, 106 id, 107 revision: 0, 108 peer: bound.peer, 109 rumorHash: bound.id, 110 createdAt: bound.createdAt 111 }; 112 const current = () => { 113 const observed = rumorPlanSnapshot(plan); 114 return ( 115 actor.current() && 116 observed?.owner === captured.owner && 117 observed.peer === captured.peer && 118 observed.id === captured.rumorHash && 119 observed.createdAt === captured.createdAt && 120 observed.wire === bound.wire && 121 rumorReservationCommand(plan) === id 122 ); 123 }; 124 if (!current()) return failure('stopped'); 125 possibleOriginals.set(plan, true); 126 const result = await reservePrivateSendReservation( 127 repository, 128 JSON.stringify(captured), 129 seconds, 130 current 131 ); 132 if (!result.ok) { 133 possibleOriginals.set( 134 plan, 135 result.disposition === 'not_attempted' 136 ? previouslyPossible 137 : result.disposition !== 'not_created' 138 ); 139 return failure(result.reason); 140 } 141 if (!current()) return failure('stopped'); 142 const identity = Object.freeze({}) as ReservedSendIdentity; 143 identities.set(identity, { record: result.value, plan, current }); 144 return { 145 status: result.state === 'created' ? 'reserved' : 'existing', 146 disposition: 'stored_original', 147 identity 148 }; 149 } 150 ); 151 } catch { 152 return failure('unavailable'); 153 } 154 } 155 156 export function reservedSendSnapshot( 157 identity: ReservedSendIdentity 158 ): PrivateSendReservation | undefined { 159 const value = identities.get(identity); 160 return value?.current() ? { ...value.record } : undefined; 161 } 162 // Restore the original actual command from authenticated stored self evidence; 163 // never re-reserve it using the current clock or a detached caller hash. 164 export function restoreRecoveredSendIdentity( 165 session: IdentitySession, 166 recovered: RecoveredSelfEnvelope, 167 plan: RumorPlan 168 ): ReservedSendIdentity | undefined { 169 const snapshot = recoveredSelfEnvelopeSnapshot(recovered), 170 ownership = identityMessagingOwnership(session), 171 rumor = rumorPlanSnapshot(plan); 172 if ( 173 !snapshot || 174 !ownership?.current() || 175 !rumor || 176 ownership.owner !== snapshot.record.owner || 177 rumor.owner !== snapshot.record.owner || 178 rumor.peer !== snapshot.record.peer || 179 rumor.id !== snapshot.record.rumorHash || 180 rumor.createdAt !== snapshot.record.createdAt || 181 rumor.wire !== snapshot.rumorWire 182 ) 183 return undefined; 184 const record: PrivateSendReservation = { 185 schema: 1, 186 family: 'private_send_reservation', 187 owner: snapshot.record.owner, 188 id: snapshot.record.id, 189 revision: 0, 190 peer: snapshot.record.peer, 191 rumorHash: snapshot.record.rumorHash, 192 createdAt: snapshot.record.createdAt 193 }; 194 const current = () => { 195 const observed = rumorPlanSnapshot(plan), 196 source = recoveredSelfEnvelopeSnapshot(recovered); 197 return ( 198 ownership.current() && 199 !!source && 200 observed?.wire === source.rumorWire && 201 source.record.id === record.id && 202 source.record.owner === record.owner && 203 source.record.peer === record.peer && 204 source.record.rumorHash === record.rumorHash && 205 source.record.createdAt === record.createdAt 206 ); 207 }; 208 const identity = Object.freeze({}) as ReservedSendIdentity; 209 identities.set(identity, { record, plan, current }); 210 return current() ? identity : undefined; 211 } 212 // Internal memory-only input to future encryption. A detached wire/snapshot is 213 // neither reserved identity nor effect permission and cannot retarget a send. 214 export function reservedSendRumorWire( 215 identity: ReservedSendIdentity 216 ): string | undefined { 217 const value = identities.get(identity); 218 return value?.current() ? rumorPlanSnapshot(value.plan)?.wire : undefined; 219 }