app

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

commit c308a5f7d60dfae874957da9dc60327f61dafc0d
parent c18902ab68335fa0607a9acd8c06b106ed032219
Author: triesap <tyson@radroots.org>
Date:   Wed,  7 Oct 2026 16:26:33 +0000

harvestcircle: reserve stable private send identities

- Bind reviewed commands to genuine current owner and immutable rumor plans
- Commit metadata only through owner locks and atomic IndexedDB completion
- Reject tuple changes and same-second collisions without future timestamps
- Verify reservation bounds, concurrent tabs, retries, aborts and preservation

Diffstat:
Aweb/src/lib/messaging/send-identity.ts | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/src/lib/persistence/private-send-reservations.ts | 279+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/harness/private-send-reservations.ts | 165+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/private-send-reservations.spec.ts | 385+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/unit/private-send-reservations.test.ts | 113+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5 files changed, 1054 insertions(+), 0 deletions(-)

diff --git a/web/src/lib/messaging/send-identity.ts b/web/src/lib/messaging/send-identity.ts @@ -0,0 +1,112 @@ +import { canonicalLocalId } from '../private-handles.ts'; +import { safeUnsignedInteger } from '../nostr/envelope-bounds.ts'; +import { + identityMessagingOwnership, + type IdentitySession +} from '../runtime/identity-session.ts'; +import { rumorPlanSnapshot, type RumorPlan } from './rumor-plan.ts'; +import { + privateSendReservationOwner, + reservePrivateSendReservation, + type PrivateSendReservationRepository, + type PrivateSendReservation, + type ReservationFailure +} from '../persistence/private-send-reservations.ts'; +declare const reservedBrand: unique symbol; +export type ReservedSendIdentity = Readonly<{ [reservedBrand]: true }>; +export type SendIdentityResult = + | Readonly<{ + status: 'reserved' | 'existing'; + identity: ReservedSendIdentity; + }> + | Readonly<{ status: ReservationFailure | 'busy' }>; +type Controller = { + record: PrivateSendReservation; + plan: RumorPlan; + current(): boolean; +}; +const identities = new WeakMap<ReservedSendIdentity, Controller>(); +// Explicit reviewed local reservation only. No plaintext persistence or SDK +// effect; later owners revalidate this identity before encryption/preparation. +export async function reserveSendIdentity( + repository: PrivateSendReservationRepository, + session: IdentitySession, + commandId: unknown, + plan: RumorPlan, + review: unknown +): Promise<SendIdentityResult> { + const id = canonicalLocalId(commandId), + ownership = identityMessagingOwnership(session), + snapshot = rumorPlanSnapshot(plan); + if (review !== 'reviewed_private_intent' || !id) return { status: 'invalid' }; + if (!ownership || !ownership.current() || !snapshot) + return { status: 'stopped' }; + if ( + snapshot.owner !== ownership.owner || + privateSendReservationOwner(repository) !== ownership.owner + ) + return { status: 'invalid_scope' }; + const captured = { + schema: 1 as const, + family: 'private_send_reservation' as const, + owner: ownership.owner, + id, + revision: 0 as const, + peer: snapshot.peer, + rumorHash: snapshot.id, + createdAt: snapshot.createdAt + }; + const current = () => { + const observed = rumorPlanSnapshot(plan); + return ( + ownership.current() && + observed?.owner === captured.owner && + observed.peer === captured.peer && + observed.id === captured.rumorHash + ); + }; + try { + if (typeof window === 'undefined' || !navigator.locks?.request) + return { status: 'unavailable' }; + return await navigator.locks.request( + 'harvestcircle:owner:' + captured.owner, + { mode: 'exclusive', ifAvailable: true }, + async (lock): Promise<SendIdentityResult> => { + if (!lock) return { status: 'busy' }; + if (!current()) return { status: 'stopped' }; + const milliseconds = safeUnsignedInteger(Date.now()); + if (milliseconds === undefined) return { status: 'clock_conflict' }; + const result = await reservePrivateSendReservation( + repository, + JSON.stringify(captured), + Math.floor(milliseconds / 1000), + current + ); + if (!result.ok) return { status: result.reason }; + if (!current()) return { status: 'stopped' }; + const identity = Object.freeze({}) as ReservedSendIdentity; + identities.set(identity, { record: result.value, plan, current }); + return { + status: result.state === 'created' ? 'reserved' : 'existing', + identity + }; + } + ); + } catch { + return { status: 'unavailable' }; + } +} +export function reservedSendSnapshot( + identity: ReservedSendIdentity +): PrivateSendReservation | undefined { + const value = identities.get(identity); + return value?.current() ? { ...value.record } : undefined; +} +// Internal memory-only input to future encryption. A detached wire/snapshot is +// neither reserved identity nor effect permission and cannot retarget a send. +export function reservedSendRumorWire( + identity: ReservedSendIdentity +): string | undefined { + const value = identities.get(identity); + return value?.current() ? rumorPlanSnapshot(value.plan)?.wire : undefined; +} diff --git a/web/src/lib/persistence/private-send-reservations.ts b/web/src/lib/persistence/private-send-reservations.ts @@ -0,0 +1,279 @@ +import { canonicalPublicKey } from '../contracts/public-key.ts'; +import { exactLocalFields } from '../contracts/local-records.ts'; +import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts'; +import { canonicalLocalId } from '../private-handles.ts'; +import { safeUnsignedInteger } from '../nostr/envelope-bounds.ts'; +import { LOCAL_PERSISTENCE_BUDGETS } from '../config/budgets.ts'; +import { + browserDatabaseState, + browserDatabaseTransaction, + type BrowserDatabase +} from './database.ts'; +export type PrivateSendReservation = Readonly<{ + schema: 1; + family: 'private_send_reservation'; + owner: string; + id: string; + revision: 0; + peer: string; + rumorHash: string; + createdAt: number; +}>; +declare const repositoryBrand: unique symbol; +export type PrivateSendReservationRepository = Readonly<{ + [repositoryBrand]: true; +}>; +export type ReservationFailure = + | 'invalid' + | 'invalid_scope' + | 'unavailable' + | 'aborted' + | 'unknown_completion' + | 'corrupt_record' + | 'capacity' + | 'conflict' + | 'clock_conflict' + | 'stopped'; +export type ReservationResult = + | Readonly<{ + ok: true; + state: 'created' | 'existing'; + value: PrivateSendReservation; + }> + | Readonly<{ ok: false; reason: ReservationFailure }>; +type Scope = { database: BrowserDatabase; owner: string }; +const repositories = new WeakMap<PrivateSendReservationRepository, Scope>(); +const failed = (reason: ReservationFailure): ReservationResult => ({ + ok: false, + reason +}); +// Metadata only, never a plaintext/private-draft or encrypted-send decoder. +// Future paired-ciphertext/recovery families retain their own admission owner. +export function inspectPrivateSendReservation( + raw: unknown, + expectedOwner: unknown, + expectedId: unknown +): PrivateSendReservation | undefined { + const owner = canonicalPublicKey(expectedOwner), + id = canonicalLocalId(expectedId); + if (!owner || !id || typeof raw !== 'string' || !boundedUtf8(raw, 4096)) + return undefined; + try { + const value: unknown = JSON.parse(raw); + if ( + !exactLocalFields(value, [ + 'schema', + 'family', + 'owner', + 'id', + 'revision', + 'peer', + 'rumorHash', + 'createdAt' + ]) || + value.schema !== 1 || + value.family !== 'private_send_reservation' || + value.owner !== owner || + value.id !== id || + value.revision !== 0 + ) + return undefined; + const peer = canonicalPublicKey(value.peer), + createdAt = safeUnsignedInteger(value.createdAt); + if ( + !peer || + peer === owner || + createdAt === undefined || + typeof value.rumorHash !== 'string' || + !/^[0-9a-f]{64}$/.test(value.rumorHash) + ) + return undefined; + return { + schema: 1, + family: 'private_send_reservation', + owner, + id, + revision: 0, + peer, + rumorHash: value.rumorHash, + createdAt + }; + } catch { + return undefined; + } +} +export function createPrivateSendReservationRepository( + database: BrowserDatabase, + expectedOwner: unknown +): PrivateSendReservationRepository | undefined { + const owner = canonicalPublicKey(expectedOwner); + try { + if (!owner || browserDatabaseState(database).state !== 'ready') + return undefined; + const token = Object.freeze({}) as PrivateSendReservationRepository; + repositories.set(token, { database, owner }); + return token; + } catch { + return undefined; + } +} +export function privateSendReservationOwner( + repository: PrivateSendReservationRepository +) { + return repositories.get(repository)?.owner; +} +// Atomic local metadata CAS, not identity, signing, encryption, relay delivery +// or global uniqueness proof. Completion, never request success, grants credit. +export function reservePrivateSendReservation( + repository: PrivateSendReservationRepository, + rawReservation: unknown, + observedSeconds: unknown, + current: () => boolean +): Promise<ReservationResult> { + const scope = repositories.get(repository); + if ( + !scope || + typeof rawReservation !== 'string' || + typeof current !== 'function' + ) + return Promise.resolve(failed('invalid')); + let candidateId: unknown; + try { + if (!boundedUtf8(rawReservation, 4096)) + return Promise.resolve(failed('invalid')); + const input: unknown = JSON.parse(rawReservation); + if (typeof input !== 'object' || input === null || Array.isArray(input)) + return Promise.resolve(failed('invalid')); + candidateId = (input as Record<string, unknown>).id; + } catch { + return Promise.resolve(failed('invalid')); + } + const candidate = inspectPrivateSendReservation( + rawReservation, + scope.owner, + candidateId + ), + seconds = safeUnsignedInteger(observedSeconds); + if (!candidate || seconds === undefined) + return Promise.resolve(failed('invalid')); + const wire = JSON.stringify(candidate), + next = { owner: scope.owner, id: candidate.id, wire }; + let transaction: IDBTransaction; + try { + transaction = browserDatabaseTransaction( + scope.database, + ['private_sends'], + 'readwrite' + ); + } catch { + return Promise.resolve(failed('unavailable')); + } + return new Promise((resolve) => { + let outcome: ReservationResult | undefined; + let existing: PrivateSendReservation | undefined; + let count = 0, + bytes = 0, + collision = false; + function refuse(reason: ReservationFailure) { + outcome = failed(reason); + try { + transaction.abort(); + } catch { + outcome = failed('unknown_completion'); + } + } + transaction.addEventListener('complete', () => + resolve(outcome ?? failed('unknown_completion')) + ); + transaction.addEventListener('abort', () => + resolve(outcome && !outcome.ok ? outcome : failed('aborted')) + ); + try { + const store = transaction.objectStore('private_sends'); + const request = store + .index('by_owner') + .openCursor(IDBKeyRange.only(scope.owner)); + request.addEventListener('success', () => { + try { + if (!current()) { + refuse('stopped'); + return; + } + const cursor = request.result; + if (cursor) { + const key = cursor.primaryKey, + id = + Array.isArray(key) && key.length === 2 && key[0] === scope.owner + ? canonicalLocalId(key[1]) + : undefined; + const row: unknown = cursor.value; + if ( + !id || + !exactLocalFields(row, ['owner', 'id', 'wire']) || + row.owner !== scope.owner || + row.id !== id || + typeof row.wire !== 'string' + ) { + refuse('corrupt_record'); + return; + } + const value = inspectPrivateSendReservation( + row.wire, + scope.owner, + id + ); + if (!value) { + refuse('corrupt_record'); + return; + } + count += 1; + if (value.id === candidate.id) existing = value; + if (value.rumorHash === candidate.rumorHash) collision = true; + bytes += new TextEncoder().encode(JSON.stringify(row)).length; + if ( + count > LOCAL_PERSISTENCE_BUDGETS.unfinishedPrivateSends || + bytes > LOCAL_PERSISTENCE_BUDGETS.privateSendBytes + ) { + refuse('capacity'); + return; + } + cursor.continue(); + return; + } + if (existing) { + if (JSON.stringify(existing) !== wire) { + refuse('conflict'); + return; + } + outcome = { ok: true, state: 'existing', value: existing }; + return; + } + if (candidate.createdAt !== seconds || collision) { + refuse('clock_conflict'); + return; + } + if ( + count >= LOCAL_PERSISTENCE_BUDGETS.unfinishedPrivateSends || + bytes + new TextEncoder().encode(JSON.stringify(next)).length > + LOCAL_PERSISTENCE_BUDGETS.privateSendBytes + ) { + refuse('capacity'); + return; + } + if (!current()) { + refuse('stopped'); + return; + } + // The owner cursor proved this key absent in the same readwrite + // transaction; put cannot replace another concurrent reservation. + store.put(next); + outcome = { ok: true, state: 'created', value: candidate }; + } catch { + refuse('aborted'); + } + }); + } catch { + refuse('aborted'); + } + }); +} diff --git a/web/tests/e2e/harness/private-send-reservations.ts b/web/tests/e2e/harness/private-send-reservations.ts @@ -0,0 +1,165 @@ +import { finalizeEvent, type NostrEvent } from 'applesauce-core/helpers'; +import { verifyEnvelope } from '../../../src/lib/nostr/verified-envelope.ts'; +import { captureEnquiryContext } from '../../../src/lib/messaging/enquiry-context.ts'; +import { + captureEnquiryRumor, + type RumorPlan +} from '../../../src/lib/messaging/rumor-plan.ts'; +import { + openBrowserDatabase, + closeBrowserDatabase, + browserDatabaseTransaction +} from '../../../src/lib/persistence/database.ts'; +import { + createIdentitySession, + connectIdentity, + probeIdentityMessaging, + disconnectIdentity +} from '../../../src/lib/runtime/identity-session.ts'; +import { createPrivateSendReservationRepository } from '../../../src/lib/persistence/private-send-reservations.ts'; +import { + reserveSendIdentity, + reservedSendSnapshot, + reservedSendRumorWire +} from '../../../src/lib/messaging/send-identity.ts'; +export { reserveSendIdentity, reservedSendSnapshot, reservedSendRumorWire }; +export const owner = + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'; +export const command = '12345678-1234-4234-8234-123456789abc'; +export type Shared = { event: NostrEvent; milliseconds: number }; +// Controlled source-only clock/provider fixtures; real browser IDB/WebLocks, +// never installed extensions, cryptographic messaging or real clock Q evidence. +export async function makeFixture(shared?: Shared) { + const previousNow = Date.now; + let milliseconds = shared?.milliseconds ?? previousNow(), + signs = 0, + encrypts = 0, + decrypts = 0; + Date.now = () => milliseconds; + function publicFood() { + const key = crypto.getRandomValues(new Uint8Array(32)); + try { + return finalizeEvent( + { + kind: 30402, + created_at: 1700000060, + content: 'Public carrots', + tags: [ + ['d', 'carrots'], + ['title', 'Carrots'], + ['summary', 'Fresh carrots'], + ['published_at', '1700000000'], + ['location', 'Victoria'], + ['price', '3.5', 'CAD'], + ['radroots:price_unit', 'lb'], + ['status', 'active'] + ] + }, + key + ); + } finally { + key.fill(0); + } + } + const event = shared?.event ?? publicFood(), + proof = verifyEnvelope(JSON.stringify(event)); + if (!proof.ok) throw Error('invalid public source fixture'); + const context = captureEnquiryContext(proof.value); + if (!context) throw Error('invalid Food context'); + const capturedContext = context; + Object.defineProperty(window, 'nostr', { + configurable: true, + value: { + getPublicKey: () => Promise.resolve(owner), + signEvent: () => { + signs++; + return Promise.reject(Error('unexpected sign')); + }, + nip44: { + encrypt: (_peer: string, text: string) => { + encrypts++; + return Promise.resolve('fixture:' + text); + }, + decrypt: (_peer: string, text: string) => { + decrypts++; + return Promise.resolve(text.slice(8)); + } + } + } + }); + const identity = createIdentitySession(); + await connectIdentity(identity); + await probeIdentityMessaging(identity, 'reviewed_self_copy'); + const opened = await openBrowserDatabase(); + if (opened.state !== 'ready') + throw Error('browser fixture database unavailable'); + const database = opened.owner, + repository = createPrivateSendReservationRepository(database, owner); + if (!repository) throw Error('invalid source repository'); + function plan( + text = 'Private reservation sentinel', + seconds = Math.floor(milliseconds / 1000) + ) { + const value = captureEnquiryRumor(identity, capturedContext, text, seconds); + if (!value) throw Error('expected local source plan'); + return value; + } + async function rows() { + const transaction = browserDatabaseTransaction( + database, + ['private_sends'], + 'readonly' + ), + request = transaction.objectStore('private_sends').getAll(); + return await new Promise<unknown[]>((resolve, reject) => { + transaction.addEventListener('complete', () => + resolve(request.result as unknown[]) + ); + transaction.addEventListener('abort', () => + reject(Error('inspection aborted')) + ); + }); + } + async function inject(value: unknown) { + const transaction = browserDatabaseTransaction( + database, + ['private_sends'], + 'readwrite' + ); + transaction.objectStore('private_sends').put(value); + await new Promise<void>((resolve, reject) => { + transaction.addEventListener('complete', () => resolve()); + transaction.addEventListener('abort', () => + reject(Error('fixture injection aborted')) + ); + }); + } + return { + identity, + repository, + database, + event, + plan, + rows, + inject, + shared: (): Shared => ({ event, milliseconds }), + setTime: (value: number) => { + milliseconds = value; + }, + counts: () => ({ signs, encrypts, decrypts }), + reserve: (id: string, value: RumorPlan) => + reserveSendIdentity( + repository, + identity, + id, + value, + 'reviewed_private_intent' + ), + disconnect: () => disconnectIdentity(identity), + close() { + disconnectIdentity(identity); + closeBrowserDatabase(database); + Date.now = previousNow; + } + }; +} diff --git a/web/tests/e2e/private-send-reservations.spec.ts b/web/tests/e2e/private-send-reservations.spec.ts @@ -0,0 +1,385 @@ +import { expect, test, type Page } from '@playwright/test'; +import { build } from 'vite'; +import { fileURLToPath } from 'node:url'; +import { createHash } from 'node:crypto'; +import { createStaticHarness } from '../integration/harness/static.ts'; +import type * as Reservations from './harness/private-send-reservations.ts'; +import type { RumorPlan } from '../../src/lib/messaging/rumor-plan.ts'; +declare global { + interface Window { + hcp074: typeof Reservations; + hcp074Fixture: Awaited<ReturnType<typeof Reservations.makeFixture>>; + hcp074Plan: RumorPlan; + hcp074Release: () => void; + hcp074Held: Promise<unknown>; + } +} +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/private-send-reservations.ts', import.meta.url) + ), + name: 'hcp074', + formats: ['iife'] + } + } + }); + const output = Array.isArray(result) ? result[0] : result; + if (!('output' in output)) throw Error('missing bundle'); + const chunks = output.output.filter((item) => item.type === 'chunk'); + expect(chunks).toHaveLength(1); + bundle = chunks[0].code; + console.log( + JSON.stringify({ + fixture: 'HCP074_ACTUAL_OWNER_LOCKS_IDB_RESERVATIONS', + bundleSha256: createHash('sha256').update(bundle).digest('hex'), + moduleIds: Object.keys(chunks[0].modules), + qualification: + 'Controlled local Chromium clock/provider; not actual operator/installed extension/real clock qualification' + }) + ); +}); +test.afterAll(async () => server.close()); +async function load(page: Page, shared?: Reservations.Shared) { + await page.goto(server.url + '/search'); + await page.addScriptTag({ content: bundle }); + return page.evaluate(async (shared) => { + window.hcp074Fixture = await window.hcp074.makeFixture(shared); + window.hcp074Plan = window.hcp074Fixture.plan(); + return window.hcp074Fixture.shared(); + }, shared); +} +test('one command retries the identical rumor and stores only bounded metadata', async ({ + page +}) => { + await load(page); + const result = await page.evaluate(async () => { + const s = window.hcp074, + f = window.hcp074Fixture, + before = f.counts(); + const first = await f.reserve(s.command, window.hcp074Plan), + retry = await f.reserve(s.command, window.hcp074Plan); + const metadata = + first.status === 'reserved' + ? s.reservedSendSnapshot(first.identity) + : undefined; + const wire = + first.status === 'reserved' + ? s.reservedSendRumorWire(first.identity) + : undefined; + const rows = await f.rows(); + return { + first: first.status, + retry: retry.status, + metadata, + wirePresent: typeof wire === 'string', + stored: JSON.stringify(rows), + counts: f.counts(), + before + }; + }); + expect(result.first).toBe('reserved'); + expect(result.retry).toBe('existing'); + expect(result.wirePresent).toBe(true); + expect(result.stored).not.toContain('Private reservation sentinel'); + expect(result.stored).not.toContain('Carrots'); + expect(result.stored).not.toContain('nostr:'); + expect(result.stored).not.toContain('"content"'); + expect(result.counts).toEqual(result.before); + expect(result.metadata?.id).toBe('12345678-1234-4234-8234-123456789abc'); +}); +test('changed same command conflicts and distinct same-second identical intent cannot merge', async ({ + page +}) => { + await load(page); + const result = await page.evaluate(async () => { + const f = window.hcp074Fixture, + s = window.hcp074; + await f.reserve(s.command, window.hcp074Plan); + const changed = await f.reserve(s.command, f.plan('Different body')); + const collision = await f.reserve( + '12345678-1234-4234-8234-123456789abd', + f.plan() + ); + return { + changed: changed.status, + collision: collision.status, + count: (await f.rows()).length + }; + }); + expect(result).toEqual({ + changed: 'conflict', + collision: 'clock_conflict', + count: 1 + }); +}); +test('actual observed clock progress permits a distinct intent without future timestamp or custom tags', async ({ + page +}) => { + await load(page); + const result = await page.evaluate(async () => { + const s = window.hcp074, + f = window.hcp074Fixture, + original = f.shared().milliseconds; + const first = await f.reserve(s.command, window.hcp074Plan); + f.setTime(original + 1000); + const nextPlan = f.plan(); + const next = await f.reserve( + '12345678-1234-4234-8234-123456789abd', + nextPlan + ); + if (first.status !== 'reserved' || next.status !== 'reserved') + throw Error('expected source reservations'); + const a = s.reservedSendSnapshot(first.identity)!, + b = s.reservedSendSnapshot(next.identity)!; + const wire = JSON.parse(s.reservedSendRumorWire(next.identity)!) as { + created_at: number; + tags: string[][]; + }; + const retry = await f.reserve(s.command, window.hcp074Plan); + return { + different: a.rumorHash !== b.rumorHash, + observed: wire.created_at === Math.floor(Date.now() / 1000), + pOnly: wire.tags.length === 1 && wire.tags[0][0] === 'p', + retry: retry.status, + count: (await f.rows()).length + }; + }); + expect(result).toEqual({ + different: true, + observed: true, + pOnly: true, + retry: 'existing', + count: 2 + }); +}); +test('new future or stale template fails safely before metadata changes', async ({ + page +}) => { + await load(page); + const result = await page.evaluate(async () => { + const f = window.hcp074Fixture, + seconds = Math.floor(Date.now() / 1000); + const future = await f.reserve( + window.hcp074.command, + f.plan('Future', seconds + 1) + ); + const stale = await f.reserve( + window.hcp074.command, + f.plan('Stale', seconds - 1) + ); + return { + future: future.status, + stale: stale.status, + count: (await f.rows()).length + }; + }); + expect(result).toEqual({ + future: 'clock_conflict', + stale: 'clock_conflict', + count: 0 + }); +}); +test('two tabs share owner CAS and only one distinct identical intent can reserve', async ({ + page, + context +}) => { + const shared = await load(page), + second = await context.newPage(); + await load(second, shared); + const [a, b] = await Promise.all([ + page.evaluate( + async () => + ( + await window.hcp074Fixture.reserve( + window.hcp074.command, + window.hcp074Plan + ) + ).status + ), + second.evaluate( + async () => + ( + await window.hcp074Fixture.reserve( + '12345678-1234-4234-8234-123456789abd', + window.hcp074Plan + ) + ).status + ) + ]); + expect([a, b].filter((status) => status === 'reserved')).toHaveLength(1); + expect( + [a, b].filter((status) => status === 'busy' || status === 'clock_conflict') + ).toHaveLength(1); + expect( + await page.evaluate(async () => (await window.hcp074Fixture.rows()).length) + ).toBe(1); +}); +test('held origin owner lock reports busy and identity disconnect cannot mint a reservation', async ({ + page +}) => { + await load(page); + await page.evaluate(async () => { + let entered = () => {}; + const ready = new Promise<void>((resolve) => { + entered = resolve; + }); + window.hcp074Held = navigator.locks.request( + 'harvestcircle:owner:' + window.hcp074.owner, + () => + new Promise<void>((resolve) => { + window.hcp074Release = resolve; + entered(); + }) + ); + await ready; + }); + expect( + await page.evaluate( + async () => + ( + await window.hcp074Fixture.reserve( + window.hcp074.command, + window.hcp074Plan + ) + ).status + ) + ).toBe('busy'); + await page.evaluate(async () => { + window.hcp074Release(); + await window.hcp074Held; + window.hcp074Fixture.disconnect(); + }); + const result = await page.evaluate(async () => ({ + status: ( + await window.hcp074Fixture.reserve( + window.hcp074.command, + window.hcp074Plan + ) + ).status, + count: (await window.hcp074Fixture.rows()).length + })); + expect(result.status).toBe('stopped'); + expect(result.count).toBe(0); +}); +test('corrupt owner records stay preserved without implicit reset', async ({ + page +}) => { + await load(page); + const result = await page.evaluate(async () => { + const f = window.hcp074Fixture; + await f.inject({ + owner: window.hcp074.owner, + id: '12345678-1234-4234-8234-123456789abe', + wire: '{bad' + }); + const before = JSON.stringify(await f.rows()), + value = await f.reserve(window.hcp074.command, window.hcp074Plan); + return { + status: value.status, + unchanged: before === JSON.stringify(await f.rows()) + }; + }); + expect(result).toEqual({ status: 'corrupt_record', unchanged: true }); +}); +test('another owner namespace is ignored and remains preserved', async ({ + page +}) => { + await load(page); + const result = await page.evaluate(async () => { + const f = window.hcp074Fixture, + other = + 'c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5'; + const foreign = { + owner: other, + id: window.hcp074.command, + wire: JSON.stringify({ + schema: 1, + family: 'private_send_reservation', + owner: other, + id: window.hcp074.command, + revision: 0, + peer: window.hcp074.owner, + rumorHash: 'f'.repeat(64), + createdAt: Math.floor(Date.now() / 1000) + }) + }; + await f.inject(foreign); + const value = await f.reserve(window.hcp074.command, window.hcp074Plan); + const rows = await f.rows(); + return { + status: value.status, + count: rows.length, + foreignPreserved: rows.some( + (row) => JSON.stringify(row) === JSON.stringify(foreign) + ) + }; + }); + expect(result).toEqual({ + status: 'reserved', + count: 2, + foreignPreserved: true + }); +}); +test('real transaction abort never grants a reserved identity or leaves metadata', async ({ + page +}) => { + await load(page); + const result = await page.evaluate(async () => { + const original = Reflect.get<IDBObjectStore, 'put'>( + IDBObjectStore.prototype, + 'put' + ); + IDBObjectStore.prototype.put = function (...args) { + const request = original.apply(this, args); + request.addEventListener('success', () => this.transaction.abort(), { + once: true + }); + return request; + }; + let value: Awaited<ReturnType<typeof window.hcp074Fixture.reserve>>; + try { + value = await window.hcp074Fixture.reserve( + window.hcp074.command, + window.hcp074Plan + ); + } finally { + IDBObjectStore.prototype.put = original; + } + return { + status: value.status, + identityPresent: 'identity' in value, + count: (await window.hcp074Fixture.rows()).length + }; + }); + expect(['aborted', 'unknown_completion']).toContain(result.status); + expect(result.identityPresent).toBe(false); + expect(result.count).toBe(0); +}); +test('100 unfinished metadata reservations enforce the existing count cap without eviction', async ({ + page +}) => { + await load(page); + const result = await page.evaluate(async () => { + const s = window.hcp074, + f = window.hcp074Fixture; + for (let index = 0; index < 100; index++) { + const id = + '12345678-1234-4234-8234-' + index.toString(16).padStart(12, '0'); + const value = await f.reserve(id, f.plan('Intent ' + index)); + if (value.status !== 'reserved') + throw Error('capacity fixture not admitted'); + } + const value = await f.reserve(s.command, window.hcp074Plan); + return { status: value.status, count: (await f.rows()).length }; + }); + expect(result).toEqual({ status: 'capacity', count: 100 }); +}); diff --git a/web/tests/unit/private-send-reservations.test.ts b/web/tests/unit/private-send-reservations.test.ts @@ -0,0 +1,113 @@ +import { expect, it } from 'vitest'; +import { inspectPrivateSendReservation } from '../../src/lib/persistence/private-send-reservations.ts'; +const owner = + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + peer = 'c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5', + id = '12345678-1234-4234-8234-123456789abc'; +const row = { + schema: 1, + family: 'private_send_reservation', + owner, + id, + revision: 0, + peer, + rumorHash: 'f'.repeat(64), + createdAt: 1700000100 +}; +const read = (value: unknown) => + inspectPrivateSendReservation(JSON.stringify(value), owner, id); +it('reservation contains stable command and rumor metadata without plaintext fields', () => { + expect(read(row)).toEqual(row); + expect(Object.keys(read(row)!).sort()).toEqual([ + 'createdAt', + 'family', + 'id', + 'owner', + 'peer', + 'revision', + 'rumorHash', + 'schema' + ]); +}); +it('body, subject, private context, tags, wire and unknown fields are not admitted', () => { + for (const key of [ + 'body', + 'content', + 'subject', + 'product', + 'contact', + 'tags', + 'wire', + 'unknown' + ]) + expect(read({ ...row, [key]: 'Private sentinel' })).toBeUndefined(); +}); +it('owner and UUID command namespace are exact and cannot be coerced', () => { + expect( + inspectPrivateSendReservation(JSON.stringify(row), peer, id) + ).toBeUndefined(); + expect( + inspectPrivateSendReservation( + JSON.stringify(row), + owner, + '12345678-1234-4234-8234-123456789abd' + ) + ).toBeUndefined(); + for (const value of [ + null, + 1, + owner.toUpperCase(), + '0'.repeat(64), + { toString: () => owner } + ]) + expect( + inspectPrivateSendReservation(JSON.stringify(row), value, id) + ).toBeUndefined(); + for (const value of [ + null, + id.toUpperCase(), + 'a'.repeat(64), + '12345678-1234-1234-8234-123456789abc' + ]) + expect(read({ ...row, id: value })).toBeUndefined(); +}); +it('self, malformed/noncanonical peers and unsupported revisions/families are rejected', () => { + for (const value of [owner, peer.toUpperCase(), '0'.repeat(64), null]) + expect(read({ ...row, peer: value })).toBeUndefined(); + for (const value of [1, -1, '0', null]) + expect(read({ ...row, revision: value })).toBeUndefined(); + expect(read({ ...row, schema: 2 })).toBeUndefined(); + expect(read({ ...row, family: 'private_send' })).toBeUndefined(); +}); +it('rumor ID and timestamp are bounded canonical data, never floats or coercions', () => { + for (const value of ['F'.repeat(64), 'f'.repeat(63), null, 0]) + expect(read({ ...row, rumorHash: value })).toBeUndefined(); + for (const value of [-1, 1.5, Number.MAX_SAFE_INTEGER + 1, '100', null]) + expect(read({ ...row, createdAt: value })).toBeUndefined(); + expect( + inspectPrivateSendReservation( + JSON.stringify(row).replace('1700000100', '-0'), + owner, + id + ) + ).toBeUndefined(); + expect(read({ ...row, createdAt: 0 })!.createdAt).toBe(0); +}); +it('raw objects cannot invoke conversion and oversized/malformed input stays unsupported', () => { + let converted = false; + expect( + inspectPrivateSendReservation( + { + toJSON() { + converted = true; + return row; + } + }, + owner, + id + ) + ).toBeUndefined(); + expect(converted).toBe(false); + for (const raw of ['', '{', 'null', '[]', ' '.repeat(4097)]) + expect(inspectPrivateSendReservation(raw, owner, id)).toBeUndefined(); +});