app

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

commit 24f5c12471695a8d759afdce764f594f2042717d
parent a83bb81ef99647ad5a2483da126ef311e0353402
Author: triesap <tyson@radroots.org>
Date:   Fri,  9 Oct 2026 06:28:37 +0000

messages: scope unlocked projections and deduplication to the active identity (HCP-093)

Diffstat:
Mweb/src/lib/messaging/admit-conversation.ts | 8++++++++
Aweb/src/lib/messaging/unlocked-session.ts | 172+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/src/lib/nostr/unwrap-admission.ts | 20+++++++++++++++++++-
Aweb/tests/e2e/harness/unlocked-session.ts | 324+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/unlocked-session.spec.ts | 293+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5 files changed, 816 insertions(+), 1 deletion(-)

diff --git a/web/src/lib/messaging/admit-conversation.ts b/web/src/lib/messaging/admit-conversation.ts @@ -9,6 +9,7 @@ import { import { safeUnsignedInteger } from '../nostr/envelope-bounds.ts'; import { receivedNestedEnvelopeSnapshot, + receivedNestedEnvelopeOwnership, type ReceivedNestedEnvelope } from '../nostr/unwrap-admission.ts'; @@ -128,3 +129,10 @@ export function conversationSnapshot( ? inspectConversationData(nested.rumorWire, nested.owner, saved.role) : undefined; } + +// Original immutable identity generation is observed only from the actual +// admitted nested proof; same-owner strings do not import another session. +export function conversationOwnership(token: AdmittedConversation) { + const saved = rooms.get(token); + return saved && receivedNestedEnvelopeOwnership(saved.nested); +} diff --git a/web/src/lib/messaging/unlocked-session.ts b/web/src/lib/messaging/unlocked-session.ts @@ -0,0 +1,172 @@ +import { + privateSessionOwnership, + subscribePrivateSessionClose, + type PrivateSession +} from '../runtime/private-session.ts'; +import { + getPrivateCacheScope, + retainPrivateCacheWire, + privateCacheWire, + privateCacheSnapshot, + clearPrivateCacheScope +} from '../nostr/private-cache-scope.ts'; +import { LOCAL_PERSISTENCE_BUDGETS } from '../config/budgets.ts'; +import { + conversationSnapshot, + conversationOwnership, + type AdmittedConversation, + type ConversationData +} from './admit-conversation.ts'; +declare const unlockedBrand: unique symbol; +export type UnlockedSession = Readonly<{ [unlockedBrand]: true }>; +export type UnlockedAdmission = + 'added' | 'duplicate' | 'conflict' | 'rejected' | 'limit' | 'closed'; +type View = Readonly<{ + status: 'ready' | 'conflict' | 'closed' | 'rejected'; + messages: readonly ConversationData[]; +}>; +type Snapshot = Readonly<{ closed: boolean; count: number; bytes: number }>; +type Controller = { + current(): boolean; + accept(room: AdmittedConversation): UnlockedAdmission; + read(): View; + snapshot(): Snapshot; + close(): void; +}; +const controllers = new WeakMap<UnlockedSession, Controller>(), + sessions = new WeakMap<PrivateSession, UnlockedSession>(); +// Explicit owner-generation memory scope only. No decryption, shared SDK +// memoized helpers, public EventStore, persistence or network side effect. +export function captureUnlockedSession( + session: PrivateSession, + review: unknown +): UnlockedSession | undefined { + if (typeof window === 'undefined' || review !== 'reviewed_messages_unlock') + return undefined; + const observed = privateSessionOwnership(session); + if (!observed) return undefined; + const capture = observed; + const previous = sessions.get(session); + if (previous && controllers.get(previous)?.current()) return previous; + let observedCache; + try { + observedCache = getPrivateCacheScope(session, 'projection_ownership'); + } catch { + return undefined; + } + if (!observedCache) return undefined; + const cache = observedCache; + const token = Object.freeze({}) as UnlockedSession, + entries = new Map<string, string>(); + let closed = false, + bytes = 0, + off = () => {}; + function close() { + if (closed) return; + closed = true; + entries.clear(); + bytes = 0; + clearPrivateCacheScope(cache); + off(); + // Drop our reachable private refs. Detached caller copies and JavaScript + // heap/garbage-collection timing cannot be securely zeroized or recalled. + controllers.set(token, { + current: () => false, + accept: () => 'closed', + read: () => ({ status: 'closed', messages: [] }), + snapshot: () => ({ closed: true, count: 0, bytes: 0 }), + close: () => {} + }); + } + function current() { + if (closed || !capture.current() || privateCacheSnapshot(cache).closed) { + close(); + return false; + } + return true; + } + const state: Controller = { + current, + accept(room) { + if (!current()) return 'closed'; + // Authenticate original room and generation before even a dedup lookup. + const ownership = conversationOwnership(room); + if ( + !ownership?.current() || + ownership.owner !== capture.owner || + ownership.session !== capture.session + ) + return 'rejected'; + const data = conversationSnapshot(room); + if ( + !data || + data.owner !== capture.owner || + !current() || + !ownership.current() + ) + return 'rejected'; + const wire = JSON.stringify(data), + size = new TextEncoder().encode(wire).length, + existing = entries.get(data.rumorId); + if (existing !== undefined) + return existing === wire && + privateCacheWire(cache, data.rumorId) === wire + ? 'duplicate' + : 'conflict'; + if ( + entries.size >= LOCAL_PERSISTENCE_BUDGETS.receivedEnvelopes || + size > LOCAL_PERSISTENCE_BUDGETS.receivedCiphertextBytes - bytes + ) + return 'limit'; + const result = retainPrivateCacheWire(cache, data.rumorId, wire); + if (result !== 'accepted' && result !== 'duplicate') return result; + if (!current() || !ownership.current()) return 'closed'; + if (privateCacheWire(cache, data.rumorId) !== wire) return 'conflict'; + entries.set(data.rumorId, wire); + bytes += size; + return 'added'; + }, + read() { + if (!current()) return { status: 'closed', messages: [] }; + for (const [id, wire] of entries) { + // A generic internal cache port is not projection authority. Exact own + // immutable bytes must agree; poisoning never substitutes another row. + if (privateCacheWire(cache, id) !== wire) + return { status: 'conflict', messages: [] }; + } + const messages = Array.from( + entries.values(), + (wire) => JSON.parse(wire) as ConversationData + ); + return current() + ? { status: 'ready', messages } + : { status: 'closed', messages: [] }; + }, + snapshot: () => + current() + ? { closed: false, count: entries.size, bytes } + : { closed: true, count: 0, bytes: 0 }, + close + }; + controllers.set(token, state); + sessions.set(session, token); + off = subscribePrivateSessionClose(session, close); + return current() ? token : undefined; +} +export function acceptUnlockedConversation( + scope: UnlockedSession, + room: AdmittedConversation +): UnlockedAdmission { + return controllers.get(scope)?.accept(room) ?? 'rejected'; +} +export function readUnlockedMessages(scope: UnlockedSession): View { + return controllers.get(scope)?.read() ?? { status: 'rejected', messages: [] }; +} +export function unlockedSessionSnapshot(scope: UnlockedSession): Snapshot { + return ( + controllers.get(scope)?.snapshot() ?? { closed: true, count: 0, bytes: 0 } + ); +} +export function closeUnlockedSession(scope: UnlockedSession): void { + controllers.get(scope)?.close(); +} diff --git a/web/src/lib/nostr/unwrap-admission.ts b/web/src/lib/nostr/unwrap-admission.ts @@ -258,7 +258,7 @@ type Reader = { const readers = new WeakMap<ReceivedUnwrap, Reader>(); const nested = new WeakMap< ReceivedNestedEnvelope, - { snapshot: Snapshot; current(): boolean } + { snapshot: Snapshot; session: symbol; current: () => boolean } >(); // No common unwrap helper/cache or caller event objects are consulted. Original // owner storage finishes each IDB transaction before serialized SDK work begins. @@ -413,6 +413,7 @@ export function captureReceivedUnwrap( // wait before minting original retained-record custody. const token = Object.freeze({}) as ReceivedNestedEnvelope; nested.set(token, { + session: ownership.session, snapshot: { owner: ownership.owner, outerId: id, @@ -467,3 +468,20 @@ export function receivedNestedEnvelopeSnapshot( ? (JSON.parse(JSON.stringify(saved.snapshot)) as Snapshot) : undefined; } + +// HCP093 original-generation custody port. This observation is not a Send, +// persistence, inbox-readiness or AUTH capability. Structural copies never +// replace the original nested proof in the WeakMap. +export function receivedNestedEnvelopeOwnership( + token: ReceivedNestedEnvelope +): + Readonly<{ owner: string; session: symbol; current(): boolean }> | undefined { + const saved = nested.get(token); + return saved?.current() + ? { + owner: saved.snapshot.owner, + session: saved.session, + current: saved.current + } + : undefined; +} diff --git a/web/tests/e2e/harness/unlocked-session.ts b/web/tests/e2e/harness/unlocked-session.ts @@ -0,0 +1,324 @@ +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') { + const f = await makeRecoveryFixture(), + 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 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 anotherWrap() { + 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(seal)) + }, + 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: rumor.id }; + }, + stop() { + if (reader) stopReceivedUnwrap(reader); + }, + close() { + 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/unlocked-session.spec.ts b/web/tests/e2e/unlocked-session.spec.ts @@ -0,0 +1,293 @@ +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/unlocked-session.ts'; +declare global { + interface Window { + hcp093: typeof Fixture; + hcp093Fixture: 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/unlocked-session.ts', import.meta.url) + ), + name: 'hcp093', + 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.hcp093Fixture = await window.hcp093.makeFixture(); + }); +}); +test.afterEach(async ({ page }) => { + if (!page.isClosed()) + await page.evaluate(() => window.hcp093Fixture?.close()); +}); +test('cache capture requires explicit reviewed action and performs no extension or store effect', async ({ + page +}) => { + const r = await page.evaluate(() => { + const f = window.hcp093Fixture, + before = f.counts(); + return { + capture: f.captureCache('unreviewed'), + messages: f.messages(), + before, + after: f.counts() + }; + }); + expect(r.capture).toBe(false); + expect(r.messages).toBeUndefined(); + expect(r.after).toEqual(r.before); +}); +test('only actual admitted room enters current cache without another SDK operation', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = window.hcp093Fixture; + await f.unlock(); + f.admit('inbound'); + f.captureCache(); + const before = f.counts(); + return { + result: f.cache(), + messages: f.messages(), + snapshot: f.cacheSnapshot(), + before, + after: f.counts(), + peer: f.peer, + id: f.rumorId + }; + }); + expect(r.result).toBe('added'); + expect(r.messages?.status).toBe('ready'); + expect(r.messages?.messages).toHaveLength(1); + expect(r.messages?.messages[0]).toMatchObject({ + peer: r.peer, + rumorId: r.id, + role: 'inbound' + }); + expect(r.snapshot).toMatchObject({ closed: false, count: 1 }); + expect(r.after).toEqual(r.before); +}); +test('multiple genuine encrypted wraps of same immutable rumor create one logical projection', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = window.hcp093Fixture; + await f.unlock(); + f.admit('inbound'); + f.captureCache(); + const first = f.cache(); + const next = await f.anotherWrap(); + return { + first, + next, + second: f.cache(), + messages: f.messages(), + snapshot: f.cacheSnapshot(), + id: f.rumorId + }; + }); + expect(r.first).toBe('added'); + expect(r.second).toBe('duplicate'); + expect(r.next.rumorId).toBe(r.id); + expect(r.messages?.messages).toHaveLength(1); + expect(r.snapshot?.count).toBe(1); +}); +test('mutating detached returned projection cannot alias a different sender or rumor', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = window.hcp093Fixture; + await f.unlock(); + f.admit('inbound'); + f.captureCache(); + f.cache(); + const copy = f.messages(); + if (copy?.status === 'ready') { + const row = copy.messages[0] as unknown as { + peer: string; + rumorId: string; + content: string; + }; + row.peer = f.other; + row.rumorId = '0'.repeat(64); + row.content = 'MUTATED_CALLER_COPY'; + } + return { fresh: f.messages(), peer: f.peer, id: f.rumorId }; + }); + expect(r.fresh?.messages[0]).toMatchObject({ + peer: r.peer, + rumorId: r.id, + content: 'Actual encrypted room fixture' + }); +}); +test('forged and copied room capabilities cannot populate cache', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = window.hcp093Fixture; + await f.unlock(); + f.admit('inbound'); + f.captureCache(); + return { + fake: f.forgedCache(), + copy: f.copiedCache(), + messages: f.messages(), + snapshot: f.cacheSnapshot() + }; + }); + expect(r.fake).toBe('rejected'); + expect(r.copy).toBe('rejected'); + expect(r.messages?.messages).toEqual([]); + expect(r.snapshot?.count).toBe(0); +}); +test('same owner with different actual identity generation cannot import old room proof', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = window.hcp093Fixture; + await f.unlock(); + f.admit('inbound'); + f.captureCache(); + return { other: await f.otherGeneration(), original: f.cache() }; + }); + expect(r.other.accepted).toBe('rejected'); + expect(r.other.snapshot.count).toBe(0); + expect(r.original).toBe('added'); +}); +test('logout clears reachable projections and rejects late original admission', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = window.hcp093Fixture; + await f.unlock(); + f.admit('inbound'); + f.captureCache(); + f.cache(); + f.disconnect(); + return { + messages: f.messages(), + snapshot: f.cacheSnapshot(), + raw: f.rawCacheSnapshot(), + late: f.cache() + }; + }); + expect(r.messages).toMatchObject({ status: 'closed', messages: [] }); + expect(r.snapshot).toMatchObject({ closed: true, count: 0, bytes: 0 }); + expect(r.late).toBe('closed'); + expect(r.raw).toMatchObject({ closed: true, count: 0, bytes: 0 }); +}); +test('explicit cache Stop discards preview and does not cancel or repeat provider calls', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = window.hcp093Fixture; + await f.unlock(); + f.admit('inbound'); + f.captureCache(); + f.cache(); + const before = f.counts(); + f.closeCache(); + return { + messages: f.messages(), + snapshot: f.cacheSnapshot(), + before, + after: f.counts() + }; + }); + expect(r.messages).toMatchObject({ status: 'closed', messages: [] }); + expect(r.snapshot).toMatchObject({ closed: true, count: 0, bytes: 0 }); + expect(r.after).toEqual(r.before); +}); +test('original private-session close clears cache while public identity may remain connected', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = window.hcp093Fixture; + await f.unlock(); + f.admit('inbound'); + f.captureCache(); + f.cache(); + f.closePrivate(); + return { messages: f.messages(), snapshot: f.cacheSnapshot() }; + }); + expect(r.messages).toMatchObject({ status: 'closed', messages: [] }); + expect(r.snapshot?.count).toBe(0); +}); +test('actual fresh changed extension owner invalidates generation and cached preview', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = window.hcp093Fixture; + await f.unlock(); + f.admit('inbound'); + f.captureCache(); + f.cache(); + await f.changedOwner(); + return { messages: f.messages(), snapshot: f.cacheSnapshot() }; + }); + expect(r.messages).toMatchObject({ status: 'closed', messages: [] }); + expect(r.snapshot?.count).toBe(0); +}); +test('actual scoped cache quota refuses new verified projection without eviction or automatic reset', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = window.hcp093Fixture; + await f.unlock(); + f.admit('inbound'); + f.captureCache(); + return { + quota: f.quota(), + result: f.cache(), + raw: f.rawCacheSnapshot(), + snapshot: f.cacheSnapshot(), + messages: f.messages() + }; + }); + expect(r.quota).toBe(2000); + expect(r.result).toBe('limit'); + expect(r.raw).toMatchObject({ closed: false, count: 2000, bytes: 4000 }); + expect(r.snapshot?.count).toBe(0); + expect(r.messages?.messages).toEqual([]); +}); +test('poisoned existing serialized cache cannot substitute another peer under a verified rumor hash', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = window.hcp093Fixture; + await f.unlock(); + f.admit('inbound'); + f.captureCache(); + f.cache(); + return { injected: f.corruptCachedWire(), messages: f.messages() }; + }); + expect(r.injected).toBe('accepted'); + expect(r.messages).toMatchObject({ status: 'conflict', messages: [] }); +});