app

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

listing-publisher.ts (10585B)


      1 import type { NostrEvent } from 'applesauce-core/helpers';
      2 import { operationEnabled } from '../config/operation-flags.ts';
      3 import { publicRelayTargets, type RelayPolicy } from '../config/relays.ts';
      4 import {
      5   listingPublicationOwnership,
      6   type ListingPublication
      7 } from '../publishing/sign-listing.ts';
      8 import {
      9   listingResumeOwnership,
     10   type ListingResumption
     11 } from '../publishing/resume-listing.ts';
     12 import {
     13   listingRetryOwnership,
     14   type ListingRetry
     15 } from '../publishing/retry-listing.ts';
     16 import {
     17   identityMessagingOwnership,
     18   identityPublicOperationOwnership,
     19   recheckIdentityOwner,
     20   type IdentitySession
     21 } from '../runtime/identity-session.ts';
     22 import { preferencePolicyFingerprint } from './inbox-preference-publication.ts';
     23 import { readPublicListingIntent } from '../persistence/public-publications.ts';
     24 import {
     25   decodePublicRecord,
     26   publicRecordSnapshot,
     27   type PublicRecordHandle
     28 } from '../persistence/records.ts';
     29 declare const leaseBrand: unique symbol;
     30 declare const permissionBrand: unique symbol;
     31 export type ListingDeliveryLease = Readonly<{ [leaseBrand]: true }>;
     32 export type ListingAttemptPermission = Readonly<{ [permissionBrand]: true }>;
     33 type Original = NonNullable<
     34   | ReturnType<typeof listingPublicationOwnership>
     35   | ReturnType<typeof listingResumeOwnership>
     36 >;
     37 type Owner = Readonly<{
     38   original: Original;
     39   policy: RelayPolicy;
     40   signal?: AbortSignal;
     41   current(): boolean;
     42 }>;
     43 type Permission = Readonly<{
     44   owner: Owner;
     45   origin: string;
     46   mode: 'publish' | 'readback';
     47   wire: string;
     48 }>;
     49 const leases = new WeakMap<ListingDeliveryLease, Owner>();
     50 const permissions = new WeakMap<ListingAttemptPermission, Permission>();
     51 // Stop releases this action's wait and author lock. The extension promise may
     52 // settle later; it cannot resurrect the revoked network lease or a signer.
     53 async function recheckDeliveryOwner(
     54   identity: IdentitySession,
     55   signal?: AbortSignal
     56 ): Promise<boolean> {
     57   if (signal?.aborted) return false;
     58   if (!signal) {
     59     await recheckIdentityOwner(identity);
     60     return true;
     61   }
     62   let stop = () => {};
     63   const stopped = new Promise<boolean>((resolve) => {
     64     stop = () => resolve(false);
     65     signal.addEventListener('abort', stop, { once: true });
     66     if (signal.aborted) stop();
     67   });
     68   try {
     69     return await Promise.race([
     70       recheckIdentityOwner(identity).then(() => true),
     71       stopped
     72     ]);
     73   } finally {
     74     signal.removeEventListener('abort', stop);
     75   }
     76 }
     77 // Receipt revisions may grow, but the complete original operation payload and
     78 // verified artifact stay exact. No new command, author or destination is adopted.
     79 export async function readRetainedListingDelivery(
     80   lease: ListingDeliveryLease
     81 ): Promise<PublicRecordHandle | undefined> {
     82   const owner = leases.get(lease);
     83   if (!owner) return;
     84   const original = owner.original;
     85   const expected = decodePublicRecord(
     86     original.recordWire,
     87     original.owner,
     88     original.command
     89   );
     90   if (!expected.ok) return;
     91   const baseline = publicRecordSnapshot(
     92     expected.value,
     93     original.owner,
     94     original.command
     95   );
     96   if (
     97     baseline?.family !== 'public_operation' ||
     98     !(
     99       baseline.capture.kind === 30402 ||
    100       (baseline.capture.kind === 5 && baseline.source.type === 'public_head')
    101     ) ||
    102     !baseline.artifact ||
    103     baseline.revision !== 2
    104   )
    105     return;
    106   const read = await readPublicListingIntent(
    107     original.repository,
    108     original.command
    109   );
    110   if (read.status !== 'found') return;
    111   const row = publicRecordSnapshot(
    112     read.record,
    113     original.owner,
    114     original.command
    115   );
    116   if (
    117     row?.family !== 'public_operation' ||
    118     row.revision < baseline.revision ||
    119     JSON.stringify({
    120       ...row,
    121       revision: baseline.revision,
    122       receipts: baseline.receipts
    123     }) !== JSON.stringify(baseline)
    124   )
    125     return;
    126   return read.record;
    127 }
    128 // Current authority is mandatory for every new network permission. Retained
    129 // exact storage observation above remains usable for bookkeeping after Stop.
    130 export async function readOwnedListingDelivery(
    131   lease: ListingDeliveryLease
    132 ): Promise<PublicRecordHandle | undefined> {
    133   const owner = leases.get(lease);
    134   if (!owner?.current()) return;
    135   const read = readRetainedListingDelivery(lease);
    136   let stop = () => {};
    137   const stopped =
    138     owner.signal &&
    139     new Promise<undefined>((resolve) => {
    140       stop = () => resolve(undefined);
    141       owner.signal!.addEventListener('abort', stop, { once: true });
    142       if (owner.signal!.aborted) stop();
    143     });
    144   let record: PublicRecordHandle | undefined;
    145   try {
    146     record = await (stopped ? Promise.race([read, stopped]) : read);
    147   } finally {
    148     owner.signal?.removeEventListener('abort', stop);
    149   }
    150   return owner.current() ? record : undefined;
    151 }
    152 export function listingDeliveryOwnership(lease: ListingDeliveryLease) {
    153   const owner = leases.get(lease);
    154   return owner?.current()
    155     ? {
    156         repository: owner.original.repository,
    157         owner: owner.original.owner,
    158         command: owner.original.command,
    159         current: owner.current
    160       }
    161     : undefined;
    162 }
    163 export type ListingOwnershipResult<T> =
    164   | Readonly<{ status: 'completed'; value: T }>
    165   | Readonly<{ status: 'invalid' | 'unavailable' | 'busy' | 'stopped' }>;
    166 // One original author lock spans this finite explicitly requested network
    167 // action. It never spans a native IDB transaction and cannot mint a signer.
    168 export async function withListingDeliveryOwnership<T>(
    169   publication: ListingPublication | ListingResumption,
    170   policy: RelayPolicy,
    171   consent: unknown,
    172   work: (lease: ListingDeliveryLease) => Promise<T>,
    173   control?: ListingRetry
    174 ): Promise<ListingOwnershipResult<T>> {
    175   const signed = listingPublicationOwnership(publication as ListingPublication),
    176     resumed = listingResumeOwnership(publication as ListingResumption),
    177     original = signed ?? resumed,
    178     retry = control && listingRetryOwnership(control);
    179   if (
    180     !original ||
    181     (control
    182       ? !retry ||
    183         retry.source !== publication ||
    184         retry.policy !== policy ||
    185         retry.consent !== consent
    186       : !signed || consent !== 'publish_stored_listing') ||
    187     original.policy !== policy
    188   )
    189     return { status: 'invalid' };
    190   if (retry && !retry.current()) return { status: 'stopped' };
    191   if (typeof window === 'undefined' || !navigator.locks?.request)
    192     return { status: 'unavailable' };
    193   try {
    194     return await navigator.locks.request(
    195       'harvestcircle:owner:' + original.owner,
    196       { mode: 'exclusive', ifAvailable: true },
    197       async (lock): Promise<ListingOwnershipResult<T>> => {
    198         if (!lock) return { status: 'busy' };
    199         if (!(await recheckDeliveryOwner(original.identity, retry?.signal)))
    200           return { status: 'stopped' };
    201         const operation =
    202             signed &&
    203             identityPublicOperationOwnership(
    204               original.identity,
    205               signed.operation
    206             ),
    207           // A signed public update retains its original public operation.
    208           // New-listing inbox readiness stays in original.current(); edits
    209           // do not require a messaging probe. Resumptions keep their gate.
    210           identity = signed
    211             ? operation
    212             : identityMessagingOwnership(original.identity);
    213         if (
    214           !identity ||
    215           (signed && !operation) ||
    216           identity.owner !== original.owner ||
    217           (operation &&
    218             (operation.owner !== original.owner ||
    219               operation.session !== identity.session)) ||
    220           !original.current() ||
    221           (retry && !retry.current())
    222         )
    223           return { status: 'stopped' };
    224         let active = true;
    225         const owner: Owner = {
    226           original,
    227           policy,
    228           signal: retry?.signal,
    229           current: () =>
    230             active &&
    231             original.current() &&
    232             identity.current() &&
    233             (!operation || operation.current()) &&
    234             (!retry || retry.current())
    235         };
    236         const lease = Object.freeze({}) as ListingDeliveryLease;
    237         leases.set(lease, owner);
    238         try {
    239           if (!(await readOwnedListingDelivery(lease)))
    240             return {
    241               status: retry && !retry.current() ? 'stopped' : 'unavailable'
    242             };
    243           return { status: 'completed', value: await work(lease) };
    244         } finally {
    245           active = false;
    246         }
    247       }
    248     );
    249   } catch {
    250     return { status: 'unavailable' };
    251   }
    252 }
    253 // Each permission comes from actual stored signed bytes, fresh identity and
    254 // unchanged original policy. Preference/private capabilities cannot enter it.
    255 export async function authorizeListingAttempt(
    256   lease: ListingDeliveryLease,
    257   origin: string,
    258   mode: 'publish' | 'readback'
    259 ): Promise<ListingAttemptPermission | undefined> {
    260   const owner = leases.get(lease);
    261   if (!owner || !owner.current() || (mode !== 'publish' && mode !== 'readback'))
    262     return;
    263   try {
    264     const record = await readOwnedListingDelivery(lease),
    265       original = owner.original;
    266     const row =
    267       record && publicRecordSnapshot(record, original.owner, original.command);
    268     const targets = publicRelayTargets(owner.policy, 'write'),
    269       fingerprint = await preferencePolicyFingerprint(owner.policy);
    270     if (
    271       row?.family !== 'public_operation' ||
    272       !row.artifact ||
    273       !operationEnabled(owner.policy, 'posting') ||
    274       fingerprint !== row.capture.policyFingerprint ||
    275       JSON.stringify(targets) !== JSON.stringify(row.capture.targets) ||
    276       !row.capture.targets.includes(origin)
    277     )
    278       return;
    279     if (!(await recheckDeliveryOwner(original.identity, owner.signal))) return;
    280     if (!owner.current()) return;
    281     const token = Object.freeze({}) as ListingAttemptPermission;
    282     permissions.set(token, { owner, origin, mode, wire: row.artifact.wire });
    283     return token;
    284   } catch {
    285     return;
    286   }
    287 }
    288 // Original once-only token: detached metadata, wrong role, policy or origin
    289 // cannot supply a raw event. SDK effects remain owned by the public pool.
    290 export function takeListingPublication(
    291   token: ListingAttemptPermission,
    292   policy: RelayPolicy,
    293   origin: string,
    294   mode: 'publish' | 'readback'
    295 ):
    296   | Readonly<{ event: NostrEvent; wire: string; current(): boolean }>
    297   | undefined {
    298   const saved = permissions.get(token);
    299   if (!saved) return;
    300   permissions.delete(token);
    301   if (
    302     saved.owner.policy !== policy ||
    303     saved.origin !== origin ||
    304     saved.mode !== mode ||
    305     !saved.owner.current()
    306   )
    307     return;
    308   return {
    309     event: JSON.parse(saved.wire) as NostrEvent,
    310     wire: saved.wire,
    311     current: saved.owner.current
    312   };
    313 }