app

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

commit 675fc297233682acc94c657ef33856cbdb8ad11e
parent ffbe195822e3a0d23d9d331bdd7ffd4129718c95
Author: triesap <tyson@radroots.org>
Date:   Sat, 10 Oct 2026 02:05:44 +0000

publishing: capture immutable public listing intents (HCP-110)

Diffstat:
Aweb/src/lib/persistence/public-publications.ts | 223+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/src/lib/persistence/quota.ts | 66+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mweb/src/lib/publishing/draft-controller.ts | 33+++++++++++++++++++++++++++++++++
Aweb/src/lib/publishing/prepare-listing.ts | 292+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/harness/prepare-listing.ts | 507+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/prepare-listing.spec.ts | 167+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/unit/prepare-listing.test.ts | 46++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 1333 insertions(+), 1 deletion(-)

diff --git a/web/src/lib/persistence/public-publications.ts b/web/src/lib/persistence/public-publications.ts @@ -0,0 +1,223 @@ +import type { PublicDraftRecord } from '../contracts/local-records.ts'; +import { canonicalLocalId } from '../private-handles.ts'; +import { + createPublicDraftRepository, + publicDraftRepositoryOwner, + type PublicDraftRepository +} from './drafts.ts'; +import { + browserDatabaseTransaction, + type BrowserDatabase +} from './database.ts'; +import { + createPublicQuotaRepository, + publicQuotaOwner, + claimPublicDraftOperation, + type PublicQuotaRepository, + type PublicQuotaFailure +} from './quota.ts'; +import { + decodePublicRecord, + publicRecordSnapshot, + type PublicRecordHandle +} from './records.ts'; +import { + publicDraftControllerOwnership, + type PublicDraftController +} from '../publishing/draft-controller.ts'; +import { exactLocalFields } from '../contracts/local-records.ts'; + +declare const repositoryBrand: unique symbol; +export type PublicPublicationRepository = Readonly<{ [repositoryBrand]: true }>; +type Scope = Readonly<{ + database: BrowserDatabase; + drafts: PublicDraftRepository; + quota: PublicQuotaRepository; + owner: string; +}>; +const repositories = new WeakMap<PublicPublicationRepository, Scope>(); +function scopeOf(repository: PublicPublicationRepository): Scope | undefined { + const scope = repositories.get(repository); + return scope && + publicDraftRepositoryOwner(scope.drafts) === scope.owner && + publicQuotaOwner(scope.quota) === scope.owner + ? scope + : undefined; +} +export function createPublicPublicationRepository( + database: BrowserDatabase, + owner: unknown +): PublicPublicationRepository | undefined { + const drafts = createPublicDraftRepository(database, owner), + quota = createPublicQuotaRepository(database, owner); + const admittedOwner = drafts && publicDraftRepositoryOwner(drafts); + if ( + !drafts || + !quota || + !admittedOwner || + publicQuotaOwner(quota) !== admittedOwner + ) + return undefined; + const handle = Object.freeze({}) as PublicPublicationRepository; + repositories.set(handle, { database, drafts, quota, owner: admittedOwner }); + return handle; +} +export function publicPublicationDraftRepository( + repository: PublicPublicationRepository +): PublicDraftRepository | undefined { + return scopeOf(repository)?.drafts; +} +export function publicPublicationOwner( + repository: PublicPublicationRepository +): string | undefined { + return scopeOf(repository)?.owner; +} +export type PublicListingSave = + | Readonly<{ status: 'saved' | 'existing'; record: PublicRecordHandle }> + | Readonly<{ status: PublicQuotaFailure | 'busy' }>; +export type PublicListingRead = + | Readonly<{ status: 'found'; record: PublicRecordHandle }> + | Readonly<{ status: 'missing' | 'unavailable' | 'corrupt_record' }>; +// Readback is exact local observation, never global absence or relay receipt. +export function readPublicListingIntent( + repository: PublicPublicationRepository, + command: unknown +): Promise<PublicListingRead> { + const scope = scopeOf(repository), + id = canonicalLocalId(command); + if (!scope || !id) return Promise.resolve({ status: 'unavailable' }); + let transaction: IDBTransaction; + try { + transaction = browserDatabaseTransaction( + scope.database, + ['public_operations'], + 'readonly' + ); + } catch { + return Promise.resolve({ status: 'unavailable' }); + } + return new Promise((resolve) => { + let decision: PublicListingRead | undefined; + transaction.addEventListener('complete', () => + resolve( + scopeOf(repository) + ? (decision ?? { status: 'unavailable' }) + : { status: 'unavailable' } + ) + ); + transaction.addEventListener('abort', () => + resolve({ status: 'unavailable' }) + ); + try { + const request = transaction + .objectStore('public_operations') + .get([scope.owner, id]); + request.addEventListener('success', () => { + const value: unknown = request.result; + if (value === undefined) { + decision = { status: 'missing' }; + return; + } + if ( + !exactLocalFields(value, ['owner', 'id', 'wire']) || + value.owner !== scope.owner || + value.id !== id + ) { + decision = { status: 'corrupt_record' }; + return; + } + const decoded = decodePublicRecord(value.wire, scope.owner, id); + const row = + decoded.ok && publicRecordSnapshot(decoded.value, scope.owner, id); + decision = + decoded.ok && row && row.family === 'public_operation' + ? { status: 'found', record: decoded.value } + : { status: 'corrupt_record' }; + }); + } catch { + decision = { status: 'unavailable' }; + try { + transaction.abort(); + } catch { + resolve({ status: 'unavailable' }); + } + } + }); +} +// Only a short local transaction is held. Extension/relay effects are later +// checkpoint owners and are absent from this repository. +export async function savePublicListingIntent( + repository: PublicPublicationRepository, + controller: PublicDraftController, + record: PublicRecordHandle, + expected: PublicDraftRecord, + editVersion: number, + command: string, + current: (this: void) => boolean +): Promise<PublicListingSave> { + try { + const scope = scopeOf(repository), + custody = publicDraftControllerOwnership(controller); + const row = scope && publicRecordSnapshot(record, scope.owner, command); + if ( + !scope || + !custody || + custody.repository !== scope.drafts || + !row || + row.family !== 'public_operation' || + row.source.type !== 'draft' + ) + return { status: 'invalid_scope' }; + if ( + !current() || + typeof window === 'undefined' || + !navigator.locks?.request + ) + return { status: 'unavailable' }; + return await navigator.locks.request( + 'harvestcircle:owner:' + scope.owner, + { mode: 'exclusive', ifAvailable: true }, + async (lock): Promise<PublicListingSave> => { + if (!lock) return { status: 'busy' }; + const fresh = (): boolean => scopeOf(repository) === scope && current(); + if (!fresh()) return { status: 'unavailable' }; + const claimed = await claimPublicDraftOperation( + scope.quota, + row.id, + record, + { + expected, + current: fresh, + draftCurrent: () => + custody.current(JSON.stringify(expected), editVersion) + } + ); + if (!fresh()) return { status: 'unavailable' }; + if (claimed.ok) + return { + status: claimed.value.state === 'created' ? 'saved' : 'existing', + record: claimed.value.record + }; + if (claimed.reason === 'unknown_completion') { + const observed = await readPublicListingIntent(repository, row.id); + const original = + observed.status === 'found' && + publicRecordSnapshot(observed.record, scope.owner, row.id); + if (!fresh()) return { status: 'unavailable' }; + if ( + observed.status === 'found' && + original && + original.family === 'public_operation' && + JSON.stringify(original.source) === JSON.stringify(row.source) && + JSON.stringify(original.capture) === JSON.stringify(row.capture) + ) + return { status: 'existing', record: observed.record }; + if (original) return { status: 'conflict' }; + } + return { status: claimed.reason }; + } + ); + } catch { + return { status: 'unavailable' }; + } +} diff --git a/web/src/lib/persistence/quota.ts b/web/src/lib/persistence/quota.ts @@ -1,7 +1,8 @@ import { canonicalPublicKey } from '../contracts/public-key.ts'; import { exactLocalFields, - type PublicRecord + type PublicRecord, + type PublicDraftRecord } from '../contracts/local-records.ts'; import { canonicalLocalId } from '../private-handles.ts'; import { LOCAL_PERSISTENCE_BUDGETS } from '../config/budgets.ts'; @@ -287,6 +288,38 @@ export function claimPublicOperation( Readonly<{ state: 'created' | 'existing'; record: PublicRecordHandle }> > > { + return claimOperation(repository, expectedId, handle); +} +type DraftAdmission = Readonly<{ + expected: PublicDraftRecord; + current(this: void): boolean; + draftCurrent(this: void): boolean; +}>; +// Storage-only atomic draft/CAS reservation. Current original account/review +// ownership is supplied by the public listing command owner, never a UI flag. +// Existing commands retain their original capture even after future draft edits. +export function claimPublicDraftOperation( + repository: PublicQuotaRepository, + expectedId: unknown, + handle: PublicRecordHandle, + admission: DraftAdmission +): Promise< + PublicQuotaResult< + Readonly<{ state: 'created' | 'existing'; record: PublicRecordHandle }> + > +> { + return claimOperation(repository, expectedId, handle, admission); +} +function claimOperation( + repository: PublicQuotaRepository, + expectedId: unknown, + handle: PublicRecordHandle, + draft?: DraftAdmission +): Promise< + PublicQuotaResult< + Readonly<{ state: 'created' | 'existing'; record: PublicRecordHandle }> + > +> { const scope = scopeOf(repository), id = canonicalLocalId(expectedId); if (!scope) return Promise.resolve(failed('invalid_scope')); @@ -309,6 +342,10 @@ export function claimPublicOperation( return transaction< Readonly<{ state: 'created' | 'existing'; record: PublicRecordHandle }> >(scope, 'readwrite', (rows, active, refuse) => { + if (draft && !draft.current()) { + refuse('unavailable'); + return; + } const previous = rows.find( (row) => row.record.family !== 'public_draft' && row.record.id === id ); @@ -332,6 +369,29 @@ export function claimPublicOperation( } return { ok: true, value: { state: 'existing', record: decoded.value } }; } + if (draft) { + const source = + record.family === 'public_operation' ? record.source : undefined; + const previousDraft = rows.find( + (row) => + row.record.family === 'public_draft' && + row.record.id === draft.expected.id + ); + if ( + !source || + source.type !== 'draft' || + draft.expected.owner !== scope.owner || + source.id !== draft.expected.id || + source.revision !== draft.expected.revision || + !previousDraft || + JSON.stringify(previousDraft.record) !== + JSON.stringify(draft.expected) || + !draft.draftCurrent() + ) { + refuse('conflict'); + return; + } + } const operations = rows.filter( (row) => row.record.family !== 'public_draft' ); @@ -343,6 +403,10 @@ export function claimPublicOperation( refuse('capacity'); return; } + if (draft && (!draft.current() || !draft.draftCurrent())) { + refuse('conflict'); + return; + } active.objectStore(store).put({ owner: scope.owner, id, wire }); return { ok: true, value: { state: 'created', record: handle } }; }); diff --git a/web/src/lib/publishing/draft-controller.ts b/web/src/lib/publishing/draft-controller.ts @@ -26,6 +26,14 @@ export type DraftControllerSnapshot = Readonly<{ state: 'editing' | 'saving' | 'saved' | 'failed' | 'closed'; failure: DraftFailure | null; }>; +export type PublicDraftControllerOwnership = Readonly<{ + repository: PublicDraftRepository; + current( + this: void, + expectedWire: string, + expectedEditVersion: number + ): boolean; +}>; type Controller = { edit(form: unknown): boolean; flush(): Promise<boolean>; @@ -33,6 +41,7 @@ type Controller = { saveClose(): Promise<boolean>; close(): void; snapshot(): DraftControllerSnapshot; + ownership(): PublicDraftControllerOwnership; }; const controllers = new WeakMap<PublicDraftController, Controller>(); export async function createPublicDraftController( @@ -155,6 +164,23 @@ export async function createPublicDraftController( return work; } const value: Controller = { + ownership() { + return { + repository, + current(expectedWire, expectedEditVersion) { + return ( + !closed && + failure === null && + state === 'saved' && + publicDraftRepositoryOwner(repository) !== undefined && + savedEditVersion === editVersion && + editVersion === expectedEditVersion && + saved !== null && + JSON.stringify(saved) === expectedWire + ); + } + }; + }, edit(input) { if (closed || editVersion === Number.MAX_SAFE_INTEGER) return false; const next = publicDraftFormSnapshot(input); @@ -232,6 +258,13 @@ export function publicDraftControllerSnapshot( ): DraftControllerSnapshot | undefined { return controllers.get(controller)?.snapshot(); } +// Original controller/repository custody, not a copied saved-state boolean. +// This grants only an observation of the exact acknowledged draft revision. +export function publicDraftControllerOwnership( + controller: PublicDraftController +): PublicDraftControllerOwnership | undefined { + return controllers.get(controller)?.ownership(); +} export function flushPublicDraft( controller: PublicDraftController ): Promise<boolean> { diff --git a/web/src/lib/publishing/prepare-listing.ts b/web/src/lib/publishing/prepare-listing.ts @@ -0,0 +1,292 @@ +import { buildFoodTemplate } from '../contracts/food-availability-v1/write.ts'; +import type { + PublicDraftRecord, + PublicDraftForm +} from '../contracts/local-records.ts'; +import { canonicalLocalId, newLocalId } from '../private-handles.ts'; +import { readRelayPolicy, publicRelayTargets } from '../config/relays.ts'; +import { inspectLocalTemplate } from '../nostr/local-template.ts'; +import { + decodePublicRecord, + type PublicRecordHandle +} from '../persistence/records.ts'; +import { + publicPublicationOwner, + publicPublicationDraftRepository, + savePublicListingIntent, + type PublicPublicationRepository, + type PublicListingSave +} from '../persistence/public-publications.ts'; +import { + publicDraftControllerOwnership, + publicDraftControllerSnapshot, + flushPublicDraft, + type PublicDraftController +} from './draft-controller.ts'; +import { + newListingReadinessOwnership, + type NewListingReadiness +} from './new-listing-readiness.ts'; + +declare const reviewBrand: unique symbol; +export type ListingReview = Readonly<{ [reviewBrand]: true }>; +export type ListingPreview = Readonly<{ + owner: string; + command: string; + draftId: string; + draftRevision: number; + identifier: string; + createdAtSeconds: number; + form: PublicDraftForm; + summary: string; + templateWire: string; + expectedHash: string; + targets: readonly string[]; + policyFingerprint: string; +}>; +type Review = Readonly<{ + repository: PublicPublicationRepository; + controller: PublicDraftController; + expected: PublicDraftRecord; + editVersion: number; + command: string; + readiness: NewListingReadiness; + record: PublicRecordHandle; + previewWire: string; + current(this: void): boolean; +}>; +const reviews = new WeakMap<ListingReview, Review>(); +const commands = new WeakMap< + PublicPublicationRepository, + Map<string, ListingReview> +>(); +const activeReservations = new WeakMap< + ListingReview, + Promise<ListingReservation> +>(); +export type ListingReviewResult = + | Readonly<{ status: 'review'; review: ListingReview }> + | Readonly<{ + status: 'blocked'; + reason: + | 'invalid_scope' + | 'invalid_command' + | 'unavailable' + | 'invalid_form' + | 'conflict'; + }>; +export type ListingReservation = + PublicListingSave | Readonly<{ status: 'invalid' }>; +// Review flushes local draft state and prepares an exact immutable template; +// it neither reserves a publication nor asks the extension to sign. +export async function reviewNewListing( + repository: PublicPublicationRepository, + controller: PublicDraftController, + readiness: NewListingReadiness, + command: unknown, + consent: unknown +): Promise<ListingReviewResult> { + try { + const custody = publicDraftControllerOwnership(controller), + owner = publicPublicationOwner(repository); + if ( + !custody || + !owner || + custody.repository !== publicPublicationDraftRepository(repository) + ) + return { status: 'blocked', reason: 'invalid_scope' }; + const id = canonicalLocalId(command); + if (!id) return { status: 'blocked', reason: 'invalid_command' }; + const ready = newListingReadinessOwnership(readiness); + if ( + !ready || + ready.owner !== owner || + !ready.current() || + consent !== 'reviewed_new_listing' + ) + return { status: 'blocked', reason: 'unavailable' }; + if (!(await flushPublicDraft(controller))) + return { status: 'blocked', reason: 'unavailable' }; + const snapshot = publicDraftControllerSnapshot(controller), + expected = snapshot?.draft; + if ( + !snapshot || + !expected || + expected.owner !== owner || + !custody.current(JSON.stringify(expected), snapshot.editVersion) + ) + return { status: 'blocked', reason: 'conflict' }; + const cached = commands.get(repository)?.get(id); + if (cached) { + const original = reviews.get(cached); + if ( + original && + original.controller === controller && + original.readiness === readiness && + JSON.stringify(original.expected) === JSON.stringify(expected) && + original.current() && + custody.current(JSON.stringify(expected), snapshot.editVersion) + ) { + return { status: 'review', review: cached }; + } + return { status: 'blocked', reason: 'conflict' }; + } + const identifier = newLocalId(), + createdAtSeconds = Math.floor(Date.now() / 1000); + if (!identifier) return { status: 'blocked', reason: 'unavailable' }; + const form = expected.form; + if (form.contactType === '' && form.contactValue !== '') + return { status: 'blocked', reason: 'invalid_form' }; + const contact = + form.contactType === '' + ? undefined + : { + type: form.contactType, + value: form.contactValue, + public: true as const + }; + const built = buildFoodTemplate({ + identifier, + title: form.title, + description: form.description, + location: form.location, + amount: form.amount, + currency: form.currency, + unit: form.unit, + ...(form.quantity === '' ? {} : { quantity: form.quantity }), + created_at: createdAtSeconds, + published_at: createdAtSeconds, + status: 'active', + ...(contact ? { contact } : {}) + }); + if (!built.ok) return { status: 'blocked', reason: 'invalid_form' }; + const manifest = readRelayPolicy(ready.policy), + targets = publicRelayTargets(ready.policy, 'write'); + const templateWire = JSON.stringify({ + pubkey: owner, + kind: 30402, + created_at: createdAtSeconds, + tags: built.wire_parts.tags, + content: built.wire_parts.content + }); + const template = inspectLocalTemplate(templateWire, owner, 30402); + if (!template || !manifest.postingEnabled || targets.length === 0) + return { status: 'blocked', reason: 'unavailable' }; + const digest = await crypto.subtle.digest( + 'SHA-256', + new TextEncoder().encode(JSON.stringify(manifest)) + ); + const policyFingerprint = Array.from(new Uint8Array(digest), (value) => + value.toString(16).padStart(2, '0') + ).join(''); + // Hashing is outside any IDB transaction; recheck original mutable owners. + if ( + !ready.current() || + publicPublicationOwner(repository) !== owner || + !custody.current(JSON.stringify(expected), snapshot.editVersion) + ) + return { status: 'blocked', reason: 'conflict' }; + // Another review may have completed while this one awaited hashing. The + // first retained command owns its ID/time/template; never replace it. + const racing = commands.get(repository)?.get(id); + if (racing) { + const original = reviews.get(racing); + if ( + original && + original.controller === controller && + original.readiness === readiness && + JSON.stringify(original.expected) === JSON.stringify(expected) && + original.current() && + custody.current(JSON.stringify(expected), snapshot.editVersion) + ) + return { status: 'review', review: racing }; + return { status: 'blocked', reason: 'conflict' }; + } + const admitted = decodePublicRecord( + JSON.stringify({ + schema: 1, + family: 'public_operation', + owner, + id, + revision: 0, + source: { type: 'draft', id: expected.id, revision: expected.revision }, + capture: { + kind: 30402, + wire: templateWire, + hash: template.hash, + targets, + policyFingerprint + }, + artifact: null, + receipts: [] + }), + owner, + id + ); + if (!admitted.ok) return { status: 'blocked', reason: 'invalid_form' }; + const review = Object.freeze({}) as ListingReview; + reviews.set(review, { + repository, + controller, + expected, + editVersion: snapshot.editVersion, + command: id, + readiness, + record: admitted.value, + previewWire: JSON.stringify({ + owner, + command: id, + draftId: expected.id, + draftRevision: expected.revision, + identifier, + createdAtSeconds, + form, + summary: built.summary, + templateWire, + expectedHash: template.hash, + targets, + policyFingerprint + }), + current: () => + ready.current() && publicPublicationOwner(repository) === owner + }); + const cache = commands.get(repository) ?? new Map<string, ListingReview>(); + cache.set(id, review); + commands.set(repository, cache); + return { status: 'review', review }; + } catch { + return { status: 'blocked', reason: 'unavailable' }; + } +} +export function listingReviewSnapshot( + review: ListingReview +): ListingPreview | undefined { + const value = reviews.get(review); + return value ? (JSON.parse(value.previewWire) as ListingPreview) : undefined; +} +// One original review deduplicates simultaneous clicks. Failed/uncertain work +// remains the same capture for later explicit retry; no fresh ID/time/template. +export function reserveNewListing( + review: ListingReview, + consent: unknown +): Promise<ListingReservation> { + const value = reviews.get(review); + if (!value || consent !== 'publish_reviewed_listing') + return Promise.resolve({ status: 'invalid' }); + const active = activeReservations.get(review); + if (active) return active; + const work = savePublicListingIntent( + value.repository, + value.controller, + value.record, + value.expected, + value.editVersion, + value.command, + value.current + ).finally(() => { + if (activeReservations.get(review) === work) + activeReservations.delete(review); + }); + activeReservations.set(review, work); + return work; +} diff --git a/web/tests/e2e/harness/prepare-listing.ts b/web/tests/e2e/harness/prepare-listing.ts @@ -0,0 +1,507 @@ +import { + reviewNewListing, + listingReviewSnapshot, + reserveNewListing +} from '../../../src/lib/publishing/prepare-listing.ts'; +import { + createPublicPublicationRepository, + publicPublicationDraftRepository, + readPublicListingIntent +} from '../../../src/lib/persistence/public-publications.ts'; +import { captureNewListingReadiness } from '../../../src/lib/publishing/new-listing-readiness.ts'; +import { + createInboxSetupView, + checkInboxSetupView, + unlockInboxSetupView, + stopInboxSetupView, + closeInboxSetupView +} from '../../../src/lib/messaging/inbox-setup-view.ts'; +import { + openBrowserDatabase, + closeBrowserDatabase, + browserDatabaseTransaction +} from '../../../src/lib/persistence/database.ts'; +import { + createPublicDraftController, + editPublicDraft, + flushPublicDraft, + publicDraftControllerSnapshot, + closePublicDraftController +} from '../../../src/lib/publishing/draft-controller.ts'; +import { publicRecordSnapshot } from '../../../src/lib/persistence/records.ts'; +import { inspectLocalTemplate } from '../../../src/lib/nostr/local-template.ts'; +import { makeSetupFixture, fixturePolicy, inbox } from './inbox-setup.ts'; +export async function createFixture() { + const f = await makeSetupFixture([['relay', inbox]]); + // HC_TEST_ONLY_QUALIFICATION_PORT: genuine original owners with exercised + // controlled observations, never actual operator/relay qualification. + const setup = createInboxSetupView({ + identity: f.identity, + policy: fixturePolicy(), + lookup: () => Promise.resolve(f.resolve().resolver), + observeAccess: (context) => ({ + ...context, + readTargets: context.readTargets.slice(), + archiveTargets: context.archiveTargets.slice(), + receive: 'qualified_exercised', + archive: 'qualified_exercised', + current: () => true + }) + }); + if (!setup) throw Error('original setup missing'); + await checkInboxSetupView(setup); + await unlockInboxSetupView(setup); + const ready = captureNewListingReadiness( + f.identity, + setup, + 'reviewed_new_listing_inbox' + ); + if (!ready) throw Error('original readiness missing'); + const originalReady = ready; + const opened = await openBrowserDatabase(); + if (opened.state !== 'ready') throw Error(opened.reason); + const database = opened.owner; + const repository = createPublicPublicationRepository(database, f.owner); + const drafts = repository && publicPublicationDraftRepository(repository); + if (!repository || !drafts) + throw Error('original publication repository missing'); + const originalRepository = repository; + const form = { + title: 'Carrots', + description: 'First complete description', + location: 'Local farm', + amount: '2', + currency: 'USD', + unit: 'kg', + quantity: '', + contactType: '' as const, + contactValue: '' + }; + const controller = await createPublicDraftController(drafts, form); + if (!controller) throw Error('original controller missing'); + const originalController = controller; + const command = '3d030bf5-901d-45e1-8251-41cbdf805e96'; + async function review() { + const result = await reviewNewListing( + originalRepository, + originalController, + originalReady, + command, + 'reviewed_new_listing' + ); + if (result.status !== 'review') throw Error(result.reason); + return result.review; + } + function operations(): Promise<number> { + return new Promise((resolve, reject) => { + const tx = browserDatabaseTransaction( + database, + ['public_operations'], + 'readonly' + ); + const count = tx + .objectStore('public_operations') + .index('by_owner') + .count(IDBKeyRange.only(f.owner)); + tx.addEventListener('complete', () => resolve(count.result)); + tx.addEventListener('abort', () => reject(Error('actual count aborted'))); + }); + } + return { + async unknown(mode: 'exact' | 'unavailable' | 'mismatch') { + const original = await review(), + preview = listingReviewSnapshot(original); + if (!preview) throw Error('original preview missing'); + const put = Object.getOwnPropertyDescriptor( + IDBObjectStore.prototype, + 'put' + ), + abort = Object.getOwnPropertyDescriptor( + IDBTransaction.prototype, + 'abort' + ), + get = Object.getOwnPropertyDescriptor(IDBObjectStore.prototype, 'get'); + if (!put || !abort || !get) throw Error('native descriptors missing'); + const nativePut = put.value as IDBObjectStore['put'], + nativeGet = get.value as IDBObjectStore['get']; + let nativePuts = 0; + const different = JSON.parse(preview.templateWire) as { + pubkey: string; + kind: number; + created_at: number; + tags: string[][]; + content: string; + }; + different.tags = different.tags.map((tag) => + tag[0] === 'd' ? ['d', 'f04a1fd7-e3c7-4e75-8949-4fdc8a6b2246'] : tag + ); + const wire = JSON.stringify(different), + template = inspectLocalTemplate(wire, f.owner, 30402); + if (!template) throw Error('actual changed template invalid'); + const changed = { + schema: 1, + family: 'public_operation', + owner: f.owner, + id: command, + revision: 0, + source: { + type: 'draft', + id: preview.draftId, + revision: preview.draftRevision + }, + capture: { + kind: 30402, + wire, + hash: template.hash, + targets: preview.targets, + policyFingerprint: preview.policyFingerprint + }, + artifact: null, + receipts: [] + }; + Object.defineProperty(IDBObjectStore.prototype, 'put', { + ...put, + value: function ( + this: IDBObjectStore, + ...args: Parameters<IDBObjectStore['put']> + ) { + const request = nativePut.apply(this, args); + if (this.name === 'public_operations') nativePuts++; + if (this.name === 'public_operations' && nativePuts === 1) { + if (mode === 'mismatch') + request.addEventListener('success', () => { + nativePut.call(this, { + owner: f.owner, + id: command, + wire: JSON.stringify(changed) + }); + nativePuts++; + }); + throw Error( + 'HC_TEST_ONLY lost acknowledgement after actual native put' + ); + } + return request; + } + }); + Object.defineProperty(IDBTransaction.prototype, 'abort', { + ...abort, + value() { + throw Error('HC_TEST_ONLY unavailable abort channel'); + } + }); + if (mode === 'unavailable') + Object.defineProperty(IDBObjectStore.prototype, 'get', { + ...get, + value: function ( + this: IDBObjectStore, + ...args: Parameters<IDBObjectStore['get']> + ) { + if (this.name === 'public_operations') + throw new DOMException( + 'HC_TEST_ONLY read setup unavailable', + 'InvalidStateError' + ); + return nativeGet.apply(this, args); + } + }); + let result; + try { + result = await reserveNewListing(original, 'publish_reviewed_listing'); + } finally { + Object.defineProperty(IDBObjectStore.prototype, 'put', put); + Object.defineProperty(IDBTransaction.prototype, 'abort', abort); + Object.defineProperty(IDBObjectStore.prototype, 'get', get); + } + const observed = await readPublicListingIntent( + originalRepository, + command + ); + const row = + observed.status === 'found' + ? publicRecordSnapshot(observed.record, f.owner, command) + : undefined; + Object.defineProperty(IDBObjectStore.prototype, 'put', { + ...put, + value: function ( + this: IDBObjectStore, + ...args: Parameters<IDBObjectStore['put']> + ) { + if (this.name === 'public_operations') nativePuts++; + return nativePut.apply(this, args); + } + }); + let retry; + try { + retry = await reserveNewListing(original, 'publish_reviewed_listing'); + } finally { + Object.defineProperty(IDBObjectStore.prototype, 'put', put); + } + return { + status: result.status, + nativePuts, + originalCapture: + row?.family === 'public_operation' && + row.source.type === 'draft' && + row.source.id === preview.draftId && + row.source.revision === preview.draftRevision && + row.capture.wire === preview.templateWire && + row.capture.hash === preview.expectedHash && + JSON.stringify(row.capture.targets) === + JSON.stringify(preview.targets) && + row.capture.policyFingerprint === preview.policyFingerprint && + listingReviewSnapshot(original)?.identifier === preview.identifier, + operations: await operations(), + retry: retry.status, + signatures: f.counts().signs + }; + }, + async failedRead() { + const descriptor = Object.getOwnPropertyDescriptor( + IDBObjectStore.prototype, + 'get' + ); + if (!descriptor) throw Error('native get descriptor missing'); + Object.defineProperty(IDBObjectStore.prototype, 'get', { + ...descriptor, + value() { + throw new DOMException( + 'HC_TEST_ONLY native read setup failure', + 'InvalidStateError' + ); + } + }); + let status: string; + try { + status = (await readPublicListingIntent(originalRepository, command)) + .status; + } catch { + status = 'rejected'; + } finally { + Object.defineProperty(IDBObjectStore.prototype, 'get', descriptor); + } + return { + status, + operations: await operations(), + signatures: f.counts().signs + }; + }, + async concurrentReviews() { + const [first, second] = await Promise.all([review(), review()]); + const firstPreview = listingReviewSnapshot(first), + secondPreview = listingReviewSnapshot(second); + const firstSave = await reserveNewListing( + first, + 'publish_reviewed_listing' + ); + const secondSave = await reserveNewListing( + second, + 'publish_reviewed_listing' + ); + return { + sameReview: first === second, + sameTemplate: + firstPreview?.templateWire === secondPreview?.templateWire, + first: firstSave.status, + second: secondSave.status, + operations: await operations(), + signatures: f.counts().signs + }; + }, + async doubleSubmit() { + const original = await review(), + preview = listingReviewSnapshot(original); + if (!preview) throw Error('preview missing'); + const first = reserveNewListing(original, 'publish_reviewed_listing'), + second = reserveNewListing(original, 'publish_reviewed_listing'); + const samePromise = first === second; + const results = await Promise.all([first, second]); + if (results[0].status !== 'saved' || results[1].status !== 'saved') + throw Error('original double submit did not save'); + const repeatedReview = await review(); + const repeatedPreview = listingReviewSnapshot(repeatedReview); + const repeated = await reserveNewListing( + repeatedReview, + 'publish_reviewed_listing' + ); + editPublicDraft(controller, { + ...form, + description: 'Changed future description' + }); + await flushPublicDraft(controller); + const retry = await reserveNewListing( + original, + 'publish_reviewed_listing' + ); + const stored = + retry.status === 'existing' + ? publicRecordSnapshot(retry.record, f.owner, command) + : undefined; + return { + same: samePromise && results[0].record === results[1].record, + repeatReview: repeated.status, + repeatCaptureUnchanged: + repeatedPreview?.identifier === preview.identifier && + repeatedPreview?.createdAtSeconds === preview.createdAtSeconds && + repeatedPreview?.expectedHash === preview.expectedHash, + operations: await operations(), + futureCaptureUnchanged: + stored?.family === 'public_operation' && + stored.capture.wire === preview.templateWire && + listingReviewSnapshot(original)?.templateWire === + preview.templateWire, + retry: retry.status, + signatures: f.counts().signs + }; + }, + async commandConflict() { + const original = await review(), + before = listingReviewSnapshot(original); + if (!before) throw Error('preview missing'); + const saved = await reserveNewListing( + original, + 'publish_reviewed_listing' + ); + if (saved.status !== 'saved') throw Error('original save missing'); + editPublicDraft(controller, { ...form, title: 'Different carrots' }); + const other = await reviewNewListing( + originalRepository, + originalController, + originalReady, + command, + 'reviewed_new_listing' + ); + const conflict = + other.status === 'blocked' + ? { status: other.reason } + : await reserveNewListing(other.review, 'publish_reviewed_listing'); + return { + conflict: conflict.status, + identifierRandom: + /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test( + before.identifier + ) && !before.identifier.includes(form.title), + identifierStable: + listingReviewSnapshot(original)?.identifier === before.identifier, + operations: await operations(), + signatures: f.counts().signs + }; + }, + async exactRevision() { + await flushPublicDraft(controller); + editPublicDraft(controller, { + ...form, + description: 'Second complete description' + }); + const original = await review(), + preview = listingReviewSnapshot(original), + savedDraft = publicDraftControllerSnapshot(controller)?.draft; + if (!preview || !savedDraft) throw Error('exact draft missing'); + const targets = preview.targets.slice(); + (preview.targets as string[]).push('wss://unapproved.foodtrace.net'); + const result = await reserveNewListing( + original, + 'publish_reviewed_listing' + ); + if (result.status !== 'saved') throw Error('exact reservation failed'); + const row = publicRecordSnapshot(result.record, f.owner, command); + return { + exact: + row?.family === 'public_operation' && + row.source.type === 'draft' && + row.source.id === savedDraft.id && + row.source.revision === savedDraft.revision && + savedDraft.revision === 1 && + row.capture.hash === preview.expectedHash && + row.owner === f.owner && + row.capture.wire === preview.templateWire, + description: savedDraft.form.description, + targetsFrozen: + row?.family === 'public_operation' && + JSON.stringify(row.capture.targets) === JSON.stringify(targets), + signatures: f.counts().signs + }; + }, + async stale() { + const original = await review(), + saved = publicDraftControllerSnapshot(controller)?.draft; + if (!saved) throw Error('saved draft missing'); + const other = await createPublicDraftController(drafts, form, saved.id); + if (!other) throw Error('other original controller missing'); + editPublicDraft(other, { + ...form, + description: 'Actual other tab revision' + }); + await flushPublicDraft(other); + const changedDraft = await reserveNewListing( + original, + 'publish_reviewed_listing' + ); + closePublicDraftController(other); + stopInboxSetupView(setup); + const retired = await reserveNewListing( + original, + 'publish_reviewed_listing' + ); + return { + changedDraft: changedDraft.status, + retired: retired.status, + operations: await operations(), + signatures: f.counts().signs + }; + }, + async abort() { + const original = await review(), + preview = listingReviewSnapshot(original); + const descriptor = Object.getOwnPropertyDescriptor( + IDBObjectStore.prototype, + 'put' + ); + if (!descriptor) throw Error('native put descriptor missing'); + const nativePut = descriptor.value as IDBObjectStore['put']; + let armed = true; + IDBObjectStore.prototype.put = function ( + ...args: Parameters<typeof nativePut> + ) { + const request = nativePut.apply(this, args); + if (armed && this.name === 'public_operations') { + armed = false; + request.addEventListener('success', () => this.transaction.abort()); + } + return request; + }; + let result; + try { + result = await reserveNewListing(original, 'publish_reviewed_listing'); + } finally { + Object.defineProperty(IDBObjectStore.prototype, 'put', descriptor); + } + const beforeRetry = await operations(); + const retry = await reserveNewListing( + original, + 'publish_reviewed_listing' + ); + const row = + retry.status === 'saved' + ? publicRecordSnapshot(retry.record, f.owner, command) + : undefined; + return { + aborted: result.status, + beforeRetry, + retry: retry.status, + operations: await operations(), + originalCapture: + row?.family === 'public_operation' && + row.capture.wire === preview?.templateWire && + row.capture.hash === preview?.expectedHash, + signatures: f.counts().signs + }; + }, + close() { + closePublicDraftController(controller); + closeInboxSetupView(setup); + closeBrowserDatabase(database); + f.close(); + } + }; +} diff --git a/web/tests/e2e/prepare-listing.spec.ts b/web/tests/e2e/prepare-listing.spec.ts @@ -0,0 +1,167 @@ +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/prepare-listing.ts'; +declare global { + interface Window { + hcp110: typeof Fixture; + hcp110Fixture: 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/prepare-listing.ts', import.meta.url) + ), + name: 'hcp110', + 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 }); + await page.evaluate(async () => { + window.hcp110Fixture = await window.hcp110.createFixture(); + }); +}); +test.afterEach(async ({ page }) => { + if (!page.isClosed()) + await page.evaluate(() => window.hcp110Fixture?.close()); +}); + +test('HCP110 double submit retains one immutable intent and future edits cannot replace it', async ({ + page +}) => { + const result = await page.evaluate(() => window.hcp110Fixture.doubleSubmit()); + expect(result.same).toBe(true); + expect(result.repeatReview).toBe('existing'); + expect(result.repeatCaptureUnchanged).toBe(true); + expect(result.operations).toBe(1); + expect(result.futureCaptureUnchanged).toBe(true); + expect(result.retry).toBe('existing'); + expect(result.signatures).toBe(0); +}); +test('HCP110 concurrent original reviews retain one command capture across asynchronous hashing', async ({ + page +}) => { + const result = await page.evaluate(() => + window.hcp110Fixture.concurrentReviews() + ); + expect(result.sameReview).toBe(true); + expect(result.sameTemplate).toBe(true); + expect(result.first).toBe('saved'); + expect(result.second).toBe('existing'); + expect(result.operations).toBe(1); + expect(result.signatures).toBe(0); +}); +test('HCP110 actual committed intent with lost acknowledgement reconciles exact original capture without another write', async ({ + page +}) => { + const result = await page.evaluate(() => + window.hcp110Fixture.unknown('exact') + ); + expect(result.status).toBe('existing'); + expect(result.nativePuts).toBe(1); + expect(result.originalCapture).toBe(true); + expect(result.operations).toBe(1); + expect(result.retry).toBe('existing'); + expect(result.signatures).toBe(0); +}); +test('HCP110 failed native readback preserves original unknown completion before explicit retry', async ({ + page +}) => { + const result = await page.evaluate(() => + window.hcp110Fixture.unknown('unavailable') + ); + expect(result.status).toBe('unknown_completion'); + expect(result.nativePuts).toBe(1); + expect(result.originalCapture).toBe(true); + expect(result.operations).toBe(1); + expect(result.retry).toBe('existing'); + expect(result.signatures).toBe(0); +}); +test('HCP110 actual mismatched readback refuses the original command without adopting another capture', async ({ + page +}) => { + const result = await page.evaluate(() => + window.hcp110Fixture.unknown('mismatch') + ); + expect(result.status).toBe('conflict'); + expect(result.originalCapture).toBe(false); + expect(result.nativePuts).toBe(2); + expect(result.operations).toBe(1); + expect(result.retry).toBe('conflict'); + expect(result.signatures).toBe(0); +}); +test('HCP110 native read request setup failure resolves typed unavailable without writes', async ({ + page +}) => { + const result = await page.evaluate(() => window.hcp110Fixture.failedRead()); + expect(result.status).toBe('unavailable'); + expect(result.operations).toBe(0); + expect(result.signatures).toBe(0); +}); + +test('HCP110 changing the same command conflicts and a random listing identifier is independent of title', async ({ + page +}) => { + const result = await page.evaluate(() => + window.hcp110Fixture.commandConflict() + ); + expect(result.conflict).toBe('conflict'); + expect(result.identifierRandom).toBe(true); + expect(result.identifierStable).toBe(true); + expect(result.operations).toBe(1); + expect(result.signatures).toBe(0); +}); + +test('HCP110 exact acknowledged draft revision and original frozen destinations are reserved', async ({ + page +}) => { + const result = await page.evaluate(() => + window.hcp110Fixture.exactRevision() + ); + expect(result.exact).toBe(true); + expect(result.description).toBe('Second complete description'); + expect(result.targetsFrozen).toBe(true); + expect(result.signatures).toBe(0); +}); + +test('HCP110 stale draft revision or original readiness retirement cannot reserve a new intent', async ({ + page +}) => { + const result = await page.evaluate(() => window.hcp110Fixture.stale()); + expect(result.changedDraft).toBe('conflict'); + expect(result.retired).toBe('unavailable'); + expect(result.operations).toBe(0); + expect(result.signatures).toBe(0); +}); + +test('HCP110 actual transaction abort creates no operation and original explicit retry reconciles the same capture', async ({ + page +}) => { + const result = await page.evaluate(() => window.hcp110Fixture.abort()); + expect(result.aborted).toBe('aborted'); + expect(result.beforeRetry).toBe(0); + expect(result.retry).toBe('saved'); + expect(result.operations).toBe(1); + expect(result.originalCapture).toBe(true); + expect(result.signatures).toBe(0); +}); diff --git a/web/tests/unit/prepare-listing.test.ts b/web/tests/unit/prepare-listing.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from 'vitest'; +import { + reviewNewListing, + listingReviewSnapshot, + reserveNewListing, + type ListingReview +} from '../../src/lib/publishing/prepare-listing.ts'; +import { + createPublicPublicationRepository, + publicPublicationDraftRepository, + type PublicPublicationRepository +} from '../../src/lib/persistence/public-publications.ts'; +import type { BrowserDatabase } from '../../src/lib/persistence/database.ts'; +import type { PublicDraftController } from '../../src/lib/publishing/draft-controller.ts'; +import type { NewListingReadiness } from '../../src/lib/publishing/new-listing-readiness.ts'; + +describe('HCP110 immutable public listing intent admission', () => { + it('SSR and copied database cannot acquire a publication repository', () => { + expect( + createPublicPublicationRepository({} as BrowserDatabase, '0'.repeat(64)) + ).toBeUndefined(); + }); + it('copied repository cannot expose an original draft repository', () => { + expect( + publicPublicationDraftRepository({} as PublicPublicationRepository) + ).toBeUndefined(); + }); + it('copied controller/readiness cannot prepare an intent', async () => { + expect( + await reviewNewListing( + {} as PublicPublicationRepository, + {} as PublicDraftController, + {} as NewListingReadiness, + '3d030bf5-901d-45e1-8251-41cbdf805e96', + 'reviewed_new_listing' + ) + ).toEqual({ status: 'blocked', reason: 'invalid_scope' }); + }); + it('copied review and boolean consent cannot reserve or reveal a template', async () => { + const copied = {} as ListingReview; + expect(listingReviewSnapshot(copied)).toBeUndefined(); + expect(await reserveNewListing(copied, true)).toEqual({ + status: 'invalid' + }); + }); +});