app

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

inbox-setup.ts (12436B)


      1 import { exactLocalFields } from '../contracts/local-records.ts';
      2 import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts';
      3 import { safeUnsignedInteger } from '../nostr/envelope-bounds.ts';
      4 import { inspectLocalTemplate } from '../nostr/local-template.ts';
      5 import {
      6   inboxPreferenceSnapshot,
      7   inboxPreferenceWire
      8 } from '../nostr/inbox-preferences.ts';
      9 import {
     10   canonicalRelayOrigin,
     11   readRelayPolicy,
     12   publicRelayTargets,
     13   inboxRelayTargets,
     14   type RelayPolicy
     15 } from '../config/relays.ts';
     16 import {
     17   identityMessagingOwnership,
     18   type IdentitySession
     19 } from '../runtime/identity-session.ts';
     20 import {
     21   decodePublicRecord,
     22   publicRecordSnapshot,
     23   type PublicRecordHandle
     24 } from '../persistence/records.ts';
     25 import { canonicalLocalId } from '../private-handles.ts';
     26 import { operationEnabled } from '../config/operation-flags.ts';
     27 import {
     28   inboxResolutionSnapshot,
     29   inboxResolverCurrentAfterSample,
     30   type InboxResolver
     31 } from './resolve-inbox.ts';
     32 
     33 declare const reviewBrand: unique symbol;
     34 export type InboxSetupReview = Readonly<{ [reviewBrand]: true }>;
     35 type Preview = {
     36   author: string;
     37   originalWire: string | null;
     38   baseId: string | null;
     39   wire: string;
     40   hash: string;
     41   policyFingerprint: string;
     42   selectedInboxes: string[];
     43   destinations: string[];
     44   removedTagIndices: number[];
     45   removedExtraFields: string[];
     46   globalEffect: string;
     47 };
     48 type Saved = Readonly<{
     49   identity: IdentitySession;
     50   session: symbol;
     51   policy: RelayPolicy;
     52   previewWire: string;
     53 }>;
     54 const reviews = new WeakMap<InboxSetupReview, Saved>();
     55 const globalEffect =
     56   'This replaces your public inbox preference for other clients. Relay acceptance and readback are still required; this review does not publish.';
     57 function base(resolver: InboxResolver, policy: RelayPolicy, owner: string) {
     58   const resolution = inboxResolutionSnapshot(resolver),
     59     discovery = publicRelayTargets(policy, 'read');
     60   if (
     61     resolution.author !== owner ||
     62     resolution.coverage !== 'bounded-eose' ||
     63     resolution.status === 'inconclusive' ||
     64     discovery.length === 0 ||
     65     discovery.length !== resolution.sources.length ||
     66     !discovery.every((origin) =>
     67       resolution.sources.some(
     68         (row) => row.source === origin && row.state === 'eose'
     69       )
     70     )
     71   )
     72     return undefined;
     73   if (resolution.status === 'missing')
     74     return !resolution.head && !resolution.knownBase
     75       ? { wire: null, id: null, createdAt: undefined }
     76       : undefined;
     77   const head = resolution.head && inboxPreferenceSnapshot(resolution.head),
     78     wire = resolution.head && inboxPreferenceWire(resolution.head);
     79   return head &&
     80     wire &&
     81     head.author === owner &&
     82     head.id === resolution.knownBase?.id
     83     ? { wire, id: head.id, createdAt: head.createdAt }
     84     : undefined;
     85 }
     86 // Explicit source review only. The clock is an internal observation port like
     87 // the resolver clock; production uses actual wall time, tests control it. No
     88 // caller event extras enter the canonical signing contract implicitly.
     89 export async function reviewInboxSetup(
     90   identity: IdentitySession,
     91   resolver: InboxResolver,
     92   policy: RelayPolicy,
     93   raw: unknown,
     94   observeNow: () => number = () => Math.floor(Date.now() / 1000)
     95 ): Promise<
     96   | Readonly<{ status: 'review'; review: InboxSetupReview }>
     97   | Readonly<{ status: 'blocked'; reason: string }>
     98 > {
     99   try {
    100     const capture = identityMessagingOwnership(identity),
    101       manifest = readRelayPolicy(policy);
    102     if (
    103       !capture ||
    104       !capture.current() ||
    105       !operationEnabled(policy, 'messaging')
    106     )
    107       return { status: 'blocked', reason: 'unavailable' };
    108     const previous = base(resolver, policy, capture.owner);
    109     if (!previous || typeof raw !== 'string' || !boundedUtf8(raw, 65536))
    110       return { status: 'blocked', reason: 'unavailable' };
    111     const input: unknown = JSON.parse(raw);
    112     if (
    113       !exactLocalFields(input, [
    114         'selectedInboxes',
    115         'removeTagIndices',
    116         'removeExtraFields',
    117         'createdAt'
    118       ]) ||
    119       !Array.isArray(input.selectedInboxes) ||
    120       input.selectedInboxes.length < 1 ||
    121       input.selectedInboxes.length > 3 ||
    122       !Array.isArray(input.removeTagIndices) ||
    123       !Array.isArray(input.removeExtraFields)
    124     )
    125       return { status: 'blocked', reason: 'invalid_selection' };
    126     const time = safeUnsignedInteger(input.createdAt),
    127       now = safeUnsignedInteger(observeNow());
    128     if (
    129       time === undefined ||
    130       now !== time ||
    131       (previous.createdAt !== undefined && time <= previous.createdAt)
    132     )
    133       return { status: 'blocked', reason: 'clock_conflict' };
    134     const selected: string[] = [];
    135     function appendSelected(value: string) {
    136       selected.push(value);
    137     }
    138     for (const value of input.selectedInboxes as unknown[]) {
    139       if (
    140         typeof value !== 'string' ||
    141         selected.includes(value) ||
    142         !inboxRelayTargets(policy, [value], 'read').includes(value) ||
    143         !inboxRelayTargets(policy, [value], 'write').includes(value)
    144       )
    145         return { status: 'blocked', reason: 'invalid_selection' };
    146       appendSelected(value);
    147     }
    148     const old =
    149       previous.wire === null
    150         ? undefined
    151         : (JSON.parse(previous.wire) as { tags: string[][]; content: string });
    152     const tags = old?.tags ?? [];
    153     const removeTags: number[] = [],
    154       removeFields: string[] = [];
    155     function appendTagIndex(value: number) {
    156       removeTags.push(value);
    157     }
    158     function appendField(value: string) {
    159       removeFields.push(value);
    160     }
    161     if (
    162       input.removeTagIndices.length > tags.length ||
    163       input.removeExtraFields.length > 64
    164     )
    165       return { status: 'blocked', reason: 'invalid_selection' };
    166     for (const index of input.removeTagIndices as unknown[]) {
    167       if (
    168         typeof index !== 'number' ||
    169         safeUnsignedInteger(index) === undefined ||
    170         index >= tags.length ||
    171         removeTags.includes(index)
    172       )
    173         return { status: 'blocked', reason: 'invalid_selection' };
    174       appendTagIndex(index);
    175     }
    176     const standard = [
    177       'id',
    178       'sig',
    179       'pubkey',
    180       'kind',
    181       'created_at',
    182       'tags',
    183       'content'
    184     ];
    185     const extras: string[] = [];
    186     function appendExtra(value: string) {
    187       extras.push(value);
    188     }
    189     if (old)
    190       for (const key in old) if (!standard.includes(key)) appendExtra(key);
    191     for (const key of input.removeExtraFields as unknown[]) {
    192       if (
    193         typeof key !== 'string' ||
    194         !extras.includes(key) ||
    195         removeFields.includes(key)
    196       )
    197         return { status: 'blocked', reason: 'invalid_selection' };
    198       appendField(key);
    199     }
    200     // Unsigned extra fields cannot survive the existing exact five-field signer.
    201     // Block until the owner chooses every removal; retaining only the old source
    202     // would not constitute preservation in the outgoing replacement.
    203     if (extras.some((key) => !removeFields.includes(key)))
    204       return { status: 'blocked', reason: 'unsupported_extra_fields' };
    205     let nextTags = tags.filter((_tag, index) => !removeTags.includes(index));
    206     for (const origin of selected)
    207       if (
    208         !nextTags.some(
    209           (tag) => tag.length === 2 && tag[0] === 'relay' && tag[1] === origin
    210         )
    211       )
    212         nextTags = nextTags.concat([['relay', origin]]);
    213     // Reuse the public preference grammar without signing a synthetic event:
    214     // every retained relay tag must remain a canonical advertised origin. Other
    215     // tags/content/order/duplicates survive unchanged, including >3 advertisements.
    216     if (
    217       nextTags.some(
    218         (tag) =>
    219           tag[0] === 'relay' &&
    220           (tag.length !== 2 || !canonicalRelayOrigin(tag[1]))
    221       )
    222     )
    223       return { status: 'blocked', reason: 'unsupported_profile' };
    224     const wire = JSON.stringify({
    225       pubkey: capture.owner,
    226       kind: 10050,
    227       created_at: time,
    228       tags: nextTags,
    229       content: old?.content ?? ''
    230     });
    231     const template = inspectLocalTemplate(wire, capture.owner, 10050),
    232       destinations = publicRelayTargets(policy, 'write');
    233     if (!template || destinations.length === 0)
    234       return { status: 'blocked', reason: 'unsupported_profile' };
    235     const digest = await crypto.subtle.digest(
    236       'SHA-256',
    237       new TextEncoder().encode(JSON.stringify(manifest))
    238     );
    239     const policyFingerprint = Array.from(new Uint8Array(digest), (value) =>
    240       value.toString(16).padStart(2, '0')
    241     ).join('');
    242     if (!capture.current() || !inboxResolverCurrentAfterSample(resolver))
    243       return { status: 'blocked', reason: 'unavailable' };
    244     const preview: Preview = {
    245       author: capture.owner,
    246       originalWire: previous.wire,
    247       baseId: previous.id,
    248       wire,
    249       hash: template.hash,
    250       policyFingerprint,
    251       selectedInboxes: selected,
    252       destinations: destinations.slice(),
    253       removedTagIndices: removeTags,
    254       removedExtraFields: removeFields,
    255       globalEffect
    256     };
    257     const review = Object.freeze({}) as InboxSetupReview;
    258     reviews.set(review, {
    259       identity,
    260       session: capture.session,
    261       policy,
    262       previewWire: JSON.stringify(preview)
    263     });
    264     return { status: 'review', review };
    265   } catch {
    266     return { status: 'blocked', reason: 'unavailable' };
    267   }
    268 }
    269 export function inboxSetupPreview(
    270   review: InboxSetupReview
    271 ): Preview | undefined {
    272   const saved = reviews.get(review);
    273   return saved ? (JSON.parse(saved.previewWire) as Preview) : undefined;
    274 }
    275 export type InboxSetupCapture =
    276   | Readonly<{ status: 'captured'; record: PublicRecordHandle; owner: string }>
    277   | Readonly<{ status: 'invalid' | 'conflict' | 'unavailable' }>;
    278 // No effect permission: this exact reviewed record must be durably admitted
    279 // before later signing/publication. Fresh lookup is bounded knowledge, never CAS.
    280 export function captureInboxSetup(
    281   review: InboxSetupReview,
    282   resolver: InboxResolver,
    283   command: unknown,
    284   consent: unknown
    285 ): InboxSetupCapture {
    286   try {
    287     const saved = reviews.get(review),
    288       id = canonicalLocalId(command);
    289     if (!saved || !id || consent !== 'reviewed_global_inbox_replacement')
    290       return { status: 'invalid' };
    291     const preview = JSON.parse(saved.previewWire) as Preview,
    292       capture = identityMessagingOwnership(saved.identity);
    293     if (
    294       !capture ||
    295       capture.owner !== preview.author ||
    296       capture.session !== saved.session
    297     )
    298       return { status: 'unavailable' };
    299     const current = base(resolver, saved.policy, preview.author);
    300     if (!current) return { status: 'unavailable' };
    301     if (current.id !== preview.baseId || current.wire !== preview.originalWire)
    302       return { status: 'conflict' };
    303     const record = decodePublicRecord(
    304       JSON.stringify({
    305         schema: 1,
    306         family: 'preference_operation',
    307         owner: preview.author,
    308         id,
    309         revision: 0,
    310         source: { type: 'inbox_head', wire: preview.originalWire },
    311         consent: 'explicit_review',
    312         capture: {
    313           kind: 10050,
    314           wire: preview.wire,
    315           hash: preview.hash,
    316           targets: preview.destinations,
    317           policyFingerprint: preview.policyFingerprint
    318         },
    319         artifact: null,
    320         receipts: []
    321       }),
    322       preview.author,
    323       id
    324     );
    325     if (
    326       !record.ok ||
    327       !capture.current() ||
    328       !inboxResolverCurrentAfterSample(resolver)
    329     )
    330       return { status: 'unavailable' };
    331     return { status: 'captured', record: record.value, owner: preview.author };
    332   } catch {
    333     return { status: 'unavailable' };
    334   }
    335 }
    336 // Informational known-base fence only, never a signing or network capability.
    337 // Exact already-published artifact is an allowed observation on explicit resume;
    338 // competing/partial observations still block. This is not a global CAS.
    339 export function inboxSetupRecordCurrent(
    340   record: PublicRecordHandle,
    341   owner: string,
    342   id: string,
    343   resolver: InboxResolver,
    344   policy: RelayPolicy
    345 ): boolean {
    346   try {
    347     const row = publicRecordSnapshot(record, owner, id),
    348       observed = base(resolver, policy, owner);
    349     if (!row || row.family !== 'preference_operation' || !observed)
    350       return false;
    351     const matches =
    352       observed.wire === row.source.wire ||
    353       (row.artifact !== null &&
    354         observed.id === row.artifact.eventId &&
    355         observed.wire === row.artifact.wire);
    356     return matches && inboxResolverCurrentAfterSample(resolver);
    357   } catch {
    358     return false;
    359   }
    360 }