app

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

local-public-hides.ts (16117B)


      1 import { canonicalPublicKey } from '../contracts/public-key.ts';
      2 import { exactLocalFields } from '../contracts/local-records.ts';
      3 import { LOCAL_PERSISTENCE_BUDGETS } from '../config/budgets.ts';
      4 import {
      5   verifiedEnvelopeSnapshot,
      6   type VerifiedEnvelope
      7 } from '../nostr/verified-envelope.ts';
      8 import {
      9   identityLocalOwnership,
     10   subscribeIdentityInvalidation
     11 } from '../runtime/identity-session.ts';
     12 import {
     13   identityViewSession,
     14   subscribeIdentityView,
     15   type IdentityViewContext
     16 } from '../runtime/view-context.ts';
     17 import {
     18   openBrowserDatabase,
     19   closeBrowserDatabase,
     20   browserDatabaseState,
     21   browserDatabaseTransaction,
     22   type BrowserDatabase
     23 } from './database.ts';
     24 
     25 declare const hidesBrand: unique symbol;
     26 export type LocalPublicHides = Readonly<{ [hidesBrand]: true }>;
     27 export const LOCAL_PUBLIC_HIDES_CONTEXT = 'harvestcircle_local_public_hides';
     28 export const PUBLIC_HIDE_DISCLOSURE =
     29   'Hiding a publisher is local to this account in this browser. It does not delete listings, remote copies or your publication receipts, and sends no public report. Undo restores eligible listings; operator policy still applies. Browser storage is not a backup.';
     30 type Failure =
     31   | 'invalid'
     32   | 'stopped'
     33   | 'busy'
     34   | 'unavailable'
     35   | 'aborted'
     36   | 'unknown_completion'
     37   | 'corrupt_record'
     38   | 'conflict'
     39   | 'capacity';
     40 export type PublicHidesSnapshot =
     41   | Readonly<{ state: 'guest' | 'loading' }>
     42   | Readonly<{ state: 'unavailable'; reason?: Failure }>
     43   | Readonly<{
     44       state: 'ready';
     45       owner: string;
     46       revision: number;
     47       publishers: readonly string[];
     48     }>;
     49 type Result<T> =
     50   Readonly<{ ok: true; value: T }> | Readonly<{ ok: false; reason: Failure }>;
     51 type Row = {
     52   schema: 1;
     53   family: 'public_hides';
     54   owner: string;
     55   id: 'public_hides';
     56   revision: number;
     57   publishers: string[];
     58 };
     59 type Stored = { row: Row; wire: string | null };
     60 type Scope = { owner: string; database: BrowserDatabase; current(): boolean };
     61 export type PublicHideResult = Readonly<{
     62   status: 'saved' | 'existing' | Failure;
     63 }>;
     64 type Controller = {
     65   snapshot(): PublicHidesSnapshot;
     66   mount(): Promise<void>;
     67   refresh(): Promise<void>;
     68   hide(proof: VerifiedEnvelope, review: unknown): Promise<PublicHideResult>;
     69   undo(publisher: unknown, review: unknown): Promise<PublicHideResult>;
     70   subscribe(listener: () => void): () => void;
     71   close(): void;
     72 };
     73 const controllers = new WeakMap<LocalPublicHides, Controller>();
     74 const failed = (reason: Failure): Result<never> => ({ ok: false, reason });
     75 function decode(value: unknown, owner: string): Stored | undefined {
     76   if (value === undefined)
     77     return {
     78       row: {
     79         schema: 1,
     80         family: 'public_hides',
     81         owner,
     82         id: 'public_hides',
     83         revision: 0,
     84         publishers: []
     85       },
     86       wire: null
     87     };
     88   if (
     89     !exactLocalFields(value, ['owner', 'id', 'wire']) ||
     90     value.owner !== owner ||
     91     value.id !== 'public_hides' ||
     92     typeof value.wire !== 'string' ||
     93     new TextEncoder().encode(value.wire).length >
     94       LOCAL_PERSISTENCE_BUDGETS.receivedCiphertextBytes
     95   )
     96     return;
     97   let row: unknown;
     98   try {
     99     row = JSON.parse(value.wire);
    100   } catch {
    101     return;
    102   }
    103   if (
    104     !exactLocalFields(row, [
    105       'schema',
    106       'family',
    107       'owner',
    108       'id',
    109       'revision',
    110       'publishers'
    111     ]) ||
    112     row.schema !== 1 ||
    113     row.family !== 'public_hides' ||
    114     row.owner !== owner ||
    115     row.id !== 'public_hides' ||
    116     !Number.isSafeInteger(row.revision) ||
    117     typeof row.revision !== 'number' ||
    118     row.revision < 1 ||
    119     !Array.isArray(row.publishers) ||
    120     row.publishers.length > LOCAL_PERSISTENCE_BUDGETS.receivedEnvelopes ||
    121     row.publishers.some(
    122       (key: unknown) =>
    123         typeof key !== 'string' || canonicalPublicKey(key) !== key
    124     ) ||
    125     new Set(row.publishers).size !== row.publishers.length ||
    126     row.publishers.some(
    127       (key: string, index: number, publishers: string[]) =>
    128         index > 0 && key <= publishers[index - 1]
    129     )
    130   )
    131     return;
    132   const admitted: Row = {
    133     schema: 1,
    134     family: 'public_hides',
    135     owner,
    136     id: 'public_hides',
    137     revision: row.revision,
    138     publishers: row.publishers.slice() as string[]
    139   };
    140   return JSON.stringify(admitted) === value.wire
    141     ? { row: admitted, wire: value.wire }
    142     : undefined;
    143 }
    144 // One fixed owner/key record, with bounded publisher entries. This avoids
    145 // scanning or adopting future private-block preferences in the same store.
    146 function transaction<T>(
    147   scope: Scope,
    148   mode: 'readonly' | 'readwrite',
    149   apply: (stored: Stored, tx: IDBTransaction) => Result<T>
    150 ): Promise<Result<T>> {
    151   if (!scope.current()) return Promise.resolve(failed('stopped'));
    152   let tx: IDBTransaction;
    153   try {
    154     tx = browserDatabaseTransaction(
    155       scope.database,
    156       ['local_preferences'],
    157       mode
    158     );
    159   } catch {
    160     return Promise.resolve(failed('unavailable'));
    161   }
    162   return new Promise((resolve) => {
    163     let result: Result<T> | undefined;
    164     const refuse = (reason: Failure) => {
    165       result = failed(reason);
    166       try {
    167         tx.abort();
    168       } catch {
    169         result = failed('unknown_completion');
    170       }
    171     };
    172     tx.addEventListener('complete', () =>
    173       resolve(
    174         scope.current()
    175           ? (result ?? failed('unknown_completion'))
    176           : failed('stopped')
    177       )
    178     );
    179     tx.addEventListener('abort', () =>
    180       resolve(
    181         !scope.current()
    182           ? failed('stopped')
    183           : result && !result.ok && result.reason !== 'unknown_completion'
    184             ? result
    185             : failed('aborted')
    186       )
    187     );
    188     try {
    189       const request = tx
    190         .objectStore('local_preferences')
    191         .get([scope.owner, 'public_hides']);
    192       request.addEventListener('success', () => {
    193         if (!scope.current()) {
    194           refuse('stopped');
    195           return;
    196         }
    197         try {
    198           const row = decode(request.result, scope.owner);
    199           if (!row) {
    200             refuse('corrupt_record');
    201             return;
    202           }
    203           result = apply(row, tx);
    204           if (!result.ok) refuse(result.reason);
    205         } catch {
    206           refuse('aborted');
    207         }
    208       });
    209     } catch {
    210       refuse('aborted');
    211     }
    212   });
    213 }
    214 // Construction has no browser effect and holds no server-global account state.
    215 export function createLocalPublicHides(
    216   context: IdentityViewContext
    217 ): LocalPublicHides {
    218   const token = Object.freeze({}) as LocalPublicHides;
    219   const listeners = new Map<symbol, () => void>();
    220   let state: PublicHidesSnapshot,
    221     mounted = false,
    222     closed = false;
    223   state = { state: 'guest' };
    224   let scope: Scope | undefined,
    225     generation = Symbol(),
    226     cancel: AbortController | undefined;
    227   let offIdentity = () => {},
    228     offInvalidation = () => {};
    229   function notify() {
    230     for (const listener of listeners.values()) {
    231       try {
    232         listener();
    233       } catch {
    234         /* Isolate presentation. */
    235       }
    236     }
    237   }
    238   function retire() {
    239     generation = Symbol();
    240     cancel?.abort();
    241     cancel = undefined;
    242     offInvalidation();
    243     offInvalidation = () => {};
    244     if (scope) closeBrowserDatabase(scope.database);
    245     scope = undefined;
    246     state = { state: 'guest' };
    247   }
    248   function snapshot(): PublicHidesSnapshot {
    249     if (closed) return { state: 'unavailable', reason: 'stopped' };
    250     if (scope && !scope.current()) {
    251       const session = identityViewSession(context);
    252       const connected = session && identityLocalOwnership(session)?.current();
    253       retire();
    254       if (connected) state = { state: 'unavailable', reason: 'unavailable' };
    255       notify();
    256     }
    257     return state.state === 'ready'
    258       ? { ...state, publishers: state.publishers.slice() }
    259       : { ...state };
    260   }
    261   async function refresh() {
    262     retire();
    263     notify();
    264     if (!mounted || closed) return;
    265     const session = identityViewSession(context),
    266       capture = session && identityLocalOwnership(session);
    267     if (!session || !capture?.current()) return;
    268     const original = generation;
    269     const current = () =>
    270       !closed &&
    271       mounted &&
    272       original === generation &&
    273       identityViewSession(context) === session &&
    274       capture.current();
    275     state = { state: 'loading' };
    276     notify();
    277     cancel = new AbortController();
    278     offInvalidation = subscribeIdentityInvalidation(session, () => {
    279       retire();
    280       notify();
    281     });
    282     const opened = await openBrowserDatabase(cancel.signal);
    283     if (!current()) {
    284       if (opened.state === 'ready') closeBrowserDatabase(opened.owner);
    285       return;
    286     }
    287     if (opened.state !== 'ready') {
    288       state = { state: 'unavailable', reason: 'unavailable' };
    289       notify();
    290       return;
    291     }
    292     const acquired: Scope = {
    293       owner: capture.owner,
    294       database: opened.owner,
    295       current: () =>
    296         current() && browserDatabaseState(opened.owner).state === 'ready'
    297     };
    298     scope = acquired;
    299     const read = await transaction(acquired, 'readonly', (stored) => ({
    300       ok: true,
    301       value: stored
    302     }));
    303     if (!acquired.current()) return;
    304     state = read.ok
    305       ? {
    306           state: 'ready',
    307           owner: acquired.owner,
    308           revision: read.value.row.revision,
    309           publishers: read.value.row.publishers.slice()
    310         }
    311       : { state: 'unavailable', reason: read.reason };
    312     notify();
    313   }
    314   async function change(
    315     publisher: string,
    316     hidden: boolean,
    317     original: Scope
    318   ): Promise<PublicHideResult> {
    319     if (!original.current()) return { status: 'stopped' };
    320     if (!navigator.locks?.request) return { status: 'unavailable' };
    321     try {
    322       return await navigator.locks.request(
    323         'harvestcircle:owner:' + original.owner,
    324         { mode: 'exclusive', ifAvailable: true },
    325         async (lock) => {
    326           if (!lock) return { status: 'busy' as const };
    327           if (!original.current()) return { status: 'stopped' as const };
    328           const loaded = await transaction(original, 'readonly', (stored) => ({
    329             ok: true,
    330             value: stored
    331           }));
    332           if (!original.current()) return { status: 'stopped' as const };
    333           if (!loaded.ok) return { status: loaded.reason };
    334           const before = loaded.value;
    335           if (before.row.publishers.includes(publisher) === hidden) {
    336             // Another controller may have acknowledged this complete native
    337             // row. Reconcile all preferences without another write/revision.
    338             state = {
    339               state: 'ready',
    340               owner: original.owner,
    341               revision: before.row.revision,
    342               publishers: before.row.publishers.slice()
    343             };
    344             notify();
    345             return { status: 'existing' as const };
    346           }
    347           if (
    348             before.row.revision >= Number.MAX_SAFE_INTEGER ||
    349             (hidden &&
    350               before.row.publishers.length >=
    351                 LOCAL_PERSISTENCE_BUDGETS.receivedEnvelopes)
    352           )
    353             return { status: 'capacity' as const };
    354           const next: Row = {
    355             ...before.row,
    356             revision: before.row.revision + 1,
    357             publishers: hidden
    358               ? before.row.publishers.concat(publisher).sort()
    359               : before.row.publishers.filter((key) => key !== publisher)
    360           };
    361           const wire = JSON.stringify(next);
    362           const written = await transaction<boolean>(
    363             original,
    364             'readwrite',
    365             (stored, tx) => {
    366               if (stored.wire !== before.wire) return failed('conflict');
    367               tx.objectStore('local_preferences').put({
    368                 owner: original.owner,
    369                 id: 'public_hides',
    370                 wire
    371               });
    372               return { ok: true, value: true };
    373             }
    374           );
    375           if (!original.current()) return { status: 'stopped' as const };
    376           if (!written.ok) return { status: written.reason };
    377           const readback = await transaction(
    378             original,
    379             'readonly',
    380             (stored) => ({ ok: true, value: stored })
    381           );
    382           if (!original.current()) return { status: 'stopped' as const };
    383           if (!readback.ok) return { status: 'unknown_completion' as const };
    384           if (readback.value.wire !== wire)
    385             return { status: 'conflict' as const };
    386           state = {
    387             state: 'ready',
    388             owner: original.owner,
    389             revision: next.revision,
    390             publishers: next.publishers.slice()
    391           };
    392           notify();
    393           return { status: 'saved' as const };
    394         }
    395       );
    396     } catch {
    397       return { status: original.current() ? 'unknown_completion' : 'stopped' };
    398     }
    399   }
    400   controllers.set(token, {
    401     snapshot,
    402     async mount() {
    403       if (closed || mounted || typeof window === 'undefined') return;
    404       mounted = true;
    405       // Subscribe before initial load; pending/guest transitions revoke the
    406       // previous generation before an asynchronous open can expose its rows.
    407       let initial = true;
    408       offIdentity = subscribeIdentityView(context, () => {
    409         if (initial) {
    410           initial = false;
    411           return;
    412         }
    413         void refresh();
    414       });
    415       await refresh();
    416     },
    417     refresh,
    418     async hide(proof, review) {
    419       const event = verifiedEnvelopeSnapshot(proof);
    420       if (
    421         !event ||
    422         event.kind !== 30402 ||
    423         !canonicalPublicKey(event.pubkey) ||
    424         review !== 'reviewed_local_public_hide'
    425       )
    426         return { status: 'invalid' };
    427       const original = scope;
    428       if (!original || state.state !== 'ready')
    429         return { status: 'unavailable' };
    430       return change(event.pubkey, true, original);
    431     },
    432     async undo(publisher, review) {
    433       const key = canonicalPublicKey(publisher);
    434       if (!key || review !== 'reviewed_local_public_undo')
    435         return { status: 'invalid' };
    436       const original = scope;
    437       if (!original || state.state !== 'ready')
    438         return { status: 'unavailable' };
    439       if (!state.publishers.includes(key)) return { status: 'invalid' };
    440       return change(key, false, original);
    441     },
    442     subscribe(listener) {
    443       if (closed) return () => {};
    444       const id = Symbol();
    445       listeners.set(id, listener);
    446       return () => {
    447         listeners.delete(id);
    448       };
    449     },
    450     close() {
    451       if (closed) return;
    452       closed = true;
    453       offIdentity();
    454       retire();
    455       notify();
    456       listeners.clear();
    457     }
    458   });
    459   return token;
    460 }
    461 export function localPublicHidesSnapshot(
    462   token: LocalPublicHides
    463 ): PublicHidesSnapshot {
    464   return controllers.get(token)?.snapshot() ?? { state: 'unavailable' };
    465 }
    466 export function localPublicPublisherAllowed(
    467   token: LocalPublicHides,
    468   publisher: string
    469 ): boolean {
    470   const owned = controllers.get(token);
    471   if (!owned) return false;
    472   const state = owned.snapshot();
    473   return state.state === 'loading' ||
    474     (state.state === 'unavailable' && state.reason === 'stopped')
    475     ? false
    476     : state.state !== 'ready' || !state.publishers.includes(publisher);
    477 }
    478 export function mountLocalPublicHides(token: LocalPublicHides): Promise<void> {
    479   return controllers.get(token)?.mount() ?? Promise.resolve();
    480 }
    481 export function refreshLocalPublicHides(
    482   token: LocalPublicHides
    483 ): Promise<void> {
    484   return controllers.get(token)?.refresh() ?? Promise.resolve();
    485 }
    486 export function subscribeLocalPublicHides(
    487   token: LocalPublicHides,
    488   listener: () => void
    489 ): () => void {
    490   return controllers.get(token)?.subscribe(listener) ?? (() => {});
    491 }
    492 export function hideLocalPublicPublisher(
    493   token: LocalPublicHides,
    494   proof: VerifiedEnvelope,
    495   review: unknown
    496 ): Promise<PublicHideResult> {
    497   return (
    498     controllers.get(token)?.hide(proof, review) ??
    499     Promise.resolve({ status: 'invalid' })
    500   );
    501 }
    502 export function undoLocalPublicPublisher(
    503   token: LocalPublicHides,
    504   publisher: unknown,
    505   review: unknown
    506 ): Promise<PublicHideResult> {
    507   return (
    508     controllers.get(token)?.undo(publisher, review) ??
    509     Promise.resolve({ status: 'invalid' })
    510   );
    511 }
    512 export function closeLocalPublicHides(token: LocalPublicHides): void {
    513   controllers.get(token)?.close();
    514 }