app

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

commit 034c9f224be72f2d17f2cb882fbc90a65d7c22fb
parent 2979f764dc1cd9b0082a3da37aacedde8c6a2517
Author: triesap <tyson@radroots.org>
Date:   Tue,  6 Oct 2026 21:27:02 +0000

storage: define owner-scoped durable record envelopes (HCP-046)

- Admit bounded owner-scoped public draft and operation records
- Link signed public source captures and keep preference records separate
- Preserve detached record handles and reject private data from public types
- Verify malformed input, genuine conflicting captures and metadata boundaries

Diffstat:
Mweb/src/lib/config/budgets.ts | 20++++++++++++++++++++
Aweb/src/lib/contracts/local-records.ts | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/src/lib/nostr/local-template.ts | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/src/lib/persistence/records.ts | 399+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/integration/local-records.test.ts | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/unit/local-records.test.ts | 435+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 1079 insertions(+), 0 deletions(-)

diff --git a/web/src/lib/config/budgets.ts b/web/src/lib/config/budgets.ts @@ -58,3 +58,23 @@ export const PUBLIC_NIP50_BUDGETS = Object.freeze({ requestedPerRelay: 100, candidatesPerSource: 100 }); + +// Browser-local logical admission, independent of desktop SQLite and the public +// memory store. Repository transactions enforce aggregate counts/bytes later. +export const LOCAL_PERSISTENCE_BUDGETS = Object.freeze({ + publicDrafts: 20, + draftComposedBytes: 16384, + publicOperations: 100, + publicOperationBytes: 8388608, + unfinishedPrivateSends: 100, + privateSendBytes: 8388608, + receivedEnvelopes: 2000, + receivedCiphertextBytes: 50331648 +}); + +// Approved explicit public publication action; user approval time is separate +// from this future network scheduler bound. Codecs validate attempt metadata. +export const PUBLIC_PUBLICATION_BUDGETS = Object.freeze({ + attemptsPerTargetAction: 3, + networkActionMilliseconds: 45000 +}); diff --git a/web/src/lib/contracts/local-records.ts b/web/src/lib/contracts/local-records.ts @@ -0,0 +1,109 @@ +// Local record vocabulary, not Nostr schemas, installed identity or effect +// capabilities. Storage codecs admit structure; repositories own CAS/effects. +// JSON-shaped own enumerable data fields only; no getters are acquired. +export function exactLocalFields( + value: unknown, + fields: readonly string[] +): value is Record<string, unknown> { + if (typeof value !== 'object' || value === null || Array.isArray(value)) + return false; + let count = 0; + function own(key: string): boolean { + const descriptor = Object.getOwnPropertyDescriptor(value, key); + return ( + descriptor !== undefined && + descriptor.get === undefined && + descriptor.set === undefined + ); + } + for (const key in value) { + if (!fields.includes(key) || !own(key)) return false; + count++; + } + return count === fields.length; +} +export type PublicDraftForm = Readonly<{ + title: string; + description: string; + location: string; + amount: string; + currency: string; + unit: string; + quantity: string; + contactType: '' | 'email' | 'phone' | 'https'; + contactValue: string; +}>; +export type PublicDraftRecord = Readonly<{ + schema: 1; + family: 'public_draft'; + owner: string; + id: string; + revision: number; + savedAtMilliseconds: number; + form: PublicDraftForm; +}>; +export type PublicCaptureSource = + | Readonly<{ type: 'draft'; id: string; revision: number }> + | Readonly<{ type: 'public_head'; wire: string }>; +export type PreferenceCaptureSource = Readonly<{ + type: 'inbox_head'; + // Null retains no base event; it never proves global absence/lookup readiness. + wire: string | null; +}>; +export type CapturedTemplate<Kind extends 30402 | 5 | 10050> = Readonly<{ + kind: Kind; + wire: string; + hash: string; + targets: readonly string[]; + policyFingerprint: string; +}>; +export type SignedPublicArtifact = Readonly<{ + eventId: string; + wire: string; +}>; +// Recorded local observation metadata, not independently proven relay/operator +// evidence. Exact readback and a named ACK remain distinct, even when both exist. +export type PublicTargetReceipt = Readonly<{ + actionId: string; + origin: string; + role: 'publication' | 'preference'; + attempt: number; + eventId: string; + status: 'accepted' | 'refused' | 'timed_out' | 'unknown' | 'stopped'; + observedAtMilliseconds: number; + readbackWire: string | null; +}>; +export type PublicOperationRecord = Readonly<{ + schema: 1; + family: 'public_operation'; + owner: string; + id: string; + revision: number; + source: PublicCaptureSource; + capture: CapturedTemplate<30402 | 5>; + artifact: SignedPublicArtifact | null; + receipts: readonly PublicTargetReceipt[]; +}>; +export type PreferenceOperationRecord = Readonly<{ + schema: 1; + family: 'preference_operation'; + owner: string; + id: string; + revision: number; + source: PreferenceCaptureSource; + consent: 'explicit_review'; + capture: CapturedTemplate<10050>; + artifact: SignedPublicArtifact | null; + receipts: readonly PublicTargetReceipt[]; +}>; +// Private body/subject/contact/product associations have no member in this +// public union. Encrypted private-send records retain their own later owner. +export type PublicRecord = + PublicDraftRecord | PublicOperationRecord | PreferenceOperationRecord; +export type ConversationMappingRecord = Readonly<{ + schema: 1; + family: 'conversation_handle'; + owner: string; + id: string; + peer: string; +}>; diff --git a/web/src/lib/nostr/local-template.ts b/web/src/lib/nostr/local-template.ts @@ -0,0 +1,63 @@ +import { getEventHash, type NostrEvent } from 'applesauce-core/helpers'; +import { PUBLIC_INGRESS_BUDGETS } from '../config/budgets.ts'; +import { canonicalPublicKey } from '../contracts/public-key.ts'; +import { exactLocalFields } from '../contracts/local-records.ts'; +import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts'; +import { boundedEnvelopeNumbers } from './envelope-bounds.ts'; +import { boundedEnvelopeTags } from './verified-envelope.ts'; +export type PublicSignedFields = NostrEvent; +export type LocalUnsignedTemplate = Readonly<{ + pubkey: string; + kind: number; + created_at: number; + tags: readonly (readonly string[])[]; + content: string; + hash: string; +}>; +// Hashing uses the qualified SDK. Admission conveys no signer/transport/store +// capability, supported Food profile, current-head or publishing authorization. +export function inspectLocalTemplate( + raw: unknown, + expectedOwner: unknown, + expectedKind: unknown +): LocalUnsignedTemplate | undefined { + const owner = canonicalPublicKey(expectedOwner); + if ( + !owner || + ![30402, 5, 10050].some((kind) => kind === expectedKind) || + typeof raw !== 'string' || + !boundedUtf8(raw, PUBLIC_INGRESS_BUDGETS.eventBytes) + ) + return undefined; + try { + const value: unknown = JSON.parse(raw); + if ( + !exactLocalFields(value, [ + 'pubkey', + 'kind', + 'created_at', + 'tags', + 'content' + ]) || + JSON.stringify(value) !== raw || + value.pubkey !== owner || + value.kind !== expectedKind || + !boundedEnvelopeTags(value.tags) || + typeof value.content !== 'string' || + !boundedUtf8(value.content, PUBLIC_INGRESS_BUDGETS.eventBytes) + ) + return undefined; + const numbers = boundedEnvelopeNumbers(value.kind, value.created_at); + if (!numbers) return undefined; + const template = { + pubkey: owner, + kind: numbers.kind, + created_at: numbers.created_at, + tags: value.tags, + content: value.content + }; + return { ...template, hash: getEventHash(template) }; + } catch { + return undefined; + } +} diff --git a/web/src/lib/persistence/records.ts b/web/src/lib/persistence/records.ts @@ -0,0 +1,399 @@ +import { + inspectLocalTemplate, + type PublicSignedFields, + type LocalUnsignedTemplate +} from '../nostr/local-template.ts'; +import { exactLocalFields } from '../contracts/local-records.ts'; +import { canonicalDeletionCoordinate } from '../nostr/deletion-adapter.ts'; +import { + createPublicHeadCandidate, + publicHeadSnapshot +} from '../catalog/heads.ts'; +import { + LOCAL_PERSISTENCE_BUDGETS, + PUBLIC_INGRESS_BUDGETS, + PUBLIC_PUBLICATION_BUDGETS, + RELAY_BUDGETS +} from '../config/budgets.ts'; +import { canonicalRelayOrigin } from '../config/relays.ts'; +import { canonicalPublicKey } from '../contracts/public-key.ts'; +import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts'; +import { canonicalLocalId } from '../private-handles.ts'; +import { safeUnsignedInteger } from '../nostr/envelope-bounds.ts'; +import { + verifyEnvelope, + verifiedEnvelopeSnapshot +} from '../nostr/verified-envelope.ts'; +import type { + ConversationMappingRecord, + PublicRecord +} from '../contracts/local-records.ts'; + +declare const recordBrand: unique symbol; +declare const mappingBrand: unique symbol; +export type PublicRecordHandle = Readonly<{ [recordBrand]: true }>; +export type ConversationMappingHandle = Readonly<{ [mappingBrand]: true }>; +type Saved = Readonly<{ owner: string; id: string; wire: string }>; +const records = new WeakMap<PublicRecordHandle, Saved>(); +const mappings = new WeakMap<ConversationMappingHandle, Saved>(); +export type RecordFailure = + | 'invalid_scope' + | 'oversized' + | 'malformed' + | 'unsupported_schema' + | 'owner_mismatch' + | 'id_mismatch'; +type Result<T> = + | Readonly<{ ok: true; value: T }> + | Readonly<{ ok: false; reason: RecordFailure }>; +function object(value: unknown): value is Record<string, unknown> { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} +const exact = exactLocalFields; +function hash(value: unknown): value is string { + return typeof value === 'string' && /^[0-9a-f]{64}$/.test(value); +} +function unsigned(value: unknown): value is number { + return safeUnsignedInteger(value) !== undefined; +} +function signed( + wire: unknown, + owner: string, + kinds: readonly number[] +): PublicSignedFields | undefined { + if (typeof wire !== 'string') return undefined; + const verified = verifyEnvelope(wire); + if (!verified.ok) return undefined; + const event = verifiedEnvelopeSnapshot(verified.value); + return event && + exact(event, [ + 'id', + 'pubkey', + 'created_at', + 'kind', + 'tags', + 'content', + 'sig' + ]) && + event.pubkey === owner && + kinds.includes(event.kind) + ? event + : undefined; +} +function draft(form: unknown): boolean { + const keys = [ + 'title', + 'description', + 'location', + 'amount', + 'currency', + 'unit', + 'quantity', + 'contactType', + 'contactValue' + ]; + if ( + !exact(form, keys) || + typeof form.contactType !== 'string' || + !['', 'email', 'phone', 'https'].includes(form.contactType) + ) + return false; + let bytes = 0; + for (const key of keys) { + const value = form[key]; + if ( + typeof value !== 'string' || + !boundedUtf8(value, LOCAL_PERSISTENCE_BUDGETS.draftComposedBytes) + ) + return false; + bytes += new TextEncoder().encode(value).length; + if (bytes > LOCAL_PERSISTENCE_BUDGETS.draftComposedBytes) return false; + } + // Incomplete strings remain exact; publication validation is a separate step. + return true; +} +function capture( + value: unknown, + owner: string, + preference: boolean +): Record<string, unknown> | undefined { + if ( + !exact(value, ['kind', 'wire', 'hash', 'targets', 'policyFingerprint']) || + !(preference + ? value.kind === 10050 + : value.kind === 30402 || value.kind === 5) || + !hash(value.hash) || + !hash(value.policyFingerprint) || + typeof value.wire !== 'string' || + !boundedUtf8(value.wire, PUBLIC_INGRESS_BUDGETS.eventBytes) || + !Array.isArray(value.targets) || + value.targets.length === 0 || + value.targets.length > RELAY_BUDGETS.public || + value.targets.some( + (target: unknown) => canonicalRelayOrigin(target) !== target + ) || + new Set(value.targets).size !== value.targets.length + ) + return undefined; + const template = inspectLocalTemplate(value.wire, owner, value.kind); + return template?.hash === value.hash ? value : undefined; +} +function linkedSource( + raw: unknown, + owner: string, + template: LocalUnsignedTemplate +): boolean { + if (typeof raw !== 'string') return false; + const proof = verifyEnvelope(raw); + if (!proof.ok) return false; + const source = createPublicHeadCandidate(proof.value); + if (!source) return false; + const head = publicHeadSnapshot(source); + if (head.kind !== 30402 || head.pubkey !== owner) return false; + if (template.kind === 30402) { + const identifier = template.tags.find((tag) => tag[0] === 'd')?.[1] ?? ''; + const event = verifiedEnvelopeSnapshot(proof.value); + return ( + identifier === head.identifier && + template.created_at > head.created_at && + template.tags.find((tag) => tag[0] === 'published_at')?.[1] === + event?.tags.find((tag) => tag[0] === 'published_at')?.[1] + ); + } + if (template.kind !== 5 || template.created_at < head.created_at) + return false; + const coordinate = `30402:${owner}:${head.identifier}`; + let targets = 0; + for (const tag of template.tags) { + if (tag[0] === 'e') { + if (tag[1]?.toLowerCase() !== head.id) return false; + targets++; + } else if (tag[0] === 'a') { + if ( + typeof tag[1] !== 'string' || + canonicalDeletionCoordinate(tag[1]) !== coordinate + ) + return false; + targets++; + } + } + return targets > 0; +} +function operation(row: Record<string, unknown>): boolean { + const preference = row.family === 'preference_operation'; + const keys = [ + 'schema', + 'family', + 'owner', + 'id', + 'revision', + 'source', + 'capture', + 'artifact', + 'receipts' + ]; + if (preference) keys.push('consent'); + if ( + !exact(row, keys) || + (preference && row.consent !== 'explicit_review') || + typeof row.owner !== 'string' + ) + return false; + const prepared = capture(row.capture, row.owner, preference); + if (!prepared || !object(row.source)) return false; + const source = row.source; + const template = inspectLocalTemplate( + prepared.wire, + row.owner, + prepared.kind + ); + if (!template) return false; + if (preference) { + if ( + !exact(source, ['type', 'wire']) || + source.type !== 'inbox_head' || + (source.wire !== null && !signed(source.wire, row.owner, [10050])) + ) + return false; + } else if (source.type === 'draft') { + if ( + prepared.kind !== 30402 || + !exact(source, ['type', 'id', 'revision']) || + !canonicalLocalId(source.id) || + !unsigned(source.revision) + ) + return false; + } else if ( + !exact(source, ['type', 'wire']) || + source.type !== 'public_head' || + !signed(source.wire, row.owner, [30402]) || + !linkedSource(source.wire, row.owner, template) + ) + return false; + let artifact: PublicSignedFields | undefined; + if (row.artifact !== null) { + if ( + !exact(row.artifact, ['eventId', 'wire']) || + row.artifact.eventId !== prepared.hash + ) + return false; + artifact = signed(row.artifact.wire, row.owner, [Number(prepared.kind)]); + if (!artifact || artifact.id !== prepared.hash) return false; + } + if (!Array.isArray(row.receipts) || (!artifact && row.receipts.length !== 0)) + return false; + for (const receipt of row.receipts as unknown[]) { + if ( + !exact(receipt, [ + 'actionId', + 'origin', + 'role', + 'attempt', + 'eventId', + 'status', + 'observedAtMilliseconds', + 'readbackWire' + ]) || + !canonicalLocalId(receipt.actionId) || + receipt.role !== (preference ? 'preference' : 'publication') || + !(prepared.targets as unknown[]).includes(receipt.origin) || + receipt.eventId !== prepared.hash || + !unsigned(receipt.attempt) || + receipt.attempt < 1 || + receipt.attempt > PUBLIC_PUBLICATION_BUDGETS.attemptsPerTargetAction || + !unsigned(receipt.observedAtMilliseconds) || + typeof receipt.status !== 'string' || + !['accepted', 'refused', 'timed_out', 'unknown', 'stopped'].includes( + receipt.status + ) + ) + return false; + if (receipt.readbackWire !== null) { + const observed = signed(receipt.readbackWire, row.owner, [ + Number(prepared.kind) + ]); + if ( + !artifact || + !observed || + observed.id !== artifact.id || + observed.sig !== artifact.sig + ) + return false; + } + } + return true; +} +function read( + raw: unknown, + expectedOwner: unknown, + expectedId: unknown +): Result<Saved> { + const owner = canonicalPublicKey(expectedOwner), + id = canonicalLocalId(expectedId); + if (!owner || !id) return { ok: false, reason: 'invalid_scope' }; + if (typeof raw !== 'string') return { ok: false, reason: 'malformed' }; + if (!boundedUtf8(raw, LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes)) + return { ok: false, reason: 'oversized' }; + try { + const row: unknown = JSON.parse(raw); + if (!object(row) || JSON.stringify(row) !== raw) + return { ok: false, reason: 'malformed' }; + if (row.schema !== 1) return { ok: false, reason: 'unsupported_schema' }; + if (row.owner !== owner) return { ok: false, reason: 'owner_mismatch' }; + if (row.id !== id) return { ok: false, reason: 'id_mismatch' }; + return { ok: true, value: { owner, id, wire: raw } }; + } catch { + return { ok: false, reason: 'malformed' }; + } +} +export function decodePublicRecord( + raw: unknown, + expectedOwner: unknown, + expectedId: unknown +): Result<PublicRecordHandle> { + const parsed = read(raw, expectedOwner, expectedId); + if (!parsed.ok) return parsed; + try { + const row: Record<string, unknown> = JSON.parse( + parsed.value.wire + ) as Record<string, unknown>; + if (!unsigned(row.revision)) return { ok: false, reason: 'malformed' }; + const valid = + row.family === 'public_draft' + ? exact(row, [ + 'schema', + 'family', + 'owner', + 'id', + 'revision', + 'savedAtMilliseconds', + 'form' + ]) && + unsigned(row.savedAtMilliseconds) && + draft(row.form) + : (row.family === 'public_operation' || + row.family === 'preference_operation') && + operation(row); + if (!valid) return { ok: false, reason: 'malformed' }; + const token = Object.freeze({}) as PublicRecordHandle; + records.set(token, parsed.value); + return { ok: true, value: token }; + } catch { + return { ok: false, reason: 'malformed' }; + } +} +export function publicRecordSnapshot( + handle: PublicRecordHandle, + owner: unknown, + id: unknown +): PublicRecord | undefined { + const saved = records.get(handle); + return saved && + saved.owner === canonicalPublicKey(owner) && + saved.id === canonicalLocalId(id) + ? (JSON.parse(saved.wire) as PublicRecord) + : undefined; +} +export function publicRecordWire( + handle: PublicRecordHandle, + owner: unknown, + id: unknown +): string | undefined { + const saved = records.get(handle); + return saved && + saved.owner === canonicalPublicKey(owner) && + saved.id === canonicalLocalId(id) + ? saved.wire + : undefined; +} +export function decodeConversationMapping( + raw: unknown, + expectedOwner: unknown, + expectedId: unknown +): Result<ConversationMappingHandle> { + const parsed = read(raw, expectedOwner, expectedId); + if (!parsed.ok) return parsed; + const row: unknown = JSON.parse(parsed.value.wire); + if ( + !exact(row, ['schema', 'family', 'owner', 'id', 'peer']) || + row.family !== 'conversation_handle' || + !canonicalPublicKey(row.peer) || + row.peer === row.owner + ) + return { ok: false, reason: 'malformed' }; + const token = Object.freeze({}) as ConversationMappingHandle; + mappings.set(token, parsed.value); + return { ok: true, value: token }; +} +export function conversationMappingSnapshot( + handle: ConversationMappingHandle, + owner: unknown, + id: unknown +): ConversationMappingRecord | undefined { + const saved = mappings.get(handle); + return saved && + saved.owner === canonicalPublicKey(owner) && + saved.id === canonicalLocalId(id) + ? (JSON.parse(saved.wire) as ConversationMappingRecord) + : undefined; +} diff --git a/web/tests/integration/local-records.test.ts b/web/tests/integration/local-records.test.ts @@ -0,0 +1,53 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + decodePublicRecord, + publicRecordSnapshot +} from '../../src/lib/persistence/records.ts'; +await test('actual bounded record codec revalidates stored public strings without opening storage or adopting a foreign author', () => { + const owner = + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'; + const peer = + 'c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5'; + const id = '3d030bf5-901d-45e1-8251-41cbdf805e96'; + const row = { + schema: 1, + family: 'public_draft', + owner, + id, + revision: 2, + savedAtMilliseconds: 1000, + form: { + title: '', + description: 'incomplete public description', + location: '', + amount: '.', + currency: '', + unit: '', + quantity: '', + contactType: '', + contactValue: '' + } + }; + const original = Object.getOwnPropertyDescriptor(globalThis, 'indexedDB'); + Object.defineProperty(globalThis, 'indexedDB', { + configurable: true, + get() { + throw new Error('No IDB capability may be acquired by a codec'); + } + }); + try { + const ready = decodePublicRecord(JSON.stringify(row), owner, id); + if (!ready.ok) throw new Error(ready.reason); + assert.equal(ready.ok, true); + assert.deepEqual(publicRecordSnapshot(ready.value, owner, id), row); + assert.equal(publicRecordSnapshot(ready.value, peer, id), undefined); + assert.deepEqual(decodePublicRecord(JSON.stringify(row), peer, id), { + ok: false, + reason: 'owner_mismatch' + }); + } finally { + if (original) Object.defineProperty(globalThis, 'indexedDB', original); + else Reflect.deleteProperty(globalThis, 'indexedDB'); + } +}); diff --git a/web/tests/unit/local-records.test.ts b/web/tests/unit/local-records.test.ts @@ -0,0 +1,435 @@ +import { describe, expect, it } from 'vitest'; +import { finalizeEvent, getEventHash } from 'applesauce-core/helpers'; +import { verifyEnvelope } from '../../src/lib/nostr/verified-envelope.ts'; +import { LOCAL_PERSISTENCE_BUDGETS } from '../../src/lib/config/budgets.ts'; +import type { + PublicDraftRecord, + PublicRecord +} from '../../src/lib/contracts/local-records.ts'; +import { + decodePublicRecord, + publicRecordSnapshot, + publicRecordWire, + decodeConversationMapping, + conversationMappingSnapshot, + type PublicRecordHandle +} from '../../src/lib/persistence/records.ts'; +const owner = + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'; +const peer = 'c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5'; +const id = '3d030bf5-901d-45e1-8251-41cbdf805e96'; +const anotherId = 'b1d6d23d-79f3-4779-9b03-e289712cc73f'; +const form = { + title: '', + description: '', + location: '', + amount: '.', + currency: '', + unit: '', + quantity: '', + contactType: '' as const, + contactValue: '' +}; +const draft: PublicDraftRecord = { + schema: 1, + family: 'public_draft', + owner, + id, + revision: 0, + savedAtMilliseconds: 1000, + form +}; +function read(value: unknown, expectedOwner = owner, expectedId = id) { + return decodePublicRecord(JSON.stringify(value), expectedOwner, expectedId); +} +function operation( + kind: 30402 | 5 | 10050, + tagsOverride?: (eventId: string, pubkey: string) => string[][], + createdAt = 101 +) { + const key = crypto.getRandomValues(new Uint8Array(32)); + try { + const base = finalizeEvent( + { + kind: kind === 10050 ? 10050 : 30402, + created_at: 100, + tags: + kind === 10050 + ? [] + : [ + ['d', 'public'], + ['published_at', '100'] + ], + content: 'public source fixture' + }, + key + ); + const template = { + pubkey: base.pubkey, + kind, + created_at: createdAt, + tags: tagsOverride + ? tagsOverride(base.id, base.pubkey) + : kind === 5 + ? [ + ['e', base.id], + ['a', `30402:${base.pubkey}:public`] + ] + : kind === 10050 + ? [] + : [ + ['d', 'public'], + ['published_at', '100'] + ], + content: 'public outgoing fixture' + }; + const templateWire = JSON.stringify(template); + const templateHash = getEventHash(template); + const artifact = finalizeEvent( + { ...template, tags: template.tags.map((tag) => [...tag]) }, + key + ); + return { + schema: 1, + family: kind === 10050 ? 'preference_operation' : 'public_operation', + owner: base.pubkey, + id, + revision: 1, + ...(kind === 10050 ? { consent: 'explicit_review' } : {}), + source: { + type: kind === 10050 ? 'inbox_head' : 'public_head', + wire: JSON.stringify(base) + }, + capture: { + kind, + wire: templateWire, + hash: templateHash, + targets: ['wss://one.example.org'], + policyFingerprint: 'a'.repeat(64) + }, + artifact: { eventId: artifact.id, wire: JSON.stringify(artifact) }, + receipts: [ + { + actionId: anotherId, + origin: 'wss://one.example.org', + role: kind === 10050 ? 'preference' : 'publication', + attempt: 1, + eventId: artifact.id, + status: 'accepted', + observedAtMilliseconds: 1234, + readbackWire: JSON.stringify(artifact) + } + ] + }; + } finally { + key.fill(0); + } +} +describe('owner-scoped canonical public record codecs', () => { + it('preserves incomplete strings exactly without publication validation', () => { + const result = read(draft); + expect(result.ok).toBe(true); + if (!result.ok) throw new Error(result.reason); + expect(publicRecordSnapshot(result.value, owner, id)).toEqual(draft); + expect(publicRecordWire(result.value, owner, id)).toBe( + JSON.stringify(draft) + ); + }); + it('rejects cross-owner/cross-ID decoding and handle reads', () => { + expect(read(draft, peer)).toEqual({ ok: false, reason: 'owner_mismatch' }); + expect(read(draft, owner, anotherId)).toEqual({ + ok: false, + reason: 'id_mismatch' + }); + const result = read(draft); + if (!result.ok) throw new Error(result.reason); + expect(publicRecordSnapshot(result.value, peer, id)).toBeUndefined(); + expect(publicRecordWire(result.value, owner, anotherId)).toBeUndefined(); + }); + it('rejects noncanonical owner/UUID scope rather than normalizing it', () => { + for (const bad of ['', owner.toUpperCase(), '0'.repeat(64)]) + expect(read(draft, bad).ok).toBe(false); + for (const bad of ['', id.toUpperCase(), 'a'.repeat(64)]) + expect(read(draft, owner, bad).ok).toBe(false); + }); + for (const schema of [0, 2, '1', null]) + it(`rejects unknown schema ${String(schema)}`, () => { + expect(read({ ...draft, schema })).toEqual({ + ok: false, + reason: 'unsupported_schema' + }); + }); + it('rejects malformed/noncanonical/duplicate-key input without coercion', () => { + for (const raw of [ + '{', + 'null', + '[]', + JSON.stringify(draft, null, 2), + JSON.stringify(draft).replace('"schema":1', '"schema":2,"schema":1'), + JSON.stringify(draft).replace('"revision":0', '"revision":-0') + ]) + expect(decodePublicRecord(raw, owner, id).ok).toBe(false); + }); + it('does not inspect getters on non-string database input', () => { + let touched = false; + const raw = { + get schema() { + touched = true; + throw new Error('test-only'); + } + }; + expect(decodePublicRecord(raw, owner, id)).toEqual({ + ok: false, + reason: 'malformed' + }); + expect(touched).toBe(false); + }); + it('bounds malformed raw bytes before parsing', () => { + expect( + decodePublicRecord( + 'x'.repeat(LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes + 1), + owner, + id + ) + ).toEqual({ ok: false, reason: 'oversized' }); + expect( + decodePublicRecord( + 'é'.repeat(LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes / 2 + 1), + owner, + id + ) + ).toEqual({ ok: false, reason: 'oversized' }); + }); + it('counts composed UTF8 at the inclusive draft limit', () => { + const blank = { ...form, amount: '' }; + expect( + read({ ...draft, form: { ...blank, description: 'é'.repeat(8192) } }).ok + ).toBe(true); + expect( + read({ + ...draft, + form: { ...blank, description: 'é'.repeat(8192), title: 'x' } + }).ok + ).toBe(false); + expect( + read({ ...draft, form: { ...blank, description: '\ud800' } }).ok + ).toBe(false); + }); + it('rejects unknown/private fields, raw private families and unsafe revisions', () => { + for (const record of [ + { ...draft, body: 'test-only private body' }, + { ...draft, family: 'private_message' }, + { ...draft, form: { ...form, subject: 'test-only' } }, + { ...draft, revision: -1 }, + { ...draft, revision: Number.MAX_SAFE_INTEGER + 1 }, + { ...draft, savedAtMilliseconds: -1 }, + { ...draft, form: { ...form, contactType: 'legacy' } } + ]) + expect(read(record).ok).toBe(false); + // Executable TypeScript check: a private-body field has no public member. + const wrong: PublicRecord = { + ...draft, + // @ts-expect-error private body is outside the public record contract + body: 'test-only private body' + }; + expect(read(wrong).ok).toBe(false); + }); + it('detaches snapshots and rejects fabricated capabilities', () => { + const result = read(draft); + if (!result.ok) throw new Error(result.reason); + const first = publicRecordSnapshot( + result.value, + owner, + id + ) as PublicDraftRecord; + Object.assign(first.form, { description: 'changed' }); + expect(publicRecordSnapshot(result.value, owner, id)).toEqual(draft); + expect( + publicRecordSnapshot(Object.freeze({}) as PublicRecordHandle, owner, id) + ).toBeUndefined(); + }); + for (const kind of [30402, 5, 10050] as const) + it(`binds actual signed ${kind} artifacts and separate named ACK/readback metadata`, () => { + const value = operation(kind), + result = read(value, value.owner); + expect(result.ok).toBe(true); + if (!result.ok) throw new Error(result.reason); + expect(publicRecordSnapshot(result.value, value.owner, id)).toEqual( + value + ); + }); + it('rejects changed template/hash, artifact identity and destination bindings', () => { + const value = operation(30402); + for (const row of [ + { ...value, capture: { ...value.capture, hash: 'b'.repeat(64) } }, + { + ...value, + capture: { + ...value.capture, + wire: value.capture.wire.replace('outgoing', 'changed') + } + }, + { + ...value, + capture: { + ...value.capture, + targets: ['wss://one.example.org', 'wss://one.example.org'] + } + }, + { ...value, capture: { ...value.capture, targets: ['wss://127.0.0.1'] } }, + { ...value, artifact: { ...value.artifact, eventId: 'b'.repeat(64) } }, + { + ...value, + receipts: [{ ...value.receipts[0], origin: 'wss://other.example.org' }] + }, + { ...value, receipts: [{ ...value.receipts[0], attempt: 4 }] }, + { ...value, receipts: [{ ...value.receipts[0], role: 'archive' }] }, + { + ...value, + receipts: [{ ...value.receipts[0], eventId: 'b'.repeat(64) }] + }, + { ...value, artifact: null } + ]) + expect(read(row, value.owner).ok).toBe(false); + }); + it('binds genuine replacement coordinates, original publication time and advancing revision time', () => { + for (const value of [ + operation(30402, () => [ + ['d', 'other'], + ['published_at', '100'] + ]), + operation(30402, () => [ + ['d', 'public'], + ['published_at', '101'] + ]), + operation(30402, undefined, 100) + ]) + expect(read(value, value.owner).ok).toBe(false); + }); + it('binds genuine withdrawal to the captured version/coordinate and rejects additional unrelated targets', () => { + for (const value of [ + operation(5, () => [['e', 'b'.repeat(64)]]), + operation(5, (_, pubkey) => [['a', `30402:${pubkey}:other`]]), + operation(5, (eventId) => [ + ['e', eventId], + ['e', 'b'.repeat(64)] + ]), + operation(5, () => []), + operation(5, undefined, 99) + ]) + expect(read(value, value.owner).ok).toBe(false); + }); + it('preserves original verified signed-wire layout while outer/template serialization stays canonical', () => { + const value = operation(30402); + function formatted(wire: string) { + const parsed: unknown = JSON.parse(wire); + return JSON.stringify(parsed, null, 2); + } + const aliases = { + ...value, + source: { ...value.source, wire: formatted(value.source.wire) }, + artifact: { ...value.artifact, wire: formatted(value.artifact.wire) }, + receipts: [ + { + ...value.receipts[0], + readbackWire: formatted(value.receipts[0].readbackWire) + } + ] + }; + const ready = read(aliases, aliases.owner); + expect(ready.ok).toBe(true); + if (!ready.ok) throw new Error(ready.reason); + expect(publicRecordSnapshot(ready.value, aliases.owner, id)).toEqual( + aliases + ); + }); + it('admits prepared-only records with no remote receipt claims', () => { + const value = operation(30402); + expect( + read( + { + ...value, + artifact: null, + receipts: [], + source: { type: 'draft', id, revision: 0 } + }, + value.owner + ).ok + ).toBe(true); + }); + it('rejects private signed kinds and forged signature/readback', () => { + const value = operation(30402); + for (const kind of [14, 13, 1059]) { + // Genuine generic NIP01 signatures for forbidden kinds, not qualified + // private message construction/encryption. Runtime input ignores TS casts. + const privateKind = operation(kind as 30402); + expect(verifyEnvelope(privateKind.artifact.wire).ok).toBe(true); + expect(read(privateKind, privateKind.owner).ok).toBe(false); + } + const artifact = JSON.parse(value.artifact.wire) as { + sig: string; + kind: number; + }; + artifact.sig = '0'.repeat(128); + expect( + read( + { + ...value, + artifact: { ...value.artifact, wire: JSON.stringify(artifact) } + }, + value.owner + ).ok + ).toBe(false); + expect( + read( + { + ...value, + receipts: [{ ...value.receipts[0], readbackWire: value.source.wire }] + }, + value.owner + ).ok + ).toBe(false); + }); + it('keeps preference consent/source/role distinct from public operations', () => { + const value = operation(10050); + for (const row of [ + { ...value, consent: 'inferred' }, + { ...value, source: { type: 'draft', id, revision: 0 } }, + { ...value, family: 'public_operation' }, + { ...value, receipts: [{ ...value.receipts[0], role: 'publication' }] } + ]) + expect(read(row, value.owner).ok).toBe(false); + }); +}); +describe('separate opaque conversation mapping contracts', () => { + const mapping = { schema: 1, family: 'conversation_handle', owner, id, peer }; + it('binds two distinct validated keys to an opaque local UUID', () => { + const result = decodeConversationMapping( + JSON.stringify(mapping), + owner, + id + ); + expect(result.ok).toBe(true); + if (!result.ok) throw new Error(result.reason); + expect(conversationMappingSnapshot(result.value, owner, id)).toEqual( + mapping + ); + expect(conversationMappingSnapshot(result.value, peer, id)).toBeUndefined(); + expect(read(mapping).ok).toBe(false); + }); + it('rejects self peer, private plaintext/listing fields and unknown scope', () => { + for (const row of [ + { ...mapping, peer: owner }, + { ...mapping, peer: '0'.repeat(64) }, + { ...mapping, body: 'test-only' }, + { ...mapping, listing: 'test-only' }, + { ...mapping, schema: 2 } + ]) + expect(decodeConversationMapping(JSON.stringify(row), owner, id).ok).toBe( + false + ); + expect( + decodeConversationMapping(JSON.stringify(mapping), peer, id).ok + ).toBe(false); + }); +});