app

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

prepare-listing.ts (15598B)


      1 import { buildFoodTemplate } from '../contracts/food-availability-v1/write.ts';
      2 import type {
      3   PublicDraftRecord,
      4   PublicDraftForm
      5 } from '../contracts/local-records.ts';
      6 import { canonicalLocalId, newLocalId } from '../private-handles.ts';
      7 import { readRelayPolicy, publicRelayTargets } from '../config/relays.ts';
      8 import { inspectLocalTemplate } from '../nostr/local-template.ts';
      9 import { operationEnabled } from '../config/operation-flags.ts';
     10 import {
     11   verifyEnvelope,
     12   verifiedEnvelopeSnapshot
     13 } from '../nostr/verified-envelope.ts';
     14 import {
     15   decodePublicRecord,
     16   type PublicRecordHandle
     17 } from '../persistence/records.ts';
     18 import {
     19   publicPublicationOwner,
     20   publicPublicationDraftRepository,
     21   savePublicListingIntent,
     22   type PublicPublicationRepository,
     23   type PublicListingSave
     24 } from '../persistence/public-publications.ts';
     25 import {
     26   publicDraftControllerOwnership,
     27   publicDraftControllerSnapshot,
     28   flushPublicDraft,
     29   type PublicDraftController
     30 } from './draft-controller.ts';
     31 import {
     32   newListingReadinessOwnership,
     33   captureOwnedListingReadiness,
     34   closeNewListingReadiness,
     35   type NewListingReadiness
     36 } from './new-listing-readiness.ts';
     37 import {
     38   authorizeOwnedEditSource,
     39   type OwnedEditSource
     40 } from './edit-source.ts';
     41 import {
     42   assessFutureTimestamp,
     43   wallClockAvailable
     44 } from '../catalog/clock-policy.ts';
     45 
     46 declare const reviewBrand: unique symbol;
     47 export type ListingReview = Readonly<{ [reviewBrand]: true }>;
     48 export type ListingPreview = Readonly<{
     49   owner: string;
     50   command: string;
     51   draftId: string;
     52   draftRevision: number;
     53   identifier: string;
     54   createdAtSeconds: number;
     55   form: PublicDraftForm;
     56   summary: string;
     57   templateWire: string;
     58   expectedHash: string;
     59   targets: readonly string[];
     60   policyFingerprint: string;
     61   withdrawal?: Readonly<{ coordinate: string; eventId: string }>;
     62   revision?: Readonly<{
     63     coordinate: string;
     64     publishedAtSeconds: number;
     65     status: 'active' | 'sold';
     66   }>;
     67 }>;
     68 type Review = Readonly<{
     69   repository: PublicPublicationRepository;
     70   controller: PublicDraftController;
     71   expected: PublicDraftRecord;
     72   editVersion: number;
     73   command: string;
     74   readiness: NewListingReadiness;
     75   source?: OwnedEditSource;
     76   status?: 'active' | 'sold' | 'withdrawal';
     77   record: PublicRecordHandle;
     78   revisionBase?: Readonly<{ command: string; record: PublicRecordHandle }>;
     79   previewWire: string;
     80   current(this: void): boolean;
     81 }>;
     82 const reviews = new WeakMap<ListingReview, Review>();
     83 const commands = new WeakMap<
     84   PublicPublicationRepository,
     85   Map<string, ListingReview>
     86 >();
     87 const activeReservations = new WeakMap<
     88   ListingReview,
     89   Promise<ListingReservation>
     90 >();
     91 export type ListingReviewResult =
     92   | Readonly<{ status: 'review'; review: ListingReview }>
     93   | Readonly<{
     94       status: 'blocked';
     95       reason:
     96         | 'invalid_scope'
     97         | 'invalid_command'
     98         | 'unavailable'
     99         | 'invalid_form'
    100         | 'conflict';
    101     }>;
    102 export type ListingReservation =
    103   PublicListingSave | Readonly<{ status: 'invalid' }>;
    104 // Review flushes local draft state and prepares an exact immutable template;
    105 // it neither reserves a publication nor asks the extension to sign.
    106 export async function reviewNewListing(
    107   repository: PublicPublicationRepository,
    108   controller: PublicDraftController,
    109   readiness: NewListingReadiness,
    110   command: unknown,
    111   consent: unknown
    112 ): Promise<ListingReviewResult> {
    113   return reviewListing(repository, controller, readiness, command, consent);
    114 }
    115 // Pure declared clock policy; production supplies actual Date.now below.
    116 export function ownedRevisionTimestamp(
    117   head: number,
    118   now: number
    119 ): number | undefined {
    120   if (
    121     !Number.isSafeInteger(head) ||
    122     head < 0 ||
    123     head >= Number.MAX_SAFE_INTEGER ||
    124     !wallClockAvailable(now)
    125   )
    126     return;
    127   const next = Math.max(head + 1, Math.floor(now));
    128   return assessFutureTimestamp(next, now) === 'within_policy'
    129     ? next
    130     : undefined;
    131 }
    132 export async function reviewOwnedListing(
    133   source: OwnedEditSource,
    134   controller: PublicDraftController,
    135   command: unknown,
    136   status: 'active' | 'sold' | 'withdrawal',
    137   consent: unknown
    138 ): Promise<ListingReviewResult> {
    139   const original = authorizeOwnedEditSource(source);
    140   if (!original) return { status: 'blocked', reason: 'invalid_scope' };
    141   return reviewListing(
    142     original.repository,
    143     controller,
    144     undefined,
    145     command,
    146     consent,
    147     { source, status }
    148   );
    149 }
    150 async function reviewListing(
    151   repository: PublicPublicationRepository,
    152   controller: PublicDraftController,
    153   readiness: NewListingReadiness | undefined,
    154   command: unknown,
    155   consent: unknown,
    156   revision?: Readonly<{
    157     source: OwnedEditSource;
    158     status: 'active' | 'sold' | 'withdrawal';
    159   }>
    160 ): Promise<ListingReviewResult> {
    161   try {
    162     const custody = publicDraftControllerOwnership(controller),
    163       owner = publicPublicationOwner(repository);
    164     if (
    165       !custody ||
    166       !owner ||
    167       custody.repository !== publicPublicationDraftRepository(repository)
    168     )
    169       return { status: 'blocked', reason: 'invalid_scope' };
    170     const id = canonicalLocalId(command);
    171     if (!id) return { status: 'blocked', reason: 'invalid_command' };
    172     const retained = revision && authorizeOwnedEditSource(revision.source);
    173     const ready = revision ? retained : newListingReadinessOwnership(readiness);
    174     if (
    175       !ready ||
    176       ready.owner !== owner ||
    177       !ready.current() ||
    178       consent !==
    179         (revision
    180           ? revision.status === 'withdrawal'
    181             ? 'reviewed_owned_withdrawal'
    182             : revision.status === 'sold'
    183               ? 'reviewed_sold_availability'
    184               : 'reviewed_owned_revision'
    185           : 'reviewed_new_listing')
    186     )
    187       return { status: 'blocked', reason: 'unavailable' };
    188     if (!(await flushPublicDraft(controller)))
    189       return { status: 'blocked', reason: 'unavailable' };
    190     const snapshot = publicDraftControllerSnapshot(controller),
    191       expected = snapshot?.draft;
    192     if (
    193       !snapshot ||
    194       !expected ||
    195       expected.owner !== owner ||
    196       !custody.current(JSON.stringify(expected), snapshot.editVersion)
    197     )
    198       return { status: 'blocked', reason: 'conflict' };
    199     const cached = commands.get(repository)?.get(id);
    200     if (cached) {
    201       const original = reviews.get(cached);
    202       if (
    203         original &&
    204         original.controller === controller &&
    205         (revision
    206           ? original.source === revision.source &&
    207             original.status === revision.status
    208           : original.readiness === readiness) &&
    209         JSON.stringify(original.expected) === JSON.stringify(expected) &&
    210         original.current() &&
    211         custody.current(JSON.stringify(expected), snapshot.editVersion)
    212       ) {
    213         return { status: 'review', review: cached };
    214       }
    215       return { status: 'blocked', reason: 'conflict' };
    216     }
    217     const baseProof = retained && verifyEnvelope(retained.baseWire);
    218     const base = baseProof?.ok
    219       ? verifiedEnvelopeSnapshot(baseProof.value)
    220       : undefined;
    221     const identifier = revision
    222       ? base?.tags.find((tag) => tag[0] === 'd')?.[1]
    223       : newLocalId();
    224     const now = Math.floor(Date.now() / 1000);
    225     const createdAtSeconds = revision
    226       ? base && ownedRevisionTimestamp(base.created_at, now)
    227       : now;
    228     if (!identifier || createdAtSeconds === undefined)
    229       return {
    230         status: 'blocked',
    231         reason: revision ? 'conflict' : 'unavailable'
    232       };
    233     const form = expected.form;
    234     const withdrawal = revision?.status === 'withdrawal';
    235     if (!withdrawal && form.contactType === '' && form.contactValue !== '')
    236       return { status: 'blocked', reason: 'invalid_form' };
    237     const contact =
    238       form.contactType === ''
    239         ? undefined
    240         : {
    241             type: form.contactType,
    242             value: form.contactValue,
    243             public: true as const
    244           };
    245     const built = buildFoodTemplate({
    246       identifier,
    247       title: form.title,
    248       description: form.description,
    249       location: form.location,
    250       amount: form.amount,
    251       currency: form.currency,
    252       unit: form.unit,
    253       ...(form.quantity === '' ? {} : { quantity: form.quantity }),
    254       created_at: createdAtSeconds,
    255       published_at: retained ? retained.publishedAtSeconds : createdAtSeconds,
    256       status: revision?.status === 'sold' ? 'sold' : 'active',
    257       ...(contact ? { contact } : {})
    258     });
    259     if (!withdrawal && !built.ok)
    260       return { status: 'blocked', reason: 'invalid_form' };
    261     const manifest = readRelayPolicy(ready.policy),
    262       targets = publicRelayTargets(ready.policy, 'write');
    263     const templateWire = JSON.stringify({
    264       pubkey: owner,
    265       kind: withdrawal ? 5 : 30402,
    266       created_at: createdAtSeconds,
    267       tags:
    268         withdrawal && base
    269           ? [
    270               ['e', base.id],
    271               ['a', `30402:${owner}:${identifier}`],
    272               ['k', '30402']
    273             ]
    274           : built.ok
    275             ? built.wire_parts.tags
    276             : [],
    277       content: withdrawal ? '' : built.ok ? built.wire_parts.content : ''
    278     });
    279     const template = inspectLocalTemplate(
    280       templateWire,
    281       owner,
    282       withdrawal ? 5 : 30402
    283     );
    284     if (
    285       !template ||
    286       !operationEnabled(ready.policy, retained ? 'posting' : 'new_listing') ||
    287       targets.length === 0
    288     )
    289       return { status: 'blocked', reason: 'unavailable' };
    290     const digest = await crypto.subtle.digest(
    291       'SHA-256',
    292       new TextEncoder().encode(JSON.stringify(manifest))
    293     );
    294     const policyFingerprint = Array.from(new Uint8Array(digest), (value) =>
    295       value.toString(16).padStart(2, '0')
    296     ).join('');
    297     // Hashing is outside any IDB transaction; recheck original mutable owners.
    298     if (
    299       !ready.current() ||
    300       publicPublicationOwner(repository) !== owner ||
    301       !custody.current(JSON.stringify(expected), snapshot.editVersion)
    302     )
    303       return { status: 'blocked', reason: 'conflict' };
    304     // Another review may have completed while this one awaited hashing. The
    305     // first retained command owns its ID/time/template; never replace it.
    306     const racing = commands.get(repository)?.get(id);
    307     if (racing) {
    308       const original = reviews.get(racing);
    309       if (
    310         original &&
    311         original.controller === controller &&
    312         (revision
    313           ? original.source === revision.source &&
    314             original.status === revision.status
    315           : original.readiness === readiness) &&
    316         JSON.stringify(original.expected) === JSON.stringify(expected) &&
    317         original.current() &&
    318         custody.current(JSON.stringify(expected), snapshot.editVersion)
    319       )
    320         return { status: 'review', review: racing };
    321       return { status: 'blocked', reason: 'conflict' };
    322     }
    323     const admitted = decodePublicRecord(
    324       JSON.stringify({
    325         schema: 1,
    326         family: 'public_operation',
    327         owner,
    328         id,
    329         revision: 0,
    330         source:
    331           withdrawal && retained
    332             ? { type: 'public_head', wire: retained.baseWire }
    333             : { type: 'draft', id: expected.id, revision: expected.revision },
    334         capture: {
    335           kind: withdrawal ? 5 : 30402,
    336           wire: templateWire,
    337           hash: template.hash,
    338           targets,
    339           policyFingerprint
    340         },
    341         artifact: null,
    342         receipts: []
    343       }),
    344       owner,
    345       id
    346     );
    347     if (!admitted.ok) return { status: 'blocked', reason: 'invalid_form' };
    348     const proof = revision
    349       ? captureOwnedListingReadiness(
    350           revision.source,
    351           template.hash,
    352           withdrawal ? 'reviewed_owned_withdrawal' : 'reviewed_owned_listing'
    353         )
    354       : readiness;
    355     const finalReady = newListingReadinessOwnership(proof);
    356     if (!proof || !finalReady || !finalReady.current())
    357       return { status: 'blocked', reason: 'conflict' };
    358     const review = Object.freeze({}) as ListingReview;
    359     reviews.set(review, {
    360       repository,
    361       controller,
    362       expected,
    363       editVersion: snapshot.editVersion,
    364       command: id,
    365       readiness: proof,
    366       ...(revision ? { source: revision.source, status: revision.status } : {}),
    367       record: admitted.value,
    368       ...(retained
    369         ? {
    370             revisionBase: {
    371               command: retained.sourceCommand,
    372               record: retained.sourceRecord
    373             }
    374           }
    375         : {}),
    376       previewWire: JSON.stringify({
    377         owner,
    378         command: id,
    379         draftId: expected.id,
    380         draftRevision: expected.revision,
    381         identifier,
    382         createdAtSeconds,
    383         form,
    384         summary: withdrawal ? 'Removal request' : built.ok ? built.summary : '',
    385         templateWire,
    386         expectedHash: template.hash,
    387         targets,
    388         policyFingerprint,
    389         ...(withdrawal && retained && base
    390           ? {
    391               withdrawal: { coordinate: retained.coordinate, eventId: base.id }
    392             }
    393           : {}),
    394         ...(retained && revision && !withdrawal
    395           ? {
    396               revision: {
    397                 coordinate: retained.coordinate,
    398                 publishedAtSeconds: retained.publishedAtSeconds,
    399                 status: revision.status
    400               }
    401             }
    402           : {})
    403       }),
    404       current: () =>
    405         finalReady.current() &&
    406         publicPublicationOwner(repository) === owner &&
    407         (!revision ||
    408           assessFutureTimestamp(
    409             createdAtSeconds,
    410             Math.floor(Date.now() / 1000)
    411           ) === 'within_policy')
    412     });
    413     const cache = commands.get(repository) ?? new Map<string, ListingReview>();
    414     cache.set(id, review);
    415     commands.set(repository, cache);
    416     return { status: 'review', review };
    417   } catch {
    418     return { status: 'blocked', reason: 'unavailable' };
    419   }
    420 }
    421 export function listingReviewSnapshot(
    422   review: ListingReview
    423 ): ListingPreview | undefined {
    424   const value = reviews.get(review);
    425   return value ? (JSON.parse(value.previewWire) as ListingPreview) : undefined;
    426 }
    427 export function closeListingReview(review: ListingReview): void {
    428   const original = reviews.get(review);
    429   if (original) closeNewListingReadiness(original.readiness);
    430 }
    431 // Internal original custody, not a signing or transport permission. The later
    432 // controller must reread the persisted intent and obtain its own effect lease.
    433 export function listingReviewOwnership(review: ListingReview) {
    434   const original = reviews.get(review);
    435   const ready = original && newListingReadinessOwnership(original.readiness);
    436   return original && ready && original.current()
    437     ? {
    438         repository: original.repository,
    439         record: original.record,
    440         command: original.command,
    441         readiness: ready,
    442         current: original.current
    443       }
    444     : undefined;
    445 }
    446 // One original review deduplicates simultaneous clicks. Failed/uncertain work
    447 // remains the same capture for later explicit retry; no fresh ID/time/template.
    448 export function reserveNewListing(
    449   review: ListingReview,
    450   consent: unknown
    451 ): Promise<ListingReservation> {
    452   const value = reviews.get(review);
    453   if (!value || consent !== 'publish_reviewed_listing')
    454     return Promise.resolve({ status: 'invalid' });
    455   const active = activeReservations.get(review);
    456   if (active) return active;
    457   const work = savePublicListingIntent(
    458     value.repository,
    459     value.controller,
    460     value.record,
    461     value.expected,
    462     value.editVersion,
    463     value.command,
    464     value.current,
    465     value.revisionBase
    466   ).finally(() => {
    467     if (activeReservations.get(review) === work)
    468       activeReservations.delete(review);
    469   });
    470   activeReservations.set(review, work);
    471   return work;
    472 }