app

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

message-metadata.ts (19378B)


      1 import { exactLocalFields } from '../contracts/local-records.ts';
      2 import { newLocalId } from '../private-handles.ts';
      3 import { LOCAL_PERSISTENCE_BUDGETS } from '../config/budgets.ts';
      4 import { safeUnsignedInteger } from '../nostr/envelope-bounds.ts';
      5 import {
      6   browserDatabaseState,
      7   browserDatabaseTransaction,
      8   type BrowserDatabase
      9 } from './database.ts';
     10 import {
     11   decodePrivateRecord,
     12   privateRecordSnapshot,
     13   privateRecordWire,
     14   type ReceivedEnvelopeRecord
     15 } from './private-records.ts';
     16 import {
     17   decodeConversationMapping,
     18   conversationMappingSnapshot
     19 } from './records.ts';
     20 import {
     21   privateSessionOwnership,
     22   subscribePrivateSessionClose,
     23   type PrivateSession
     24 } from '../runtime/private-session.ts';
     25 import {
     26   conversationSnapshot,
     27   conversationOwnership,
     28   conversationEnvelopeIdentity,
     29   type AdmittedConversation
     30 } from '../messaging/admit-conversation.ts';
     31 import {
     32   unlockedSessionOwnership,
     33   unlockedConversationCurrent,
     34   readUnlockedMessages,
     35   type UnlockedSession
     36 } from '../messaging/unlocked-session.ts';
     37 
     38 export const MESSAGE_METADATA_DISCLOSURE =
     39   'Read/unread is local. Ciphertext and minimal owner, peer, opaque conversation identifier, verified rumor read flag, routing and use times may persist in this browser. Someone with local access may learn peers and use times; this is not full-device encryption or backup. No private body, subject or product association is indexed. No remote Seen/Read or guaranteed notification is sent.';
     40 declare const metadataBrand: unique symbol;
     41 export type MessageMetadata = Readonly<{ [metadataBrand]: true }>;
     42 type Failure =
     43   | 'invalid'
     44   | 'stopped'
     45   | 'busy'
     46   | 'unavailable'
     47   | 'aborted'
     48   | 'unknown_completion'
     49   | 'corrupt_record'
     50   | 'capacity'
     51   | 'conflict';
     52 type Pair = Readonly<{
     53   owner: string;
     54   id: string;
     55   peer: string;
     56   wire: string;
     57   bytes: number;
     58 }>;
     59 type Cipher = Readonly<{
     60   record: ReceivedEnvelopeRecord;
     61   wire: string;
     62   bytes: number;
     63 }>;
     64 type Rows = Readonly<{ received: readonly Cipher[]; pairs: readonly Pair[] }>;
     65 type Result<T> =
     66   Readonly<{ ok: true; value: T }> | Readonly<{ ok: false; reason: Failure }>;
     67 type Scope = Readonly<{
     68   database: BrowserDatabase;
     69   owner: string;
     70   session: symbol;
     71   unlocked: UnlockedSession;
     72   current(): boolean;
     73 }>;
     74 type Snapshot =
     75   | Readonly<{
     76       status: 'ready';
     77       owner: string;
     78       readRumors: readonly string[];
     79       pairs: readonly Readonly<{ id: string; peer: string }>[];
     80     }>
     81   | Readonly<{ status: Failure }>;
     82 type Display =
     83   | Readonly<{
     84       status: 'saved' | 'existing';
     85       conversationId: string;
     86       rumorId: string;
     87     }>
     88   | Readonly<{ status: Failure }>
     89   | Readonly<{
     90       status: 'unknown_completion';
     91       phase: 'readback';
     92       reason: Failure;
     93     }>;
     94 type Controller = {
     95   snapshot(): Promise<Snapshot>;
     96   display(
     97     room: AdmittedConversation,
     98     review: unknown,
     99     markRead?: boolean
    100   ): Promise<Display>;
    101   messages(): ReturnType<typeof readUnlockedMessages>;
    102   close(): void;
    103 };
    104 const metadataOwnerships = new WeakMap<
    105   MessageMetadata,
    106   Readonly<{
    107     owner: string;
    108     session: symbol;
    109     current(): boolean;
    110   }>
    111 >();
    112 const controllers = new WeakMap<MessageMetadata, Controller>();
    113 const failed = (reason: Failure): Result<never> => ({ ok: false, reason });
    114 function cipherRow(
    115   value: unknown,
    116   owner: string,
    117   id: unknown
    118 ): Cipher | undefined {
    119   if (
    120     !exactLocalFields(value, ['owner', 'id', 'wire']) ||
    121     value.owner !== owner ||
    122     value.id !== id ||
    123     typeof value.wire !== 'string'
    124   )
    125     return;
    126   const decoded = decodePrivateRecord(value.wire, owner, id);
    127   if (!decoded.ok) return;
    128   const record = privateRecordSnapshot(decoded.value, owner, id);
    129   return record?.family === 'received_envelope' &&
    130     privateRecordWire(decoded.value, owner, id) === value.wire
    131     ? {
    132         record,
    133         wire: value.wire,
    134         bytes: new TextEncoder().encode(JSON.stringify(value)).length
    135       }
    136     : undefined;
    137 }
    138 function pairRow(value: unknown, owner: string, id: unknown): Pair | undefined {
    139   if (
    140     !exactLocalFields(value, ['owner', 'id', 'wire']) ||
    141     value.owner !== owner ||
    142     value.id !== id ||
    143     typeof value.wire !== 'string'
    144   )
    145     return;
    146   const decoded = decodeConversationMapping(value.wire, owner, id);
    147   if (!decoded.ok) return;
    148   const row = conversationMappingSnapshot(decoded.value, owner, id);
    149   return row
    150     ? {
    151         owner: row.owner,
    152         id: row.id,
    153         peer: row.peer,
    154         wire: value.wire,
    155         bytes: new TextEncoder().encode(JSON.stringify(value)).length
    156       }
    157     : undefined;
    158 }
    159 // Bounded owner-only strict scans. Existing schema/received quota unchanged;
    160 // minimum pair mappings use the same conservative logical receive ceiling.
    161 // No SDK/network await in any transaction; completion precedes readback credit.
    162 function transaction<T>(
    163   scope: Scope,
    164   mode: 'readonly' | 'readwrite',
    165   finish: (
    166     rows: Rows,
    167     tx: IDBTransaction,
    168     refuse: (reason: Failure) => void
    169   ) => Result<T> | undefined
    170 ): Promise<Result<T>> {
    171   let tx: IDBTransaction;
    172   try {
    173     if (!scope.current()) return Promise.resolve(failed('stopped'));
    174     tx = browserDatabaseTransaction(
    175       scope.database,
    176       ['received_envelopes', 'conversations'],
    177       mode
    178     );
    179   } catch {
    180     return Promise.resolve(failed('unavailable'));
    181   }
    182   return new Promise((resolve) => {
    183     let result: Result<T> | undefined,
    184       received: readonly Cipher[] = Array.from<Cipher>([]),
    185       pairs: readonly Pair[] = Array.from<Pair>([]),
    186       pending = 2,
    187       receivedBytes = 0,
    188       pairBytes = 0;
    189     function refuse(reason: Failure) {
    190       result = failed(reason);
    191       try {
    192         tx.abort();
    193       } catch {
    194         result = failed('unknown_completion');
    195       }
    196     }
    197     tx.addEventListener('complete', () =>
    198       resolve(result ?? failed('unknown_completion'))
    199     );
    200     tx.addEventListener('abort', () =>
    201       resolve(
    202         result && !result.ok && result.reason !== 'unknown_completion'
    203           ? result
    204           : failed('aborted')
    205       )
    206     );
    207     function done() {
    208       pending--;
    209       if (pending !== 0) return;
    210       if (!scope.current()) {
    211         refuse('stopped');
    212         return;
    213       }
    214       try {
    215         const value = finish({ received, pairs }, tx, refuse);
    216         if (value) result = value;
    217       } catch {
    218         refuse('aborted');
    219       }
    220     }
    221     for (const store of ['received_envelopes', 'conversations'] as const) {
    222       try {
    223         const request = tx
    224           .objectStore(store)
    225           .index('by_owner')
    226           .openCursor(IDBKeyRange.only(scope.owner));
    227         request.addEventListener('success', () => {
    228           try {
    229             const cursor = request.result;
    230             if (!cursor) {
    231               done();
    232               return;
    233             }
    234             const key = cursor.primaryKey;
    235             if (
    236               !Array.isArray(key) ||
    237               key.length !== 2 ||
    238               key[0] !== scope.owner
    239             ) {
    240               refuse('corrupt_record');
    241               return;
    242             }
    243             if (store === 'received_envelopes') {
    244               const row = cipherRow(cursor.value, scope.owner, key[1]);
    245               if (!row) {
    246                 refuse('corrupt_record');
    247                 return;
    248               }
    249               received = received.concat(row);
    250               receivedBytes += row.bytes;
    251               if (
    252                 received.length > LOCAL_PERSISTENCE_BUDGETS.receivedEnvelopes ||
    253                 receivedBytes >
    254                   LOCAL_PERSISTENCE_BUDGETS.receivedCiphertextBytes
    255               ) {
    256                 refuse('capacity');
    257                 return;
    258               }
    259             } else {
    260               const row = pairRow(cursor.value, scope.owner, key[1]);
    261               if (!row || pairs.some((x) => x.peer === row.peer)) {
    262                 refuse('corrupt_record');
    263                 return;
    264               }
    265               pairs = pairs.concat(row);
    266               pairBytes += row.bytes;
    267               if (
    268                 pairs.length > LOCAL_PERSISTENCE_BUDGETS.receivedEnvelopes ||
    269                 pairBytes > LOCAL_PERSISTENCE_BUDGETS.receivedCiphertextBytes
    270               ) {
    271                 refuse('capacity');
    272                 return;
    273               }
    274             }
    275             cursor.continue();
    276           } catch {
    277             refuse('aborted');
    278           }
    279         });
    280       } catch {
    281         refuse('aborted');
    282       }
    283     }
    284   });
    285 }
    286 export function captureMessageMetadata(
    287   database: BrowserDatabase,
    288   session: PrivateSession,
    289   unlocked: UnlockedSession,
    290   review: unknown
    291 ): MessageMetadata | undefined {
    292   if (
    293     typeof window === 'undefined' ||
    294     review !== 'reviewed_local_message_metadata'
    295   )
    296     return;
    297   const observation = privateSessionOwnership(session),
    298     cacheObservation = unlockedSessionOwnership(unlocked);
    299   if (
    300     !observation ||
    301     !cacheObservation ||
    302     observation.owner !== cacheObservation.owner ||
    303     observation.session !== cacheObservation.session ||
    304     !observation.current() ||
    305     !cacheObservation.current()
    306   )
    307     return;
    308   const observed = observation,
    309     cache = cacheObservation;
    310   const owner = observed.owner,
    311     generation = observed.session;
    312   try {
    313     if (browserDatabaseState(database).state !== 'ready') return;
    314   } catch {
    315     return;
    316   }
    317   let closed = false,
    318     off = () => {};
    319   const token = Object.freeze({}) as MessageMetadata;
    320   function close() {
    321     if (closed) return;
    322     closed = true;
    323     metadataOwnerships.delete(token);
    324     off();
    325     controllers.set(token, {
    326       snapshot: () => Promise.resolve<Snapshot>({ status: 'stopped' }),
    327       display: () => Promise.resolve<Display>({ status: 'stopped' }),
    328       messages: () => ({ status: 'closed', messages: [] }),
    329       close: () => {}
    330     });
    331   }
    332   const scope: Scope = {
    333     database,
    334     owner,
    335     session: generation,
    336     unlocked,
    337     current: () => {
    338       if (closed || !observed.current() || !cache.current()) {
    339         close();
    340         return false;
    341       }
    342       try {
    343         return browserDatabaseState(database).state === 'ready';
    344       } catch {
    345         return false;
    346       }
    347     }
    348   };
    349   async function snapshot(): Promise<Snapshot> {
    350     if (!scope.current()) return { status: 'stopped' };
    351     const loaded = await transaction(scope, 'readonly', (rows) => ({
    352       ok: true,
    353       value: {
    354         status: 'ready' as const,
    355         owner,
    356         readRumors: Array.from(
    357           new Set(
    358             rows.received.flatMap((x) =>
    359               x.record.read ? [x.record.read.rumorHash] : []
    360             )
    361           )
    362         ),
    363         pairs: rows.pairs.map((x) => ({ id: x.id, peer: x.peer }))
    364       }
    365     }));
    366     return !scope.current()
    367       ? { status: 'stopped' }
    368       : loaded.ok
    369         ? loaded.value
    370         : { status: loaded.reason };
    371   }
    372   async function display(
    373     room: AdmittedConversation,
    374     review: unknown,
    375     markRead = true
    376   ): Promise<Display> {
    377     if (!scope.current()) return { status: 'stopped' };
    378     if (
    379       review !==
    380         (markRead
    381           ? 'displayed_message'
    382           : 'reviewed_admitted_conversation_navigation') ||
    383       !unlockedConversationCurrent(unlocked, room)
    384     )
    385       return { status: 'invalid' };
    386     const data = conversationSnapshot(room),
    387       proof = conversationOwnership(room),
    388       cipher = conversationEnvelopeIdentity(room);
    389     if (
    390       !data ||
    391       !proof ||
    392       !cipher ||
    393       data.owner !== owner ||
    394       proof.owner !== owner ||
    395       proof.session !== generation ||
    396       cipher.owner !== owner
    397     )
    398       return { status: 'invalid' };
    399     const current = () =>
    400       scope.current() &&
    401       proof.current() &&
    402       unlockedConversationCurrent(unlocked, room);
    403     if (!current() || !navigator.locks?.request)
    404       return { status: 'unavailable' };
    405     try {
    406       return await navigator.locks.request(
    407         'harvestcircle:owner:' + owner,
    408         { mode: 'exclusive', ifAvailable: true },
    409         async (lock): Promise<Display> => {
    410           if (!lock) return { status: 'busy' };
    411           if (!current()) return { status: 'stopped' };
    412           const loaded = await transaction(scope, 'readonly', (rows) => ({
    413             ok: true,
    414             value: rows
    415           }));
    416           if (!current()) return { status: 'stopped' };
    417           if (!loaded.ok) return { status: loaded.reason };
    418           const row = loaded.value.received.find(
    419             (x) => x.record.id === cipher.outerId
    420           );
    421           if (!row || row.record.outer !== cipher.outerWire)
    422             return { status: 'conflict' };
    423           if (row.record.read && row.record.read.rumorHash !== data.rumorId)
    424             return { status: 'conflict' };
    425           let pair = loaded.value.pairs.find((x) => x.peer === data.peer);
    426           const existed = !!pair && (!markRead || !!row.record.read);
    427           if (!pair) {
    428             const id = newLocalId();
    429             if (!id) return { status: 'unavailable' };
    430             const wire = JSON.stringify({
    431               schema: 1,
    432               family: 'conversation_handle',
    433               owner,
    434               id,
    435               peer: data.peer
    436             });
    437             pair = pairRow({ owner, id, wire }, owner, id);
    438             if (!pair) return { status: 'invalid' };
    439           }
    440           const selected = pair;
    441           let nextWire = row.wire;
    442           if (markRead && !row.record.read) {
    443             const now = Date.now();
    444             if (
    445               safeUnsignedInteger(now) === undefined ||
    446               row.record.revision >= Number.MAX_SAFE_INTEGER
    447             )
    448               return { status: 'invalid' };
    449             nextWire = JSON.stringify({
    450               ...row.record,
    451               revision: row.record.revision + 1,
    452               read: { rumorHash: data.rumorId, atMilliseconds: now }
    453             });
    454             if (
    455               !cipherRow(
    456                 { owner, id: row.record.id, wire: nextWire },
    457                 owner,
    458                 row.record.id
    459               )
    460             )
    461               return { status: 'invalid' };
    462           }
    463           const written = await transaction(
    464             scope,
    465             'readwrite',
    466             (rows, tx, refuse) => {
    467               if (!current()) {
    468                 refuse('stopped');
    469                 return;
    470               }
    471               const latest = rows.received.find(
    472                   (x) => x.record.id === cipher.outerId
    473                 ),
    474                 existing = rows.pairs.find((x) => x.peer === data.peer);
    475               if (
    476                 latest?.wire !== row.wire ||
    477                 (existing?.wire ?? null) !==
    478                   (loaded.value.pairs.find((x) => x.peer === data.peer)?.wire ??
    479                     null) ||
    480                 rows.pairs.some(
    481                   (x) => x.id === selected.id && x.wire !== selected.wire
    482                 )
    483               ) {
    484                 refuse('conflict');
    485                 return;
    486               }
    487               const nextBytes = new TextEncoder().encode(
    488                 JSON.stringify({ owner, id: cipher.outerId, wire: nextWire })
    489               ).length;
    490               if (
    491                 rows.received.reduce((n, x) => n + x.bytes, 0) -
    492                   row.bytes +
    493                   nextBytes >
    494                   LOCAL_PERSISTENCE_BUDGETS.receivedCiphertextBytes ||
    495                 (!existing &&
    496                   (rows.pairs.length >=
    497                     LOCAL_PERSISTENCE_BUDGETS.receivedEnvelopes ||
    498                     rows.pairs.reduce((n, x) => n + x.bytes, selected.bytes) >
    499                       LOCAL_PERSISTENCE_BUDGETS.receivedCiphertextBytes))
    500               ) {
    501                 refuse('capacity');
    502                 return;
    503               }
    504               if (nextWire !== row.wire)
    505                 tx.objectStore('received_envelopes').put({
    506                   owner,
    507                   id: cipher.outerId,
    508                   wire: nextWire
    509                 });
    510               if (!existing)
    511                 tx.objectStore('conversations').put({
    512                   owner,
    513                   id: selected.id,
    514                   wire: selected.wire
    515                 });
    516               return { ok: true, value: true };
    517             }
    518           );
    519           if (!current()) return { status: 'stopped' };
    520           if (!written.ok) return { status: written.reason };
    521           const readback = await transaction(scope, 'readonly', (rows) => ({
    522             ok: true,
    523             value: rows
    524           }));
    525           if (!current()) return { status: 'stopped' };
    526           if (!readback.ok)
    527             return {
    528               status: 'unknown_completion',
    529               phase: 'readback',
    530               reason: readback.reason
    531             };
    532           if (
    533             readback.value.received.find((x) => x.record.id === cipher.outerId)
    534               ?.wire !== nextWire ||
    535             readback.value.pairs.find((x) => x.id === selected.id)?.wire !==
    536               selected.wire
    537           )
    538             return { status: 'conflict' };
    539           return {
    540             status: existed ? 'existing' : 'saved',
    541             conversationId: selected.id,
    542             rumorId: data.rumorId
    543           };
    544         }
    545       );
    546     } catch {
    547       return { status: current() ? 'unknown_completion' : 'stopped' };
    548     }
    549   }
    550   controllers.set(token, {
    551     snapshot,
    552     display,
    553     messages: () =>
    554       scope.current()
    555         ? readUnlockedMessages(unlocked)
    556         : { status: 'closed', messages: [] },
    557     close
    558   });
    559   metadataOwnerships.set(token, {
    560     owner,
    561     session: generation,
    562     current: scope.current
    563   });
    564   off = subscribePrivateSessionClose(session, close);
    565   return scope.current() ? token : undefined;
    566 }
    567 export function messageMetadataSnapshot(
    568   scope: MessageMetadata
    569 ): Promise<Snapshot> {
    570   return (
    571     controllers.get(scope)?.snapshot() ?? Promise.resolve({ status: 'invalid' })
    572   );
    573 }
    574 // Detached projection for local count calculation only, never persistence proof.
    575 export function messageMetadataMessages(scope: MessageMetadata) {
    576   return (
    577     controllers.get(scope)?.messages() ?? {
    578       status: 'rejected' as const,
    579       messages: []
    580     }
    581   );
    582 }
    583 export function markDisplayedMessage(
    584   scope: MessageMetadata,
    585   room: AdmittedConversation,
    586   review: unknown
    587 ): Promise<Display> {
    588   return (
    589     controllers.get(scope)?.display(room, review) ??
    590     Promise.resolve({ status: 'invalid' })
    591   );
    592 }
    593 
    594 // Genuine original metadata custody only. Detached snapshot pairs and owner
    595 // strings cannot substitute for this token/generation when navigating.
    596 export function messageMetadataOwnership(scope: MessageMetadata) {
    597   const owned = metadataOwnerships.get(scope);
    598   if (!owned?.current()) return;
    599   // Detached observation: caller mutation cannot rebind the private stored
    600   // owner/generation or original current check used by later admission.
    601   return {
    602     owner: owned.owner,
    603     session: owned.session,
    604     current: () => owned.current()
    605   };
    606 }
    607 // Admitted exchange may establish a room without treating navigation as read.
    608 // It retains the original cached-room proof, owner lock, full-wire CAS and
    609 // native completion/readback path; unknown route lookup never calls it.
    610 export function rememberMessageConversation(
    611   scope: MessageMetadata,
    612   room: AdmittedConversation,
    613   review: unknown
    614 ): Promise<Display> {
    615   return (
    616     controllers.get(scope)?.display(room, review, false) ??
    617     Promise.resolve({ status: 'invalid' })
    618   );
    619 }