conversation-thread.ts (13683B)
1 import { mount, unmount } from 'svelte'; 2 import Panel from './conversation-thread-panel.svelte'; 3 import { makeFixture as makeRecoveryFixture } from './resume-preparation.ts'; 4 import { makeFixture as makeRetryFixture } from './retry-send.ts'; 5 import { 6 getPublicKey, 7 getEventHash, 8 finalizeEvent, 9 type UnsignedEvent 10 } from 'applesauce-core/helpers'; 11 import { nip44 } from 'applesauce-core/helpers/encryption'; 12 import { encodeProductReference } from '../../../src/lib/nostr/references.ts'; 13 import { createPrivateSession } from '../../../src/lib/runtime/private-session.ts'; 14 import { 15 admitInboxEnvelope, 16 retainInboxEnvelope 17 } from '../../../src/lib/persistence/inbox-envelope-repository.ts'; 18 import { 19 captureReceivedUnwrap, 20 unwrapReceivedEnvelope, 21 stopReceivedUnwrap 22 } from '../../../src/lib/nostr/unwrap-admission.ts'; 23 import { admitReceivedConversation } from '../../../src/lib/messaging/admit-conversation.ts'; 24 import { 25 captureUnlockedSession, 26 acceptUnlockedConversation, 27 closeUnlockedSession 28 } from '../../../src/lib/messaging/unlocked-session.ts'; 29 import { captureMessageMetadata } from '../../../src/lib/persistence/message-metadata.ts'; 30 import { 31 captureConversationDirectory, 32 rememberAdmittedConversation, 33 closeConversationDirectory 34 } from '../../../src/lib/messaging/conversation-directory.ts'; 35 import { 36 createInboxSetupView, 37 checkInboxSetupView, 38 closeInboxSetupView 39 } from '../../../src/lib/messaging/inbox-setup-view.ts'; 40 import { 41 readRelayPolicy, 42 validateRelayPolicy 43 } from '../../../src/lib/config/relays.ts'; 44 import { 45 openBrowserDatabase, 46 closeBrowserDatabase, 47 browserDatabaseTransaction 48 } from '../../../src/lib/persistence/database.ts'; 49 import { 50 createInboxView, 51 inboxViewSnapshot, 52 unlockInboxView, 53 readNewInboxView, 54 inboxThreadSnapshot, 55 inboxMessageSnapshot, 56 resolveInboxConversation, 57 markInboxConversationDisplayed, 58 stopInboxView, 59 closeInboxView 60 } from '../../../src/lib/messaging/inbox-view.ts'; 61 import { identityMessagingOwnership } from '../../../src/lib/runtime/identity-session.ts'; 62 import type { RelayPolicy } from '../../../src/lib/config/relays.ts'; 63 import type { InboxResolver } from '../../../src/lib/messaging/resolve-inbox.ts'; 64 65 // HCP103 does not navigate; HCP104's separate harness exercises actual mounted 66 // beforeNavigate callbacks and unload/disposal. This alias owns fixture scope. 67 export function beforeNavigate(): void {} 68 69 export function goto(): never { 70 throw Error('Thread fixture must not navigate'); 71 } 72 export type Scenario = 73 | 'inbound' 74 | 'self_archive' 75 | 'contexts' 76 | 'duplicate' 77 | 'receipt' 78 | 'backfill' 79 | 'hostile'; 80 export async function renderFixture( 81 kind: Scenario = 'inbound', 82 selectedId?: string, 83 qualifiedReplyFixture = false, 84 freshOwnLookup?: ( 85 owner: string, 86 policy: RelayPolicy 87 ) => Promise<InboxResolver>, 88 initialContent?: string 89 ) { 90 // Receipt scenario performs actual original SDK retry and receives loopback 91 // OKs before mounting the readonly thread. The UI itself never publishes. 92 const delivery = kind === 'receipt' ? await makeRetryFixture() : undefined, 93 f = delivery ?? (await makeRecoveryFixture()), 94 session = await createPrivateSession( 95 f.identity, 96 'reviewed_private_session' 97 ); 98 if (!session) throw Error('no genuine current private session'); 99 let actualDelivery: unknown; 100 if (delivery) { 101 const prepared = await delivery.prepare(); 102 if (prepared.status !== 'existing' || !delivery.capture()) 103 throw Error('no actual stored pair retry'); 104 actualDelivery = await delivery.run(); 105 } 106 const ownerSecret = new Uint8Array(32).fill(83), 107 peerSecret = new Uint8Array(32).fill(84); 108 function cipher( 109 content: string, 110 createdAt: number, 111 index: number, 112 parent?: string 113 ) { 114 const sender = getPublicKey(peerSecret), 115 tags = [['p', f.owner]]; 116 if (parent) tags.push(['e', parent]); 117 const template: UnsignedEvent = { 118 pubkey: sender, 119 kind: 14, 120 created_at: createdAt, 121 tags, 122 content 123 }, 124 rumor = { id: getEventHash(template), ...template }; 125 function encrypt(key: Uint8Array, plain: string) { 126 const conversation = nip44.v2.utils.getConversationKey(key, f.owner); 127 try { 128 return nip44.v2.encrypt(plain, conversation); 129 } finally { 130 conversation.fill(0); 131 } 132 } 133 const seal = finalizeEvent( 134 { 135 kind: 13, 136 created_at: 1699999900, 137 tags: [], 138 content: encrypt(peerSecret, JSON.stringify(rumor)) 139 }, 140 peerSecret 141 ), 142 outerSecret = new Uint8Array(32).fill(85 + index); 143 try { 144 const outer = finalizeEvent( 145 { 146 kind: 1059, 147 created_at: 1699999800 + index, 148 tags: [['p', f.owner]], 149 content: encrypt(outerSecret, JSON.stringify(seal)) 150 }, 151 outerSecret 152 ); 153 return { 154 wire: JSON.stringify(outer), 155 rumorId: rumor.id, 156 body: content, 157 outerId: outer.id 158 }; 159 } finally { 160 outerSecret.fill(0); 161 } 162 } 163 const carrots = encodeProductReference({ 164 kind: 30402, 165 pubkey: f.peer, 166 identifier: 'carrots' 167 })!, 168 apples = encodeProductReference({ 169 kind: 30402, 170 pubkey: f.peer, 171 identifier: 'apples' 172 })!; 173 let first: ReturnType<typeof cipher>, 174 wires = Array.from<ReturnType<typeof cipher>>([]); 175 try { 176 if (kind === 'self_archive' || kind === 'receipt') { 177 const row = (await f.row())!.record, 178 outer = JSON.parse(row.self.wire) as { id: string }; 179 first = { 180 wire: row.self.wire, 181 outerId: outer.id, 182 rumorId: row.rumorHash, 183 body: 'Original encrypted self archive' 184 }; 185 } else 186 first = cipher( 187 initialContent ?? 188 (kind === 'hostile' 189 ? '<img src=x> Quoted price 4 GBP https://untrusted.example.org nostr:naddr1invalid' 190 : 'Actual encrypted thread fixture'), 191 1700000000, 192 0, 193 kind === 'hostile' ? 'f'.repeat(64) : undefined 194 ); 195 wires = wires.concat(first); 196 if (kind === 'contexts') 197 wires = wires.concat( 198 cipher( 199 'About carrots\nProduct: nostr:' + carrots + '\nQuoted price: 4 GBP', 200 1700000020, 201 1 202 ), 203 cipher( 204 'About apples\nProduct: nostr:' + apples + '\nQuoted price: 8 GBP', 205 1700000010, 206 2, 207 first.rumorId 208 ) 209 ); 210 if (kind === 'duplicate') 211 wires = wires.concat(cipher(first.body, 1700000000, 1)); 212 if (kind === 'backfill') 213 for (let i = 1; i <= 20; i++) 214 wires = wires.concat( 215 cipher('Actual later message ' + i, 1700000000 + i, i) 216 ); 217 for (const wire of wires) { 218 const admitted = admitInboxEnvelope( 219 wire.wire, 220 f.owner, 221 'wss://archive.example.org', 222 100 223 ); 224 if ( 225 !admitted || 226 (await retainInboxEnvelope(f.repository, session, admitted)).status !== 227 'retained' 228 ) 229 throw Error('actual ciphertext not retained'); 230 } 231 } finally { 232 ownerSecret.fill(0); 233 peerSecret.fill(0); 234 } 235 const opened = await openBrowserDatabase(); 236 if (opened.state !== 'ready') throw Error('no actual native database'); 237 const database = opened.owner; 238 // Establish only a genuine original-room owner UUID through the existing 239 // non-read native workflow, then discard the warmup plaintext cache. These 240 // preparation SDK calls are distinct from the later explicit UI count. 241 const reader = captureReceivedUnwrap( 242 f.repository, 243 f.identity, 244 first.outerId, 245 'reviewed_inbox_unlock' 246 ); 247 if (!reader) throw Error('no original nested reader'); 248 const result = await unwrapReceivedEnvelope(reader); 249 if (result.status !== 'authenticated') 250 throw Error('no actual authenticated fixture'); 251 const room = admitReceivedConversation( 252 result.envelope, 253 kind === 'self_archive' || kind === 'receipt' ? 'self_archive' : 'inbound' 254 ), 255 cache = captureUnlockedSession(session, 'reviewed_messages_unlock'); 256 if (!room || !cache || acceptUnlockedConversation(cache, room) !== 'added') 257 throw Error('no original cached room'); 258 const metadata = captureMessageMetadata( 259 database, 260 session, 261 cache, 262 'reviewed_local_message_metadata' 263 ), 264 directory = 265 metadata && 266 captureConversationDirectory( 267 session, 268 metadata, 269 'reviewed_conversation_directory' 270 ); 271 if (!directory) throw Error('no genuine directory'); 272 const remembered = await rememberAdmittedConversation( 273 directory, 274 room, 275 'reviewed_admitted_conversation_navigation' 276 ); 277 if (remembered.status !== 'saved' && remembered.status !== 'existing') 278 throw Error('no actual local UUID'); 279 const conversationId = selectedId ?? remembered.conversationId; 280 closeConversationDirectory(directory); 281 closeUnlockedSession(cache); 282 stopReceivedUnwrap(reader); 283 const policy = validateRelayPolicy( 284 JSON.stringify({ 285 ...readRelayPolicy(f.context.policy), 286 messagingEnabled: true 287 }) 288 ); 289 if (!policy) throw Error('no original policy'); 290 const setup = createInboxSetupView({ 291 identity: f.identity, 292 policy, 293 lookup: () => 294 freshOwnLookup 295 ? freshOwnLookup(f.owner, policy) 296 : Promise.resolve(f.context.own), 297 // Controlled qualification projection only, never production relay evidence. 298 observeAccess: qualifiedReplyFixture 299 ? (context) => ({ 300 ...context, 301 receive: 'qualified_exercised', 302 archive: 'qualified_exercised', 303 current: () => !!identityMessagingOwnership(f.identity)?.current() 304 }) 305 : undefined 306 }); 307 if (!setup) throw Error('no original setup'); 308 const controller = createInboxView({ 309 identity: f.identity, 310 setup, 311 conversationId 312 }); 313 if (!controller) throw Error('no genuine thread owner'); 314 const target = document.createElement('div'); 315 document.body.append(target); 316 const mounted = mount(Panel, { 317 target, 318 props: { controller, conversationId } 319 }), 320 baseline = f.counts(); 321 async function native() { 322 const tx = browserDatabaseTransaction( 323 database, 324 ['received_envelopes', 'conversations', 'private_sends'], 325 'readonly' 326 ), 327 received = tx.objectStore('received_envelopes').getAll(), 328 pairs = tx.objectStore('conversations').getAll(), 329 sends = tx.objectStore('private_sends').getAll(); 330 return await new Promise<{ 331 received: unknown[]; 332 pairs: unknown[]; 333 sends: unknown[]; 334 }>((resolve, reject) => { 335 tx.addEventListener('complete', () => 336 resolve({ 337 received: received.result, 338 pairs: pairs.result, 339 sends: sends.result 340 }) 341 ); 342 tx.addEventListener('abort', () => reject(Error('native scan aborted'))); 343 }); 344 } 345 let releaseReadLock: (() => void) | undefined, 346 readLockPending: Promise<unknown> | undefined; 347 async function holdReadLock() { 348 if (readLockPending) throw Error('already held'); 349 await new Promise<void>((resolve) => { 350 readLockPending = navigator.locks.request( 351 'harvestcircle:owner:' + f.owner, 352 async () => { 353 await new Promise<void>((release) => { 354 releaseReadLock = release; 355 resolve(); 356 }); 357 } 358 ); 359 }); 360 } 361 async function releaseRead() { 362 releaseReadLock?.(); 363 await readLockPending; 364 releaseReadLock = undefined; 365 readLockPending = undefined; 366 } 367 return { 368 identity: f.identity, 369 holdReadLock, 370 releaseRead, 371 controller, 372 replyLookup(peer: string) { 373 if (peer !== f.peer) throw Error('wrong authenticated fixture peer'); 374 return f.context.other; 375 }, 376 owner: f.owner, 377 peer: f.peer, 378 conversationId, 379 knownId: remembered.conversationId, 380 firstRumor: first.rumorId, 381 carrots, 382 apples, 383 actualDelivery, 384 preparationCounts: baseline, 385 native, 386 snapshot: () => inboxViewSnapshot(controller), 387 thread: () => inboxThreadSnapshot(controller, conversationId), 388 checkSetup: () => checkInboxSetupView(setup), 389 unlock: () => unlockInboxView(controller, 'reviewed_messages_unlock'), 390 next: () => readNewInboxView(controller, 'reviewed_decrypt_batch'), 391 delta: () => ({ 392 decrypts: f.counts().decrypts - baseline.decrypts, 393 signs: f.counts().signs - baseline.signs, 394 encrypts: f.counts().encrypts - baseline.encrypts 395 }), 396 copied: async () => ({ 397 snapshot: inboxThreadSnapshot({ ...controller }, conversationId), 398 message: inboxMessageSnapshot( 399 { ...controller }, 400 conversationId, 401 first.rumorId 402 ), 403 resolve: await resolveInboxConversation( 404 { ...controller }, 405 conversationId, 406 'reviewed_conversation_navigation' 407 ), 408 read: await markInboxConversationDisplayed( 409 { ...controller }, 410 conversationId, 411 [first.rumorId], 412 'reviewed_displayed_conversation' 413 ) 414 }), 415 resolve: (id: string) => 416 resolveInboxConversation( 417 controller, 418 id, 419 'reviewed_conversation_navigation' 420 ), 421 stop: () => stopInboxView(controller), 422 logout: () => f.disconnect(), 423 mode: f.mode, 424 settle: () => f.settle(), 425 pending: () => f.pending(), 426 async close() { 427 await releaseRead(); 428 f.settle(); 429 closeInboxView(controller); 430 closeInboxSetupView(setup); 431 await unmount(mounted); 432 closeBrowserDatabase(database); 433 f.close(); 434 target.remove(); 435 } 436 }; 437 }