app

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

inbox-preference-publication.ts (5149B)


      1 import type { NostrEvent } from 'applesauce-core/helpers';
      2 import { operationEnabled } from '../config/operation-flags.ts';
      3 import {
      4   publicRelayTargets,
      5   readRelayPolicy,
      6   type RelayPolicy
      7 } from '../config/relays.ts';
      8 import {
      9   identityMessagingOwnership,
     10   identityPublicOperationOwnership,
     11   recheckIdentityOwner,
     12   type IdentitySession,
     13   type IdentityPublicOperation
     14 } from '../runtime/identity-session.ts';
     15 import {
     16   publicEffectLeaseCurrent,
     17   type PublicEffectLease
     18 } from '../runtime/effect-ownership.ts';
     19 import {
     20   loadPreferenceOperation,
     21   type PublicQuotaRepository
     22 } from '../persistence/quota.ts';
     23 import {
     24   publicRecordSnapshot,
     25   publicRecordWire,
     26   type PublicRecordHandle
     27 } from '../persistence/records.ts';
     28 declare const publicationBrand: unique symbol;
     29 export type PreferencePublication = Readonly<{ [publicationBrand]: true }>;
     30 type Saved = Readonly<{
     31   policy: RelayPolicy;
     32   wire: string;
     33   eventId: string;
     34   origins: readonly string[];
     35   current(): boolean;
     36 }>;
     37 const publications = new WeakMap<PreferencePublication, Saved>();
     38 // Internal exact policy observation, not a Nostr cryptographic replacement.
     39 export async function preferencePolicyFingerprint(
     40   policy: RelayPolicy
     41 ): Promise<string> {
     42   const hash = await crypto.subtle.digest(
     43     'SHA-256',
     44     new TextEncoder().encode(JSON.stringify(readRelayPolicy(policy)))
     45   );
     46   return Array.from(new Uint8Array(hash), (byte) =>
     47     byte.toString(16).padStart(2, '0')
     48   ).join('');
     49 }
     50 // Only a genuine current identity operation and original lease can acquire this
     51 // one-attempt capability from actual acknowledged storage. No caller event wire.
     52 // beforeEffect is an internal bounded lookup port; its final fence is retained.
     53 export async function authorizeStoredInboxPreference(
     54   repository: PublicQuotaRepository,
     55   identity: IdentitySession,
     56   operation: IdentityPublicOperation,
     57   lease: PublicEffectLease,
     58   original: PublicRecordHandle,
     59   id: string,
     60   policy: RelayPolicy,
     61   beforeEffect: () => Promise<(() => boolean) | undefined>
     62 ): Promise<PreferencePublication | undefined> {
     63   try {
     64     if (typeof window === 'undefined') return undefined;
     65     const capture = identityPublicOperationOwnership(identity, operation);
     66     const messageOwner = identityMessagingOwnership(identity);
     67     if (
     68       !capture ||
     69       !messageOwner ||
     70       capture.owner !== messageOwner.owner ||
     71       capture.session !== messageOwner.session
     72     )
     73       return undefined;
     74     const originalWire = publicRecordWire(original, capture.owner, id),
     75       row = publicRecordSnapshot(original, capture.owner, id);
     76     if (
     77       !originalWire ||
     78       row?.family !== 'preference_operation' ||
     79       row.revision !== 0 ||
     80       row.capture.kind !== 10050
     81     )
     82       return undefined;
     83     const authority = {
     84       owner: capture.owner,
     85       id,
     86       recordWire: originalWire,
     87       session: capture.session
     88     };
     89     const fingerprint = await preferencePolicyFingerprint(policy),
     90       targets = publicRelayTargets(policy, 'write');
     91     if (
     92       !operationEnabled(policy, 'messaging') ||
     93       fingerprint !== row.capture.policyFingerprint ||
     94       JSON.stringify(targets) !== JSON.stringify(row.capture.targets)
     95     )
     96       return undefined;
     97     const read = await loadPreferenceOperation(repository, id);
     98     if (!read.ok) return undefined;
     99     const stored = publicRecordSnapshot(read.value, capture.owner, id);
    100     if (
    101       stored?.family !== 'preference_operation' ||
    102       stored.revision < 2 ||
    103       !stored.artifact ||
    104       JSON.stringify(stored.capture) !== JSON.stringify(row.capture) ||
    105       JSON.stringify(stored.source) !== JSON.stringify(row.source) ||
    106       stored.consent !== row.consent
    107     )
    108       return undefined;
    109     const headCurrent = await beforeEffect();
    110     if (!headCurrent) return undefined;
    111     await recheckIdentityOwner(identity);
    112     const current = () =>
    113       capture.current() &&
    114       messageOwner.current() &&
    115       headCurrent() &&
    116       publicEffectLeaseCurrent(lease, authority);
    117     if (!current()) return undefined;
    118     const token = Object.freeze({}) as PreferencePublication;
    119     publications.set(token, {
    120       policy,
    121       wire: stored.artifact.wire,
    122       eventId: stored.artifact.eventId,
    123       origins: [...stored.capture.targets],
    124       current
    125     });
    126     return token;
    127   } catch {
    128     return undefined;
    129   }
    130 }
    131 // Detached metadata never grants permission. Pool consumes the original token.
    132 export function preferencePublicationSnapshot(token: PreferencePublication) {
    133   const saved = publications.get(token);
    134   return saved
    135     ? { eventId: saved.eventId, origins: [...saved.origins] }
    136     : undefined;
    137 }
    138 export function takePreferencePublication(
    139   token: PreferencePublication,
    140   policy: RelayPolicy,
    141   origin: string
    142 ): Readonly<{ event: NostrEvent; current(): boolean }> | undefined {
    143   const saved = publications.get(token);
    144   if (!saved) return undefined;
    145   publications.delete(token);
    146   if (
    147     saved.policy !== policy ||
    148     !saved.origins.includes(origin) ||
    149     !saved.current()
    150   )
    151     return undefined;
    152   return {
    153     event: JSON.parse(saved.wire) as NostrEvent,
    154     current: saved.current
    155   };
    156 }