app

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

inbox-access.ts (15717B)


      1 import { canonicalPublicKey } from '../contracts/public-key.ts';
      2 import { exactLocalFields } from '../contracts/local-records.ts';
      3 import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts';
      4 import { getEventHash, type UnsignedEvent } from 'applesauce-core/helpers';
      5 import { readRelayPolicy, type RelayPolicy } from '../config/relays.ts';
      6 import {
      7   inboxOperatorQualificationSnapshot,
      8   inboxOperatorQualificationWire,
      9   type InboxOperatorQualification
     10 } from '../config/inbox-operators.ts';
     11 import {
     12   inboxAccessConstructionBinding,
     13   subscribeInboxAccessControllerClose,
     14   type InboxAccessController
     15 } from '../messaging/inbox-access-controller.ts';
     16 import {
     17   privateSessionOwnership,
     18   subscribePrivateSessionClose,
     19   withIdlePrivateLocalStorage,
     20   type PrivateSession
     21 } from '../runtime/private-session.ts';
     22 import {
     23   privateStorageOwner,
     24   commitPrivateRecord,
     25   loadPrivateRecord,
     26   type PrivateStorageRepository,
     27   type PrivateStorageFailure
     28 } from '../persistence/private-storage.ts';
     29 import {
     30   decodePrivateRecord,
     31   privateRecordWire,
     32   type PrivateAccessProbe,
     33   type PrivateRecordHandle
     34 } from '../persistence/private-records.ts';
     35 import { canonicalLocalId } from '../private-handles.ts';
     36 import { safeUnsignedInteger } from './envelope-bounds.ts';
     37 
     38 declare const probeIdentityBrand: unique symbol;
     39 export type InboxProbeIdentity = Readonly<{ [probeIdentityBrand]: true }>;
     40 export type InboxProbeReservationResult =
     41   | Readonly<{
     42       status: 'reserved' | 'existing';
     43       disposition: 'stored_original';
     44       identity: InboxProbeIdentity;
     45     }>
     46   | Readonly<{
     47       status: PrivateStorageFailure | 'invalid' | 'busy' | 'stopped';
     48       disposition: 'not_created' | 'may_exist';
     49     }>;
     50 type Saved = {
     51   session: PrivateSession;
     52   access: InboxAccessController;
     53   policy: RelayPolicy;
     54   record: PrivateAccessProbe;
     55   handle: PrivateRecordHandle;
     56   wire(): string | undefined;
     57   current(): boolean;
     58   stop(): void;
     59 };
     60 type Action = {
     61   repository: PrivateStorageRepository;
     62   session: PrivateSession;
     63   policy: RelayPolicy;
     64   operator: InboxOperatorQualification;
     65   pending(): boolean;
     66   possible(): boolean;
     67   result(): InboxProbeReservationResult | undefined;
     68 };
     69 const identities = new WeakMap<InboxProbeIdentity, Saved>();
     70 const actions = new WeakMap<InboxAccessController, Action>();
     71 // A fixed diagnostic, never a Message composer input or recognition/suppression
     72 // authority. Only the separate current genuine construction owner sees its wire.
     73 const diagnostic = 'Harvestcircle private inbox access check v1: ';
     74 
     75 export async function reserveInboxProbeIdentity(
     76   repository: PrivateStorageRepository,
     77   session: PrivateSession,
     78   policy: RelayPolicy,
     79   access: InboxAccessController,
     80   operator: InboxOperatorQualification,
     81   review: unknown
     82 ): Promise<InboxProbeReservationResult> {
     83   const prior = actions.get(access);
     84   const failure = (
     85     status: PrivateStorageFailure | 'invalid' | 'busy' | 'stopped'
     86   ): InboxProbeReservationResult => ({
     87     status,
     88     disposition: prior?.possible() ? 'may_exist' : 'not_created'
     89   });
     90   if (review !== 'reviewed_inbox_probe_reservation') return failure('invalid');
     91   if (prior) {
     92     if (
     93       prior.repository !== repository ||
     94       prior.session !== session ||
     95       prior.policy !== policy ||
     96       prior.operator !== operator
     97     )
     98       return failure('conflict');
     99     if (prior.pending()) return failure('busy');
    100     const original = prior.result();
    101     if (original && 'identity' in original) {
    102       return inboxProbeSnapshot(original.identity)
    103         ? { ...original, status: 'existing' }
    104         : failure('stopped');
    105     }
    106     return original ?? failure('stopped');
    107   }
    108   const proof = inboxAccessConstructionBinding(access, session, policy),
    109     owner = privateSessionOwnership(session),
    110     declaration = inboxOperatorQualificationSnapshot(operator),
    111     operatorWire = inboxOperatorQualificationWire(operator, policy);
    112   if (
    113     !proof ||
    114     !owner?.current() ||
    115     proof.owner !== owner.owner ||
    116     proof.session !== owner.session ||
    117     privateStorageOwner(repository) !== owner.owner
    118   )
    119     return failure('invalid_scope');
    120   if (
    121     !declaration ||
    122     !operatorWire ||
    123     declaration.authority === 'unconfigured' ||
    124     ![...proof.readTargets, ...proof.archiveTargets].every((origin) => {
    125       const row = declaration.relays.find((entry) => entry.origin === origin);
    126       return (
    127         row &&
    128         row.auth !== 'unsupported' &&
    129         row.recipientRead === 'supported' &&
    130         row.namedArchiveAck === 'supported' &&
    131         row.exactReadback === 'supported' &&
    132         row.retention === 'operator_defined'
    133       );
    134     })
    135   )
    136     return failure('unavailable');
    137   const binding = {
    138     preferenceId: proof.preferenceId,
    139     preferenceCreatedAt: proof.preferenceCreatedAt,
    140     readTargets: [...proof.readTargets],
    141     archiveTargets: [...proof.archiveTargets],
    142     policyWire: JSON.stringify(readRelayPolicy(policy)),
    143     operatorWire
    144   };
    145   const frozenBinding = JSON.stringify(binding);
    146   let pending = true,
    147     possible = false,
    148     result: InboxProbeReservationResult | undefined;
    149   const action: Action = {
    150     repository,
    151     session,
    152     policy,
    153     operator,
    154     pending: () => pending,
    155     possible: () => possible,
    156     result: () => result
    157   };
    158   actions.set(access, action);
    159   const refuse = (
    160     status: PrivateStorageFailure | 'invalid' | 'busy' | 'stopped'
    161   ): InboxProbeReservationResult => ({
    162     status,
    163     disposition: possible ? 'may_exist' : 'not_created'
    164   });
    165   const actorCurrent = () => {
    166     const actual = inboxAccessConstructionBinding(access, session, policy);
    167     return (
    168       owner.current() &&
    169       proof.current() &&
    170       !!actual &&
    171       actual.session === owner.session &&
    172       actual.owner === owner.owner &&
    173       JSON.stringify({
    174         preferenceId: actual.preferenceId,
    175         preferenceCreatedAt: actual.preferenceCreatedAt,
    176         readTargets: actual.readTargets,
    177         archiveTargets: actual.archiveTargets,
    178         policyWire: JSON.stringify(readRelayPolicy(policy)),
    179         operatorWire: inboxOperatorQualificationWire(operator, policy)
    180       }) === frozenBinding
    181     );
    182   };
    183   let captured: InboxProbeIdentity | undefined;
    184   try {
    185     if (typeof window === 'undefined' || !navigator.locks?.request)
    186       return (result = refuse('unavailable'));
    187     result = await navigator.locks.request(
    188       'harvestcircle:owner:' + owner.owner,
    189       { mode: 'exclusive', ifAvailable: true },
    190       async (lock) => {
    191         if (!lock) return refuse('busy');
    192         if (!actorCurrent()) return refuse('stopped');
    193         const idle = await withIdlePrivateLocalStorage(
    194           session,
    195           async (): Promise<InboxProbeReservationResult> => {
    196             if (!actorCurrent()) return refuse('stopped');
    197             const milliseconds = safeUnsignedInteger(Date.now()),
    198               id = canonicalLocalId(crypto.randomUUID());
    199             if (milliseconds === undefined || !id || !actorCurrent())
    200               return refuse('invalid_record');
    201             const createdAt = Math.floor(milliseconds / 1000),
    202               nonceBytes = crypto.getRandomValues(new Uint8Array(32));
    203             let wire: string | undefined;
    204             try {
    205               const nonce = Array.from(nonceBytes, (byte) =>
    206                 byte.toString(16).padStart(2, '0')
    207               ).join('');
    208               const rumor: UnsignedEvent = {
    209                 pubkey: owner.owner,
    210                 created_at: createdAt,
    211                 kind: 14,
    212                 tags: [['p', owner.owner]],
    213                 content: diagnostic + nonce
    214               };
    215               wire = JSON.stringify({ id: getEventHash(rumor), ...rumor });
    216             } finally {
    217               nonceBytes.fill(0);
    218             }
    219             if (!wire || !actorCurrent()) return refuse('stopped');
    220             const rumorHash = (JSON.parse(wire) as { id: string }).id;
    221             if (
    222               !inboxProbeRumorMatches(wire, owner.owner, rumorHash, createdAt)
    223             )
    224               return refuse('invalid_record');
    225             const record: PrivateAccessProbe = {
    226               schema: 1,
    227               family: 'private_access_probe',
    228               owner: owner.owner,
    229               id,
    230               revision: 0,
    231               rumorHash,
    232               createdAt,
    233               binding,
    234               self: null,
    235               receipts: []
    236             };
    237             const handle = decodePrivateRecord(
    238               JSON.stringify(record),
    239               owner.owner,
    240               id
    241             );
    242             if (!handle.ok || !actorCurrent()) return refuse('invalid_record');
    243             const originalWire = privateRecordWire(
    244               handle.value,
    245               owner.owner,
    246               id
    247             );
    248             if (!originalWire) return refuse('invalid_record');
    249             const token = Object.freeze({}) as InboxProbeIdentity;
    250             let stopped = false,
    251               offSession = () => {},
    252               offAccess = () => {};
    253             const saved: Saved = {
    254               session,
    255               access,
    256               policy,
    257               record,
    258               handle: handle.value,
    259               wire: () => wire,
    260               current() {
    261                 if (stopped || !actorCurrent()) {
    262                   saved.stop();
    263                   return false;
    264                 }
    265                 return wire !== undefined;
    266               },
    267               stop() {
    268                 stopped = true;
    269                 wire = undefined;
    270                 offSession();
    271                 offAccess();
    272               }
    273             };
    274             captured = token;
    275             identities.set(token, saved);
    276             offSession = subscribePrivateSessionClose(session, () =>
    277               saved.stop()
    278             );
    279             offAccess = subscribeInboxAccessControllerClose(access, () =>
    280               saved.stop()
    281             );
    282             if (!saved.current()) {
    283               saved.stop();
    284               return refuse('stopped');
    285             }
    286             possible = true;
    287             const committed = await commitPrivateRecord(
    288               repository,
    289               handle.value,
    290               null
    291             );
    292             if (!committed.ok) {
    293               possible = ![
    294                 'capacity',
    295                 'invalid_record',
    296                 'invalid_scope',
    297                 'aborted'
    298               ].includes(committed.reason);
    299               saved.stop();
    300               return refuse(committed.reason);
    301             }
    302             if (!saved.current()) return refuse('stopped');
    303             const readback = await loadPrivateRecord(
    304               repository,
    305               'private_sends',
    306               id
    307             );
    308             if (
    309               !readback.ok ||
    310               privateRecordWire(readback.value, owner.owner, id) !==
    311                 originalWire ||
    312               !saved.current()
    313             ) {
    314               saved.stop();
    315               return refuse(readback.ok ? 'conflict' : readback.reason);
    316             }
    317             return {
    318               status:
    319                 committed.value.state === 'committed' ? 'reserved' : 'existing',
    320               disposition: 'stored_original',
    321               identity: token
    322             };
    323           }
    324         );
    325         return idle.ok
    326           ? idle.value
    327           : refuse(actorCurrent() ? 'busy' : 'stopped');
    328       }
    329     );
    330     return result;
    331   } catch {
    332     if (captured) identities.get(captured)?.stop();
    333     return (result = refuse('unavailable'));
    334   } finally {
    335     pending = false;
    336     if (!result || !('identity' in result)) {
    337       if (captured) identities.get(captured)?.stop();
    338     }
    339   }
    340 }
    341 export function inboxProbeSnapshot(
    342   identity: InboxProbeIdentity
    343 ): PrivateAccessProbe | undefined {
    344   const saved = identities.get(identity);
    345   return saved?.current()
    346     ? (JSON.parse(JSON.stringify(saved.record)) as PrivateAccessProbe)
    347     : undefined;
    348 }
    349 // Genuine original session association; neither detached wire nor a same-owner
    350 // replacement session can supply the original memory-only crypto input.
    351 export function inboxProbeRumorWire(
    352   identity: InboxProbeIdentity,
    353   session: PrivateSession
    354 ): string | undefined {
    355   const saved = identities.get(identity);
    356   return saved?.session === session && saved.current()
    357     ? saved.wire()
    358     : undefined;
    359 }
    360 export function inboxProbeReservationHandle(
    361   identity: InboxProbeIdentity
    362 ): PrivateRecordHandle | undefined {
    363   const saved = identities.get(identity);
    364   return saved?.current() ? saved.handle : undefined;
    365 }
    366 export function stopInboxProbeIdentity(identity: InboxProbeIdentity): void {
    367   identities.get(identity)?.stop();
    368 }
    369 
    370 // Canonical policy bytes cannot substitute for the original opaque policy.
    371 export function inboxProbePolicyMatches(
    372   identity: InboxProbeIdentity,
    373   session: PrivateSession,
    374   policy: RelayPolicy
    375 ): boolean {
    376   const saved = identities.get(identity);
    377   return (
    378     !!saved &&
    379     saved.session === session &&
    380     saved.policy === policy &&
    381     saved.current()
    382   );
    383 }
    384 
    385 // Only the genuine original construction chain can name its action owner.
    386 // Recovery has a separate proof family and cannot enter seal/wrap construction.
    387 export function inboxProbeActionOwner(
    388   identity: InboxProbeIdentity,
    389   session: PrivateSession,
    390   policy: RelayPolicy
    391 ): InboxAccessController | undefined {
    392   const saved = identities.get(identity);
    393   return saved && inboxProbePolicyMatches(identity, session, policy)
    394     ? saved.access
    395     : undefined;
    396 }
    397 
    398 // The original reserved action, never an equal decoded declaration, supplies
    399 // the opaque operator association used by later access qualification.
    400 export function inboxProbeOperatorBinding(
    401   identity: InboxProbeIdentity,
    402   repository: PrivateStorageRepository,
    403   session: PrivateSession,
    404   policy: RelayPolicy
    405 ): InboxOperatorQualification | undefined {
    406   const saved = identities.get(identity),
    407     action = saved && actions.get(saved.access),
    408     result = action?.result();
    409   return saved &&
    410     action &&
    411     action.repository === repository &&
    412     action.session === session &&
    413     action.policy === policy &&
    414     result &&
    415     'identity' in result &&
    416     result.identity === identity &&
    417     inboxProbePolicyMatches(identity, session, policy)
    418     ? action.operator
    419     : undefined;
    420 }
    421 
    422 // Detached inspection only. Actual SDK decryption and original native/current
    423 // associations are necessary to issue a recovered probe capability.
    424 export function inboxProbeRumorMatches(
    425   raw: unknown,
    426   owner: unknown,
    427   hash: unknown,
    428   createdAt: unknown
    429 ): boolean {
    430   const author = canonicalPublicKey(owner);
    431   if (
    432     !author ||
    433     typeof hash !== 'string' ||
    434     !/^[0-9a-f]{64}$/.test(hash) ||
    435     safeUnsignedInteger(createdAt) === undefined ||
    436     typeof raw !== 'string' ||
    437     !boundedUtf8(raw, 8192)
    438   )
    439     return false;
    440   try {
    441     const rumor: unknown = JSON.parse(raw);
    442     if (
    443       !exactLocalFields(rumor, [
    444         'id',
    445         'pubkey',
    446         'created_at',
    447         'kind',
    448         'tags',
    449         'content'
    450       ]) ||
    451       rumor.id !== hash ||
    452       rumor.pubkey !== author ||
    453       rumor.created_at !== createdAt ||
    454       rumor.kind !== 14 ||
    455       JSON.stringify(rumor.tags) !== JSON.stringify([['p', author]]) ||
    456       typeof rumor.content !== 'string' ||
    457       !rumor.content.startsWith(diagnostic) ||
    458       !/^[0-9a-f]{64}$/.test(rumor.content.slice(diagnostic.length))
    459     )
    460       return false;
    461     const event: UnsignedEvent = {
    462       pubkey: author,
    463       created_at: createdAt as number,
    464       kind: 14,
    465       tags: [['p', author]],
    466       content: rumor.content
    467     };
    468     return (
    469       getEventHash(event) === hash &&
    470       JSON.stringify({ id: hash, ...event }) === raw
    471     );
    472   } catch {
    473     return false;
    474   }
    475 }