rumor-plan.ts (9363B)
1 import { buildCanonicalPairRumor } from '../nostr/rumor-template.ts'; 2 import { messageFromWireParts } from '../contracts/message-v1/index.ts'; 3 import { canonicalLocalId } from '../private-handles.ts'; 4 import { safeUnsignedInteger } from '../nostr/envelope-bounds.ts'; 5 import { 6 identityMessagingOwnership, 7 subscribeIdentityInvalidation, 8 type IdentitySession 9 } from '../runtime/identity-session.ts'; 10 import { buildEnquiryMessage, type EnquiryContext } from './enquiry-context.ts'; 11 import { 12 recoveredSelfEnvelopeSnapshot, 13 type RecoveredSelfEnvelope 14 } from '../nostr/self-recovery-reader.ts'; 15 import { 16 privateSessionOwnership, 17 type PrivateSession 18 } from '../runtime/private-session.ts'; 19 import { 20 unlockedSessionOwnership, 21 unlockedConversationCurrent, 22 type UnlockedSession 23 } from './unlocked-session.ts'; 24 import { 25 conversationSnapshot, 26 conversationOwnership, 27 type AdmittedConversation 28 } from './admit-conversation.ts'; 29 declare const rumorBrand: unique symbol; 30 export type RumorPlan = Readonly<{ readonly [rumorBrand]: true }>; 31 export type RumorPlanSnapshot = Readonly<{ 32 owner: string; 33 peer: string; 34 id: string; 35 createdAt: number; 36 wire: string; 37 }>; 38 type Controller = RumorPlanSnapshot & { 39 reservationCommand?: string; 40 recovered?: boolean; 41 current(): boolean; 42 unsubscribe(): void; 43 }; 44 const plans = new WeakMap<RumorPlan, Controller>(); 45 // Local memory-only planning capability, not cryptographically admitted inbound 46 // history, inbox readiness, CAS reservation, mounted view or encryption/Send. 47 // Incoming replies later require085/092 authenticated seal/rumor/room admission. 48 function capture( 49 session: IdentitySession, 50 rawMessage: string, 51 observedTime: unknown, 52 additionalCurrent: () => boolean = () => true 53 ): RumorPlan | undefined { 54 const ownership = identityMessagingOwnership(session); 55 if (!ownership || !ownership.current() || !additionalCurrent()) 56 return undefined; 57 const rumor = buildCanonicalPairRumor( 58 rawMessage, 59 ownership.owner, 60 observedTime 61 ); 62 if (!rumor || !ownership.current() || !additionalCurrent()) return undefined; 63 const peer = rumor.tags.find((row) => row[0] === 'p')?.[1]; 64 if (!peer) return undefined; 65 const token = Object.freeze({}) as RumorPlan; 66 const unsubscribe = subscribeIdentityInvalidation(session, () => { 67 if (!ownership.current() || !additionalCurrent()) stopRumorPlan(token); 68 }); 69 plans.set(token, { 70 owner: ownership.owner, 71 peer, 72 id: rumor.id, 73 createdAt: rumor.created_at, 74 wire: JSON.stringify(rumor), 75 current: () => ownership.current() && additionalCurrent(), 76 unsubscribe 77 }); 78 return token; 79 } 80 // Reply authority comes from the original authenticated room and its exact 81 // private/cache generation. A detached snapshot, parent hash or outer author 82 // cannot select the peer or borrow a same-owner session. 83 export function captureAuthenticatedReplyRumor( 84 identity: IdentitySession, 85 session: PrivateSession, 86 unlocked: UnlockedSession, 87 room: AdmittedConversation, 88 text: unknown, 89 observedTime: unknown 90 ): RumorPlan | undefined { 91 const owner = identityMessagingOwnership(identity), 92 privateOwner = privateSessionOwnership(session), 93 cache = unlockedSessionOwnership(unlocked), 94 admitted = conversationOwnership(room), 95 data = conversationSnapshot(room); 96 if ( 97 !owner || 98 !privateOwner || 99 !cache || 100 !admitted || 101 !data || 102 typeof text !== 'string' 103 ) 104 return; 105 const current = () => { 106 const actual = conversationSnapshot(room); 107 return ( 108 owner.current() && 109 privateOwner.current() && 110 cache.current() && 111 admitted.current() && 112 owner.owner === data.owner && 113 privateOwner.owner === owner.owner && 114 privateOwner.session === owner.session && 115 cache.owner === owner.owner && 116 cache.session === owner.session && 117 admitted.owner === owner.owner && 118 admitted.session === owner.session && 119 actual?.owner === data.owner && 120 actual.peer === data.peer && 121 actual.rumorId === data.rumorId && 122 unlockedConversationCurrent(unlocked, room) 123 ); 124 }; 125 if (!current()) return; 126 return capture( 127 identity, 128 JSON.stringify({ 129 recipients: [{ public_key: data.peer, relay_url: null }], 130 content: text, 131 reply_to: { id: data.rumorId, relays: null }, 132 subject: null 133 }), 134 observedTime, 135 current 136 ); 137 } 138 export function captureEnquiryRumor( 139 session: IdentitySession, 140 context: EnquiryContext, 141 text: unknown, 142 observedTime: unknown, 143 additionalCurrent: () => boolean = () => true 144 ): RumorPlan | undefined { 145 const parts = buildEnquiryMessage(context, text); 146 const message = parts && messageFromWireParts(JSON.stringify(parts)); 147 return message 148 ? capture(session, JSON.stringify(message), observedTime, additionalCurrent) 149 : undefined; 150 } 151 export function captureReplyRumor( 152 session: IdentitySession, 153 parent: RumorPlan, 154 text: unknown, 155 observedTime: unknown 156 ): RumorPlan | undefined { 157 if (typeof text !== 'string') return undefined; 158 const original = rumorPlanSnapshot(parent), 159 ownership = identityMessagingOwnership(session); 160 if ( 161 !original || 162 !ownership || 163 !ownership.current() || 164 (ownership.owner !== original.owner && ownership.owner !== original.peer) 165 ) 166 return undefined; 167 const peer = 168 ownership.owner === original.owner ? original.peer : original.owner; 169 // The parent hash comes only from a genuine captured local rumor, never a 170 // caller-provided product ID/body/URL/detached snapshot or outer signer. 171 return capture( 172 session, 173 JSON.stringify({ 174 recipients: [{ public_key: peer, relay_url: null }], 175 content: text, 176 reply_to: { id: original.id, relays: null }, 177 subject: null 178 }), 179 observedTime 180 ); 181 } 182 // Historical time/hash/wire are admitted only by actual authenticated SDK 183 // recovery. This creates no new intent, reservation, event or persistent body. 184 export function restoreRecoveredRumor( 185 session: IdentitySession, 186 recovered: RecoveredSelfEnvelope 187 ): RumorPlan | undefined { 188 const ownership = identityMessagingOwnership(session), 189 snapshot = recoveredSelfEnvelopeSnapshot(recovered); 190 if ( 191 !ownership?.current() || 192 !snapshot || 193 snapshot.record.owner !== ownership.owner 194 ) 195 return undefined; 196 const token = Object.freeze({}) as RumorPlan; 197 const current = () => 198 ownership.current() && !!recoveredSelfEnvelopeSnapshot(recovered); 199 const unsubscribe = subscribeIdentityInvalidation(session, () => { 200 if (!current()) stopRumorPlan(token); 201 }); 202 plans.set(token, { 203 owner: snapshot.record.owner, 204 peer: snapshot.record.peer, 205 id: snapshot.record.rumorHash, 206 createdAt: snapshot.record.createdAt, 207 wire: snapshot.rumorWire, 208 recovered: true, 209 reservationCommand: snapshot.record.id, 210 current, 211 unsubscribe 212 }); 213 return current() ? token : undefined; 214 } 215 // Planning is memory-only. The first owner-locked reservation binds the actual 216 // wall second once; every possible durable attempt keeps that original wire. 217 // Recovered ciphertext never enters this new-intent clock boundary. 218 export function bindFirstRumorReservation( 219 plan: RumorPlan, 220 commandId: unknown, 221 observedSeconds: unknown 222 ): RumorPlanSnapshot | undefined { 223 const value = plans.get(plan), 224 command = canonicalLocalId(commandId), 225 seconds = safeUnsignedInteger(observedSeconds); 226 if (!value?.current() || value.recovered || !command || seconds === undefined) 227 return undefined; 228 if (value.reservationCommand) 229 return value.reservationCommand === command 230 ? rumorPlanSnapshot(plan) 231 : undefined; 232 if (seconds < value.createdAt) return undefined; 233 const original = JSON.parse(value.wire) as { 234 kind: number; 235 tags: string[][]; 236 content: string; 237 }; 238 const message = messageFromWireParts( 239 JSON.stringify({ 240 kind: original.kind, 241 tags: original.tags, 242 content: original.content 243 }) 244 ); 245 const rumor = 246 message && 247 buildCanonicalPairRumor(JSON.stringify(message), value.owner, seconds); 248 if (!rumor || !value.current()) return undefined; 249 plans.set(plan, { 250 ...value, 251 id: rumor.id, 252 createdAt: rumor.created_at, 253 wire: JSON.stringify(rumor), 254 reservationCommand: command 255 }); 256 return rumorPlanSnapshot(plan); 257 } 258 export function rumorReservationCommand(plan: RumorPlan): string | undefined { 259 const value = plans.get(plan); 260 return value?.current() ? value.reservationCommand : undefined; 261 } 262 export function rumorPlanSnapshot( 263 plan: RumorPlan 264 ): RumorPlanSnapshot | undefined { 265 const value = plans.get(plan); 266 if (!value) return undefined; 267 if (!value.current()) { 268 stopRumorPlan(plan); 269 return undefined; 270 } 271 return { 272 owner: value.owner, 273 peer: value.peer, 274 id: value.id, 275 createdAt: value.createdAt, 276 wire: value.wire 277 }; 278 } 279 export function rumorEnvelopePlan(plan: RumorPlan) { 280 const value = rumorPlanSnapshot(plan); 281 return value 282 ? [ 283 { role: 'peer' as const, recipient: value.peer, rumorWire: value.wire }, 284 { 285 role: 'self_archive' as const, 286 recipient: value.owner, 287 rumorWire: value.wire 288 } 289 ] 290 : undefined; 291 } 292 export function stopRumorPlan(plan: RumorPlan): void { 293 const value = plans.get(plan); 294 plans.delete(plan); 295 value?.unsubscribe(); 296 }