app

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

inbox-setup-verification.ts (9853B)


      1 import {
      2   readRelayPolicy,
      3   publicRelayTargets,
      4   type RelayPolicy
      5 } from '../config/relays.ts';
      6 import { publicRecordSnapshot } from '../persistence/records.ts';
      7 import {
      8   loadPreferenceOperation,
      9   commitPublicOperationTransition,
     10   observePublicOperationTransition,
     11   publicQuotaOwner,
     12   type PublicQuotaRepository
     13 } from '../persistence/quota.ts';
     14 import { preparePublicReceiptTransition } from '../persistence/artifact-records.ts';
     15 import { preferencePolicyFingerprint } from '../nostr/inbox-preference-publication.ts';
     16 import {
     17   inboxReadbackSnapshot,
     18   inboxReadbackEvidence,
     19   useInboxReadback,
     20   type InboxReadback
     21 } from '../nostr/inbox-readback.ts';
     22 import {
     23   identityMessagingOwnership,
     24   recheckIdentityOwner,
     25   type IdentitySession
     26 } from '../runtime/identity-session.ts';
     27 import {
     28   privateSessionOwnership,
     29   type PrivateSession
     30 } from '../runtime/private-session.ts';
     31 import {
     32   inboxResolverCurrentAfterSample,
     33   type InboxResolver
     34 } from './resolve-inbox.ts';
     35 import {
     36   messagingReadinessSnapshot,
     37   type ObserveInboxAccess,
     38   type InboxAccessObservation
     39 } from './readiness.ts';
     40 type Peer = Readonly<{ author: unknown; resolver: InboxResolver }>;
     41 type Status =
     42   | 'invalid'
     43   | 'unknown'
     44   | 'stopped'
     45   | 'busy'
     46   | 'storage_failed'
     47   | 'awaiting_acceptance'
     48   | 'awaiting_readback'
     49   | 'conflict'
     50   | 'access_unavailable'
     51   | 'verified'
     52   | 'compatible_existing';
     53 export type InboxSetupVerificationResult = Readonly<{
     54   status: Status;
     55   setupComplete: boolean;
     56   newListingReady: boolean;
     57   sendReady: boolean;
     58   knownHead?: Readonly<{ id: string; createdAt: number }>;
     59 }>;
     60 function blocked(
     61   status: Status,
     62   knownHead?: InboxSetupVerificationResult['knownHead']
     63 ): InboxSetupVerificationResult {
     64   return {
     65     status,
     66     setupComplete: false,
     67     newListingReady: false,
     68     sendReady: false,
     69     ...(knownHead ? { knownHead } : {})
     70   };
     71 }
     72 // Existing compatible configuration does not create a local command or perform
     73 // a redundant write. This is detached information, never effect permission.
     74 export function existingInboxSetupSnapshot(
     75   identity: IdentitySession,
     76   session: PrivateSession | undefined,
     77   policy: RelayPolicy,
     78   own: InboxResolver,
     79   observeAccess?: ObserveInboxAccess,
     80   peer?: Peer
     81 ): InboxSetupVerificationResult {
     82   const ready = messagingReadinessSnapshot(
     83     identity,
     84     session,
     85     policy,
     86     own,
     87     peer,
     88     observeAccess
     89   );
     90   if (ready.ownAccess !== 'qualified_exercised')
     91     return blocked('access_unavailable');
     92   return {
     93     status: 'compatible_existing',
     94     setupComplete: true,
     95     newListingReady:
     96       readRelayPolicy(policy).postingEnabled && ready.newListingReady,
     97     sendReady: ready.sendReady
     98   };
     99 }
    100 // Explicit verification of a chosen durable operation. ACK and exact readback
    101 // remain separate facts. No EVENT, extension signing, AUTH or auto replacement.
    102 export async function verifyInboxSetupOperation(
    103   repository: PublicQuotaRepository,
    104   identity: IdentitySession,
    105   session: PrivateSession | undefined,
    106   policy: RelayPolicy,
    107   reader: InboxReadback,
    108   observeAccess?: ObserveInboxAccess,
    109   peer?: Peer
    110 ): Promise<InboxSetupVerificationResult> {
    111   const initial = inboxReadbackSnapshot(reader);
    112   if (!initial) return blocked('invalid');
    113   if (!useInboxReadback(reader)) return blocked('stopped', initial.knownHead);
    114   try {
    115     if (typeof window === 'undefined' || !navigator.locks?.request)
    116       return blocked('unknown');
    117     await recheckIdentityOwner(identity);
    118     const owner = identityMessagingOwnership(identity);
    119     if (
    120       !owner ||
    121       owner.owner !== initial.owner ||
    122       publicQuotaOwner(repository) !== owner.owner
    123     )
    124       return blocked('stopped');
    125     return await navigator.locks.request(
    126       'harvestcircle:owner:' + owner.owner,
    127       { mode: 'exclusive', ifAvailable: true },
    128       async (lock) => {
    129         if (!lock) return blocked('busy');
    130         const evidence = inboxReadbackEvidence(reader);
    131         if (!evidence || !owner.current())
    132           return blocked('unknown', initial.knownHead);
    133         const original = publicRecordSnapshot(
    134           evidence.record,
    135           owner.owner,
    136           evidence.id
    137         );
    138         const read = await loadPreferenceOperation(repository, evidence.id);
    139         if (!read.ok) return blocked('storage_failed');
    140         const row = publicRecordSnapshot(read.value, owner.owner, evidence.id);
    141         if (
    142           row?.family !== 'preference_operation' ||
    143           original?.family !== 'preference_operation' ||
    144           !row.artifact ||
    145           row.artifact.wire !== original.artifact?.wire ||
    146           JSON.stringify(row.capture) !== JSON.stringify(original.capture) ||
    147           JSON.stringify(row.source) !== JSON.stringify(original.source) ||
    148           row.consent !== original.consent ||
    149           evidence.policy !== policy ||
    150           row.capture.policyFingerprint !==
    151             (await preferencePolicyFingerprint(policy)) ||
    152           JSON.stringify(row.capture.targets) !==
    153             JSON.stringify(publicRelayTargets(policy, 'write')) ||
    154           !owner.current() ||
    155           !evidence.current()
    156         )
    157           return blocked('stopped');
    158         const accepted = row.receipts.filter(
    159           (fact) =>
    160             fact.status === 'accepted' && fact.eventId === row.artifact!.eventId
    161         );
    162         if (accepted.length === 0)
    163           return blocked('awaiting_acceptance', evidence.knownHead);
    164         // Named ACK and discovery readback may come from different fixed relays.
    165         // Each readback retains its own actual source, never an ACK at that source.
    166         const observed = evidence.wires;
    167         if (observed.length === 0)
    168           return blocked(
    169             evidence.status === 'conflict' ? 'conflict' : 'awaiting_readback',
    170             evidence.knownHead
    171           );
    172         // A fresh readback action retains prior ACK facts and records the actual
    173         // read observation; it never claims a new EVENT or new relay ACK.
    174         const actionId = crypto.randomUUID();
    175         for (const proof of observed) {
    176           const prior =
    177             accepted.find((fact) => fact.origin === proof.origin) ??
    178             accepted[0];
    179           if (!owner.current() || !evidence.current())
    180             return blocked('stopped');
    181           const current = await loadPreferenceOperation(
    182             repository,
    183             evidence.id
    184           );
    185           if (!current.ok) return blocked('storage_failed');
    186           const stored = publicRecordSnapshot(
    187             current.value,
    188             owner.owner,
    189             evidence.id
    190           );
    191           if (stored?.family !== 'preference_operation')
    192             return blocked('storage_failed');
    193           if (
    194             stored.receipts.some(
    195               (fact) =>
    196                 fact.origin === prior.origin &&
    197                 fact.readbackOrigin === proof.origin &&
    198                 fact.status === 'accepted' &&
    199                 fact.readbackWire === proof.wire
    200             )
    201           )
    202             continue;
    203           const transition = preparePublicReceiptTransition(
    204             current.value,
    205             owner.owner,
    206             evidence.id,
    207             JSON.stringify({
    208               actionId,
    209               origin: prior.origin,
    210               readbackOrigin: proof.origin,
    211               role: 'preference',
    212               attempt: prior.attempt,
    213               eventId: row.artifact.eventId,
    214               status: 'accepted',
    215               observedAtMilliseconds: Date.now(),
    216               readbackWire: proof.wire
    217             })
    218           );
    219           if (!owner.current() || !evidence.current())
    220             return blocked('stopped');
    221           if (
    222             !transition.ok ||
    223             !(
    224               await commitPublicOperationTransition(
    225                 repository,
    226                 transition.value
    227               )
    228             ).ok ||
    229             (
    230               await observePublicOperationTransition(
    231                 repository,
    232                 transition.value
    233               )
    234             ).state !== 'committed'
    235           )
    236             return blocked('storage_failed');
    237         }
    238         const privateOwner = session && privateSessionOwnership(session);
    239         let observedAccess: InboxAccessObservation | undefined;
    240         const ready = messagingReadinessSnapshot(
    241           identity,
    242           session,
    243           policy,
    244           evidence.resolver,
    245           peer,
    246           observeAccess
    247             ? (context) => {
    248                 const observation = observeAccess(context);
    249                 observedAccess = observation;
    250                 return observation;
    251               }
    252             : undefined
    253         );
    254         // The last head sample can invalidate exercised access. Recheck the
    255         // retained access proof before the final clock-free ownership fences.
    256         const final = inboxReadbackSnapshot(reader);
    257         const accessCurrent = observedAccess?.current() ?? false;
    258         if (
    259           !final ||
    260           !owner.current() ||
    261           !privateOwner?.current() ||
    262           !evidence.current() ||
    263           (peer && !inboxResolverCurrentAfterSample(peer.resolver))
    264         )
    265           return blocked('stopped', final?.knownHead);
    266         if (final.status === 'conflict')
    267           return blocked('conflict', final.knownHead);
    268         if (final.status !== 'readback' || !final.complete)
    269           return blocked('unknown', final.knownHead);
    270         if (ready.ownAccess !== 'qualified_exercised' || !accessCurrent)
    271           return blocked('access_unavailable', final.knownHead);
    272         return {
    273           status: 'verified',
    274           setupComplete: true,
    275           newListingReady:
    276             readRelayPolicy(policy).postingEnabled && ready.newListingReady,
    277           sendReady: ready.sendReady,
    278           knownHead: final.knownHead
    279         };
    280       }
    281     );
    282   } catch {
    283     return blocked('unknown');
    284   }
    285 }