sigelo-contact 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/carrier.mjs CHANGED
@@ -8,11 +8,33 @@
8
8
  // short: the long code is also parked at the relay under a short one
9
9
  // await c.unpark(short) → the long code parked under a short one, taken from the relay (one use)
10
10
  // await c.accept(code, { name, wait }) → { status: 'connected' | 'waiting' | 'pending', … } a long code or a short one
11
- // c.contacts() → { contacts, invites, answers } each contact with its four words (fingerprint)
12
- // await c.send(to, content, { label }) → { status: 'sent' | 'queued', … }, or throws the relay's code
13
- // await c.sendAll(to, contents, { label }) → one result each ('refused' with its code), one login
14
- // await c.inbox({ wait }) → { messages, events, dropped, offline? }: all are taken (messages: those kept)
11
+ // (refused after a short code was fetched: .long, keepLong)
12
+ // await c.cancelInvite(code) → { cancelled, name }: an unanswered invite of this agent's withdrawn
13
+ // c.rename(who, name) the owner's name for a contact (store.mjs rename) → { did, name }
14
+ // c.contacts() → { contacts, invites, answers, failed } each contact with its four words (fingerprint),
15
+ // pair id, chain, tier (store.mjs: own, friend, quiet) and tier_by, prekeys: its
16
+ // bundle is here (false: messages wait for it), waiting: why they wait, or null;
17
+ // failed: pairing_failed events (code_expired: an answer that outlived its code) until inbox
18
+ // await c.send(to, content, { label, local }) → { status: 'sent' | 'queued', … }, or throws the relay's code
19
+ // await c.sendAll(to, contents, { label, local }) → one result each ('refused' with its code), one login
20
+ // await c.sendFile(to, path, { local }) → { status, to, name, file: {id, name, size, sha256, chunks} }: a file of at most
21
+ // 8 MiB as FILE_LABEL messages (file.mjs), one login; throws as send does. Chunks
22
+ // queued wait in files/.out (0600), the state names them; gone once sent or refused.
23
+ // local (all three): no session, queued in the state file for a started carrier
24
+ // of the same identity elsewhere (a watcher), which sends it at its next sync()
25
+ // await c.inbox({ wait, tiers, local, paired }) → { messages, events, dropped, offline? }: all are taken (messages: those kept;
26
+ // tiers: only those from contacts of these tiers, the rest stay); local: no
27
+ // session, the state file only (a started carrier elsewhere is connected);
28
+ // paired: the wait also ends at a pairing (enrol.mjs)
29
+ // c.peek(), c.take(pick) the messages kept for inbox(), each with its sender's tier: read, or those
30
+ // pick(message, tier) chooses taken; no session (a started carrier's owner)
31
+ // c.setTier(who, tier) the owner's tier for a contact (store.mjs setTier) → { did, name, tier }
32
+ // c.observe(bundle) a contact's full bundle seen: its operator attestations (store.mjs observe)
33
+ // a file received whole is one item {type: "file", from, contact, name, size,
34
+ // sha256, path, …}, saved under `files` (pathsFor), never opened
15
35
  // await c.forget(did) → { name, did, revoked: true, released, offline? }
36
+ // c.lastError the error behind the last offline of inbox or forget (SIGELO_DEBUG)
37
+ // c.clockOffset(), await c.checkClock() → { relay, offset, checked } | null: the relay's clock less this one's, seconds
16
38
  // await c.start(), c.sync(), c.stop() stay connected, reconnecting with backoff; events reach onEvent
17
39
  //
18
40
  // identity() → { secret, bundle }: the agent's current secret key and SPEC §8 bundle, read again at
@@ -25,8 +47,9 @@
25
47
  // default only without onEvent, so a message onEvent took is not left at rest after the keys that
26
48
  // opened it are gone (contacts.md §3: keys stolen today must not open yesterday's messages).
27
49
  // One connected carrier per identity: every process logs in with the identity's one MQTT client
28
- // id, so a CLI verb run beside a started carrier takes the session from it (the files stay sound
29
- // under the lock; the started one reconnects with backoff).
50
+ // id, so a second login takes the session from a started carrier (the files stay sound under the
51
+ // lock; the started one reconnects with backoff). Beside one, use inbox and send with local: the
52
+ // state file only (sigelo-agent's one-owner rule, adapters/moadim/WATCH.md).
30
53
  //
31
54
  // What this adds to the wire, beside the envelope (envelope.mjs) and the invite (invite.mjs); the
32
55
  // bytes are pinned in fixtures/carrier-v0.json (gen-carrier.mjs --check):
@@ -117,6 +140,18 @@
117
140
  // cannot be told from the thief's: refused alike; the owner writes again once paired again.
118
141
  // What an earlier inbox() returned, or onEvent got, cannot be taken back: the `rotated` event
119
142
  // of such a notice lists the DIDs it overruled (`overruled`).
143
+ // - Operator hints (label OPERATOR_LABEL, a message like any other): an agent attested by
144
+ // operators (sigelo-relay/operator) tells each contact {hints: HMAC-SHA256(K, "sigelo-operator/0
145
+ // hint\n" ‖ its original DID ‖ "\n" ‖ operator DID)}, once per pairing and set of operators. A
146
+ // contact run by the same operator, or that operator itself, recognises one and answers {asks}
147
+ // (the same with "ask" and its own DID: it knows the operator's DID, an echo does not), and only
148
+ // then the agent sends {proof}: its chain with those attestations and their issuers, which the
149
+ // contact verifies (SPEC §9) and files (store.mjs observe): the contact's tier becomes own. A
150
+ // proof is taken only after asks of ours, at most NOTICE_CHECKS an hour, and only if its chain
151
+ // ends at the sender's current DID as held (store.mjs current_did). A renewed attestation is
152
+ // hinted and proved again; asks for the same operators go at most every RESYNC. A contact
153
+ // learns from the hints only which operator DIDs it guesses right (THREAT-MODEL §2.12). An
154
+ // agent on an older version gets the hints as messages with that label. send refuses the label.
120
155
  // - Mailboxes: an agent holds the topics of every ISO week from `retention` ago to AHEAD (7 days,
121
156
  // or its retention if shorter) ahead. The relay drops a publish to a topic nobody claimed (and
122
157
  // says no_reader), so next week's topic must be claimed before a contact writes in it while
@@ -138,10 +173,11 @@
138
173
  // round, so topics are asked in the order they matter (#want). A refused topic is asked again
139
174
  // at the next hourly round (ASK_AGAIN).
140
175
  import { createHash } from 'node:crypto';
141
- import { closeSync, existsSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
142
- import { basename, dirname, join } from 'node:path';
176
+ import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
177
+ import { basename, dirname, join, resolve, sep } from 'node:path';
143
178
  import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
144
179
  import { hkdf } from '@noble/hashes/hkdf.js';
180
+ import { hmac } from '@noble/hashes/hmac.js';
145
181
  import { sha256 } from '@noble/hashes/sha2.js';
146
182
  import { concatBytes, hexToBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils.js';
147
183
  import { connect } from 'mqtt';
@@ -150,12 +186,14 @@ import { KIND, acceptPrekeys, expire, header, open, pad, prekeysMissing, restart
150
186
  import { answerId, buildAnswer, buildReply, checkAnswer, checkReply, inviteKeys, keyOf, makeInvite, parseInvite } from './invite.mjs';
151
187
  import { MsgError, checkNow, fail, hex, isoWeek, pairId, topic } from './kdf.mjs';
152
188
  import { Prekeys, exact, kemDecapsulate, kemEncapsulate, kemKey } from './prekeys.mjs';
153
- import { Contacts } from './store.mjs';
154
- import { SHORT_TTL, codeHash, fingerprint, formatShort, isShort, makeShort } from './short.mjs';
189
+ import { Contacts, OPERATOR_CTX, TIERS } from './store.mjs';
190
+ import { SHORT_TTL, codeHash, codeKind, fingerprint, formatShort, makeShort, normaliseShort } from './short.mjs';
191
+ import { FILE_LABEL, MAX_FILE, assemble, checkChunk, checkManifest, chunkHead, isManifest, safeName, splitFile } from './file.mjs';
155
192
 
156
193
  export const V = 'sigelo-carrier/0';
157
194
  export const DEFAULT_RELAY = 'relay.sigelo.ai', MQTT_PORT = 8883, NOTICE = '$sigelo/notice';
158
195
  export const LABEL_PREKEYS = 'sigelo-msg/0 prekeys', KIND_NOTICE = 4, KIND_PREKEYS = 5, TYP_NOTICE = 'contact-notice';
196
+ export const OPERATOR_LABEL = 'sigelo-operator/0';
159
197
  // The relay login (relay-plan §3 "Login"): the body GET /challenge answers and the agent signs. A
160
198
  // type of its own, never a SPEC §5.2 challenge: a world that passed the relay's nonce on as its own
161
199
  // challenge would get the agent's relay login back from sign-challenge.
@@ -190,6 +228,8 @@ const POISON_TRIES = 3;
190
228
  // Events kept for the next inbox(): pairings, rotations, failed pairings. The oldest go first.
191
229
  // Messages kept for it (keep), likewise.
192
230
  const EVENTS_MAX = 1000, INBOX_MAX = 1000;
231
+ // Files arriving at once from one contact (#onFile): each holds up to 8 MiB of parts here.
232
+ const FILES_OPEN = 8;
193
233
  // Half the relay's publish brake (20 a second, 200 at once): past it the relay refuses publishes
194
234
  // ("rate"), and closes the connection after 500 refusals in a minute (every refused publish
195
235
  // counts, a no_reader too).
@@ -259,6 +299,14 @@ const b64 = (b) => Buffer.from(b).toString('base64');
259
299
  const unb64 = (s) => new Uint8Array(Buffer.from(s, 'base64'));
260
300
  const randomId = () => hex(randomBytes(8));
261
301
  const clientIdOf = (original) => 's' + createHash('sha256').update(original, 'utf8').digest('hex').slice(0, 24);
302
+ // Operators as hinted and proved: each with its attestation's expiry, so a renewal goes again.
303
+ const opKey = (mine, ops) => [...ops].sort().map((d) => `${d} ${mine.exp.get(d)}`).join();
304
+ // Whether a session as the state holds it (dumpSession) has a prekey bundle of contact c's that an
305
+ // epoch can begin on (envelope.mjs prekeysMissing): of this pairing, signed as c's current DID, unexpired.
306
+ const theirPrekeys = (c, d, pair, now) => {
307
+ const p = d?.pair === pair ? d.out.prekeys : null;
308
+ return Boolean(p) && p.did === c.current_did && now < p.exp;
309
+ };
262
310
  // The four words of a pairing (short.mjs), from its pairing key as the store holds it (hex), or null.
263
311
  const wordsOf = (pairKey) => (typeof pairKey === 'string' ? fingerprint(pairId(hexToBytes(pairKey))) : null);
264
312
  // The refusals of POST /park this client names (relay/park.mjs, and the login's: auth.mjs).
@@ -266,10 +314,10 @@ const PARK_CHECKS = new Set(['park', 'park_taken', 'park_full', 'pow', ...LOGIN_
266
314
 
267
315
  // ---------------------------------------------------------------- configuration
268
316
 
269
- /** The contact store and this carrier's state, beside the identity file: x.json → x.contacts.json, x.carrier.json. */
317
+ /** The contact store, this carrier's state and the files received, beside the identity file: x.json → x.contacts.json, x.carrier.json, x.files/. */
270
318
  export function pathsFor(identityFile) {
271
319
  const base = identityFile.replace(/\.json$/, '');
272
- return { store: `${base}.contacts.json`, state: `${base}.carrier.json` };
320
+ return { store: `${base}.contacts.json`, state: `${base}.carrier.json`, files: `${base}.files` };
273
321
  }
274
322
 
275
323
  /**
@@ -319,7 +367,7 @@ export function optionsFromEnv(env = process.env) {
319
367
  const o = {};
320
368
  if (env.SIGELO_RELAY) o.relay = env.SIGELO_RELAY;
321
369
  if (env.SIGELO_RELAY_ENDPOINTS) {
322
- try { o.endpoints = JSON.parse(env.SIGELO_RELAY_ENDPOINTS); } catch { fail('relay', 'SIGELO_RELAY_ENDPOINTS is not JSON'); }
370
+ try { o.endpoints = JSON.parse(env.SIGELO_RELAY_ENDPOINTS); } catch { fail('relay', 'SIGELO_RELAY_ENDPOINTS is not JSON: want {"<relay>": {"mqtt": "mqtts://…", "http": "https://…"}}'); }
323
371
  }
324
372
  if (env.SIGELO_RELAY_RETENTION_DAYS) {
325
373
  const n = Number(env.SIGELO_RELAY_RETENTION_DAYS);
@@ -418,6 +466,8 @@ function loadSession(s, d) {
418
466
 
419
467
  const ZERO_EPOCH = new Uint8Array(16), FRAME_HEAD = 22, NONCE = 24;
420
468
  /** The contact notice's key: HKDF-SHA256(K, salt "sigelo-notice/0", info = from ‖ "\n" ‖ to), original DIDs. */
469
+ // The header's "Operator hints": what `from` (an original DID) shows of operator `op`, as hex.
470
+ export const operatorHint = (K, kind, from, op) => hex(hmac(sha256, K, utf8ToBytes(`${OPERATOR_LABEL} ${kind}\n${from}\n${op}`)));
421
471
  export const noticeKey = (K, from, to) => hkdf(sha256, K, utf8ToBytes('sigelo-notice/0'), utf8ToBytes(`${from}\n${to}`), 32);
422
472
  /** The prekeys frame's key: HKDF-SHA256(K, salt "sigelo-prekeys/0", info = from ‖ "\n" ‖ to), original DIDs. */
423
473
  export const prekeysKey = (K, from, to) => hkdf(sha256, K, utf8ToBytes('sigelo-prekeys/0'), utf8ToBytes(`${from}\n${to}`), 32);
@@ -528,28 +578,73 @@ export async function solvePow(host, original, nonce, bits, deadline = Infinity)
528
578
  // past publicRelay's check on the code's host. A relay never needs one: `connect`.
529
579
  async function http(url, init = {}) {
530
580
  let res;
531
- try { res = await fetch(url, { ...init, redirect: 'manual', signal: AbortSignal.timeout(HTTP_MS) }); } catch (e) { fail('connect', `${url}: ${e.cause?.code ?? e.message}`); }
581
+ const at = where(url), http = { url, method: init.method ?? 'GET' };
582
+ const t0 = Date.now();
583
+ try { res = await fetch(url, { ...init, redirect: 'manual', signal: AbortSignal.timeout(HTTP_MS) }); } catch (e) {
584
+ const why = e.name === 'TimeoutError' ? `no answer within ${HTTP_MS / 1000} s` : e.cause?.code ?? e.cause?.message ?? e.message;
585
+ fail('connect', `cannot reach the relay at ${at} (${why}): check the network and SIGELO_RELAY / SIGELO_RELAY_ENDPOINTS, then try again`, { cause: e, http });
586
+ }
587
+ http.status = res.status;
588
+ // The relay's clock (Date, whole seconds) and the round trip to it, for clockOffset.
589
+ const rtt = Date.now() - t0, date = Date.parse(res.headers.get('date') ?? '');
532
590
  if ((res.status >= 300 && res.status < 400) || res.type === 'opaqueredirect') {
533
591
  try { await res.body?.cancel(); } catch {}
534
- fail('connect', `${url}: answered ${res.status}, a redirect, which this client does not follow`);
592
+ fail('connect', `${at}: answered ${res.status}, a redirect, which this client does not follow`, { http });
535
593
  }
536
- if (Number(res.headers.get('content-length') ?? 0) > HTTP_MAX) fail('connect', `${url}: answer over ${HTTP_MAX} bytes`);
594
+ if (Number(res.headers.get('content-length') ?? 0) > HTTP_MAX) fail('connect', `${at}: answer over ${HTTP_MAX} bytes`, { http });
537
595
  const chunks = [];
538
596
  let n = 0;
539
597
  try {
540
598
  // Leaving the loop by a throw cancels the stream: nothing more is read.
541
599
  for await (const chunk of res.body ?? []) {
542
600
  n += chunk.length;
543
- if (n > HTTP_MAX) fail('connect', `${url}: answer over ${HTTP_MAX} bytes`);
601
+ if (n > HTTP_MAX) fail('connect', `${at}: answer over ${HTTP_MAX} bytes`, { http });
544
602
  chunks.push(chunk);
545
603
  }
546
604
  } catch (e) {
547
605
  if (e instanceof MsgError) throw e;
548
- fail('connect', `${url}: ${e.cause?.code ?? e.message}`);
606
+ fail('connect', `${at}: the answer broke off (${e.cause?.code ?? e.message}): try again`, { cause: e, http });
549
607
  }
550
608
  let body = null;
551
- try { body = parseBytes(concatBytes(...chunks)); } catch {}
552
- return { status: res.status, body };
609
+ const raw = concatBytes(...chunks);
610
+ try { body = parseBytes(raw); } catch {}
611
+ // Seconds the relay asks to wait (Retry-After), when it says.
612
+ const after = Number(res.headers.get('retry-after'));
613
+ // What a refusal carries for SIGELO_DEBUG: the status and the start of the body as received.
614
+ http.body = new TextDecoder().decode(raw.subarray(0, 512));
615
+ return { status: res.status, body, retryAfter: Number.isSafeInteger(after) && after > 0 ? after : null, http, date: Number.isNaN(date) ? null : date, rtt };
616
+ }
617
+
618
+ // A URL as a refusal shows it: no query (it carries the DID), no code hash.
619
+ function where(url) {
620
+ try { const u = new URL(url); return u.origin + u.pathname.replace(/\/[0-9a-f]{64}$/, '/<code hash>'); } catch { return String(url); }
621
+ }
622
+ // A refusal of a relay's HTTP answer r, with the answer kept for SIGELO_DEBUG.
623
+ const refuse = (check, why, r) => fail(check, why, { http: r.http });
624
+ // When to try again after a 429: the relay's Retry-After, else the window its brake counts in.
625
+ const retryIn = (r, window) => (r.retryAfter ? `wait ${r.retryAfter} s` : `wait ${window}`);
626
+ // A status no answer about this agent: the relay is down, restarting, or behind a proxy that is.
627
+ const statusWhy = (r, what) => `the relay answered ${r.status} to ${what}${r.status >= 500 ? ': it is down or restarting; try again in a few minutes' : ': try again later; SIGELO_DEBUG=1 shows the answer'}`;
628
+ /** A long code (or one fetched by a short one: parked) read with parseInvite; a malformed one
629
+ * is refused saying how the input was read, so a mistyped short code never reads "does not
630
+ * start with sgl1". */
631
+ export function readCode(text, now, how = 'long') {
632
+ try { return parseInvite(text, now); } catch (e) {
633
+ if (!(e instanceof MsgError) || !['code_checksum', 'code_length', 'code_version'].includes(e.check)) throw e;
634
+ const as = how === 'parked' ? 'the long code the relay holds for this short code does not parse; ask the inviter for a new one'
635
+ : `read as a long code (it starts sgl1, or has more than 12 characters; a short code has 8, like K7F3-Q9ZP): ${reason(e)}`;
636
+ throw new MsgError(e.check, how === 'parked' ? `${as} (${reason(e)})` : as, { cause: e });
637
+ }
638
+ }
639
+
640
+ // A short code is spent once fetched (unpark): a refusal after that would lose the long code it
641
+ // stood for, so the refusal carries it (.long, and in its words). Not when the answer it made
642
+ // still stands (queued, or held by the relay: .kept) nor when the code was answered already.
643
+ export function keepLong(e, long) {
644
+ if (e?.kept || e?.lapsed || e?.check === 'mailbox_taken') return e;
645
+ const k = new MsgError(e instanceof MsgError ? e.check : 'error', `${e instanceof Error ? reason(e) : String(e)}. The short code is used up; its long code: ${long} (keep this; accept it with the long code)`, { cause: e, http: e?.http });
646
+ k.long = long;
647
+ return k;
553
648
  }
554
649
 
555
650
  // Text a relay writes reaches the operator, and perhaps a model, inside this client's messages:
@@ -580,11 +675,20 @@ async function named(ep, creds, err) {
580
675
  try {
581
676
  const r = await http(`${ep.http}/check`, { method: 'POST', body: JSON.stringify({ username: creds.username, client_id: creds.clientId, password: creds.password }) });
582
677
  if (r.body?.ok === false && typeof r.body.check === 'string') {
583
- return new MsgError(LOGIN_CHECKS.has(r.body.check) ? r.body.check : 'connect', `the relay refused the login (${relaySays(`${r.body.check}: ${r.body.detail}`)})`);
678
+ const check = LOGIN_CHECKS.has(r.body.check) ? r.body.check : 'connect';
679
+ return new MsgError(check, `the relay refused the login (${relaySays(`${r.body.check}: ${r.body.detail}`)})${LOGIN_NEXT[check] ? `: ${LOGIN_NEXT[check]}` : ''}`, { cause: err, http: r.http });
584
680
  }
585
681
  } catch {}
586
- return err instanceof MsgError ? err : new MsgError('connect', err.message);
682
+ return err instanceof MsgError ? err : new MsgError('connect', `the relay at ${ep.mqtt} did not take the connection (${err.message}): check the network and SIGELO_RELAY / SIGELO_RELAY_ENDPOINTS, then try again`, { cause: err });
587
683
  }
684
+ // What to do after a login refusal, by its check (relay/auth.mjs). bundle: sigelo-agent adds the lockout.
685
+ const LOGIN_NEXT = {
686
+ rate: 'too many logins from this network: wait a minute, then try again',
687
+ relay_full: 'the relay is full: try again later',
688
+ challenge_expired: 'the login took longer than its challenge lives (a slow proof of work): try again',
689
+ challenge_unknown: 'try again',
690
+ connect: 'try again later',
691
+ };
588
692
 
589
693
  /**
590
694
  * Reads each MQTT packet's fixed header (a type byte, then its length in 1 to 4 bytes of 7 bits,
@@ -668,9 +772,10 @@ export class Carrier {
668
772
  #links = new Map(); #work = Promise.resolve(); #busy = 0; #lastWork = 0; #routes = new Map(); #results = new Map();
669
773
  #claimed = new Set(); #refusedTopics = new Map(); #handshakes = new Map(); #soon = new Set();
670
774
  #started = false; #tick = null; #timers = new Map(); #attempts = new Map(); #connecting = new Set(); #powFails = new Map(); #ask = false;
775
+ #mineMemo = null; #clocks = new Map();
671
776
 
672
777
  constructor({ identity, store, state, relay = DEFAULT_RELAY, endpoints = {}, retentionDays, clock = () => Math.floor(Date.now() / 1000),
673
- onEvent, keep, backoff = BACKOFF, tick = TICK }) {
778
+ onEvent, keep, backoff = BACKOFF, tick = TICK, files }) {
674
779
  if (typeof identity !== 'function') throw new TypeError('identity: a function returning { secret, bundle }');
675
780
  if (typeof store !== 'string' || typeof state !== 'string') throw new TypeError('store, state: file paths (pathsFor(identityFile))');
676
781
  if (retentionDays !== undefined && !retentionOk(retentionDays)) throw new TypeError(`retentionDays: 1 to ${RETENTION_MAX_DAYS}`);
@@ -681,6 +786,9 @@ export class Carrier {
681
786
  if (keep !== undefined && typeof keep !== 'boolean') throw new TypeError('keep: true or false');
682
787
  Object.assign(this, { identity, storePath: store, statePath: state, relay, endpoints, retention: retentionDays * DAY, clock, onEvent: onEvent ?? (() => {}),
683
788
  keep: keep ?? onEvent === undefined, backoff, tick });
789
+ // Files received (#onFile): files, else beside the state as pathsFor names it (x.carrier.json → x.files).
790
+ if (files !== undefined && typeof files !== 'string') throw new TypeError('files: a directory path (pathsFor(identityFile))');
791
+ this.filesDir = resolve(files ?? state.replace(/(\.carrier)?\.json$/, '') + '.files');
684
792
  }
685
793
 
686
794
  // ---- files, under the lock
@@ -705,16 +813,48 @@ export class Carrier {
705
813
  #with(write, fn) {
706
814
  return withLock(this.statePath, () => {
707
815
  const now = checkNow(this.clock()), me = this.#me(now);
708
- const ctx = { now, me, store: new Contacts(this.storePath, me.did), st: loadState(this.statePath, me.did) };
816
+ const ctx = { now, me, store: new Contacts(this.storePath, me.did, { mine: () => this.#mine(me, now) }), st: loadState(this.statePath, me.did) };
709
817
  // Before anything reads the store: a recovery made by another process (sigelo-agent recover)
710
818
  // is seen at once. The store's marks are written first; the state keeps the events.
711
819
  if (this.#markRecovered(ctx)) saveState(this.statePath, ctx.st);
820
+ if (this.#lapse(ctx)) saveState(this.statePath, ctx.st);
712
821
  const out = fn(ctx);
822
+ // Answers that fn's adds and takes found expired.
823
+ if (this.#lapse(ctx) && !write) saveState(this.statePath, ctx.st);
713
824
  if (write) { saveState(this.statePath, ctx.st); ctx.store.commit(); }
714
825
  return out;
715
826
  });
716
827
  }
717
828
  #locked(fn) { return this.#with(true, fn); }
829
+
830
+ // For tiers (store.mjs): this agent's chain, and its operators: the issuers of the unexpired
831
+ // sigelo-relay/operator attestations its bundle carries that verify (operator DID → exp). Kept
832
+ // until the bundle changes or one of them expires.
833
+ #mine(me, now) {
834
+ const key = JSON.stringify([me.chain, me.bundle.attestations ?? [], me.bundle.issuers ?? []]), m = this.#mineMemo;
835
+ if (m && m.key === key && now < m.until) return m.value;
836
+ const operators = new Map();
837
+ try {
838
+ const r = verify({ ...me.bundle, bindings: [] }, now);
839
+ for (const [iss, bodies] of Object.entries(r.attestations)) {
840
+ for (const b of bodies) if (b.ctx === OPERATOR_CTX && !me.chain.includes(iss)) operators.set(iss, Math.max(operators.get(iss) ?? 0, b.exp));
841
+ }
842
+ } catch {}
843
+ const value = { chain: me.chain, operators: [...operators.keys()], exp: operators };
844
+ this.#mineMemo = { key, until: Math.min(Infinity, ...operators.values()), value };
845
+ return value;
846
+ }
847
+
848
+ // An answer that expired before the inviter's reply came: the accept said "waiting", so the next
849
+ // inbox (and contacts until then) says it failed, rather than nothing at all.
850
+ #lapse({ now, store, st }) {
851
+ const gone = store.lapsed(now);
852
+ for (const p of gone) {
853
+ this.#emit(this.#note(st, now, { type: 'pairing_failed', did: p.code_did, name: p.name, code: 'code_expired',
854
+ detail: `the code from ${p.name} expired at ${new Date(p.exp * 1000).toISOString().replace('.000', '')} before the inviter's agent replied: ask the inviter for a new code` }));
855
+ }
856
+ return gone.length > 0;
857
+ }
718
858
  #read(fn) { return this.#with(false, fn); }
719
859
 
720
860
  // This agent recovered after it last told a contact of its keys (`announced`: a DID at or before
@@ -862,7 +1002,7 @@ export class Carrier {
862
1002
  if (c.revoked) fail('revoked', `${c.did} was revoked by this owner`);
863
1003
  } else {
864
1004
  const hits = this.#liveContacts(store).filter((x) => x.name === to);
865
- if (hits.length === 0) fail('not_contact', `no contact named ${JSON.stringify(to)}`);
1005
+ if (hits.length === 0) fail('not_contact', `no contact named ${JSON.stringify(to)}: contacts lists them; a contact comes from an invite and its accept`);
866
1006
  if (hits.length > 1) fail('name', `${hits.length} contacts are named ${JSON.stringify(to)}: use the DID`);
867
1007
  c = hits[0];
868
1008
  }
@@ -992,6 +1132,16 @@ export class Carrier {
992
1132
  st.dropped[e.check] = (st.dropped[e.check] ?? 0) + 1;
993
1133
  events.push({ type: 'dropped', check: e.check, detail: e.message });
994
1134
  }
1135
+ } else if (r.body.label === FILE_LABEL) {
1136
+ // A file's manifest or chunk (file.mjs): kept apart until the file is whole (#onFile).
1137
+ events.push(...this.#onFile(ctx, c, r, now));
1138
+ } else if (r.body.label === OPERATOR_LABEL) {
1139
+ // Operator hints, asks and proofs (the header): taken here, never an inbox message. One refused is counted.
1140
+ try { events.push(...this.#onOperator(ctx, c, r.body.content)); } catch (e) {
1141
+ if (!(e instanceof MsgError)) throw e;
1142
+ st.dropped[e.check] = (st.dropped[e.check] ?? 0) + 1;
1143
+ events.push({ type: 'dropped', check: e.check, detail: e.message });
1144
+ }
995
1145
  } else {
996
1146
  // last_resort: the epoch began on the last-resort prekey, which may serve many epochs: weaker
997
1147
  // forward secrecy (plan §3 "Prekeys"), and routine for a while after a rotation (#next).
@@ -1007,6 +1157,170 @@ export class Carrier {
1007
1157
  return events;
1008
1158
  }
1009
1159
 
1160
+ // The header's "Operator hints". Hints of contact c's operators: those this agent knows (its own
1161
+ // operators, or itself) are asked for, once per set. Asks: proofs of this agent's operators the
1162
+ // contact showed it knows, once per set. A proof: c's chain with operator attestations, filed.
1163
+ // Answers go first in c's outbox. → events: `tier` when c's tier changed.
1164
+ #onOperator({ now, me, store, st }, c, v) {
1165
+ const K = hexToBytes(c.pair_key), e = this.#entry(st, c.did), mine = this.#mine(me, now);
1166
+ const list = (x) => (Array.isArray(x) && x.length <= 8 && x.every((h) => typeof h === 'string') ? x : fail('operator', 'hints and asks: at most 8 strings'));
1167
+ if (v?.hints !== undefined) {
1168
+ const hints = list(v.hints), known = [...mine.operators, ...mine.chain].filter((d) => hints.includes(operatorHint(K, 'hint', c.did, d))).sort();
1169
+ // Again for the same operators at most every RESYNC: the contact hints anew once their
1170
+ // attestations are renewed (#next), and its proof must come again before the old one lapses.
1171
+ if (known.length > 0 && (e.op_asked !== known.join() || now - (e.op_asked_at ?? 0) >= RESYNC)) {
1172
+ e.op_asked = known.join(); e.op_asked_at = now;
1173
+ e.outbox.unshift({ id: randomId(), label: OPERATOR_LABEL, content: { asks: known.map((d) => operatorHint(K, 'ask', me.did, d)) } });
1174
+ }
1175
+ return [];
1176
+ }
1177
+ if (v?.asks !== undefined) {
1178
+ // Proved again once an attestation shown is renewed (its expiry is in the key).
1179
+ const asks = list(v.asks), shown = mine.operators.filter((d) => asks.includes(operatorHint(K, 'ask', c.did, d))).sort(), key = opKey(mine, shown);
1180
+ if (shown.length > 0 && e.op_proved !== key) {
1181
+ e.op_proved = key;
1182
+ const b = me.bundle, iss = new Set(shown);
1183
+ const proof = { v: b.v, typ: 'bundle', genesis: b.genesis, rotations: b.rotations, bindings: [],
1184
+ attestations: (b.attestations ?? []).filter((a) => a?.body?.ctx === OPERATOR_CTX && iss.has(a.body.iss)), issuers: (b.issuers ?? []).filter((g) => iss.has(didOf(g))) };
1185
+ e.outbox.unshift({ id: randomId(), label: OPERATOR_LABEL, content: { proof } });
1186
+ }
1187
+ return [];
1188
+ }
1189
+ if (v?.proof !== undefined) {
1190
+ // Only in answer to asks of ours, and so many an hour: each costs SPEC §9 (THREAT-MODEL §2.12).
1191
+ if (!e.op_asked) fail('operator', 'an operator proof nobody asked for');
1192
+ const recent = (e.op_checks ?? []).filter((x) => x > now - RESYNC);
1193
+ if (recent.length >= NOTICE_CHECKS) fail('operator_rate', `${recent.length} operator proofs of this contact checked within ${RESYNC} s, the most`);
1194
+ e.op_checks = [...recent, now];
1195
+ const p = v.proof;
1196
+ if (![p?.rotations, p?.attestations, p?.issuers].every(Array.isArray) || p.rotations.length > MAX_ROTATIONS || p.attestations.length > 8 || p.issuers.length > 8) {
1197
+ fail('operator', `an operator proof is a bundle of at most ${MAX_ROTATIONS} rotations, 8 attestations and 8 issuers`);
1198
+ }
1199
+ let r;
1200
+ try { r = verify(p, now); } catch (err) { fail('operator', `the contact's operator proof does not verify: ${err.message}`); }
1201
+ if (r.chain[0] !== c.did) fail('operator', 'the operator proof is not the chain of the contact that sent it');
1202
+ // store.observe refuses a chain that ends anywhere but the contact's current DID (current_did).
1203
+ const before = store.tierOf(c, now), after = store.observe(c.did, r, now);
1204
+ return after === before ? [] : [{ type: 'tier', did: c.did, name: c.name, tier: after }];
1205
+ }
1206
+ fail('operator', 'an operator message is {hints}, {asks} or {proof}');
1207
+ }
1208
+
1209
+ // ---- files (file.mjs; design/human-ui-plan.md §4)
1210
+
1211
+ // A FILE_LABEL message from contact c, opened (r). The manifest is kept in the state (files,
1212
+ // under a key of the contact and the file's id), each chunk under filesDir/.partial/<key>/<i>
1213
+ // (0600, directories 0700); once all have come, the file is checked (size, SHA-256), saved as
1214
+ // filesDir/<contact>/<sha256[0..8]>-<name> (0600), and given to inbox() as one item of type
1215
+ // "file". Never opened, never made executable. Anything wrong with the message is counted in
1216
+ // dropped by its check, as a refused bundle is above; the envelope stays opened either way.
1217
+ // A chunk before its manifest (none: the sender sends the manifest first, in one login) is
1218
+ // dropped, file_chunk. The disk is written before the state: a crash between them leaves a
1219
+ // chunk that the delivery, unacknowledged, writes again.
1220
+ #onFile(ctx, c, r, now) {
1221
+ const { st } = ctx, content = r.body.content;
1222
+ st.files ??= {};
1223
+ const drop = (e) => {
1224
+ if (!(e instanceof MsgError)) throw e;
1225
+ st.dropped[e.check] = (st.dropped[e.check] ?? 0) + 1;
1226
+ return [{ type: 'dropped', check: e.check, detail: `a file from ${c.name}: ${e.message}` }];
1227
+ };
1228
+ const keyOf = (id) => hex(sha256(utf8ToBytes(`${c.did}\n${id}`)).subarray(0, 16));
1229
+ let key, p;
1230
+ try {
1231
+ if (isManifest(content)) {
1232
+ const m = checkManifest(content);
1233
+ key = keyOf(m.id);
1234
+ const had = st.files[key];
1235
+ if (had) {
1236
+ if (had.sha256 !== m.sha256 || had.size !== m.size) fail('file', 'a second manifest for one file id, with another content');
1237
+ return [];
1238
+ }
1239
+ // At most FILES_OPEN files arriving at once per contact: each holds up to 8 MiB here.
1240
+ if (Object.values(st.files).filter((x) => x.from === c.did).length >= FILES_OPEN) fail('file_busy', `${FILES_OPEN} files from this contact are incomplete already`);
1241
+ p = st.files[key] = { from: c.did, ...m, got: [], first: now };
1242
+ } else {
1243
+ const h = chunkHead(content);
1244
+ key = keyOf(h.id);
1245
+ p = st.files[key] ?? fail('file_chunk', 'a chunk of a file whose manifest has not come');
1246
+ const bytes = checkChunk(content, p);
1247
+ if (!p.got.includes(h.i)) {
1248
+ const dir = this.#partDir(key);
1249
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
1250
+ writeFileSync(join(dir, String(h.i)), bytes, { mode: 0o600 });
1251
+ p.got.push(h.i);
1252
+ }
1253
+ }
1254
+ } catch (e) { return drop(e); }
1255
+ if (p.got.length < p.chunks) return [];
1256
+ // Whole: checked, saved, and the parts gone whatever the check said.
1257
+ let bytes;
1258
+ try {
1259
+ bytes = assemble(p, Array.from({ length: p.chunks }, (_, i) => readFileSync(join(this.#partDir(key), String(i)))));
1260
+ } catch (e) {
1261
+ delete st.files[key];
1262
+ rmSync(this.#partDir(key), { recursive: true, force: true });
1263
+ return drop(e);
1264
+ }
1265
+ const dir = join(this.filesDir, safeName(c.name || c.did));
1266
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
1267
+ chmodSync(this.filesDir, 0o700); chmodSync(dir, 0o700);
1268
+ const path = join(dir, `${p.sha256.slice(0, 8)}-${p.name}`), tmp = join(dir, `.${randomId()}.tmp`);
1269
+ writeFileSync(tmp, bytes, { mode: 0o600, flag: 'wx' });
1270
+ renameSync(tmp, path);
1271
+ delete st.files[key];
1272
+ rmSync(this.#partDir(key), { recursive: true, force: true });
1273
+ const item = { type: 'file', from: c.did, contact: c.name, current_did: r.body.from, label: FILE_LABEL, name: p.name, size: p.size, sha256: p.sha256, path,
1274
+ iat: r.body.iat, received: now, last_resort: r.last_resort };
1275
+ // Kept for inbox() as a message is (#onPeer), and so many at most.
1276
+ if (this.keep) {
1277
+ st.inbox.push(item);
1278
+ if (st.inbox.length > INBOX_MAX) { const n = st.inbox.length - INBOX_MAX; st.inbox.splice(0, n); st.dropped.inbox_full = (st.dropped.inbox_full ?? 0) + n; }
1279
+ }
1280
+ return [item];
1281
+ }
1282
+
1283
+ #partDir(key) { return join(this.filesDir, '.partial', key); }
1284
+
1285
+ // A file's chunks wait in filesDir/.out/<item id>.json (0600, directory 0700), not in the state:
1286
+ // base64 in an outbox item, 8 MiB were rewritten with the state at every chunk sent. The outbox
1287
+ // item keeps { id, label, spool: true }. A contact's name never starts with a dot (safeName), so
1288
+ // .out is no contact's directory. Written under the lock with the items that name them.
1289
+ #spoolDir() { return join(this.filesDir, '.out'); }
1290
+ #spool(id, content) {
1291
+ const dir = this.#spoolDir();
1292
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
1293
+ chmodSync(this.filesDir, 0o700); chmodSync(dir, 0o700);
1294
+ writeFileSync(join(dir, `${id}.json`), JSON.stringify(content), { mode: 0o600, flag: 'wx' });
1295
+ }
1296
+ #spooled(id) {
1297
+ try { return JSON.parse(readFileSync(join(this.#spoolDir(), `${id}.json`), 'utf8')); } catch (e) {
1298
+ fail('file', `a queued part of a file is gone from ${this.#spoolDir()} (${e.code ?? e.message}): send the file again`);
1299
+ }
1300
+ }
1301
+ // Spooled parts no outbox or pending entry names any more (sent, refused, forgotten): removed.
1302
+ #sweepSpool(st) {
1303
+ let names;
1304
+ try { names = readdirSync(this.#spoolDir()); } catch { return; }
1305
+ const held = new Set();
1306
+ for (const e of Object.values(st.peers)) for (const x of e.outbox ?? []) if (x.spool) held.add(x.id);
1307
+ for (const p of st.pending) if (p.item?.spool) held.add(p.item.id);
1308
+ for (const n of names) if (/^[0-9a-f]{16}\.json$/.test(n) && !held.has(n.slice(0, -5))) rmSync(join(this.#spoolDir(), n), { force: true });
1309
+ }
1310
+
1311
+ // Files still incomplete after the retention (the relay has dropped whatever of them was left to
1312
+ // come): their parts go, counted file_incomplete, and inbox() says which.
1313
+ #sweepFiles(st, now) {
1314
+ for (const [key, p] of Object.entries(st.files ?? {})) {
1315
+ if (p.first + this.retention > now) continue;
1316
+ rmSync(this.#partDir(key), { recursive: true, force: true });
1317
+ delete st.files[key];
1318
+ st.dropped.file_incomplete = (st.dropped.file_incomplete ?? 0) + 1;
1319
+ this.#emit(this.#note(st, now, { type: 'dropped', check: 'file_incomplete', from: p.from,
1320
+ detail: `${p.name} (${p.size} bytes): ${p.got.length} of ${p.chunks} parts came within the retention; the rest will not: ask for it again` }));
1321
+ }
1322
+ }
1323
+
1010
1324
  // A bundle from the contact was accepted into s (acceptPrekeys). want: it asked for ours, which
1011
1325
  // goes unless one went within RESYNC (the header's "Prekeys").
1012
1326
  #tookPrekeys(st, s, want, now) {
@@ -1362,10 +1676,16 @@ export class Carrier {
1362
1676
  if (missing !== null) e.asked = now;
1363
1677
  return this.#queue(st, { relay, topic: t, bytes: frame, kind: KIND_PREKEYS, peer: c.did, control: 'prekeys' });
1364
1678
  }
1679
+ // This agent's operator hints, once per pairing and set of operators (#onOperator).
1680
+ const mine = this.#mine(me, now), ops = mine.operators, hinted = opKey(mine, ops);
1681
+ if (ops.length > 0 && e.op_hinted !== hinted) {
1682
+ e.op_hinted = hinted;
1683
+ e.outbox.unshift({ id: randomId(), label: OPERATOR_LABEL, content: { hints: [...ops].sort().map((d) => operatorHint(K, 'hint', me.did, d)) } });
1684
+ }
1365
1685
  while (e.outbox.length > 0) {
1366
1686
  const item = e.outbox[0];
1367
1687
  try {
1368
- const m = send(s, { label: item.label, content: item.content }, now);
1688
+ const m = send(s, { label: item.label, content: item.spool ? this.#spooled(item.id) : item.content }, now);
1369
1689
  e.outbox.shift();
1370
1690
  if (e.waiting === noReader(c.name)) e.waiting = null;
1371
1691
  this.#persist(st, s);
@@ -1452,6 +1772,10 @@ export class Carrier {
1452
1772
  }
1453
1773
 
1454
1774
  async #flush(link) {
1775
+ try { await this.#flushing(link); } finally { try { this.#locked(({ st }) => this.#sweepSpool(st)); } catch {} }
1776
+ }
1777
+
1778
+ async #flushing(link) {
1455
1779
  for (;;) {
1456
1780
  if (!link.up) return;
1457
1781
  const e = this.#locked((ctx) => this.#next(ctx, link));
@@ -1591,11 +1915,12 @@ export class Carrier {
1591
1915
  const { me, proven } = this.#read(({ me, st }) => ({ me, proven: st.relays[relay]?.proven === true }));
1592
1916
  const powMax = relay === this.relay ? POW_MAX : POW_MAX_OTHER;
1593
1917
  const r = await http(`${ep.http}/challenge?did=${encodeURIComponent(me.current_did)}`);
1594
- if (r.status === 429) fail('rate', `GET /challenge: too many challenges from this network (${relaySays(r.body?.error)})`);
1918
+ this.#clockFrom(relay, r);
1919
+ if (r.status === 429) refuse('rate', `the relay ${relay} turned the login away: too many logins from this network (${relaySays(r.body?.error ?? r.body?.detail)}): ${retryIn(r, 'a minute')}, then try again`, r);
1595
1920
  // Any other status is no answer about this agent (nginx says 502 while the relay restarts):
1596
1921
  // `connect`, retried. `challenge`, which no retry fixes, is a 200 that is not this relay's
1597
1922
  // challenge for this agent.
1598
- if (r.status !== 200) fail('connect', `GET /challenge answered ${r.status}`);
1923
+ if (r.status !== 200) refuse('connect', `${relay}: ${statusWhy(r, 'GET /challenge')}`, r);
1599
1924
  const ch = r.body?.challenge;
1600
1925
  if (!exact(ch, ['v', 'typ', 'did', 'relay', 'nonce']) || ch.v !== LOGIN_V || ch.typ !== TYP_LOGIN || typeof ch.nonce !== 'string' || ch.nonce.length > 128) {
1601
1926
  fail('challenge', `GET /challenge did not answer a login body {v: "${LOGIN_V}", typ: "${TYP_LOGIN}", did, relay, nonce}`);
@@ -1646,6 +1971,7 @@ export class Carrier {
1646
1971
  this.#ask = false;
1647
1972
  try {
1648
1973
  const r = await http(`${ep.http}/relay.json`);
1974
+ this.#clockFrom(this.relay, r);
1649
1975
  const n = r.status === 200 ? retentionOf(r.body) : null;
1650
1976
  if (n !== null) this.retention = n * DAY;
1651
1977
  } catch {}
@@ -1653,6 +1979,26 @@ export class Carrier {
1653
1979
 
1654
1980
  get retentionDays() { return this.retention / DAY; }
1655
1981
 
1982
+ // The relay's clock less this agent's (this.clock), in seconds, from an answer r of relay: its
1983
+ // Date header (whole seconds, so +0.5) taken as of the middle of the round trip.
1984
+ #clockFrom(relay, r) {
1985
+ if (r?.date == null) return;
1986
+ const now = this.clock();
1987
+ this.#clocks.set(relay, { offset: Math.round((r.date + 500 - r.rtt / 2) / 1000 - now), checked: now });
1988
+ }
1989
+
1990
+ /** { relay, offset, checked } as last measured at relay (a login, relay.json, a short code), or null. offset: seconds, relay minus local. */
1991
+ clockOffset(relay = this.relay) {
1992
+ const c = this.#clocks.get(relay);
1993
+ return c ? { relay, ...c } : null;
1994
+ }
1995
+
1996
+ /** Measures the offset now at this agent's own relay (GET /relay.json). → clockOffset(); throws as a relay that does not answer does. */
1997
+ async checkClock() {
1998
+ this.#clockFrom(this.relay, await http(`${endpointOf(this.relay, this.endpoints).http}/relay.json`));
1999
+ return this.clockOffset();
2000
+ }
2001
+
1656
2002
  async #dial(relay) {
1657
2003
  const ep = endpointOf(relay, this.endpoints), link = new Link(relay, relay === this.relay);
1658
2004
  const info = link.own && this.#ask ? this.#relayInfo(ep) : null;
@@ -1807,11 +2153,16 @@ export class Carrier {
1807
2153
  const creds = await this.#credentials(code.relay, ep);
1808
2154
  const r = await http(`${ep.http}/park`, { method: 'POST', body: JSON.stringify({ username: creds.username, client_id: creds.clientId, password: creds.password, code_hash: codeHash(s), invite: code.text, exp }) });
1809
2155
  const check = typeof r.body?.check === 'string' ? r.body.check : null;
1810
- if (r.status === 429) fail('rate', `POST /park: ${relaySays(r.body?.detail)}`);
1811
- if ((r.status === 404 || r.status === 405) && check === null) fail('park', `${code.relay} takes no short codes: use the long code (invite --long)`);
1812
- if (r.status !== 200) fail('connect', `POST /park answered ${r.status}`);
1813
- if (r.body?.ok !== true) fail(PARK_CHECKS.has(check) ? check : 'park', `the relay refused the short code (${relaySays(`${check}: ${r.body?.detail}`)})`);
1814
- return { code: code.text, did: code.did, relay: code.relay, exp: code.exp, short: formatShort(s), short_exp: exp };
2156
+ if (r.status === 429) refuse('rate', `the relay ${code.relay} parks no more short codes from this network for now (${relaySays(r.body?.detail)}): ${retryIn(r, 'up to an hour')}, or use the long code (invite --long)`, r);
2157
+ if ((r.status === 404 || r.status === 405) && check === null) refuse('park', `the relay ${code.relay} takes no short codes: use the long code (invite --long)`, r);
2158
+ if (r.status !== 200) refuse('connect', `${code.relay}: ${statusWhy(r, 'POST /park')}`, r);
2159
+ // exp is this machine's clock: one far off the relay's is refused (relay/park.mjs PARK_SKEW).
2160
+ const clock = typeof r.body?.detail === 'string' && r.body.detail.startsWith('exp:') ? ': this machine\'s clock may be off (date -u), or use the long code (invite --long)' : '';
2161
+ if (r.body?.ok !== true) refuse(PARK_CHECKS.has(check) ? check : 'park', `the relay refused the short code (${relaySays(`${check}: ${r.body?.detail}`)})${clock}`, r);
2162
+ // The relay keeps the code until its own exp (park.mjs: at most SHORT_TTL by its clock), not
2163
+ // this machine's: that is the one shown. This machine's only when the relay names none.
2164
+ const held = Number.isSafeInteger(r.body.exp) && r.body.exp > 0 ? r.body.exp : exp;
2165
+ return { code: code.text, did: code.did, relay: code.relay, exp: code.exp, short: formatShort(s), short_exp: held };
1815
2166
  } catch (e) {
1816
2167
  try { this.#locked(({ store }) => store.cancelInvite(code.nonce)); } catch {}
1817
2168
  throw e;
@@ -1822,21 +2173,30 @@ export class Carrier {
1822
2173
  // GET /park/<code hash>, which the relay answers once. Whatever it answers is a code to parse
1823
2174
  // like any other (accept); the four words show whether the pairing is the inviter's.
1824
2175
  async unpark(text) {
1825
- const ep = endpointOf(this.relay, this.endpoints);
2176
+ const shown = formatShort(normaliseShort(text)), ep = endpointOf(this.relay, this.endpoints);
1826
2177
  const r = await http(`${ep.http}/park/${codeHash(text)}`);
1827
- if (r.status === 429) fail('rate', `GET /park: ${relaySays(r.body?.detail)}`);
2178
+ if (r.status === 429) refuse('rate', `the relay ${this.relay} looks up no more short codes from this network for now (${relaySays(r.body?.detail)}): ${retryIn(r, 'up to 10 minutes')}, or ask for the long code (invite --long)`, r);
1828
2179
  if (r.status === 404 && r.body?.check === 'park_unknown') {
1829
- fail('park_unknown', `no invite waits under this short code at ${this.relay}: mistyped, used already, or older than 10 minutes. Ask for a new one (a code made at another relay works only as the long code: invite --long)`);
2180
+ refuse('park_unknown', `short code ${shown}: no invite waits under it at ${this.relay}. It expired (a short code lives 10 minutes), was used already (once only), or is mistyped; ask the inviter for a new one. If the inviter's agent uses another relay than ${this.relay} (SIGELO_RELAY), ask for the long code (invite --long)`, r);
1830
2181
  }
1831
- if (r.status === 404 || r.status === 405) fail('park', `${this.relay} takes no short codes: ask for the long code (invite --long)`);
1832
- if (r.status !== 200 || r.body?.ok !== true || typeof r.body.invite !== 'string') fail('connect', `GET /park answered ${r.status}`);
2182
+ if (r.status === 404 || r.status === 405) refuse('park', `the relay ${this.relay} takes no short codes: ask the inviter for the long code (invite --long)`, r);
2183
+ if (r.status !== 200) refuse('connect', `${this.relay}: ${statusWhy(r, 'GET /park')}`, r);
2184
+ if (r.body?.ok !== true || typeof r.body.invite !== 'string') refuse('connect', `${this.relay}: GET /park answered 200 without a parked code: try again later; SIGELO_DEBUG=1 shows the answer`, r);
1833
2185
  return r.body.invite;
1834
2186
  }
1835
2187
 
1836
- async accept(text, { name, wait = 10 } = {}) {
1837
- if (isShort(text)) text = await this.unpark(text);
2188
+ async accept(text, opts = {}) {
2189
+ // Short or long by the input's shape, before either parser runs (short.mjs codeKind).
2190
+ const how = codeKind(text) === 'short' ? 'parked' : 'long';
2191
+ if (how !== 'parked') return this.#answer(text, how, opts);
2192
+ const long = await this.unpark(text);
2193
+ try { return await this.#answer(long, how, opts); } catch (e) { throw keepLong(e, long); }
2194
+ }
2195
+
2196
+ async #answer(text, how, { name, wait = 10, tier } = {}) {
2197
+ if (tier !== undefined && !TIERS.includes(tier)) fail('tier', `a tier is ${TIERS.join(', ')}; not ${JSON.stringify(tier)}`);
1838
2198
  const { code, id, entry } = this.#locked(({ now, me, store, st }) => {
1839
- const code = parseInvite(text, now);
2199
+ const code = readCode(text, now, how);
1840
2200
  // This agent's own relay, and those its operator configured, are the operator's choice.
1841
2201
  if (code.relay !== this.relay && !Object.hasOwn(this.endpoints ?? {}, code.relay) && !publicRelay(code.relay)) {
1842
2202
  fail('code_relay', `the code names ${code.relay}, an address or a local name, not a public relay: allow it in SIGELO_RELAY_ENDPOINTS if it is yours`);
@@ -1850,7 +2210,7 @@ export class Carrier {
1850
2210
  const id = answerId(answer);
1851
2211
  // Unnamed: the code's DID's first digits ("z5esAbCd"), as operators shorten a DID. Named, the
1852
2212
  // name also replaces a known contact's on a re-pair (#onReply).
1853
- store.addAccept(code, id, name ?? code.did.slice('did:sigelo:'.length, 'did:sigelo:'.length + 8), now, hex(k.secretKey), me.current_did, name !== undefined);
2213
+ store.addAccept(code, id, name ?? code.did.slice('did:sigelo:'.length, 'did:sigelo:'.length + 8), now, hex(k.secretKey), me.current_did, name !== undefined, tier ?? null);
1854
2214
  const entry = this.#queue(st, { relay: code.relay, topic: keys.answer_topic, bytes: frame, kind: KIND.invite_answer, control: 'answer', needs: [keys.reply_topic], exp: code.exp });
1855
2215
  return { code, id, entry: entry.id };
1856
2216
  } finally { k.secretKey.fill(0); }
@@ -1863,7 +2223,8 @@ export class Carrier {
1863
2223
  // Done early too once the reply topic or the answer is refused (a code answered before:
1864
2224
  // mailbox_taken), not after the whole wait.
1865
2225
  const reply = inviteKeys(code.secret).reply_topic;
1866
- const settled = () => this.#handshakes.has(id) || this.#refusedTopics.has(reply) || Boolean(this.#results.get(entry)?.code);
2226
+ // And once the code expires (#lapse): the answer is dead, so --wait does not run out first.
2227
+ const settled = () => this.#handshakes.has(id) || this.#refusedTopics.has(reply) || Boolean(this.#results.get(entry)?.code) || this.clock() >= code.exp;
1867
2228
  try { await this.#session([code.relay], { max: wait * 1000, until: settled }); } catch (e) {
1868
2229
  // A relay other than this agent's own that refuses it for good would be dialled again at
1869
2230
  // every connection, until the code expires, for an answer it never takes: and a stranger's
@@ -1879,32 +2240,72 @@ export class Carrier {
1879
2240
  return 'withdrawn';
1880
2241
  });
1881
2242
  const why = { withdrawn: 'the answer is withdrawn', queued: 'the answer stays queued: it goes at the next connection', delivered: 'the relay holds the answer: the reply is read at a later connection' }[left];
1882
- throw new MsgError(e.check ?? 'connect', `${reason(e)} (${why})`);
2243
+ const err = new MsgError(e.check ?? 'connect', `${reason(e)} (${why})`, { cause: e, http: e.http });
2244
+ if (left !== 'withdrawn') err.kept = true;
2245
+ throw err;
1883
2246
  }
1884
2247
  const h = this.#handshakes.get(id), sent = this.#results.get(entry);
1885
2248
  this.#handshakes.delete(id); this.#results.delete(entry);
1886
2249
  if (h?.check) fail(h.check, h.detail);
1887
2250
  if (h) return { status: 'connected', contact: h.contact };
1888
- if (this.#refusedTopics.has(reply)) { const r = this.#refusedTopics.get(reply); drop(r.code, `the relay did not let this agent claim the reply topic (${relaySays(r.detail)})`); }
2251
+ if (this.#refusedTopics.has(reply)) {
2252
+ const r = this.#refusedTopics.get(reply);
2253
+ // The reply topic is the code's: held by another identity, someone answered the code first.
2254
+ drop(r.code, r.code === 'mailbox_taken' ? `this code was answered already, by another agent (a code works once): ask the inviter for a new one (${relaySays(r.detail)})`
2255
+ : `the relay did not let this agent claim the reply topic (${relaySays(r.detail)})`);
2256
+ }
1889
2257
  if (sent?.code) drop(sent.code, `the relay refused the answer (${relaySays(sent.detail)})`);
2258
+ // The code expired during the wait: #lapse emitted pairing_failed (onEvent); the refusal says
2259
+ // it here, so the next inbox does not say it again. No long code to keep (keepLong): it is dead.
2260
+ const lapsed = this.#locked(({ now, store, st }) => {
2261
+ if (now < code.exp) return null;
2262
+ st.pending = st.pending.filter((p) => p.id !== entry); store.take('accepts', id, now);
2263
+ const at = new Date(code.exp * 1000).toISOString().replace('.000', '');
2264
+ const i = st.events.findIndex((e) => e.type === 'pairing_failed' && e.code === 'code_expired' && e.did === code.did && e.detail?.includes(at));
2265
+ return i >= 0 ? st.events.splice(i, 1)[0].detail : `the code expired at ${at} before the inviter's agent replied: ask the inviter for a new code`;
2266
+ });
2267
+ if (lapsed) throw Object.assign(new MsgError('code_expired', lapsed), { lapsed: true });
1890
2268
  if (!sent) return { status: 'pending', did: code.did, relay: code.relay, detail: 'the answer has not reached the relay yet: it goes at the next connection' };
1891
2269
  return { status: 'waiting', did: code.did, relay: code.relay, detail: 'answer delivered; the pairing completes when the inviter\'s agent next connects' };
1892
2270
  }
1893
2271
 
2272
+ // An invite this agent made and nobody has answered, withdrawn: code, its long code (invite's
2273
+ // `code`). Its answer topic is given up at the next round; a short code parked for it leads to
2274
+ // nothing. → { cancelled: true, name }.
2275
+ async cancelInvite(code) {
2276
+ const { relay, name } = this.#locked(({ now, store }) => {
2277
+ const c = readCode(code, now), p = store.load().s.invites[c.nonce];
2278
+ store.cancelInvite(c.nonce);
2279
+ return { relay: c.relay, name: p.name };
2280
+ });
2281
+ this.#routes = new Map();
2282
+ if (this.#links.get(relay)?.up) this.#refreshSoon(relay);
2283
+ return { cancelled: true, name };
2284
+ }
2285
+
2286
+ /** The owner renames a contact (a name or any DID of its chain; store.mjs rename) → { did, name }. */
2287
+ rename(who, name) { return this.#locked(({ store }) => store.rename(who, name)); }
2288
+
1894
2289
  contacts() {
1895
2290
  return this.#read(({ now, store, st }) => {
1896
2291
  const s = store.load().s;
1897
2292
  return {
1898
- contacts: Object.values(s.contacts).map((c) => ({ name: c.name, did: c.did, current_did: c.current_did, revoked: c.revoked, relay: c.relay, queued: st.peers[c.did]?.outbox.length ?? 0,
1899
- re_pair: c.re_pair ?? null, fingerprint: c.revoked ? null : wordsOf(c.pair_key) })),
2293
+ contacts: Object.values(s.contacts).map((c) => {
2294
+ const e = st.peers[c.did], pair = c.revoked || !c.pair_key ? null : pairId(hexToBytes(c.pair_key));
2295
+ return { name: c.name, did: c.did, current_did: c.current_did, chain: c.chain, revoked: c.revoked, relay: c.relay, queued: e?.outbox.length ?? 0,
2296
+ re_pair: c.re_pair ?? null, fingerprint: c.revoked ? null : wordsOf(c.pair_key), pair, tier: store.tierOf(c, now), tier_by: c.tier_by ?? null,
2297
+ prekeys: pair !== null && theirPrekeys(c, e?.session, pair, now), waiting: e?.waiting ?? null };
2298
+ }),
1900
2299
  invites: Object.values(s.invites).filter((p) => p.exp > now).map((p) => ({ name: p.name, exp: p.exp, relay: p.relay })),
1901
2300
  answers: Object.values(s.accepts).filter((p) => p.exp > now).map((p) => ({ name: p.name, did: p.code_did, exp: p.exp, relay: p.relay })),
2301
+ // Pairings that failed since the last inbox, which takes them as events.
2302
+ failed: st.events.filter((e) => e.type === 'pairing_failed').map(({ name, did, code, detail, at }) => ({ name, did, code, detail, at })),
1902
2303
  };
1903
2304
  });
1904
2305
  }
1905
2306
 
1906
- async send(to, content, { label = '' } = {}) {
1907
- const [r] = await this.sendAll(to, [content], { label });
2307
+ async send(to, content, { label = '', local = false } = {}) {
2308
+ const [r] = await this.sendAll(to, [content], { label, local });
1908
2309
  if (r.status === 'refused') fail(r.code, `refused (${r.detail})`);
1909
2310
  return r;
1910
2311
  }
@@ -1912,9 +2313,13 @@ export class Carrier {
1912
2313
  // Several messages to one contact in one session: one login, where `send` costs one each (the
1913
2314
  // relay allows 30 logins a minute per network). sent: the relay accepted it, and holds it for
1914
2315
  // the contact's claim on the topic; queued: it goes at the next connection.
1915
- async sendAll(to, contents, { label = '' } = {}) {
2316
+ async sendAll(to, contents, { label = '', local = false } = {}) { return this.#sendAll(to, contents, label, false, local); }
2317
+
2318
+ // spool: every content after the first waits on disk (#spool), as a file's chunks do. local: queued
2319
+ // only, for the started carrier of this identity in another process (inbox's local, for sending).
2320
+ async #sendAll(to, contents, label, spool, local = false) {
1916
2321
  if (typeof label !== 'string') fail('body', 'label must be a string');
1917
- if (label === LABEL_PREKEYS) fail('body', `the label ${JSON.stringify(LABEL_PREKEYS)} is the carrier's own`);
2322
+ if (label === LABEL_PREKEYS || label === OPERATOR_LABEL) fail('body', `the label ${JSON.stringify(label)} is the carrier's own`);
1918
2323
  if (!Array.isArray(contents) || contents.length === 0) fail('body', 'at least one message');
1919
2324
  for (const content of contents) {
1920
2325
  if (content === undefined) fail('body', 'content is required');
@@ -1925,7 +2330,7 @@ export class Carrier {
1925
2330
  // contact already, re-pairs) and goes under the key the reply brings.
1926
2331
  const answered = this.#read(({ now, store }) => [...new Set(Object.values(store.load().s.accepts)
1927
2332
  .filter((p) => p.exp > now && (p.name === to || p.code_did === to)).map((p) => p.relay))]);
1928
- if (answered.length > 0) {
2333
+ if (answered.length > 0 && !local) {
1929
2334
  try { await this.#session(answered); } catch {}
1930
2335
  this.#routes = new Map();
1931
2336
  this.#read(({ now, store }) => {
@@ -1938,11 +2343,16 @@ export class Carrier {
1938
2343
  }
1939
2344
  const { ids, c } = this.#locked(({ store, st }) => {
1940
2345
  const c = this.#resolve(store, to), outbox = this.#entry(st, c.did).outbox;
1941
- const ids = contents.map((content) => { const id = randomId(); outbox.push({ id, label, content }); return id; });
2346
+ const ids = contents.map((content, i) => {
2347
+ const id = randomId();
2348
+ if (spool && i > 0) { this.#spool(id, content); outbox.push({ id, label, spool: true }); } else outbox.push({ id, label, content });
2349
+ return id;
2350
+ });
1942
2351
  return { ids, c };
1943
2352
  });
2353
+ if (local) return ids.map((id) => ({ status: 'queued', id, to: c.did, name: c.name, detail: 'kept for the process that holds this identity\'s relay session: it sends it' }));
1944
2354
  try { await this.#session([c.relay]); } catch (e) {
1945
- throw new MsgError(e.check ?? 'connect', `${reason(e)} (${ids.length === 1 ? 'the message stays' : `the ${ids.length} messages stay`} queued for ${c.name}: they go at the next connection)`);
2355
+ throw new MsgError(e.check ?? 'connect', `${reason(e)} (${ids.length === 1 ? 'the message stays' : `the ${ids.length} messages stay`} queued for ${c.name}: they go at the next connection)`, { cause: e, http: e.http });
1946
2356
  }
1947
2357
  return ids.map((id) => {
1948
2358
  const r = this.#results.get(id);
@@ -1954,32 +2364,110 @@ export class Carrier {
1954
2364
  });
1955
2365
  }
1956
2366
 
1957
- async inbox({ wait = 0 } = {}) {
1958
- let offline = null;
1959
- // With nothing in use anywhere, this agent's own relay: an operator with no contacts logs in by
1960
- // `inbox` before uploading its licence (relay/site/pro.md step 2), and proves its work there.
1961
- const inUse = this.#relaysInUse(), relays = inUse.length > 0 ? inUse : [this.relay];
2367
+ // A file to a contact (file.mjs): its manifest and chunks in one sendAll, so one login. Read whole
2368
+ // first (at most MAX_FILE); this identity's own files (key, contacts, state, files received) are
2369
+ // refused, so a confused or misled agent cannot send its key. A refusal of any part throws as
2370
+ // send does: the contact gets no file, and what came of it there goes at its retention.
2371
+ async sendFile(to, path, { local = false } = {}) {
2372
+ if (typeof path !== 'string' || path === '') fail('file', 'a file path is required');
2373
+ let real, bytes;
1962
2374
  try {
1963
- await this.#session(relays, wait > 0 ? { max: wait * 1000, until: () => this.#read(({ st }) => st.inbox.length > 0) } : {});
1964
- } catch (e) { offline = e instanceof MsgError ? e.message : `connect: ${e.message}`; }
1965
- return this.#locked(({ st }) => {
1966
- const out = { messages: st.inbox, events: st.events, dropped: st.dropped, ...(offline && { offline }) };
1967
- st.inbox = []; st.events = []; st.dropped = {};
2375
+ real = realpathSync(path);
2376
+ const s = statSync(real);
2377
+ if (!s.isFile()) fail('file', `${path} is not a regular file`);
2378
+ if (s.size > MAX_FILE) fail('file_too_large', `${path} is ${s.size} bytes, at most ${MAX_FILE} (8 MiB) a file`);
2379
+ } catch (e) {
2380
+ if (e instanceof MsgError) throw e;
2381
+ fail('file', `cannot read ${path}: ${e.code === 'ENOENT' ? 'no such file' : e.code ?? e.message}`, { cause: e });
2382
+ }
2383
+ // Beside the identity: its own files (x.*) and any profile's (*.local.*, sigelo-agent's pattern).
2384
+ const own = resolve(this.statePath.replace(/(\.carrier)?\.json$/, '')), files = (() => { try { return realpathSync(this.filesDir); } catch { return this.filesDir; } })();
2385
+ let ownDir;
2386
+ try { ownDir = realpathSync(dirname(own)); } catch { ownDir = dirname(own); }
2387
+ const leaf = basename(real);
2388
+ if (real.startsWith(files + sep) || (dirname(real) === ownDir && (leaf.startsWith(`${basename(own)}.`) || leaf.includes('.local.')))) {
2389
+ fail('file', `${path} is one of this agent's identity files (key, contacts, state, files received): not sent`);
2390
+ }
2391
+ try { bytes = readFileSync(real); } catch (e) { fail('file', `cannot read ${path}: ${e.code ?? e.message}`, { cause: e }); }
2392
+ if (bytes.length > MAX_FILE) fail('file_too_large', `${path} is ${bytes.length} bytes, at most ${MAX_FILE} (8 MiB) a file`);
2393
+ const { manifest, chunks } = splitFile(bytes, basename(real));
2394
+ const results = await this.#sendAll(to, [manifest, ...chunks], FILE_LABEL, true, local);
2395
+ const refused = results.find((x) => x.status === 'refused'), queued = results.find((x) => x.status === 'queued');
2396
+ if (refused) fail(refused.code, `refused (${refused.detail}): ${manifest.name} did not go whole; send it again once that is settled`);
2397
+ const { id, name, size, sha256: sum, chunks: n } = manifest;
2398
+ return { status: queued ? 'queued' : 'sent', to: results[0].to, name: results[0].name, file: { id, name, size, sha256: sum, chunks: n },
2399
+ ...(queued && { detail: queued.detail }) };
2400
+ }
2401
+
2402
+ // tiers: only messages from contacts of these tiers are taken (and waited for); the rest stay for a
2403
+ // later inbox. Events are all taken. local: no session: what the state file holds, waited for by
2404
+ // reading it again, for a reader beside a started carrier of the same identity (a watcher), which
2405
+ // a session here would disconnect.
2406
+ async inbox({ wait = 0, tiers, local = false, paired = false } = {}) {
2407
+ const want = tiers === undefined ? null : new Set(tiers);
2408
+ if (want && ![...want].every((t) => TIERS.includes(t))) fail('tier', `tiers: some of ${TIERS.join(', ')}`);
2409
+ const picks = (store, now) => { const t = want && store.tiers(now); return (m) => !want || want.has(t.get(m.from) ?? 'friend'); };
2410
+ const ready = () => this.#read(({ now, store, st }) => st.inbox.some(picks(store, now)) || st.events.some((e) => e.type === 'pairing_failed' || (paired && e.type === 'paired')));
2411
+ let offline = null;
2412
+ if (local) {
2413
+ for (const end = Date.now() + wait * 1000; Date.now() < end && !ready();) await sleep(250);
2414
+ } else {
2415
+ // With nothing in use anywhere, this agent's own relay: an operator with no contacts logs in by
2416
+ // `inbox` before uploading its licence (relay/site/pro.md step 2), and proves its work there.
2417
+ const inUse = this.#relaysInUse(), relays = inUse.length > 0 ? inUse : [this.relay];
2418
+ try {
2419
+ await this.#session(relays, wait > 0 ? { max: wait * 1000, until: ready } : {});
2420
+ } catch (e) { this.lastError = e; offline = e instanceof MsgError ? e.message : `connect: ${e.message}`; }
2421
+ }
2422
+ return this.#locked(({ now, store, st }) => {
2423
+ this.#sweepFiles(st, now);
2424
+ const pick = picks(store, now), messages = st.inbox.filter(pick);
2425
+ const out = { messages, events: st.events, dropped: st.dropped, ...(offline && { offline }) };
2426
+ st.inbox = st.inbox.filter((m) => !pick(m)); st.events = []; st.dropped = {};
2427
+ return out;
2428
+ });
2429
+ }
2430
+
2431
+ peek() {
2432
+ return this.#read(({ now, store, st }) => { const t = store.tiers(now); return st.inbox.map((m) => ({ ...m, tier: t.get(m.from) ?? 'friend' })); });
2433
+ }
2434
+
2435
+ take(pick) {
2436
+ if (typeof pick !== 'function') throw new TypeError('take: a function (message, tier) → boolean');
2437
+ return this.#locked(({ now, store, st }) => {
2438
+ const t = store.tiers(now), out = [], keep = [];
2439
+ for (const m of st.inbox) (pick(m, t.get(m.from) ?? 'friend') ? out : keep).push(m);
2440
+ st.inbox = keep;
1968
2441
  return out;
1969
2442
  });
1970
2443
  }
1971
2444
 
2445
+ setTier(who, tier) { return this.#locked(({ now, store }) => store.setTier(who, tier, now)); }
2446
+
2447
+ // A contact's full bundle, from wherever it came (the UI reads its local agents' files): verified
2448
+ // here; → { did, tier }, or null when it is no contact's.
2449
+ observe(bundle) {
2450
+ return this.#locked(({ now, store }) => {
2451
+ let r;
2452
+ try { r = verify(bundle, now); } catch (e) { fail('bundle', `REJECT: ${e.message}`); }
2453
+ const c = store.lookup(r.chain[0]);
2454
+ if (!c || c.revoked || c.did !== r.chain[0]) return null;
2455
+ return { did: c.did, tier: store.observe(c.did, r, now) };
2456
+ });
2457
+ }
2458
+
1972
2459
  async forget(did) {
1973
2460
  const c = this.#locked(({ store, st }) => {
1974
2461
  const c = store.revoke(did);
1975
2462
  delete st.peers[c.did];
1976
2463
  st.pending = st.pending.filter((p) => p.peer !== c.did);
2464
+ this.#sweepSpool(st);
1977
2465
  return c;
1978
2466
  });
1979
2467
  this.#routes = new Map();
1980
2468
  // Revoked here whatever the relay says; offline: its mailboxes are given up at a later round.
1981
2469
  let offline = null;
1982
- try { await this.#session([c.relay]); } catch (e) { offline = e instanceof MsgError ? e.message : `connect: ${e.message}`; }
2470
+ try { await this.#session([c.relay]); } catch (e) { this.lastError = e; offline = e instanceof MsgError ? e.message : `connect: ${e.message}`; }
1983
2471
  const released = this.#read(({ st }) => !Object.values(st.relays[c.relay]?.claims ?? {}).some((x) => x.peer === c.did));
1984
2472
  return { name: c.name, did: c.did, revoked: true, released, ...(offline && { offline }) };
1985
2473
  }