app

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

commit ffbe195822e3a0d23d9d331bdd7ffd4129718c95
parent c924244ff4cb3725c79c2f451a366bbddb322152
Author: triesap <tyson@radroots.org>
Date:   Sat, 10 Oct 2026 01:03:57 +0000

publishing: gate new public listings on reply-capable inbox readiness (HCP-109)

Diffstat:
Aweb/src/lib/publishing/new-listing-readiness.ts | 176+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/harness/new-listing-readiness.ts | 147+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/new-listing-readiness.spec.ts | 113+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/unit/new-listing-readiness.test.ts | 257+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
4 files changed, 693 insertions(+), 0 deletions(-)

diff --git a/web/src/lib/publishing/new-listing-readiness.ts b/web/src/lib/publishing/new-listing-readiness.ts @@ -0,0 +1,176 @@ +import { + identityMessagingOwnership, + type IdentitySession +} from '../runtime/identity-session.ts'; +import { privateSessionOwnership } from '../runtime/private-session.ts'; +import { + inboxSetupViewOwnership, + inboxSetupViewSnapshot, + type InboxSetupView +} from '../messaging/inbox-setup-view.ts'; +import { + inboxResolutionSnapshot, + inboxResolverCurrentAfterSample +} from '../messaging/resolve-inbox.ts'; +import { existingInboxSetupSnapshot } from '../messaging/inbox-setup-verification.ts'; +import type { InboxAccessObservation } from '../messaging/readiness.ts'; +import type { RelayPolicy } from '../config/relays.ts'; + +declare const readinessBrand: unique symbol; +export type NewListingReadiness = Readonly<{ [readinessBrand]: true }>; +type Ownership = Readonly<{ + owner: string; + identity: IdentitySession; + policy: RelayPolicy; + current(this: void): boolean; +}>; +const reviews = new WeakMap< + NewListingReadiness, + { + ownership: Ownership; + close(): void; + } +>(); + +// Readiness is a prerequisite for a later new-listing command, not permission +// to sign, write a preference, reserve a listing or publish an event. Its owners +// must still validate the exact draft/author/template and final explicit action. +function sample(identity: IdentitySession, setup: InboxSetupView | undefined) { + try { + if (typeof window === 'undefined') return; + const actor = identityMessagingOwnership(identity); + const own = inboxSetupViewOwnership(setup); + const state = inboxSetupViewSnapshot(setup); + if ( + !actor?.current() || + !own?.current() || + own.identity !== identity || + !own.session || + !own.resolver || + state.busy || + !state.setupComplete + ) + return; + const privateOwner = privateSessionOwnership(own.session); + if ( + !privateOwner?.current() || + privateOwner.owner !== actor.owner || + privateOwner.session !== actor.session + ) + return; + const initial = inboxResolutionSnapshot(own.resolver); + if (!initial.knownBase || initial.author !== actor.owner) return; + let access: InboxAccessObservation | undefined; + const ready = existingInboxSetupSnapshot( + identity, + own.session, + own.policy, + own.resolver, + own.observeAccess + ? (context) => { + access = own.observeAccess!(context); + return access; + } + : undefined + ); + const final = inboxResolutionSnapshot(own.resolver); + const accessCurrent = access?.current() ?? false; + const actual = inboxSetupViewOwnership(setup); + const finalState = inboxSetupViewSnapshot(setup); + if ( + !ready.setupComplete || + !ready.newListingReady || + !accessCurrent || + final.knownBase?.id !== initial.knownBase.id || + final.status !== 'ready' || + !actor.current() || + !privateOwner.current() || + !own.current() || + !actual?.current() || + actual.identity !== identity || + actual.policy !== own.policy || + actual.session !== own.session || + actual.resolver !== own.resolver || + finalState.busy || + !finalState.setupComplete || + !inboxResolverCurrentAfterSample(own.resolver) + ) + return; + return { actor, own, privateOwner, preferenceId: final.knownBase.id }; + } catch { + return; + } +} + +// Detached display information never mints or replaces the original review. +// Draft saving has no dependency on this module and remains available here. +export function newListingReadinessSnapshot( + identity: IdentitySession, + setup: InboxSetupView | undefined +) { + const ready = !!sample(identity, setup); + return { + draft: true as const, + readyToReview: ready, + preferenceWrite: 'not_requested' as const, + copy: ready + ? 'Messages: ready to receive replies' + : 'Enable messages before publishing so buyers can contact you.' + }; +} +export function captureNewListingReadiness( + identity: IdentitySession, + setup: InboxSetupView | undefined, + review: unknown +): NewListingReadiness | undefined { + if (review !== 'reviewed_new_listing_inbox') return; + const captured = sample(identity, setup); + if (!captured) return; + let active = true; + const current = () => { + if ( + !active || + !captured.actor.current() || + !captured.own.current() || + !captured.privateOwner.current() + ) + return false; + const actual = sample(identity, setup); + return ( + !!actual && + active && + actual.actor.owner === captured.actor.owner && + actual.actor.session === captured.actor.session && + actual.own.identity === captured.own.identity && + actual.own.policy === captured.own.policy && + actual.own.session === captured.own.session && + actual.own.resolver === captured.own.resolver && + actual.preferenceId === captured.preferenceId && + captured.actor.current() && + captured.own.current() && + captured.privateOwner.current() + ); + }; + const token = Object.freeze({}) as NewListingReadiness; + reviews.set(token, { + ownership: { + owner: captured.actor.owner, + identity, + policy: captured.own.policy, + current + }, + close: () => { + active = false; + } + }); + return token; +} +export function newListingReadinessOwnership( + token: NewListingReadiness | undefined +): Ownership | undefined { + const original = token && reviews.get(token); + return original?.ownership.current() ? { ...original.ownership } : undefined; +} +export function closeNewListingReadiness(token: NewListingReadiness): void { + reviews.get(token)?.close(); +} diff --git a/web/tests/e2e/harness/new-listing-readiness.ts b/web/tests/e2e/harness/new-listing-readiness.ts @@ -0,0 +1,147 @@ +import { + newListingReadinessSnapshot, + captureNewListingReadiness, + newListingReadinessOwnership, + closeNewListingReadiness +} from '../../../src/lib/publishing/new-listing-readiness.ts'; +import { + createInboxSetupView, + checkInboxSetupView, + unlockInboxSetupView, + stopInboxSetupView, + closeInboxSetupView +} from '../../../src/lib/messaging/inbox-setup-view.ts'; +import { + disconnectIdentity, + connectIdentity +} from '../../../src/lib/runtime/identity-session.ts'; +import { + openBrowserDatabase, + closeBrowserDatabase +} from '../../../src/lib/persistence/database.ts'; +import { + createPublicDraftRepository, + listPublicDrafts +} from '../../../src/lib/persistence/drafts.ts'; +import { + createPublicDraftController, + flushPublicDraft, + publicDraftControllerSnapshot, + closePublicDraftController +} from '../../../src/lib/publishing/draft-controller.ts'; +import { makeSetupFixture, fixturePolicy, inbox } from './inbox-setup.ts'; +export async function createFixture( + mode: 'guest' | 'signing_only' | 'compatible_unqualified' | 'qualified' +) { + const f = await makeSetupFixture([['relay', inbox]]); + if (mode === 'guest') disconnectIdentity(f.identity); + if (mode === 'signing_only') { + disconnectIdentity(f.identity); + const provider = window.nostr as { + getPublicKey(): Promise<string>; + signEvent(...args: unknown[]): Promise<never>; + }; + Object.defineProperty(window, 'nostr', { + configurable: true, + value: { + getPublicKey: () => provider.getPublicKey(), + signEvent: (...args: Parameters<typeof provider.signEvent>) => + provider.signEvent(...args) + } + }); + await connectIdentity(f.identity); + } + // HC_TEST_ONLY_QUALIFICATION_PORT: actual original owners with controlled + // exercised observations; this never qualifies real extensions or relays. + const setup = createInboxSetupView({ + identity: f.identity, + policy: fixturePolicy(), + lookup: () => Promise.resolve(f.resolve().resolver), + ...(mode === 'qualified' + ? { + observeAccess: ( + context: import('../../../src/lib/messaging/readiness.ts').OwnInboxAccessContext + ) => ({ + ...context, + readTargets: context.readTargets.slice(), + archiveTargets: context.archiveTargets.slice(), + receive: 'qualified_exercised' as const, + archive: 'qualified_exercised' as const, + current: () => true + }) + } + : {}) + }); + if (setup) { + await checkInboxSetupView(setup); + await unlockInboxSetupView(setup); + } + const baseline = f.counts(); + const proof = captureNewListingReadiness( + f.identity, + setup, + 'reviewed_new_listing_inbox' + ); + const held = newListingReadinessOwnership(proof); + const opened = await openBrowserDatabase(); + if (opened.state !== 'ready') throw Error(opened.reason); + const repository = createPublicDraftRepository(opened.owner, f.owner); + if (!repository) throw Error('original draft repository unavailable'); + const form = { + title: '', + description: 'unfinished local public description', + location: '', + amount: '.', + currency: '', + unit: '', + quantity: '', + contactType: '' as const, + contactValue: '' + }; + const draft = await createPublicDraftController(repository, form); + if (!draft) throw Error('original draft controller unavailable'); + return { + snapshot() { + return { + readiness: newListingReadinessSnapshot(f.identity, setup), + captured: !!proof, + current: held?.current() ?? false, + counts: f.counts(), + baseline + }; + }, + async save() { + const saved = await flushPublicDraft(draft); + return { + saved, + snapshot: publicDraftControllerSnapshot(draft), + rows: await listPublicDrafts(repository), + counts: f.counts(), + baseline + }; + }, + copies() { + return { + copiedSetup: !!captureNewListingReadiness( + f.identity, + setup && { ...setup }, + 'reviewed_new_listing_inbox' + ), + copiedProof: !!newListingReadinessOwnership(proof && { ...proof }), + genuine: held?.current() ?? false + }; + }, + stop() { + stopInboxSetupView(setup); + }, + revoke() { + if (proof) closeNewListingReadiness(proof); + }, + close() { + closePublicDraftController(draft); + closeInboxSetupView(setup); + closeBrowserDatabase(opened.owner); + f.close(); + } + }; +} diff --git a/web/tests/e2e/new-listing-readiness.spec.ts b/web/tests/e2e/new-listing-readiness.spec.ts @@ -0,0 +1,113 @@ +import { expect, test } 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/new-listing-readiness.ts'; +declare global { + interface Window { + hcp109: typeof Fixture; + hcp109Fixture: Awaited<ReturnType<typeof Fixture.createFixture>>; + } +} +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/new-listing-readiness.ts', import.meta.url) + ), + name: 'hcp109', + formats: ['iife'] + } + } + }); + const output = Array.isArray(result) ? result[0] : result; + if (!('output' in output)) throw Error('fixture bundle missing'); + const chunks = output.output.filter((row) => row.type === 'chunk'); + expect(chunks).toHaveLength(1); + bundle = chunks[0].code; +}); +test.afterAll(async () => server.close()); +test.beforeEach(async ({ page }) => { + await page.goto(server.url + '/search'); + await page.addScriptTag({ content: bundle }); +}); +test.afterEach(async ({ page }) => { + if (!page.isClosed()) + await page.evaluate(() => window.hcp109Fixture?.close()); +}); +for (const mode of ['guest', 'signing_only', 'compatible_unqualified'] as const) + test( + 'HCP109 actual unfinished IndexedDB draft saves while new-listing review is blocked: ' + + mode, + async ({ page }) => { + await page.evaluate(async (mode) => { + window.hcp109Fixture = await window.hcp109.createFixture(mode); + }, mode); + const before = await page.evaluate(() => window.hcp109Fixture.snapshot()); + expect(before.readiness).toMatchObject({ + draft: true, + readyToReview: false, + preferenceWrite: 'not_requested' + }); + expect(before.captured).toBe(false); + expect(before.current).toBe(false); + const actual = await page.evaluate(() => window.hcp109Fixture.save()); + expect(actual.saved).toBe(true); + expect(actual.snapshot?.state).toBe('saved'); + expect(actual.snapshot?.draft?.form).toMatchObject({ + title: '', + amount: '.', + description: 'unfinished local public description' + }); + expect(actual.rows.ok).toBe(true); + if (!actual.rows.ok) throw Error(actual.rows.reason); + expect(actual.rows.value).toHaveLength(1); + expect(actual.rows.value[0]).toEqual(actual.snapshot?.draft); + expect(actual.counts).toEqual(actual.baseline); + expect(actual.counts.signs).toBe(0); + } + ); +test('HCP109 qualified existing signed inbox admits original review with no redundant preference write or signature', async ({ + page +}) => { + await page.evaluate(async () => { + window.hcp109Fixture = await window.hcp109.createFixture('qualified'); + }); + const actual = await page.evaluate(() => window.hcp109Fixture.snapshot()); + expect(actual.readiness.readyToReview).toBe(true); + expect(actual.captured).toBe(true); + expect(actual.current).toBe(true); + expect(actual.counts).toEqual(actual.baseline); + expect(actual.counts.signs).toBe(0); + expect(await page.evaluate(() => window.hcp109Fixture.copies())).toEqual({ + copiedSetup: false, + copiedProof: false, + genuine: true + }); +}); +test('HCP109 original Stop revokes held new-listing proof while incomplete draft remains saveable', async ({ + page +}) => { + await page.evaluate(async () => { + window.hcp109Fixture = await window.hcp109.createFixture('qualified'); + }); + expect( + (await page.evaluate(() => window.hcp109Fixture.snapshot())).current + ).toBe(true); + await page.evaluate(() => window.hcp109Fixture.stop()); + const stopped = await page.evaluate(() => window.hcp109Fixture.snapshot()); + expect(stopped.current).toBe(false); + expect(stopped.readiness.readyToReview).toBe(false); + const saved = await page.evaluate(() => window.hcp109Fixture.save()); + expect(saved.saved).toBe(true); + expect(saved.rows.ok).toBe(true); + expect(saved.counts.signs).toBe(0); + expect(saved.counts).toEqual(saved.baseline); +}); diff --git a/web/tests/unit/new-listing-readiness.test.ts b/web/tests/unit/new-listing-readiness.test.ts @@ -0,0 +1,257 @@ +import { expect, it } from 'vitest'; +import { + createIdentitySession, + connectIdentity, + probeIdentityMessaging, + disconnectIdentity +} from '../../src/lib/runtime/identity-session.ts'; +import { + createInboxSetupView, + checkInboxSetupView, + unlockInboxSetupView, + stopInboxSetupView, + closeInboxSetupView +} from '../../src/lib/messaging/inbox-setup-view.ts'; +import { + makeSetupFixture, + fixturePolicy, + inbox +} from '../e2e/harness/inbox-setup.ts'; +import { + newListingReadinessSnapshot, + captureNewListingReadiness, + newListingReadinessOwnership, + closeNewListingReadiness, + type NewListingReadiness +} from '../../src/lib/publishing/new-listing-readiness.ts'; +import type { ObserveInboxAccess } from '../../src/lib/messaging/readiness.ts'; + +// HC_TEST_ONLY_QUALIFICATION_PORT: exercises the original owner-bound gate, +// not real extension/relay access, retention or launch qualification. +async function fixture(access = true) { + const f = await makeSetupFixture([['relay', inbox]]); + let currentAccess = true; + const observeAccess: ObserveInboxAccess = (context) => ({ + ...context, + readTargets: context.readTargets.slice(), + archiveTargets: context.archiveTargets.slice(), + receive: 'qualified_exercised', + archive: 'qualified_exercised', + current: () => currentAccess + }); + const setup = createInboxSetupView({ + identity: f.identity, + policy: fixturePolicy(), + lookup: () => Promise.resolve(f.resolve().resolver), + ...(access ? { observeAccess } : {}) + }); + if (!setup) throw Error('original setup unavailable'); + await checkInboxSetupView(setup); + await unlockInboxSetupView(setup); + return { + ...f, + setup, + retireAccess: () => { + currentAccess = false; + }, + close() { + closeInboxSetupView(setup); + f.close(); + } + }; +} +const review = 'reviewed_new_listing_inbox'; +it('guest can draft but cannot review a new reply-capable listing', () => { + const identity = createIdentitySession(); + expect(newListingReadinessSnapshot(identity, undefined)).toMatchObject({ + draft: true, + readyToReview: false, + preferenceWrite: 'not_requested' + }); + expect( + captureNewListingReadiness(identity, undefined, review) + ).toBeUndefined(); +}); +it('actual signing-only identity cannot advertise new messaging-ready publication', async () => { + const f = await makeSetupFixture(); + try { + disconnectIdentity(f.identity); + const provider = window.nostr as { + getPublicKey(): Promise<string>; + signEvent(...args: unknown[]): Promise<never>; + }; + Object.defineProperty(window, 'nostr', { + configurable: true, + value: { + getPublicKey: () => provider.getPublicKey(), + signEvent: (...args: Parameters<typeof provider.signEvent>) => + provider.signEvent(...args) + } + }); + await connectIdentity(f.identity); + const before = f.counts(); + expect( + captureNewListingReadiness(f.identity, undefined, review) + ).toBeUndefined(); + expect( + newListingReadinessSnapshot(f.identity, undefined).readyToReview + ).toBe(false); + expect(f.counts()).toEqual(before); + } finally { + f.close(); + } +}); +it('compatible signed configuration without exercised qualified access remains blocked', async () => { + const f = await fixture(false); + try { + const before = f.counts(); + expect(newListingReadinessSnapshot(f.identity, f.setup)).toMatchObject({ + draft: true, + readyToReview: false, + preferenceWrite: 'not_requested' + }); + expect( + captureNewListingReadiness(f.identity, f.setup, review) + ).toBeUndefined(); + expect(f.counts()).toEqual(before); + } finally { + f.close(); + } +}); +it('original qualified compatible inbox permits explicit review without another preference write or signature', async () => { + const f = await fixture(); + try { + const before = f.counts(); + expect(newListingReadinessSnapshot(f.identity, f.setup).readyToReview).toBe( + true + ); + const proof = captureNewListingReadiness(f.identity, f.setup, review); + const owned = newListingReadinessOwnership(proof); + expect(owned?.owner).toBe(f.owner); + expect(owned?.identity).toBe(f.identity); + expect(owned?.current()).toBe(true); + expect(f.counts()).toEqual(before); + expect(f.counts().signs).toBe(0); + } finally { + f.close(); + } +}); +for (const mode of ['missing', 'partial', 'unsupported'] as const) + it( + 'actual signed/bounded own inbox cannot admit new review: ' + mode, + async () => { + const f = await makeSetupFixture([ + ['relay', mode === 'unsupported' ? '' : inbox] + ]); + const resolver = f.resolve( + mode === 'missing' ? null : f.event, + mode !== 'partial' + ).resolver; + const setup = createInboxSetupView({ + identity: f.identity, + policy: fixturePolicy(), + lookup: () => Promise.resolve(resolver) + }); + try { + await checkInboxSetupView(setup); + await unlockInboxSetupView(setup); + const before = f.counts(); + expect( + captureNewListingReadiness(f.identity, setup, review) + ).toBeUndefined(); + expect( + newListingReadinessSnapshot(f.identity, setup).readyToReview + ).toBe(false); + expect(f.counts()).toEqual(before); + } finally { + closeInboxSetupView(setup); + f.close(); + } + } + ); +it('copied setup and readiness tokens cannot borrow genuine owner authority', async () => { + const f = await fixture(); + try { + const proof = captureNewListingReadiness(f.identity, f.setup, review)!; + expect(newListingReadinessOwnership(proof)?.current()).toBe(true); + expect( + captureNewListingReadiness({ ...f.identity }, f.setup, review) + ).toBeUndefined(); + expect( + captureNewListingReadiness(f.identity, { ...f.setup }, review) + ).toBeUndefined(); + expect(newListingReadinessOwnership({ ...proof })).toBeUndefined(); + expect( + newListingReadinessOwnership({} as NewListingReadiness) + ).toBeUndefined(); + expect(newListingReadinessOwnership(proof)?.current()).toBe(true); + } finally { + f.close(); + } +}); +it('another original identity cannot borrow the seller setup even with the same displayed observations', async () => { + const f = await fixture(), + other = createIdentitySession(); + try { + await connectIdentity(other); + await probeIdentityMessaging(other, 'reviewed_self_copy'); + expect(captureNewListingReadiness(other, f.setup, review)).toBeUndefined(); + expect( + captureNewListingReadiness(f.identity, f.setup, review) + ).toBeDefined(); + } finally { + disconnectIdentity(other); + f.close(); + } +}); +it('retired actual exercised access revokes held proof without signing or publishing', async () => { + const f = await fixture(); + try { + const proof = captureNewListingReadiness(f.identity, f.setup, review)!; + const held = newListingReadinessOwnership(proof)!; + expect(held.current()).toBe(true); + f.retireAccess(); + expect(held.current()).toBe(false); + expect(newListingReadinessOwnership(proof)).toBeUndefined(); + expect(f.counts().signs).toBe(0); + } finally { + f.close(); + } +}); +for (const invalidate of ['stop', 'close', 'disconnect', 'revoke'] as const) + it( + 'original lifecycle invalidation revokes a new-listing review: ' + + invalidate, + async () => { + const f = await fixture(); + try { + const proof = captureNewListingReadiness(f.identity, f.setup, review)!; + const held = newListingReadinessOwnership(proof)!; + expect(held.current()).toBe(true); + if (invalidate === 'stop') stopInboxSetupView(f.setup); + if (invalidate === 'close') closeInboxSetupView(f.setup); + if (invalidate === 'disconnect') disconnectIdentity(f.identity); + if (invalidate === 'revoke') closeNewListingReadiness(proof); + expect(held.current()).toBe(false); + expect(newListingReadinessOwnership(proof)).toBeUndefined(); + expect(f.counts().signs).toBe(0); + } finally { + f.close(); + } + } + ); +it('unreviewed readiness observations cannot silently create a review capability', async () => { + const f = await fixture(); + try { + const before = f.counts(); + expect( + captureNewListingReadiness(f.identity, f.setup, undefined) + ).toBeUndefined(); + expect( + captureNewListingReadiness(f.identity, f.setup, true) + ).toBeUndefined(); + expect(f.counts()).toEqual(before); + } finally { + f.close(); + } +});