app

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

edit-source.ts (15978B)


      1 import { buildFoodTemplate } from '../contracts/food-availability-v1/write.ts';
      2 import {
      3   projectFoodParts,
      4   type FoodProjection
      5 } from '../contracts/food-availability-v1/read.ts';
      6 import type { PublicDraftForm } from '../contracts/local-records.ts';
      7 import { decodeProductReference } from '../nostr/references.ts';
      8 import { inspectLocalTemplate } from '../nostr/local-template.ts';
      9 import {
     10   verifyEnvelope,
     11   verifiedEnvelopeSnapshot
     12 } from '../nostr/verified-envelope.ts';
     13 import {
     14   publicPublicationOwner,
     15   publicPublicationDraftRepository,
     16   publicPublicationQuotaRepository,
     17   readPublicListingIntent,
     18   type PublicPublicationRepository
     19 } from '../persistence/public-publications.ts';
     20 import {
     21   inspectPublicStorage,
     22   publicInventorySnapshot
     23 } from '../persistence/quota.ts';
     24 import {
     25   publicRecordSnapshot,
     26   type PublicRecordHandle
     27 } from '../persistence/records.ts';
     28 import { readPublicDraft } from '../persistence/drafts.ts';
     29 import {
     30   identityViewSession,
     31   identityViewMatchesOwner,
     32   type IdentityViewContext
     33 } from '../runtime/view-context.ts';
     34 import { subscribeIdentityInvalidation } from '../runtime/identity-session.ts';
     35 import {
     36   createPublicView,
     37   beginPublicViewRun,
     38   disposePublicView,
     39   publicViewOwnsRun,
     40   publicViewRunCurrent,
     41   publicViewProjectionAvailable,
     42   publicRuntimePolicy,
     43   type PublicRuntime,
     44   type PublicView
     45 } from '../runtime/public-runtime.ts';
     46 import {
     47   createPublicViewHeadResolver,
     48   resolveHeads,
     49   headResolutionSnapshot,
     50   closeHeadResolver,
     51   type HeadResolver
     52 } from '../catalog/resolve-head.ts';
     53 import {
     54   createPublicHeadCandidate,
     55   publicHeadKey,
     56   publicHeadSnapshot,
     57   selectPublicHead
     58 } from '../catalog/heads.ts';
     59 import type { RelayPolicy } from '../config/relays.ts';
     60 import type { IdentitySession } from '../runtime/identity-session.ts';
     61 
     62 declare const sourceBrand: unique symbol;
     63 export type OwnedEditSource = Readonly<{ [sourceBrand]: true }>;
     64 export type OwnedEditSourceSnapshot = Readonly<{
     65   owner: string;
     66   coordinate: string;
     67   sourceEventId: string;
     68   sourceCommand: string;
     69   publishedAtSeconds: number;
     70   form: PublicDraftForm;
     71   status:
     72     'read-only' | 'checking' | 'ready' | 'partial' | 'conflict' | 'withdrawn';
     73   current?: FoodProjection;
     74   currentEventId?: string;
     75   definitiveAbsence: false;
     76 }>;
     77 type Source = {
     78   snapshot(): OwnedEditSourceSnapshot | undefined;
     79   authorize():
     80     | Readonly<{
     81         repository: PublicPublicationRepository;
     82         owner: string;
     83         coordinate: string;
     84         baseWire: string;
     85         sourceCommand: string;
     86         sourceRecord: PublicRecordHandle;
     87         publishedAtSeconds: number;
     88         identity: IdentitySession;
     89         policy: RelayPolicy;
     90         currentRevision(eventId: string): boolean;
     91         currentWithdrawal(eventId: string): boolean;
     92         current(): boolean;
     93       }>
     94     | undefined;
     95   close(): void;
     96 };
     97 const sources = new WeakMap<OwnedEditSource, Source>();
     98 // Retained prototype custody precedes network work. A public/Tera event, a
     99 // snapshot, or an arbitrary same-author signature is not adopted as local source.
    100 export async function openOwnedEditSource(
    101   repository: PublicPublicationRepository,
    102   context: IdentityViewContext,
    103   value: unknown,
    104   runtime?: PublicRuntime,
    105   signal?: AbortSignal
    106 ): Promise<OwnedEditSource | undefined> {
    107   let view: PublicView | undefined, resolver: HeadResolver | undefined;
    108   let closed = false,
    109     off = () => {};
    110   function close() {
    111     if (closed) return;
    112     closed = true;
    113     off();
    114     signal?.removeEventListener('abort', close);
    115     try {
    116       if (resolver) closeHeadResolver(resolver);
    117     } finally {
    118       if (view) disposePublicView(view);
    119     }
    120   }
    121   try {
    122     const owner = publicPublicationOwner(repository),
    123       session = identityViewSession(context),
    124       reference = decodeProductReference(value),
    125       drafts = publicPublicationDraftRepository(repository),
    126       quota = publicPublicationQuotaRepository(repository);
    127     if (
    128       !owner ||
    129       !session ||
    130       !reference ||
    131       reference.pubkey !== owner ||
    132       !drafts ||
    133       !quota ||
    134       signal?.aborted ||
    135       !identityViewMatchesOwner(context, owner)
    136     )
    137       return;
    138     const current = () =>
    139       !closed &&
    140       !signal?.aborted &&
    141       identityViewSession(context) === session &&
    142       identityViewMatchesOwner(context, owner) &&
    143       publicPublicationOwner(repository) === owner;
    144     off = subscribeIdentityInvalidation(session, () => {
    145       // A delivery recheck also notifies after observing the unchanged owner.
    146       // Only loss of this original mounted owner closes its source custody.
    147       if (!current()) close();
    148     });
    149     signal?.addEventListener('abort', close, { once: true });
    150     const inspected = await inspectPublicStorage(quota);
    151     if (!current() || !inspected.ok) {
    152       close();
    153       return;
    154     }
    155     const inventory = publicInventorySnapshot(quota, inspected.value);
    156     if (!inventory) {
    157       close();
    158       return;
    159     }
    160     let retained:
    161       | Readonly<{
    162           form: PublicDraftForm;
    163           wire: string;
    164           command: string;
    165           publishedAt: number;
    166           eventId: string;
    167           record: PublicRecordHandle;
    168         }>
    169       | undefined;
    170     let captures = Array.from<{ hash: string; createdAt: number }>([]);
    171     for (const item of inventory.rows) {
    172       if (item.family !== 'public_operation') continue;
    173       const read = await readPublicListingIntent(repository, item.id);
    174       if (!current()) {
    175         close();
    176         return;
    177       }
    178       const row =
    179         read.status === 'found' &&
    180         publicRecordSnapshot(read.record, owner, item.id);
    181       // Incomplete critical storage is not an absence that permits adoption.
    182       if (
    183         read.status !== 'found' ||
    184         !row ||
    185         row.family !== 'public_operation'
    186       ) {
    187         close();
    188         return;
    189       }
    190       if (row.capture.kind !== 30402 || row.source.type !== 'draft') continue;
    191       const template = inspectLocalTemplate(row.capture.wire, owner, 30402),
    192         projected = template && projectFoodParts(template);
    193       if (
    194         !template ||
    195         !projected ||
    196         projected.outcome !== 'focused' ||
    197         projected.projection.identifier !== reference.identifier
    198       )
    199         continue;
    200       captures = captures.concat({
    201         hash: row.capture.hash,
    202         createdAt: template.created_at
    203       });
    204       if (!row.artifact) continue;
    205       const source = await readPublicDraft(drafts, row.source.id);
    206       if (!current()) {
    207         close();
    208         return;
    209       }
    210       if (!source.ok || source.value.revision !== row.source.revision) continue;
    211       const form = source.value.form,
    212         food = projected.projection;
    213       if (form.contactType === '' && form.contactValue !== '') continue;
    214       const built = buildFoodTemplate({
    215         identifier: food.identifier,
    216         title: form.title,
    217         description: form.description,
    218         location: form.location,
    219         amount: form.amount,
    220         currency: form.currency,
    221         unit: form.unit,
    222         ...(form.quantity === '' ? {} : { quantity: form.quantity }),
    223         published_at: food.published_at,
    224         created_at: template.created_at,
    225         status: food.status,
    226         ...(form.contactType === ''
    227           ? {}
    228           : {
    229               contact: {
    230                 type: form.contactType,
    231                 value: form.contactValue,
    232                 public: true as const
    233               }
    234             })
    235       });
    236       if (
    237         !built.ok ||
    238         JSON.stringify({
    239           pubkey: owner,
    240           kind: 30402,
    241           created_at: template.created_at,
    242           tags: built.wire_parts.tags,
    243           content: built.wire_parts.content
    244         }) !== row.capture.wire
    245       )
    246         continue;
    247       const verified = verifyEnvelope(row.artifact.wire),
    248         signed = verified.ok && verifiedEnvelopeSnapshot(verified.value);
    249       if (
    250         !verified.ok ||
    251         !signed ||
    252         signed.id !== row.artifact.eventId ||
    253         signed.id !== row.capture.hash ||
    254         JSON.stringify({
    255           pubkey: signed.pubkey,
    256           kind: signed.kind,
    257           created_at: signed.created_at,
    258           tags: signed.tags,
    259           content: signed.content
    260         }) !== row.capture.wire
    261       )
    262         continue;
    263       if (retained) {
    264         const priorProof = verifyEnvelope(retained.wire);
    265         const prior =
    266           priorProof.ok && createPublicHeadCandidate(priorProof.value);
    267         const next = createPublicHeadCandidate(verified.value);
    268         // Supported revisions have strict advancing time and unchanged initial
    269         // publication time. Equal-time/duplicate/unrelated captures are ambiguous.
    270         if (
    271           !prior ||
    272           !next ||
    273           retained.publishedAt !== food.published_at ||
    274           publicHeadSnapshot(prior).created_at === signed.created_at
    275         ) {
    276           close();
    277           return;
    278         }
    279         if (selectPublicHead(prior, next).head === prior) continue;
    280       }
    281       retained = {
    282         form,
    283         wire: row.artifact.wire,
    284         command: row.id,
    285         publishedAt: food.published_at,
    286         eventId: signed.id,
    287         record: read.record
    288       };
    289     }
    290     if (!retained || !current()) {
    291       close();
    292       return;
    293     }
    294     const base = retained,
    295       proof = verifyEnvelope(base.wire);
    296     const head = proof.ok && createPublicHeadCandidate(proof.value);
    297     if (
    298       !head ||
    299       captures.some(
    300         (capture) =>
    301           capture.hash !== base.eventId &&
    302           capture.createdAt >= publicHeadSnapshot(head).created_at
    303       )
    304     ) {
    305       close();
    306       return;
    307     }
    308     const key = publicHeadKey(head);
    309     let run: ReturnType<typeof beginPublicViewRun> | undefined;
    310     if (runtime) {
    311       // A separate view/run and exact coordinate+deletion requests are independent
    312       // of keyword search. Genuine retained proof seeds the ordinary selector.
    313       view = createPublicView(runtime);
    314       run = beginPublicViewRun(view);
    315       resolver = createPublicViewHeadResolver(view, run, {
    316         nowSeconds: () => Math.floor(Date.now() / 1000)
    317       });
    318       resolveHeads(resolver, [head]);
    319     }
    320     const networkOwned = () =>
    321       !!(
    322         view &&
    323         run &&
    324         publicViewOwnsRun(view, run) &&
    325         publicViewProjectionAvailable(view)
    326       );
    327     function snapshot(): OwnedEditSourceSnapshot | undefined {
    328       if (!current()) {
    329         close();
    330         return;
    331       }
    332       const row =
    333         resolver && networkOwned()
    334           ? headResolutionSnapshot(resolver).find((row) => row.key === key)
    335           : undefined;
    336       const scopes = row && [row.headSources, row.deletionSources];
    337       const complete = !!(
    338         row &&
    339         view &&
    340         run &&
    341         publicViewRunCurrent(view, run) &&
    342         row.coverage === 'bounded-eose' &&
    343         !row.lastKnown &&
    344         scopes?.every(
    345           (scope) =>
    346             scope?.state === 'eose' && scope.result.coverage === 'bounded-eose'
    347         )
    348       );
    349       const competing = row && row.state.head.id !== base.eventId;
    350       const status: OwnedEditSourceSnapshot['status'] = !runtime
    351         ? 'read-only'
    352         : row?.deletion.outcome === 'suppressed'
    353           ? 'withdrawn'
    354           : competing
    355             ? 'conflict'
    356             : complete &&
    357                 row?.state.food &&
    358                 row.state.display === 'focused_known'
    359               ? 'ready'
    360               : scopes?.some((scope) => scope?.state === 'active')
    361                 ? 'checking'
    362                 : 'partial';
    363       return {
    364         owner: owner!,
    365         coordinate: reference!.naddr,
    366         sourceEventId: base.eventId,
    367         sourceCommand: base.command,
    368         publishedAtSeconds: base.publishedAt,
    369         form: { ...base.form },
    370         status,
    371         ...(row?.state.food ? { current: row.state.food } : {}),
    372         ...(row ? { currentEventId: row.state.head.id } : {}),
    373         definitiveAbsence: false
    374       };
    375     }
    376     const token = Object.freeze({}) as OwnedEditSource;
    377     sources.set(token, {
    378       snapshot,
    379       close,
    380       authorize() {
    381         const policy = runtime && publicRuntimePolicy(runtime);
    382         if (snapshot()?.status !== 'ready' || !policy) return;
    383         return {
    384           repository,
    385           owner,
    386           coordinate: reference.naddr,
    387           baseWire: base.wire,
    388           sourceCommand: base.command,
    389           sourceRecord: base.record,
    390           publishedAtSeconds: base.publishedAt,
    391           identity: session,
    392           policy,
    393           currentWithdrawal(eventId: string) {
    394             const state = snapshot();
    395             if (
    396               !current() ||
    397               !runtime ||
    398               publicRuntimePolicy(runtime) !== policy
    399             )
    400               return false;
    401             if (state?.status === 'ready') return true;
    402             const row =
    403               resolver && networkOwned()
    404                 ? headResolutionSnapshot(resolver).find(
    405                     (value) => value.key === key
    406                   )
    407                 : undefined;
    408             // Only the original request's verified suppression preserves its
    409             // delivery continuity. A different request/head remains fenced.
    410             return !!(
    411               state?.status === 'withdrawn' &&
    412               state.currentEventId === base.eventId &&
    413               row &&
    414               row.state.display === 'focused_known' &&
    415               row.deletion.eventReference?.requestId === eventId &&
    416               row.deletion.addressReference?.requestId === eventId &&
    417               row.coverage === 'bounded-eose' &&
    418               !row.lastKnown &&
    419               view &&
    420               run &&
    421               publicViewRunCurrent(view, run) &&
    422               [row.headSources, row.deletionSources].every(
    423                 (scope) =>
    424                   scope?.state === 'eose' &&
    425                   scope.result.coverage === 'bounded-eose'
    426               )
    427             );
    428           },
    429           currentRevision(eventId: string) {
    430             const state = snapshot();
    431             if (
    432               !current() ||
    433               !runtime ||
    434               publicRuntimePolicy(runtime) !== policy
    435             )
    436               return false;
    437             if (state?.status === 'ready') return true;
    438             // Continuity for the original immutable revision capture only. The
    439             // independent resolver must verify its exact new event, both scopes
    440             // and focused clock/display state; a competing hash remains fenced.
    441             const row =
    442               resolver && networkOwned()
    443                 ? headResolutionSnapshot(resolver).find(
    444                     (value) => value.key === key
    445                   )
    446                 : undefined;
    447             return !!(
    448               state?.status === 'conflict' &&
    449               state.currentEventId === eventId &&
    450               row?.state.food &&
    451               row.state.display === 'focused_known' &&
    452               row.coverage === 'bounded-eose' &&
    453               !row.lastKnown &&
    454               row.deletion.outcome !== 'suppressed' &&
    455               view &&
    456               run &&
    457               publicViewRunCurrent(view, run) &&
    458               [row.headSources, row.deletionSources].every(
    459                 (scope) =>
    460                   scope?.state === 'eose' &&
    461                   scope.result.coverage === 'bounded-eose'
    462               )
    463             );
    464           },
    465           current: () => snapshot()?.status === 'ready'
    466         };
    467       }
    468     });
    469     return token;
    470   } catch {
    471     close();
    472     return;
    473   }
    474 }
    475 export function ownedEditSourceSnapshot(
    476   source: OwnedEditSource
    477 ): OwnedEditSourceSnapshot | undefined {
    478   return sources.get(source)?.snapshot();
    479 }
    480 // Internal original edit custody only, never a signing/delivery lease.
    481 export function authorizeOwnedEditSource(source: OwnedEditSource) {
    482   return sources.get(source)?.authorize();
    483 }
    484 export function closeOwnedEditSource(source: OwnedEditSource): void {
    485   sources.get(source)?.close();
    486 }