app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

commit 59c3147b98db4b05a2849a39b1427ec22db7cf73
parent 24f5c12471695a8d759afdce764f594f2042717d
Author: triesap <tyson@radroots.org>
Date:   Fri,  9 Oct 2026 07:28:17 +0000

messages: persist only minimal local read and association metadata (HCP-094)

- Bind local metadata to genuine admitted room and current unlocked generation.
- Save verified read hash and opaque pair mapping on explicit display only.
- Preserve ciphertext, whole-wire CAS, quotas and readback uncertainty.
- Verify duplicate wraps, reload, delayed messages and real IDB failure boundaries.

Diffstat:
Mweb/src/lib/messaging/admit-conversation.ts | 14++++++++++++++
Mweb/src/lib/messaging/unlocked-session.ts | 34++++++++++++++++++++++++++++++++++
Aweb/src/lib/messaging/unread.ts | 37+++++++++++++++++++++++++++++++++++++
Aweb/src/lib/persistence/message-metadata.ts | 570+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/harness/message-metadata.ts | 611+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/message-metadata.spec.ts | 394+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/unit/message-metadata.test.ts | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 1721 insertions(+), 0 deletions(-)

diff --git a/web/src/lib/messaging/admit-conversation.ts b/web/src/lib/messaging/admit-conversation.ts @@ -136,3 +136,17 @@ export function conversationOwnership(token: AdmittedConversation) { const saved = rooms.get(token); return saved && receivedNestedEnvelopeOwnership(saved.nested); } + +// HCP094 ciphertext identity observation from the original authenticated room. +// Detached strings never replace genuine room custody or grant persistence. +export function conversationEnvelopeIdentity(token: AdmittedConversation) { + const saved = rooms.get(token), + nested = saved && receivedNestedEnvelopeSnapshot(saved.nested); + return nested && conversationSnapshot(token) + ? { + owner: nested.owner, + outerId: nested.outerId, + outerWire: nested.outerWire + } + : undefined; +} diff --git a/web/src/lib/messaging/unlocked-session.ts b/web/src/lib/messaging/unlocked-session.ts @@ -28,6 +28,8 @@ type View = Readonly<{ type Snapshot = Readonly<{ closed: boolean; count: number; bytes: number }>; type Controller = { current(): boolean; + ownership(): ReturnType<typeof privateSessionOwnership>; + contains(room: AdmittedConversation): boolean; accept(room: AdmittedConversation): UnlockedAdmission; read(): View; snapshot(): Snapshot; @@ -72,6 +74,8 @@ export function captureUnlockedSession( // heap/garbage-collection timing cannot be securely zeroized or recalled. controllers.set(token, { current: () => false, + ownership: () => undefined, + contains: () => false, accept: () => 'closed', read: () => ({ status: 'closed', messages: [] }), snapshot: () => ({ closed: true, count: 0, bytes: 0 }), @@ -87,6 +91,25 @@ export function captureUnlockedSession( } const state: Controller = { current, + ownership: () => (current() ? { ...capture, current } : undefined), + contains(room) { + if (!current()) return false; + const own = conversationOwnership(room), + data = conversationSnapshot(room); + if ( + !own?.current() || + own.owner !== capture.owner || + own.session !== capture.session || + !data + ) + return false; + const wire = JSON.stringify(data); + return ( + current() && + entries.get(data.rumorId) === wire && + privateCacheWire(cache, data.rumorId) === wire + ); + }, accept(room) { if (!current()) return 'closed'; // Authenticate original room and generation before even a dedup lookup. @@ -170,3 +193,14 @@ export function unlockedSessionSnapshot(scope: UnlockedSession): Snapshot { export function closeUnlockedSession(scope: UnlockedSession): void { controllers.get(scope)?.close(); } + +// Original accepted-cache custody observations only. Copies are not authority. +export function unlockedSessionOwnership(scope: UnlockedSession) { + return controllers.get(scope)?.ownership(); +} +export function unlockedConversationCurrent( + scope: UnlockedSession, + room: AdmittedConversation +): boolean { + return controllers.get(scope)?.contains(room) ?? false; +} diff --git a/web/src/lib/messaging/unread.ts b/web/src/lib/messaging/unread.ts @@ -0,0 +1,37 @@ +import { + messageMetadataSnapshot, + messageMetadataMessages, + type MessageMetadata +} from '../persistence/message-metadata.ts'; +import type { ConversationData } from './admit-conversation.ts'; +// Pure detached local display calculation. No authentication/effect permission; +// no signed timestamp or outer fetch receipt can imply a local read. +export function localUnreadRumors( + messages: readonly ConversationData[], + owner: string, + read: readonly string[] +): readonly string[] { + const seen = new Set(read); + return Array.from( + new Set( + messages + .filter( + (x) => + x.owner === owner && x.role === 'inbound' && !seen.has(x.rumorId) + ) + .map((x) => x.rumorId) + ) + ); +} +export async function readLocalUnread(scope: MessageMetadata) { + const metadata = await messageMetadataSnapshot(scope); + if (metadata.status !== 'ready') return { status: metadata.status }; + const view = messageMetadataMessages(scope); + if (view.status !== 'ready') return { status: view.status }; + const ids = localUnreadRumors( + view.messages, + metadata.owner, + metadata.readRumors + ); + return { status: 'ready' as const, count: ids.length, rumorIds: ids }; +} diff --git a/web/src/lib/persistence/message-metadata.ts b/web/src/lib/persistence/message-metadata.ts @@ -0,0 +1,570 @@ +import { exactLocalFields } from '../contracts/local-records.ts'; +import { newLocalId } from '../private-handles.ts'; +import { LOCAL_PERSISTENCE_BUDGETS } from '../config/budgets.ts'; +import { safeUnsignedInteger } from '../nostr/envelope-bounds.ts'; +import { + browserDatabaseState, + browserDatabaseTransaction, + type BrowserDatabase +} from './database.ts'; +import { + decodePrivateRecord, + privateRecordSnapshot, + privateRecordWire, + type ReceivedEnvelopeRecord +} from './private-records.ts'; +import { + decodeConversationMapping, + conversationMappingSnapshot +} from './records.ts'; +import { + privateSessionOwnership, + subscribePrivateSessionClose, + type PrivateSession +} from '../runtime/private-session.ts'; +import { + conversationSnapshot, + conversationOwnership, + conversationEnvelopeIdentity, + type AdmittedConversation +} from '../messaging/admit-conversation.ts'; +import { + unlockedSessionOwnership, + unlockedConversationCurrent, + readUnlockedMessages, + type UnlockedSession +} from '../messaging/unlocked-session.ts'; + +export const MESSAGE_METADATA_DISCLOSURE = + 'Read/unread is local. Ciphertext and minimal owner, peer, opaque conversation identifier, verified rumor read flag, routing and use times may persist in this browser. Someone with local access may learn peers and use times; this is not full-device encryption or backup. No private body, subject or product association is indexed. No remote Seen/Read or guaranteed notification is sent.'; +declare const metadataBrand: unique symbol; +export type MessageMetadata = Readonly<{ [metadataBrand]: true }>; +type Failure = + | 'invalid' + | 'stopped' + | 'busy' + | 'unavailable' + | 'aborted' + | 'unknown_completion' + | 'corrupt_record' + | 'capacity' + | 'conflict'; +type Pair = Readonly<{ + owner: string; + id: string; + peer: string; + wire: string; + bytes: number; +}>; +type Cipher = Readonly<{ + record: ReceivedEnvelopeRecord; + wire: string; + bytes: number; +}>; +type Rows = Readonly<{ received: readonly Cipher[]; pairs: readonly Pair[] }>; +type Result<T> = + Readonly<{ ok: true; value: T }> | Readonly<{ ok: false; reason: Failure }>; +type Scope = Readonly<{ + database: BrowserDatabase; + owner: string; + session: symbol; + unlocked: UnlockedSession; + current(): boolean; +}>; +type Snapshot = + | Readonly<{ + status: 'ready'; + owner: string; + readRumors: readonly string[]; + pairs: readonly Readonly<{ id: string; peer: string }>[]; + }> + | Readonly<{ status: Failure }>; +type Display = + | Readonly<{ + status: 'saved' | 'existing'; + conversationId: string; + rumorId: string; + }> + | Readonly<{ status: Failure }> + | Readonly<{ + status: 'unknown_completion'; + phase: 'readback'; + reason: Failure; + }>; +type Controller = { + snapshot(): Promise<Snapshot>; + display(room: AdmittedConversation, review: unknown): Promise<Display>; + messages(): ReturnType<typeof readUnlockedMessages>; + close(): void; +}; +const controllers = new WeakMap<MessageMetadata, Controller>(); +const failed = (reason: Failure): Result<never> => ({ ok: false, reason }); +function cipherRow( + value: unknown, + owner: string, + id: unknown +): Cipher | undefined { + if ( + !exactLocalFields(value, ['owner', 'id', 'wire']) || + value.owner !== owner || + value.id !== id || + typeof value.wire !== 'string' + ) + return; + const decoded = decodePrivateRecord(value.wire, owner, id); + if (!decoded.ok) return; + const record = privateRecordSnapshot(decoded.value, owner, id); + return record?.family === 'received_envelope' && + privateRecordWire(decoded.value, owner, id) === value.wire + ? { + record, + wire: value.wire, + bytes: new TextEncoder().encode(JSON.stringify(value)).length + } + : undefined; +} +function pairRow(value: unknown, owner: string, id: unknown): Pair | undefined { + if ( + !exactLocalFields(value, ['owner', 'id', 'wire']) || + value.owner !== owner || + value.id !== id || + typeof value.wire !== 'string' + ) + return; + const decoded = decodeConversationMapping(value.wire, owner, id); + if (!decoded.ok) return; + const row = conversationMappingSnapshot(decoded.value, owner, id); + return row + ? { + owner: row.owner, + id: row.id, + peer: row.peer, + wire: value.wire, + bytes: new TextEncoder().encode(JSON.stringify(value)).length + } + : undefined; +} +// Bounded owner-only strict scans. Existing schema/received quota unchanged; +// minimum pair mappings use the same conservative logical receive ceiling. +// No SDK/network await in any transaction; completion precedes readback credit. +function transaction<T>( + scope: Scope, + mode: 'readonly' | 'readwrite', + finish: ( + rows: Rows, + tx: IDBTransaction, + refuse: (reason: Failure) => void + ) => Result<T> | undefined +): Promise<Result<T>> { + let tx: IDBTransaction; + try { + if (!scope.current()) return Promise.resolve(failed('stopped')); + tx = browserDatabaseTransaction( + scope.database, + ['received_envelopes', 'conversations'], + mode + ); + } catch { + return Promise.resolve(failed('unavailable')); + } + return new Promise((resolve) => { + let result: Result<T> | undefined, + received: readonly Cipher[] = Array.from<Cipher>([]), + pairs: readonly Pair[] = Array.from<Pair>([]), + pending = 2, + receivedBytes = 0, + pairBytes = 0; + function refuse(reason: Failure) { + result = failed(reason); + try { + tx.abort(); + } catch { + result = failed('unknown_completion'); + } + } + tx.addEventListener('complete', () => + resolve(result ?? failed('unknown_completion')) + ); + tx.addEventListener('abort', () => + resolve( + result && !result.ok && result.reason !== 'unknown_completion' + ? result + : failed('aborted') + ) + ); + function done() { + pending--; + if (pending !== 0) return; + if (!scope.current()) { + refuse('stopped'); + return; + } + try { + const value = finish({ received, pairs }, tx, refuse); + if (value) result = value; + } catch { + refuse('aborted'); + } + } + for (const store of ['received_envelopes', 'conversations'] as const) { + try { + const request = tx + .objectStore(store) + .index('by_owner') + .openCursor(IDBKeyRange.only(scope.owner)); + request.addEventListener('success', () => { + try { + const cursor = request.result; + if (!cursor) { + done(); + return; + } + const key = cursor.primaryKey; + if ( + !Array.isArray(key) || + key.length !== 2 || + key[0] !== scope.owner + ) { + refuse('corrupt_record'); + return; + } + if (store === 'received_envelopes') { + const row = cipherRow(cursor.value, scope.owner, key[1]); + if (!row) { + refuse('corrupt_record'); + return; + } + received = received.concat(row); + receivedBytes += row.bytes; + if ( + received.length > LOCAL_PERSISTENCE_BUDGETS.receivedEnvelopes || + receivedBytes > + LOCAL_PERSISTENCE_BUDGETS.receivedCiphertextBytes + ) { + refuse('capacity'); + return; + } + } else { + const row = pairRow(cursor.value, scope.owner, key[1]); + if (!row || pairs.some((x) => x.peer === row.peer)) { + refuse('corrupt_record'); + return; + } + pairs = pairs.concat(row); + pairBytes += row.bytes; + if ( + pairs.length > LOCAL_PERSISTENCE_BUDGETS.receivedEnvelopes || + pairBytes > LOCAL_PERSISTENCE_BUDGETS.receivedCiphertextBytes + ) { + refuse('capacity'); + return; + } + } + cursor.continue(); + } catch { + refuse('aborted'); + } + }); + } catch { + refuse('aborted'); + } + } + }); +} +export function captureMessageMetadata( + database: BrowserDatabase, + session: PrivateSession, + unlocked: UnlockedSession, + review: unknown +): MessageMetadata | undefined { + if ( + typeof window === 'undefined' || + review !== 'reviewed_local_message_metadata' + ) + return; + const observation = privateSessionOwnership(session), + cacheObservation = unlockedSessionOwnership(unlocked); + if ( + !observation || + !cacheObservation || + observation.owner !== cacheObservation.owner || + observation.session !== cacheObservation.session || + !observation.current() || + !cacheObservation.current() + ) + return; + const observed = observation, + cache = cacheObservation; + const owner = observed.owner, + generation = observed.session; + try { + if (browserDatabaseState(database).state !== 'ready') return; + } catch { + return; + } + let closed = false, + off = () => {}; + const token = Object.freeze({}) as MessageMetadata; + function close() { + if (closed) return; + closed = true; + off(); + controllers.set(token, { + snapshot: () => Promise.resolve<Snapshot>({ status: 'stopped' }), + display: () => Promise.resolve<Display>({ status: 'stopped' }), + messages: () => ({ status: 'closed', messages: [] }), + close: () => {} + }); + } + const scope: Scope = { + database, + owner, + session: generation, + unlocked, + current: () => { + if (closed || !observed.current() || !cache.current()) { + close(); + return false; + } + try { + return browserDatabaseState(database).state === 'ready'; + } catch { + return false; + } + } + }; + async function snapshot(): Promise<Snapshot> { + if (!scope.current()) return { status: 'stopped' }; + const loaded = await transaction(scope, 'readonly', (rows) => ({ + ok: true, + value: { + status: 'ready' as const, + owner, + readRumors: Array.from( + new Set( + rows.received.flatMap((x) => + x.record.read ? [x.record.read.rumorHash] : [] + ) + ) + ), + pairs: rows.pairs.map((x) => ({ id: x.id, peer: x.peer })) + } + })); + return !scope.current() + ? { status: 'stopped' } + : loaded.ok + ? loaded.value + : { status: loaded.reason }; + } + async function display( + room: AdmittedConversation, + review: unknown + ): Promise<Display> { + if (!scope.current()) return { status: 'stopped' }; + if ( + review !== 'displayed_message' || + !unlockedConversationCurrent(unlocked, room) + ) + return { status: 'invalid' }; + const data = conversationSnapshot(room), + proof = conversationOwnership(room), + cipher = conversationEnvelopeIdentity(room); + if ( + !data || + !proof || + !cipher || + data.owner !== owner || + proof.owner !== owner || + proof.session !== generation || + cipher.owner !== owner + ) + return { status: 'invalid' }; + const current = () => + scope.current() && + proof.current() && + unlockedConversationCurrent(unlocked, room); + if (!current() || !navigator.locks?.request) + return { status: 'unavailable' }; + try { + return await navigator.locks.request( + 'harvestcircle:owner:' + owner, + { mode: 'exclusive', ifAvailable: true }, + async (lock): Promise<Display> => { + if (!lock) return { status: 'busy' }; + if (!current()) return { status: 'stopped' }; + const loaded = await transaction(scope, 'readonly', (rows) => ({ + ok: true, + value: rows + })); + if (!current()) return { status: 'stopped' }; + if (!loaded.ok) return { status: loaded.reason }; + const row = loaded.value.received.find( + (x) => x.record.id === cipher.outerId + ); + if (!row || row.record.outer !== cipher.outerWire) + return { status: 'conflict' }; + if (row.record.read && row.record.read.rumorHash !== data.rumorId) + return { status: 'conflict' }; + let pair = loaded.value.pairs.find((x) => x.peer === data.peer); + const existed = !!row.record.read && !!pair; + if (!pair) { + const id = newLocalId(); + if (!id) return { status: 'unavailable' }; + const wire = JSON.stringify({ + schema: 1, + family: 'conversation_handle', + owner, + id, + peer: data.peer + }); + pair = pairRow({ owner, id, wire }, owner, id); + if (!pair) return { status: 'invalid' }; + } + const selected = pair; + let nextWire = row.wire; + if (!row.record.read) { + const now = Date.now(); + if ( + safeUnsignedInteger(now) === undefined || + row.record.revision >= Number.MAX_SAFE_INTEGER + ) + return { status: 'invalid' }; + nextWire = JSON.stringify({ + ...row.record, + revision: row.record.revision + 1, + read: { rumorHash: data.rumorId, atMilliseconds: now } + }); + if ( + !cipherRow( + { owner, id: row.record.id, wire: nextWire }, + owner, + row.record.id + ) + ) + return { status: 'invalid' }; + } + const written = await transaction( + scope, + 'readwrite', + (rows, tx, refuse) => { + if (!current()) { + refuse('stopped'); + return; + } + const latest = rows.received.find( + (x) => x.record.id === cipher.outerId + ), + existing = rows.pairs.find((x) => x.peer === data.peer); + if ( + latest?.wire !== row.wire || + (existing?.wire ?? null) !== + (loaded.value.pairs.find((x) => x.peer === data.peer)?.wire ?? + null) || + rows.pairs.some( + (x) => x.id === selected.id && x.wire !== selected.wire + ) + ) { + refuse('conflict'); + return; + } + const nextBytes = new TextEncoder().encode( + JSON.stringify({ owner, id: cipher.outerId, wire: nextWire }) + ).length; + if ( + rows.received.reduce((n, x) => n + x.bytes, 0) - + row.bytes + + nextBytes > + LOCAL_PERSISTENCE_BUDGETS.receivedCiphertextBytes || + (!existing && + (rows.pairs.length >= + LOCAL_PERSISTENCE_BUDGETS.receivedEnvelopes || + rows.pairs.reduce((n, x) => n + x.bytes, selected.bytes) > + LOCAL_PERSISTENCE_BUDGETS.receivedCiphertextBytes)) + ) { + refuse('capacity'); + return; + } + if (nextWire !== row.wire) + tx.objectStore('received_envelopes').put({ + owner, + id: cipher.outerId, + wire: nextWire + }); + if (!existing) + tx.objectStore('conversations').put({ + owner, + id: selected.id, + wire: selected.wire + }); + return { ok: true, value: true }; + } + ); + if (!current()) return { status: 'stopped' }; + if (!written.ok) return { status: written.reason }; + const readback = await transaction(scope, 'readonly', (rows) => ({ + ok: true, + value: rows + })); + if (!current()) return { status: 'stopped' }; + if (!readback.ok) + return { + status: 'unknown_completion', + phase: 'readback', + reason: readback.reason + }; + if ( + readback.value.received.find((x) => x.record.id === cipher.outerId) + ?.wire !== nextWire || + readback.value.pairs.find((x) => x.id === selected.id)?.wire !== + selected.wire + ) + return { status: 'conflict' }; + return { + status: existed ? 'existing' : 'saved', + conversationId: selected.id, + rumorId: data.rumorId + }; + } + ); + } catch { + return { status: current() ? 'unknown_completion' : 'stopped' }; + } + } + controllers.set(token, { + snapshot, + display, + messages: () => + scope.current() + ? readUnlockedMessages(unlocked) + : { status: 'closed', messages: [] }, + close + }); + off = subscribePrivateSessionClose(session, close); + return scope.current() ? token : undefined; +} +export function messageMetadataSnapshot( + scope: MessageMetadata +): Promise<Snapshot> { + return ( + controllers.get(scope)?.snapshot() ?? Promise.resolve({ status: 'invalid' }) + ); +} +// Detached projection for local count calculation only, never persistence proof. +export function messageMetadataMessages(scope: MessageMetadata) { + return ( + controllers.get(scope)?.messages() ?? { + status: 'rejected' as const, + messages: [] + } + ); +} +export function markDisplayedMessage( + scope: MessageMetadata, + room: AdmittedConversation, + review: unknown +): Promise<Display> { + return ( + controllers.get(scope)?.display(room, review) ?? + Promise.resolve({ status: 'invalid' }) + ); +} diff --git a/web/tests/e2e/harness/message-metadata.ts b/web/tests/e2e/harness/message-metadata.ts @@ -0,0 +1,611 @@ +import { + captureMessageMetadata, + messageMetadataSnapshot, + markDisplayedMessage, + type MessageMetadata, + MESSAGE_METADATA_DISCLOSURE +} from '../../../src/lib/persistence/message-metadata.ts'; +import { readLocalUnread } from '../../../src/lib/messaging/unread.ts'; +import { + openBrowserDatabase, + closeBrowserDatabase, + browserDatabaseTransaction, + type BrowserDatabase +} from '../../../src/lib/persistence/database.ts'; +import { + captureUnlockedSession, + acceptUnlockedConversation, + readUnlockedMessages, + unlockedSessionSnapshot, + closeUnlockedSession, + type UnlockedSession +} from '../../../src/lib/messaging/unlocked-session.ts'; +import { + getPrivateCacheScope, + retainPrivateCacheWire, + clearPrivateCacheScope, + privateCacheSnapshot, + type PrivateCacheScope +} from '../../../src/lib/nostr/private-cache-scope.ts'; +import { + createIdentitySession, + connectIdentity, + probeIdentityMessaging, + disconnectIdentity, + recheckIdentityOwner +} from '../../../src/lib/runtime/identity-session.ts'; +import { + getPublicKey, + getEventHash, + finalizeEvent, + type UnsignedEvent +} from 'applesauce-core/helpers'; +import { nip44 } from 'applesauce-core/helpers/encryption'; +import { makeFixture as makeRecoveryFixture } from './resume-preparation.ts'; +import { + createPrivateSession, + closePrivateSession +} from '../../../src/lib/runtime/private-session.ts'; +import { + admitInboxEnvelope, + retainInboxEnvelope +} from '../../../src/lib/persistence/inbox-envelope-repository.ts'; +import { + captureReceivedUnwrap, + unwrapReceivedEnvelope, + stopReceivedUnwrap, + type ReceivedUnwrap, + type ReceivedNestedEnvelope +} from '../../../src/lib/nostr/unwrap-admission.ts'; +import { + admitReceivedConversation, + conversationSnapshot, + type AdmittedConversation +} from '../../../src/lib/messaging/admit-conversation.ts'; +type Scenario = + | 'inbound' + | 'self_archive' + | 'third_party' + | 'hostile_text' + | 'missing_parent'; +export async function makeFixture( + scenario: Scenario = 'inbound', + initialise = true +) { + const f = await makeRecoveryFixture(initialise), + privateSession = await createPrivateSession( + f.identity, + 'reviewed_private_session' + ); + if (!privateSession) throw Error('missing genuine private session'); + const ownerSecret = new Uint8Array(32).fill(83), + peerSecret = new Uint8Array(32).fill(84), + outerSecret = new Uint8Array(32).fill(85), + other = getPublicKey(outerSecret); + const senderSecret = scenario === 'self_archive' ? ownerSecret : peerSecret, + sender = getPublicKey(senderSecret), + recipient = + scenario === 'self_archive' + ? f.peer + : scenario === 'third_party' + ? other + : f.owner; + const tags: string[][] = [['p', recipient]]; + if (scenario === 'hostile_text') tags.push(['subject', other]); + if (scenario === 'missing_parent') + tags.push(['e', 'a'.repeat(64), 'wss://untrusted.example.org']); + const template: UnsignedEvent = { + pubkey: sender, + kind: 14, + created_at: 1700000000, + tags, + content: + scenario === 'hostile_text' + ? `Contact ${other} https://untrusted.example.org` + : 'Actual encrypted room fixture' + }, + rumor = { id: getEventHash(template), ...template }; + function encrypt(key: Uint8Array, target: string, plain: string) { + const conversation = nip44.v2.utils.getConversationKey(key, target); + try { + return nip44.v2.encrypt(plain, conversation); + } finally { + conversation.fill(0); + } + } + const seal = finalizeEvent( + { + kind: 13, + created_at: 1699999900, + tags: [], + content: encrypt(senderSecret, f.owner, JSON.stringify(rumor)) + }, + senderSecret + ); + const outer = finalizeEvent( + { + kind: 1059, + created_at: 1699999800, + tags: [['p', f.owner]], + content: encrypt(outerSecret, f.owner, JSON.stringify(seal)) + }, + outerSecret + ); + ownerSecret.fill(0); + peerSecret.fill(0); + outerSecret.fill(0); + const admitted = admitInboxEnvelope( + JSON.stringify(outer), + f.owner, + 'wss://archive.example.org', + 100 + ); + if (!admitted) throw Error('missing signed addressed outer'); + const saved = await retainInboxEnvelope( + f.repository, + privateSession, + admitted + ); + if (saved.status !== 'retained') throw Error('no actual retained cipher'); + let reader: ReceivedUnwrap | undefined, + nested: ReceivedNestedEnvelope | undefined, + room: AdmittedConversation | undefined; + let unlocked: UnlockedSession | undefined; + let rawCache: PrivateCacheScope | undefined; + let database: BrowserDatabase | undefined, + metadata: MessageMetadata | undefined; + let otherPrivateSession: Awaited<ReturnType<typeof createPrivateSession>>; + let otherIdentity: ReturnType<typeof createIdentitySession> | undefined; + return { + ...f, + other, + rumorId: rumor.id, + async unlock() { + reader = captureReceivedUnwrap( + f.repository, + f.identity, + outer.id, + 'reviewed_inbox_unlock' + ); + if (!reader) return 'invalid'; + const result = await unwrapReceivedEnvelope(reader); + if (result.status === 'authenticated') nested = result.envelope; + return result.status; + }, + admit(role: unknown) { + room = nested && admitReceivedConversation(nested, role); + return room && conversationSnapshot(room); + }, + snapshot() { + return room && conversationSnapshot(room); + }, + forged() { + return admitReceivedConversation({} as ReceivedNestedEnvelope, 'inbound'); + }, + copied() { + return room && conversationSnapshot({ ...room }); + }, + captureCache(review: unknown = 'reviewed_messages_unlock') { + unlocked = captureUnlockedSession(privateSession, review); + if (unlocked) + rawCache = getPrivateCacheScope(privateSession, 'projection_ownership'); + return !!unlocked; + }, + cache() { + return unlocked && room + ? acceptUnlockedConversation(unlocked, room) + : 'rejected'; + }, + messages() { + return unlocked && readUnlockedMessages(unlocked); + }, + cacheSnapshot() { + return unlocked && unlockedSessionSnapshot(unlocked); + }, + rawCacheSnapshot() { + return rawCache && privateCacheSnapshot(rawCache); + }, + forgedCache() { + return ( + unlocked && + acceptUnlockedConversation(unlocked, {} as AdmittedConversation) + ); + }, + copiedCache() { + return ( + unlocked && room && acceptUnlockedConversation(unlocked, { ...room }) + ); + }, + closeCache() { + if (unlocked) closeUnlockedSession(unlocked); + }, + closePrivate() { + closePrivateSession(privateSession); + }, + async changedOwner() { + f.mode('changed_key'); + return await recheckIdentityOwner(f.identity); + }, + async otherGeneration() { + otherIdentity = createIdentitySession(); + await connectIdentity(otherIdentity); + await probeIdentityMessaging(otherIdentity, 'reviewed_self_copy'); + otherPrivateSession = await createPrivateSession( + otherIdentity, + 'reviewed_private_session' + ); + if (!otherPrivateSession) + throw Error('missing other genuine private session'); + const scope = captureUnlockedSession( + otherPrivateSession, + 'reviewed_messages_unlock' + ); + if (!scope || !room) throw Error('missing genuine scope/room'); + return { + accepted: acceptUnlockedConversation(scope, room), + snapshot: unlockedSessionSnapshot(scope) + }; + }, + quota() { + const scope = getPrivateCacheScope( + privateSession, + 'projection_ownership' + ); + if (!scope) throw Error('missing actual scoped cache'); + for (let i = 0; i < 2000; i++) { + const result = retainPrivateCacheWire( + scope, + i.toString(16).padStart(64, '0'), + '{}' + ); + if (result !== 'accepted') + throw Error('unexpected quota fixture result ' + result); + } + return 2000; + }, + corruptCachedWire() { + const scope = getPrivateCacheScope( + privateSession, + 'projection_ownership' + ); + if (!scope || !room) throw Error('missing actual cache'); + const snapshot = conversationSnapshot(room); + if (!snapshot) throw Error('no current room'); + clearPrivateCacheScope(scope); + return retainPrivateCacheWire( + scope, + snapshot.rumorId, + JSON.stringify({ + ...snapshot, + peer: other, + content: 'HOSTILE_CACHE_POISON' + }) + ); + }, + async captureMetadata(review: unknown = 'reviewed_local_message_metadata') { + if (!database) { + const opened = await openBrowserDatabase(); + if (opened.state !== 'ready') + throw Error('actual metadata database unavailable'); + database = opened.owner; + } + if (!unlocked) return false; + metadata = captureMessageMetadata( + database, + privateSession, + unlocked, + review + ); + return !!metadata; + }, + async unread() { + return metadata && (await readLocalUnread(metadata)); + }, + async metadataSnapshot() { + return metadata && (await messageMetadataSnapshot(metadata)); + }, + async display(review: unknown = 'displayed_message') { + return metadata && room + ? await markDisplayedMessage(metadata, room, review) + : { status: 'invalid' }; + }, + async forgedDisplay() { + return metadata + ? await markDisplayedMessage( + metadata, + {} as AdmittedConversation, + 'displayed_message' + ) + : { status: 'invalid' }; + }, + async copiedDisplay() { + return metadata && room + ? await markDisplayedMessage(metadata, { ...room }, 'displayed_message') + : { status: 'invalid' }; + }, + disclosure() { + return MESSAGE_METADATA_DISCLOSURE; + }, + async rawMetadata() { + if (!database) throw Error('no actual database'); + const tx = browserDatabaseTransaction( + database, + ['received_envelopes', 'conversations'], + 'readonly' + ); + const received = tx.objectStore('received_envelopes').getAll(), + pairs = tx.objectStore('conversations').getAll(); + return await new Promise<{ received: unknown[]; pairs: unknown[] }>( + (resolve, reject) => { + tx.addEventListener('complete', () => + resolve({ received: received.result, pairs: pairs.result }) + ); + tx.addEventListener('abort', () => + reject(Error('actual raw scan aborted')) + ); + } + ); + }, + async corruptPair() { + if (!database) throw Error('no actual database'); + const tx = browserDatabaseTransaction( + database, + ['conversations'], + 'readwrite' + ); + tx.objectStore('conversations').put({ + owner: f.owner, + id: '12345678-1234-4234-8234-123456789abd', + wire: JSON.stringify({ + schema: 1, + family: 'conversation_handle', + owner: f.owner, + id: '12345678-1234-4234-8234-123456789abd', + peer: f.peer, + subject: 'FORBIDDEN_CONTEXT' + }) + }); + await new Promise<void>((resolve, reject) => { + tx.addEventListener('complete', () => resolve()); + tx.addEventListener('abort', () => + reject(Error('corruption fixture aborted')) + ); + }); + }, + abortNextWrite() { + const original = Object.getOwnPropertyDescriptor( + IDBObjectStore.prototype, + 'put' + )?.value as IDBObjectStore['put']; + let consumed = false; + IDBObjectStore.prototype.put = function ( + ...args: Parameters<typeof original> + ) { + const request = original.apply(this, args); + if (this.name === 'received_envelopes' && !consumed) { + consumed = true; + this.transaction.abort(); + } + return request; + }; + return () => { + IDBObjectStore.prototype.put = original; + }; + }, + async otherOwnerMetadata() { + f.mode('changed_key'); + otherIdentity = createIdentitySession(); + await connectIdentity(otherIdentity); + await probeIdentityMessaging(otherIdentity, 'reviewed_self_copy'); + otherPrivateSession = await createPrivateSession( + otherIdentity, + 'reviewed_private_session' + ); + if (!database || !otherPrivateSession) + throw Error('no genuine other owner'); + const scope = captureUnlockedSession( + otherPrivateSession, + 'reviewed_messages_unlock' + ); + if (!scope) throw Error('no genuine other cache'); + const m = captureMessageMetadata( + database, + otherPrivateSession, + scope, + 'reviewed_local_message_metadata' + ); + if (!m) throw Error('no genuine other metadata'); + return await messageMetadataSnapshot(m); + }, + async wrongGenerationMetadata() { + otherIdentity = createIdentitySession(); + await connectIdentity(otherIdentity); + await probeIdentityMessaging(otherIdentity, 'reviewed_self_copy'); + otherPrivateSession = await createPrivateSession( + otherIdentity, + 'reviewed_private_session' + ); + if (!database || !otherPrivateSession || !unlocked) + throw Error('no genuine generation test'); + return !!captureMessageMetadata( + database, + otherPrivateSession, + unlocked, + 'reviewed_local_message_metadata' + ); + }, + async queuedLogout() { + if (!metadata || !room) throw Error('no genuine current metadata/room'); + let release!: () => void, held!: () => void; + const ready = new Promise<void>((r) => { + held = r; + }); + const blocker = navigator.locks.request( + 'harvestcircle:owner:' + f.owner, + async () => { + held(); + await new Promise<void>((r) => { + release = r; + }); + } + ); + await ready; + const pending = markDisplayedMessage(metadata, room, 'displayed_message'); + f.disconnect(); + release(); + await blocker; + return await pending; + }, + failNextReadback() { + const original = Object.getOwnPropertyDescriptor( + IDBIndex.prototype, + 'openCursor' + )?.value as IDBIndex['openCursor']; + let reads = 0; + IDBIndex.prototype.openCursor = function ( + ...args: Parameters<typeof original> + ) { + if ( + this.objectStore.name === 'received_envelopes' && + this.objectStore.transaction.mode === 'readonly' && + ++reads === 2 + ) + throw new DOMException('actual readback failure', 'AbortError'); + return original.apply(this, args); + }; + return () => { + IDBIndex.prototype.openCursor = original; + }; + }, + async raceNextWrite() { + if (!database) throw Error('no database'); + const rows = await this.rawMetadata(), + raw = ( + rows.received as { owner: string; id: string; wire: string }[] + ).find((x) => x.owner === f.owner); + if (!raw) throw Error('missing received race row'); + const record = JSON.parse(raw.wire) as { + revision: number; + sources: string[]; + }; + const wire = JSON.stringify({ + ...record, + revision: record.revision + 1, + sources: [...record.sources, 'wss://race.example.org'] + }); + const original = Object.getOwnPropertyDescriptor( + IDBDatabase.prototype, + 'transaction' + )?.value as IDBDatabase['transaction']; + let injected = false; + IDBDatabase.prototype.transaction = function ( + ...args: Parameters<typeof original> + ) { + const stores = args[0], + mode = args[1]; + if ( + !injected && + mode === 'readwrite' && + Array.isArray(stores) && + stores.includes('received_envelopes') + ) { + injected = true; + const rival = original.call( + this, + ['received_envelopes'], + 'readwrite' + ); + rival.objectStore('received_envelopes').put({ ...raw, wire }); + } + return original.apply(this, args); + }; + return () => { + IDBDatabase.prototype.transaction = original; + }; + }, + async anotherWrap(lateOld = false) { + const selectedTemplate = { + ...template, + created_at: 1, + content: 'Late old actual encrypted rumor' + }, + selectedRumor = lateOld + ? { id: getEventHash(selectedTemplate), ...selectedTemplate } + : rumor; + let selectedSeal = seal; + if (lateOld) { + const peer = new Uint8Array(32).fill(84); + try { + selectedSeal = finalizeEvent( + { + kind: 13, + created_at: 1, + tags: [], + content: encrypt(peer, f.owner, JSON.stringify(selectedRumor)) + }, + peer + ); + } finally { + peer.fill(0); + } + } + + const key = new Uint8Array(32).fill(86); + let next; + try { + next = finalizeEvent( + { + kind: 1059, + created_at: 1699999799, + tags: [['p', f.owner]], + content: encrypt(key, f.owner, JSON.stringify(selectedSeal)) + }, + key + ); + } finally { + key.fill(0); + } + const candidate = admitInboxEnvelope( + JSON.stringify(next), + f.owner, + 'wss://archive.example.org', + 101 + ); + if (!candidate) throw Error('no second outer'); + const result = await retainInboxEnvelope( + f.repository, + privateSession, + candidate + ); + if (result.status !== 'retained') throw Error('no second retained outer'); + reader = captureReceivedUnwrap( + f.repository, + f.identity, + next.id, + 'reviewed_inbox_unlock' + ); + if (!reader) throw Error('no genuine second reader'); + const opened = await unwrapReceivedEnvelope(reader); + if (opened.status !== 'authenticated') + throw Error('no actual second decrypt'); + nested = opened.envelope; + room = admitReceivedConversation( + nested, + scenario === 'self_archive' ? 'self_archive' : 'inbound' + ); + return { outerId: next.id, rumorId: selectedRumor.id }; + }, + stop() { + if (reader) stopReceivedUnwrap(reader); + }, + close() { + if (database) closeBrowserDatabase(database); + if (unlocked) closeUnlockedSession(unlocked); + if (otherPrivateSession) closePrivateSession(otherPrivateSession); + if (otherIdentity) disconnectIdentity(otherIdentity); + if (reader) stopReceivedUnwrap(reader); + closePrivateSession(privateSession); + f.close(); + } + }; +} diff --git a/web/tests/e2e/message-metadata.spec.ts b/web/tests/e2e/message-metadata.spec.ts @@ -0,0 +1,394 @@ +import { test, expect } from '@playwright/test'; +import { build } from 'vite'; +import { fileURLToPath } from 'node:url'; +import { createStaticHarness } from '../integration/harness/static.ts'; +import type * as Fixture from './harness/message-metadata.ts'; +declare global { + interface Window { + hcp094: typeof Fixture; + hcp094Fixture: Awaited<ReturnType<typeof Fixture.makeFixture>>; + } +} +let server: Awaited<ReturnType<typeof createStaticHarness>>, bundle: string; +test.beforeAll(async () => { + server = await createStaticHarness(); + const result = await build({ + configFile: false, + logLevel: 'silent', + build: { + write: false, + minify: false, + lib: { + entry: fileURLToPath( + new URL('./harness/message-metadata.ts', import.meta.url) + ), + name: 'hcp094', + formats: ['iife'] + } + } + }); + const output = Array.isArray(result) ? result[0] : result; + if (!('output' in output)) throw Error('bundle missing'); + const chunks = output.output.filter((x) => x.type === 'chunk'); + expect(chunks).toHaveLength(1); + bundle = chunks[0].code; +}); +test.afterAll(async () => { + await server.close(); +}); +test.beforeEach(async ({ page }) => { + await page.goto(server.url + '/search'); + await page.addScriptTag({ content: bundle }); + await page.evaluate(async () => { + window.hcp094Fixture = await window.hcp094.makeFixture(); + }); +}); +test.afterEach(async ({ page }) => { + if (!page.isClosed()) + await page.evaluate(() => window.hcp094Fixture?.close()); +}); +async function ready(page: import('@playwright/test').Page, cache = true) { + return await page.evaluate(async (cache) => { + const f = window.hcp094Fixture; + await f.unlock(); + f.admit('inbound'); + f.captureCache(); + if (cache) f.cache(); + return await f.captureMetadata(); + }, cache); +} +test('metadata requires reviewed owner-generation scope without signing or persistence on capture', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = window.hcp094Fixture; + f.captureCache(); + const before = f.counts(); + const rejected = await f.captureMetadata('unreviewed'); + return { rejected, before, after: f.counts() }; + }); + expect(r.rejected).toBe(false); + expect(r.after).toEqual(r.before); +}); +test('unlock and fetch never mark a verified old rumor read', async ({ + page +}) => { + expect(await ready(page)).toBe(true); + const r = await page.evaluate(async () => { + const f = window.hcp094Fixture; + return { unread: await f.unread(), raw: await f.rawMetadata() }; + }); + expect(r.unread).toMatchObject({ status: 'ready', count: 1 }); + expect(r.raw.pairs).toEqual([]); + const rows = r.raw.received as { wire: string }[]; + expect( + rows.map((x) => (JSON.parse(x.wire) as { read: unknown }).read) + ).toEqual([null]); +}); +test('two actual encrypted wraps of one rumor retain exactly one local unread', async ({ + page +}) => { + await ready(page); + const r = await page.evaluate(async () => { + const f = window.hcp094Fixture; + await f.anotherWrap(); + f.cache(); + return { unread: await f.unread(), raw: await f.rawMetadata() }; + }); + expect(r.unread).toMatchObject({ status: 'ready', count: 1 }); + expect(r.raw.received).toHaveLength(2); +}); +test('only explicit displayed action persists minimum read and opaque pair fields without more SDK calls', async ({ + page +}) => { + await ready(page); + const r = await page.evaluate(async () => { + const f = window.hcp094Fixture; + const before = f.counts(); + return { + save: await f.display(), + unread: await f.unread(), + raw: await f.rawMetadata(), + before, + after: f.counts(), + id: f.rumorId, + owner: f.owner, + peer: f.peer + }; + }); + expect(r.save.status).toBe('saved'); + expect(r.unread).toMatchObject({ status: 'ready', count: 0 }); + expect(r.after).toEqual(r.before); + const received = JSON.parse( + (r.raw.received as { wire: string }[])[0].wire + ) as { read: { rumorHash: string; atMilliseconds: number } }; + expect(received.read.rumorHash).toBe(r.id); + expect(Object.keys(received.read).sort()).toEqual([ + 'atMilliseconds', + 'rumorHash' + ]); + expect(received.read.atMilliseconds).toBeGreaterThan(1700000000000); + const pair = JSON.parse((r.raw.pairs as { wire: string }[])[0].wire) as { + id: string; + owner: string; + peer: string; + family: string; + schema: number; + }; + expect(Object.keys(pair).sort()).toEqual([ + 'family', + 'id', + 'owner', + 'peer', + 'schema' + ]); + expect(pair).toMatchObject({ + owner: r.owner, + peer: r.peer, + family: 'conversation_handle', + schema: 1 + }); + expect(pair.id).toMatch(/^[0-9a-f-]{36}$/); + expect(JSON.stringify(r.raw)).not.toContain('Actual encrypted room fixture'); +}); +test('read fact suppresses later different wrap of same actual rumor', async ({ + page +}) => { + await ready(page); + const r = await page.evaluate(async () => { + const f = window.hcp094Fixture; + await f.display(); + await f.anotherWrap(); + f.cache(); + return { + unread: await f.unread(), + save: await f.display(), + raw: await f.rawMetadata() + }; + }); + expect(r.unread).toMatchObject({ status: 'ready', count: 0 }); + expect(r.save.status).toBe('saved'); + expect(r.raw.pairs).toHaveLength(1); +}); +test('repeating explicit display reuses exact mapping and immutable first read time', async ({ + page +}) => { + await ready(page); + const r = await page.evaluate(async () => { + const f = window.hcp094Fixture; + const first = await f.display(), + before = await f.rawMetadata(), + second = await f.display(), + after = await f.rawMetadata(); + return { first, second, before, after }; + }); + expect(r.first.status).toBe('saved'); + expect(r.second.status).toBe('existing'); + expect(r.after).toEqual(r.before); +}); +test('unreviewed display refuses read and mapping writes', async ({ page }) => { + await ready(page); + const r = await page.evaluate(async () => { + const f = window.hcp094Fixture; + return { + save: await f.display('fetched_message'), + unread: await f.unread(), + raw: await f.rawMetadata() + }; + }); + expect(r.save.status).toBe('invalid'); + expect(r.unread).toMatchObject({ count: 1 }); + expect(r.raw.pairs).toEqual([]); +}); +test('forged and copied room custody cannot persist a local read', async ({ + page +}) => { + await ready(page); + const r = await page.evaluate(async () => { + const f = window.hcp094Fixture; + return { + fake: await f.forgedDisplay(), + copy: await f.copiedDisplay(), + raw: await f.rawMetadata() + }; + }); + expect(r.fake.status).toBe('invalid'); + expect(r.copy.status).toBe('invalid'); + expect(r.raw.pairs).toEqual([]); +}); +test('authenticated room outside the accepted unlocked projection cannot mark read', async ({ + page +}) => { + await ready(page, false); + const r = await page.evaluate(() => window.hcp094Fixture.display()); + expect(r.status).toBe('invalid'); +}); +test('other actual owner has no prior read or mapping state', async ({ + page +}) => { + await ready(page); + const r = await page.evaluate(async () => { + const f = window.hcp094Fixture; + await f.display(); + return await f.otherOwnerMetadata(); + }); + expect(r).toMatchObject({ status: 'ready', readRumors: [], pairs: [] }); +}); +test('same owner different actual generation cannot capture original cache metadata authority', async ({ + page +}) => { + await ready(page); + expect( + await page.evaluate(() => window.hcp094Fixture.wrongGenerationMetadata()) + ).toBe(false); +}); +test('actual IndexedDB put abort grants no read or mapping credit and preserves unread', async ({ + page +}) => { + await ready(page); + const r = await page.evaluate(async () => { + const f = window.hcp094Fixture; + const restore = f.abortNextWrite(); + let save; + try { + save = await f.display(); + } finally { + restore(); + } + return { save, unread: await f.unread(), raw: await f.rawMetadata() }; + }); + expect(r.save.status).toBe('aborted'); + expect(r.unread).toMatchObject({ count: 1 }); + expect(r.raw.pairs).toEqual([]); +}); +test('logout while owner lock is unavailable admits no late metadata write', async ({ + page +}) => { + await ready(page); + const r = await page.evaluate(async () => { + const f = window.hcp094Fixture; + return { save: await f.queuedLogout(), raw: await f.rawMetadata() }; + }); + expect(['busy', 'stopped']).toContain(r.save.status); + expect(r.raw.pairs).toEqual([]); +}); +test('unknown pair field fails closed without clearing corrupt or ciphertext evidence', async ({ + page +}) => { + await ready(page); + const r = await page.evaluate(async () => { + const f = window.hcp094Fixture; + await f.corruptPair(); + const before = await f.rawMetadata(); + return { + save: await f.display(), + snapshot: await f.metadataSnapshot(), + before, + after: await f.rawMetadata() + }; + }); + expect(r.save.status).toBe('corrupt_record'); + expect(r.snapshot?.status).toBe('corrupt_record'); + expect(r.after).toEqual(r.before); +}); +test('disclosure accurately names local peer and use-time exposure without encrypted-device or remote-read claims', async ({ + page +}) => { + const text = await page.evaluate(() => window.hcp094Fixture.disclosure()); + expect(text).toContain('peers'); + expect(text).toContain('use times'); + expect(text).toContain('local'); + expect(text).toContain('not full-device encryption'); + expect(text).toContain('No remote Seen/Read'); +}); + +test('actual reload preserves local read across a newly encrypted wrap of the same verified rumor', async ({ + page +}) => { + await ready(page); + expect( + (await page.evaluate(() => window.hcp094Fixture.display())).status + ).toBe('saved'); + await page.evaluate(() => window.hcp094Fixture.close()); + await page.reload(); + await page.addScriptTag({ content: bundle }); + await page.evaluate(async () => { + window.hcp094Fixture = await window.hcp094.makeFixture('inbound', false); + }); + await ready(page); + expect( + await page.evaluate(() => window.hcp094Fixture.unread()) + ).toMatchObject({ status: 'ready', count: 0 }); +}); +test('a genuinely decrypted delayed old rumor remains new locally after another rumor was read', async ({ + page +}) => { + await ready(page); + const r = await page.evaluate(async () => { + const f = window.hcp094Fixture; + await f.display(); + const next = await f.anotherWrap(true), + admit = f.cache(); + return { next, admit, unread: await f.unread(), original: f.rumorId }; + }); + expect(r.admit).toBe('added'); + expect(r.next.rumorId).not.toBe(r.original); + expect(r.unread).toMatchObject({ + status: 'ready', + count: 1, + rumorIds: [r.next.rumorId] + }); +}); +test('actual postcommit readback failure reports uncertainty rather than saved credit', async ({ + page +}) => { + await ready(page); + const r = await page.evaluate(async () => { + const f = window.hcp094Fixture, + restore = f.failNextReadback(); + let save; + try { + save = await f.display(); + } finally { + restore(); + } + return { save, raw: await f.rawMetadata() }; + }); + expect(r.save).toMatchObject({ + status: 'unknown_completion', + phase: 'readback', + reason: 'aborted' + }); + expect( + ( + JSON.parse((r.raw.received as { wire: string }[])[0].wire) as { + read: unknown; + } + ).read + ).not.toBeNull(); + expect(r.raw.pairs).toHaveLength(1); +}); +test('actual rival metadata transaction defeats stale whole-wire CAS without overwriting its evidence', async ({ + page +}) => { + await ready(page); + const r = await page.evaluate(async () => { + const f = window.hcp094Fixture, + restore = await f.raceNextWrite(); + let save; + try { + save = await f.display(); + } finally { + restore(); + } + return { save, raw: await f.rawMetadata() }; + }); + expect(r.save.status).toBe('conflict'); + const row = JSON.parse((r.raw.received as { wire: string }[])[0].wire) as { + read: unknown; + sources: string[]; + }; + expect(row.read).toBeNull(); + expect(row.sources).toContain('wss://race.example.org'); + expect(r.raw.pairs).toEqual([]); +}); diff --git a/web/tests/unit/message-metadata.test.ts b/web/tests/unit/message-metadata.test.ts @@ -0,0 +1,61 @@ +import { test, expect } from 'vitest'; +import { localUnreadRumors } from '../../src/lib/messaging/unread.ts'; +import type { ConversationData } from '../../src/lib/messaging/admit-conversation.ts'; +const owner = 'a'.repeat(64), + peer = 'b'.repeat(64); +const message = (id: string, time = 1700000000): ConversationData => ({ + owner, + peer, + sender: peer, + recipient: owner, + role: 'inbound', + rumorId: id, + createdAt: time, + content: 'Private test only', + subject: null, + replyTo: null +}); +test('different envelopes of one verified rumor count once locally', () => + expect( + localUnreadRumors( + [message('1'.repeat(64)), message('1'.repeat(64))], + owner, + [] + ) + ).toEqual(['1'.repeat(64)])); +test('late old signed time is still locally unread', () => + expect(localUnreadRumors([message('1'.repeat(64), 1)], owner, [])).toEqual([ + '1'.repeat(64) + ])); +test('read flag suppresses all repetitions independent of signed order', () => + expect( + localUnreadRumors( + [message('1'.repeat(64), 200), message('1'.repeat(64), 1)], + owner, + ['1'.repeat(64)] + ) + ).toEqual([])); +test('owner isolation does not adopt another local namespace', () => + expect(localUnreadRumors([message('1'.repeat(64))], peer, [])).toEqual([])); +test('own archive is not an incoming unread notification', () => + expect( + localUnreadRumors( + [ + { + ...message('1'.repeat(64)), + sender: owner, + recipient: peer, + role: 'self_archive' + } + ], + owner, + [] + ) + ).toEqual([])); +test('reordering never changes the unique locally unread set', () => { + const a = message('1'.repeat(64), 300), + b = message('2'.repeat(64), 1); + expect(new Set(localUnreadRumors([a, b, a], owner, []))).toEqual( + new Set(localUnreadRumors([b, a, b], owner, [])) + ); +});