sigelo-contact 0.1.7 → 0.1.9

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
@@ -3,16 +3,19 @@
3
3
  // invite answers and replies and sigelo-msg/0 envelopes between contacts through a relay. The relay
4
4
  // sees random topics and ciphertext; everything here that decides who someone is runs offline.
5
5
  //
6
- // const c = new Carrier({ identity, store, state, relay, endpoints, retentionDays, clock, onEvent, keep })
6
+ // const c = new Carrier({ identity, store, state, relay, endpoints, retentionDays, clock, onEvent, keep, transport })
7
7
  // await c.invite({ name, ttl, short }) → { code, did, relay, exp, short?, short_exp? } the answer topic is claimed first;
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
+ // await c.redeemGift(code) → { exp, months }: a gift code (PRO-K7F3-Q9ZP) redeemed at this agent's relay;
11
+ // this identity is the operator whose pool is Pro until exp (relay/gifts.mjs)
10
12
  // await c.accept(code, { name, wait }) → { status: 'connected' | 'waiting' | 'pending', … } a long code or a short one
11
13
  // (refused after a short code was fetched: .long, keepLong)
12
14
  // await c.cancelInvite(code) → { cancelled, name }: an unanswered invite of this agent's withdrawn
13
15
  // c.rename(who, name) the owner's name for a contact (store.mjs rename) → { did, name }
14
16
  // 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
17
+ // pair id, chain, ours (an operator attestation of mine marks it), tier
18
+ // (store.mjs: own, friend, quiet) and tier_by, prekeys: its
16
19
  // bundle is here (false: messages wait for it), waiting: why they wait, or null;
17
20
  // failed: pairing_failed events (code_expired: an answer that outlived its code) until inbox
18
21
  // await c.send(to, content, { label, local }) → { status: 'sent' | 'queued', … }, or throws the relay's code
@@ -28,7 +31,14 @@
28
31
  // paired: the wait also ends at a pairing (enrol.mjs)
29
32
  // c.peek(), c.take(pick) the messages kept for inbox(), each with its sender's tier: read, or those
30
33
  // 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 }
34
+ // c.history({ since }) → { messages }: what inbox() and take() gave out, again, from the local log
35
+ // (`log`: x.inbox.log, pathsFor), received at or after since (unix seconds);
36
+ // no session, nothing taken
37
+ // c.setTier(who, tier) the owner's tier for a contact (store.mjs setTier) → { did, name, tier, ours }
38
+ // c.presetTier(did, tier) the same for an original DID not yet a contact, filed when it pairs
39
+ // c.answeredBy(nonce) the original DID that paired through this agent's code `nonce`, or null
40
+ // (kept in the state until a day after the code's exp; the inviter's
41
+ // paired event names the code as `invite`: its nonce, never its secret)
32
42
  // c.observe(bundle) a contact's full bundle seen: its operator attestations (store.mjs observe)
33
43
  // a file received whole is one item {type: "file", from, contact, name, size,
34
44
  // sha256, path, …}, saved under `files` (pathsFor), never opened
@@ -37,8 +47,9 @@
37
47
  // c.clockOffset(), await c.checkClock() → { relay, offset, checked } | null: the relay's clock less this one's, seconds
38
48
  // await c.start(), c.sync(), c.stop() stay connected, reconnecting with backoff; events reach onEvent
39
49
  //
40
- // identity() → { secret, bundle }: the agent's current secret key and SPEC §8 bundle, read again at
41
- // every operation, so a rotation made by another process is seen at once. store: the contact store
50
+ // identity() → { sign, bundle }: the agent's signer for its current key (sign(body) → the SPEC §3
51
+ // signature; sigelo-agent-keys.ts) and its SPEC §8 bundle, read again at every operation, so a
52
+ // rotation made by another process is seen at once. { secret, bundle }, the seed itself, still works. store: the contact store
42
53
  // (store.mjs); state: this file's own JSON (sessions, outbox, inbox), both 0600 and written under one
43
54
  // lock file, `<state>.lock`. pathsFor(identityFile) names both beside the identity file. onEvent(e):
44
55
  // each event as it happens, messages included, and `pow` / `pow_done` around a proof-of-work search
@@ -46,11 +57,23 @@
46
57
  // inbox(), in plaintext, until taken (INBOX_MAX at most: the oldest go, counted as inbox_full); by
47
58
  // default only without onEvent, so a message onEvent took is not left at rest after the keys that
48
59
  // opened it are gone (contacts.md §3: keys stolen today must not open yesterday's messages).
60
+ // log: every message and file item inbox() or take() gives out is first appended to this file
61
+ // (JSON lines, 0600, the newest LOG_MAX or LOG_BYTES; enrolment's key-carrying labels never), so a
62
+ // reader that dropped its output can read it again (history); by default x.inbox.log beside the
63
+ // state; false: none. Plaintext at rest, as the state's inbox is (THREAT-MODEL §3.9).
49
64
  // One connected carrier per identity: every process logs in with the identity's one MQTT client
50
65
  // id, so a second login takes the session from a started carrier (the files stay sound under the
51
66
  // lock; the started one reconnects with backoff). Beside one, use inbox and send with local: the
52
67
  // state file only (sigelo-agent's one-owner rule, adapters/moadim/WATCH.md).
53
68
  //
69
+ // Transport (transport, or SIGELO_RELAY_TRANSPORT): "auto" (the default), 8883 for PROBE_MS, then
70
+ // 443 for the rest of the process, so a network that lets only HTTPS out needs no setting; "mqtts",
71
+ // MQTT over TLS on 8883 only; "wss", MQTT over WebSocket on 443 only (wss://host/mqtt, or
72
+ // relay.json's endpoints.mqtt_ws on the same host), which skips the probe. Both are TLS. HTTPS_PROXY (or https_proxy), an http:// proxy, carries the HTTPS calls
73
+ // and the WebSocket dial by HTTP CONNECT, unless NO_PROXY (or no_proxy) names the host (proxyFor);
74
+ // MQTT on 8883 never goes through it. Certificates are checked as without a proxy, so
75
+ // NODE_EXTRA_CA_CERTS works the same. The event { type: "transport" } says when auto fell back.
76
+ //
54
77
  // What this adds to the wire, beside the envelope (envelope.mjs) and the invite (invite.mjs); the
55
78
  // bytes are pinned in fixtures/carrier-v0.json (gen-carrier.mjs --check):
56
79
  // - Frames for the invite answer (kind 1), the invite reply (kind 2), the contact notice (kind 4)
@@ -173,7 +196,10 @@
173
196
  // round, so topics are asked in the order they matter (#want). A refused topic is asked again
174
197
  // at the next hourly round (ASK_AGAIN).
175
198
  import { createHash } from 'node:crypto';
176
- import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
199
+ import { request as httpRequest } from 'node:http';
200
+ import { Agent as HttpsAgent, request as httpsRequest } from 'node:https';
201
+ import { connect as tlsConnect } from 'node:tls';
202
+ import { chmodSync, closeSync, existsSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
177
203
  import { basename, dirname, join, resolve, sep } from 'node:path';
178
204
  import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
179
205
  import { hkdf } from '@noble/hashes/hkdf.js';
@@ -181,13 +207,13 @@ import { hmac } from '@noble/hashes/hmac.js';
181
207
  import { sha256 } from '@noble/hashes/sha2.js';
182
208
  import { concatBytes, hexToBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils.js';
183
209
  import { connect } from 'mqtt';
184
- import { canonicalize, commitmentOf, did as didOf, parseBytes, sign, verify, verifySig } from 'sigelo';
210
+ import { canonicalize, commitmentOf, did as didOf, parseBytes, verify, verifySig } from 'sigelo';
185
211
  import { KIND, acceptPrekeys, expire, header, open, pad, prekeysMissing, restartEpoch, send, session, unpad } from './envelope.mjs';
186
212
  import { answerId, buildAnswer, buildReply, checkAnswer, checkReply, inviteKeys, keyOf, makeInvite, parseInvite } from './invite.mjs';
187
- import { MsgError, checkNow, fail, hex, isoWeek, pairId, topic } from './kdf.mjs';
213
+ import { MsgError, checkNow, fail, hex, isoWeek, pairId, signAs, topic } from './kdf.mjs';
188
214
  import { Prekeys, exact, kemDecapsulate, kemEncapsulate, kemKey } from './prekeys.mjs';
189
215
  import { Contacts, OPERATOR_CTX, TIERS } from './store.mjs';
190
- import { SHORT_TTL, codeHash, codeKind, fingerprint, formatShort, makeShort, normaliseShort } from './short.mjs';
216
+ import { SHORT_TTL, codeHash, codeKind, fingerprint, formatShort, giftHash, makeShort, normaliseShort } from './short.mjs';
191
217
  import { FILE_LABEL, MAX_FILE, assemble, checkChunk, checkManifest, chunkHead, isManifest, safeName, splitFile } from './file.mjs';
192
218
 
193
219
  export const V = 'sigelo-carrier/0';
@@ -228,6 +254,16 @@ const POISON_TRIES = 3;
228
254
  // Events kept for the next inbox(): pairings, rotations, failed pairings. The oldest go first.
229
255
  // Messages kept for it (keep), likewise.
230
256
  const EVENTS_MAX = 1000, INBOX_MAX = 1000;
257
+ // The inbox log (the constructor's log): at most so many items and bytes, the oldest go first (the
258
+ // newest is kept whatever its size). Labels it never holds: enrolment's, one of which carries a key.
259
+ export const LOG_MAX = 500, LOG_BYTES = 4 * 1024 * 1024;
260
+ const UNLOGGED = /^sigelo-(identity|enrol)\//;
261
+ // Received files of one name and hash prefix kept side by side, at most (#onFile).
262
+ const FILE_COPIES = 64;
263
+ // A contact's folder of received files: its name as safeName keeps it, and 16 hex digits of the
264
+ // SHA-256 of its original DID, so two contacts whose names reduce alike never share one, and a
265
+ // rename keeps the DID part.
266
+ export const contactDir = (c) => `${safeName(c.name || 'contact')}-${hex(sha256(utf8ToBytes(c.did))).slice(0, 16)}`;
231
267
  // Files arriving at once from one contact (#onFile): each holds up to 8 MiB of parts here.
232
268
  const FILES_OPEN = 8;
233
269
  // Half the relay's publish brake (20 a second, 200 at once): past it the relay refuses publishes
@@ -236,6 +272,13 @@ const FILES_OPEN = 8;
236
272
  const RATE = { perSecond: 10, burst: 100 };
237
273
  // Milliseconds. QUIET: no delivery for this long after connecting = the relay's queue is drained.
238
274
  const QUIET = 400, DRAIN = 4000, ACK_MS = 15000, CONNECT_MS = 15000, HTTP_MS = 15000, HTTP_MAX = 65536;
275
+ // transport "auto": MQTT over TLS gets this long to answer the CONNECT before the dial goes to MQTT
276
+ // over WebSocket on 443. A network that lets only HTTPS out drops 8883 rather than refusing it.
277
+ export const PROBE_MS = 5000;
278
+ export const TRANSPORTS = ['mqtts', 'wss', 'auto'];
279
+ // The WebSocket endpoint, as relay.json names it (relay/server.mjs WS_PATH) and as a relay with
280
+ // none is reached: on its HTTPS host.
281
+ export const WS_PATH = '/mqtt';
239
282
  // MQTT.js buffers a packet whole before handing it over, up to MQTT's 256 MB (its own size check
240
283
  // applies only to protocol version 5), and a code can name any host: a packet longer than the
241
284
  // largest a relay forwards (relay/server.mjs MAX_FRAME: a 1 MB message and its header) cuts the
@@ -311,32 +354,96 @@ const theirPrekeys = (c, d, pair, now) => {
311
354
  const wordsOf = (pairKey) => (typeof pairKey === 'string' ? fingerprint(pairId(hexToBytes(pairKey))) : null);
312
355
  // The refusals of POST /park this client names (relay/park.mjs, and the login's: auth.mjs).
313
356
  const PARK_CHECKS = new Set(['park', 'park_taken', 'park_full', 'pow', ...LOGIN_CHECKS]);
357
+ // The refusals of POST /gift this client names (relay/gifts.mjs, allowance.mjs, operator.mjs, and the login's).
358
+ const GIFT_CHECKS = new Set(['gift', 'gift_member', 'gift_term', 'pow', ...LOGIN_CHECKS]);
314
359
 
315
360
  // ---------------------------------------------------------------- configuration
316
361
 
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/. */
362
+ /** The contact store, this carrier's state, the files received and the inbox log, beside the identity file: x.json → x.contacts.json, x.carrier.json, x.files/, x.inbox.log. */
318
363
  export function pathsFor(identityFile) {
319
364
  const base = identityFile.replace(/\.json$/, '');
320
- return { store: `${base}.contacts.json`, state: `${base}.carrier.json`, files: `${base}.files` };
365
+ return { store: `${base}.contacts.json`, state: `${base}.carrier.json`, files: `${base}.files`, log: `${base}.inbox.log` };
321
366
  }
322
367
 
323
368
  /**
324
- * Where relay "host[:port]" is reached: MQTT over TLS on port (8883), HTTPS on 443. endpoints:
325
- * { [relay]: { mqtt, http } } overrides, e.g. a relay on loopback; plain mqtt:// and http:// only
326
- * to a loopback address, so nothing leaves the machine in clear.
369
+ * Where relay "host[:port]" is reached: MQTT over TLS on port (8883), HTTPS on 443, MQTT over
370
+ * WebSocket at wss://host/mqtt. endpoints: { [relay]: { mqtt, http, ws? } } overrides, e.g. a relay
371
+ * on loopback: mqtt may be mqtts:// or wss://, ws wss:// (by default the http origin at /mqtt);
372
+ * plain mqtt://, ws:// and http:// only to a loopback address, so nothing leaves the machine in clear.
327
373
  */
328
374
  export function endpointOf(relay, endpoints = {}) {
329
375
  const o = endpoints && Object.hasOwn(endpoints, relay) ? endpoints[relay] : null;
330
376
  if (!o) {
331
377
  const [host, port] = relay.split(':');
332
- return { mqtt: `mqtts://${host}:${port ?? MQTT_PORT}`, http: `https://${host}` };
378
+ return { mqtt: `mqtts://${host}:${port ?? MQTT_PORT}`, http: `https://${host}`, ws: `wss://${host}${WS_PATH}` };
333
379
  }
334
- for (const [k, secure, plain] of [['mqtt', 'mqtts:', 'mqtt:'], ['http', 'https:', 'http:']]) {
380
+ const check = (k, ok) => {
335
381
  let u;
336
382
  try { u = new URL(o[k]); } catch { fail('relay', `${relay}: endpoints.${k} is not a URL`); }
337
- if (u.protocol !== secure && !(u.protocol === plain && LOOPBACK.has(u.hostname))) fail('relay', `${relay}: endpoints.${k} must be ${secure}// (${plain}// only to a loopback address)`);
383
+ const [secure, plain] = ok.find(([sec, pl]) => u.protocol === sec || u.protocol === pl) ?? ok[0];
384
+ if (u.protocol !== secure && !(u.protocol === plain && LOOPBACK.has(u.hostname))) fail('relay', `${relay}: endpoints.${k} must be ${ok.map(([x]) => `${x}//`).join(' or ')} (${ok.map(([, x]) => `${x}//`).join(' or ')} only to a loopback address)`);
385
+ };
386
+ check('mqtt', [['mqtts:', 'mqtt:'], ['wss:', 'ws:']]);
387
+ check('http', [['https:', 'http:']]);
388
+ const http = o.http.replace(/\/+$/, '');
389
+ if (o.ws !== undefined) check('ws', [['wss:', 'ws:']]);
390
+ return { mqtt: o.mqtt, http, ws: o.ws ?? http.replace(/^http/, 'ws') + WS_PATH };
391
+ }
392
+
393
+ /**
394
+ * The HTTP CONNECT proxy for url (https: or wss:), from HTTPS_PROXY or https_proxy, unless NO_PROXY
395
+ * (or no_proxy) names its host: "*", a name (its subdomains too; a leading "." or "*." the same), an
396
+ * address, each with an optional :port. → a URL, or null. Only an http:// proxy; TLS to the relay
397
+ * runs inside the tunnel, verified as without one (NODE_EXTRA_CA_CERTS included).
398
+ */
399
+ export function proxyFor(url, env = process.env) {
400
+ const u = new URL(url);
401
+ const raw = env.HTTPS_PROXY || env.https_proxy;
402
+ if ((u.protocol !== 'https:' && u.protocol !== 'wss:') || !raw) return null;
403
+ const host = u.hostname.replace(/^\[|\]$/g, '').toLowerCase(), port = u.port || '443';
404
+ for (const e of String(env.NO_PROXY || env.no_proxy || '').toLowerCase().split(/[\s,]+/).filter(Boolean)) {
405
+ if (e === '*') return null;
406
+ const m = /^\[([^\]]+)\](?::(\d+))?$/.exec(e) ?? (e.split(':').length === 2 ? /^([^:]+):(\d+)$/.exec(e) : null);
407
+ const name = (m ? m[1] : e).replace(/^\*?\./, '.'), p = m?.[2];
408
+ if (p && p !== port) continue;
409
+ if (name.startsWith('.') ? host.endsWith(name) || host === name.slice(1) : host === name || host.endsWith(`.${name}`)) return null;
410
+ }
411
+ let p;
412
+ try { p = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `http://${raw}`); } catch { fail('connect', 'HTTPS_PROXY is not a URL: want http://host:port'); }
413
+ if (p.protocol !== 'http:') fail('connect', `HTTPS_PROXY: ${p.protocol}// proxies are not supported; want http://host:port (HTTP CONNECT)`);
414
+ return p;
415
+ }
416
+
417
+ // An https.Agent whose every connection is a tunnel through proxy (HTTP CONNECT host:port), with
418
+ // TLS to the relay inside it: for the HTTP calls (http) and for MQTT over WebSocket (ws's agent).
419
+ class Tunnel extends HttpsAgent {
420
+ constructor(proxy) { super({ keepAlive: false }); this.proxy = proxy; }
421
+ createConnection(options, cb) {
422
+ const p = this.proxy, host = options.host.includes(':') ? `[${options.host}]` : options.host, target = `${host}:${options.port || 443}`;
423
+ const auth = p.username ? { 'proxy-authorization': `Basic ${Buffer.from(`${decodeURIComponent(p.username)}:${decodeURIComponent(p.password)}`).toString('base64')}` } : {};
424
+ const req = httpRequest({ host: p.hostname.replace(/^\[|\]$/g, ''), port: p.port || 80, method: 'CONNECT', path: target, agent: false, headers: { host: target, ...auth } });
425
+ req.setTimeout(HTTP_MS, () => req.destroy(new Error(`no answer within ${HTTP_MS / 1000} s`)));
426
+ req.once('connect', (res, sock) => {
427
+ req.setTimeout(0);
428
+ if (res.statusCode !== 200) { sock.destroy(); return cb(new Error(`the proxy ${p.host} answered ${res.statusCode} to CONNECT ${target}`)); }
429
+ cb(null, tlsConnect({ ...options, socket: sock, servername: options.servername || options.host }));
430
+ });
431
+ req.once('error', (e) => cb(new Error(`the proxy ${p.host}: ${e.code ?? e.message}`)));
432
+ req.end();
338
433
  }
339
- return { mqtt: o.mqtt, http: o.http.replace(/\/+$/, '') };
434
+ }
435
+ const tunnelFor = (url) => { const p = proxyFor(url); return p ? new Tunnel(p) : null; };
436
+
437
+ // An HTTPS request through a tunnel, answered in the shape of fetch's Response as http() reads it.
438
+ function viaTunnel(url, init, agent) {
439
+ return new Promise((resolve, reject) => {
440
+ const body = init.body === undefined ? undefined : Buffer.from(init.body);
441
+ const req = httpsRequest(url, { method: init.method ?? 'GET', agent, signal: init.signal, headers: body ? { 'content-type': 'text/plain;charset=UTF-8', 'content-length': body.length } : {} }, (res) => {
442
+ resolve({ status: res.statusCode, type: 'basic', body: res, headers: { get: (k) => { const v = res.headers[k.toLowerCase()]; return v === undefined ? null : String(v); } } });
443
+ });
444
+ req.once('error', (e) => reject(Object.assign(new Error(e.message), { cause: e })));
445
+ req.end(body);
446
+ });
340
447
  }
341
448
 
342
449
  /**
@@ -362,7 +469,7 @@ export function retentionOf(info) {
362
469
  return retentionOk(n) ? n : null;
363
470
  }
364
471
 
365
- /** SIGELO_RELAY (the relay new invites name), SIGELO_RELAY_ENDPOINTS (JSON, as endpointOf), SIGELO_RELAY_RETENTION_DAYS. */
472
+ /** SIGELO_RELAY (the relay new invites name), SIGELO_RELAY_ENDPOINTS (JSON, as endpointOf), SIGELO_RELAY_RETENTION_DAYS, SIGELO_RELAY_TRANSPORT. */
366
473
  export function optionsFromEnv(env = process.env) {
367
474
  const o = {};
368
475
  if (env.SIGELO_RELAY) o.relay = env.SIGELO_RELAY;
@@ -374,6 +481,10 @@ export function optionsFromEnv(env = process.env) {
374
481
  if (!retentionOk(n)) fail('relay', `SIGELO_RELAY_RETENTION_DAYS: whole days, 1 to ${RETENTION_MAX_DAYS} (the reader's tier)`);
375
482
  o.retentionDays = n;
376
483
  }
484
+ if (env.SIGELO_RELAY_TRANSPORT) {
485
+ if (!TRANSPORTS.includes(env.SIGELO_RELAY_TRANSPORT)) fail('relay', `SIGELO_RELAY_TRANSPORT: ${TRANSPORTS.join(', ')} (MQTT over TLS on 8883, over WebSocket on 443, or the first then the second)`);
486
+ o.transport = env.SIGELO_RELAY_TRANSPORT;
487
+ }
377
488
  return o;
378
489
  }
379
490
 
@@ -396,10 +507,10 @@ function withLock(path, fn) {
396
507
  }
397
508
 
398
509
  function loadState(path, self) {
399
- const s = existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : { v: V, self, relays: {}, peers: {}, pending: [], inbox: [], events: [], dropped: {}, failing: {} };
510
+ const s = existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : { v: V, self, relays: {}, peers: {}, pending: [], inbox: [], events: [], dropped: {}, failing: {}, answered: {} };
400
511
  if (s.v !== V || s.self !== self) fail('state', `${path} is not the ${V} state of ${self}`);
401
512
  // Written by an earlier version of this file, which kept neither.
402
- s.events ??= []; s.failing ??= {};
513
+ s.events ??= []; s.failing ??= {}; s.answered ??= {};
403
514
  return s;
404
515
  }
405
516
 
@@ -580,7 +691,10 @@ async function http(url, init = {}) {
580
691
  let res;
581
692
  const at = where(url), http = { url, method: init.method ?? 'GET' };
582
693
  const t0 = Date.now();
583
- try { res = await fetch(url, { ...init, redirect: 'manual', signal: AbortSignal.timeout(HTTP_MS) }); } catch (e) {
694
+ try {
695
+ const agent = tunnelFor(url);
696
+ res = agent ? await viaTunnel(url, { ...init, signal: AbortSignal.timeout(HTTP_MS) }, agent) : await fetch(url, { ...init, redirect: 'manual', signal: AbortSignal.timeout(HTTP_MS) });
697
+ } catch (e) {
584
698
  const why = e.name === 'TimeoutError' ? `no answer within ${HTTP_MS / 1000} s` : e.cause?.code ?? e.cause?.message ?? e.message;
585
699
  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
700
  }
@@ -588,7 +702,7 @@ async function http(url, init = {}) {
588
702
  // The relay's clock (Date, whole seconds) and the round trip to it, for clockOffset.
589
703
  const rtt = Date.now() - t0, date = Date.parse(res.headers.get('date') ?? '');
590
704
  if ((res.status >= 300 && res.status < 400) || res.type === 'opaqueredirect') {
591
- try { await res.body?.cancel(); } catch {}
705
+ try { await (res.body?.cancel?.() ?? res.body?.destroy?.()); } catch {}
592
706
  fail('connect', `${at}: answered ${res.status}, a redirect, which this client does not follow`, { http });
593
707
  }
594
708
  if (Number(res.headers.get('content-length') ?? 0) > HTTP_MAX) fail('connect', `${at}: answer over ${HTTP_MAX} bytes`, { http });
@@ -647,6 +761,12 @@ export function keepLong(e, long) {
647
761
  return k;
648
762
  }
649
763
 
764
+ // Whose quota a quota_storage refusal is (relay/allowance.mjs `side`), in this client's words: a
765
+ // contact whose own queue is full, or whose operator's Pro lapsed, must not read as a broken relay.
766
+ const QUOTA_SIDES = new Set(['reader', 'sender', 'relay']);
767
+ const quotaWhy = (r, name) => (r.code !== 'quota_storage' ? null
768
+ : r.side === 'reader' ? `${name}'s side is over its storage quota (its queue is full, or its operator's Pro lapsed): nothing is wrong with your relay or your allowance; send again once ${name}'s agent has collected its messages (${relaySays(r.detail)})`
769
+ : r.side === 'sender' ? `your network has used its share of this relay's free storage: send again once messages are collected or expire (${relaySays(r.detail)})` : null);
650
770
  // Text a relay writes reaches the operator, and perhaps a model, inside this client's messages:
651
771
  // quoted and cut short, so it reads as data.
652
772
  const relaySays = (s) => `the relay says ${JSON.stringify(String(s ?? '').slice(0, 200))}`;
@@ -720,10 +840,13 @@ export function limitPackets(stream, max, cut) {
720
840
  });
721
841
  }
722
842
 
723
- function mqttConnect(url, creds, link, onPacket) {
843
+ // url: mqtts://, or wss:// (MQTT over WebSocket: through the HTTPS proxy when one applies, proxyFor;
844
+ // a frame over the largest packet, its fixed header included, refused by ws before it is held).
845
+ function mqttConnect(url, creds, link, onPacket, timeout = CONNECT_MS) {
724
846
  return new Promise((resolve, reject) => {
847
+ const agent = /^wss?:/.test(url) ? tunnelFor(url) : null;
725
848
  const client = connect(url, { protocolVersion: 4, clean: false, clientId: creds.clientId, username: creds.username, password: Buffer.from(creds.password, 'utf8'),
726
- reconnectPeriod: 0, connectTimeout: CONNECT_MS, keepalive: 60, resubscribe: false });
849
+ reconnectPeriod: 0, connectTimeout: timeout, keepalive: 60, resubscribe: false, wsOptions: { maxPayload: MAX_PACKET + 5, perMessageDeflate: false, ...(agent && { agent }) } });
727
850
  link.client = client;
728
851
  // connect() has built the socket and nothing has arrived yet. The cut is permanent at a relay
729
852
  // other than this agent's own (#retry, accept): it would send the same packet again.
@@ -743,6 +866,25 @@ function mqttConnect(url, creds, link, onPacket) {
743
866
  });
744
867
  }
745
868
 
869
+ // transport "auto": the WebSocket endpoint each MQTT endpoint fell back to, for the process lifetime,
870
+ // so a reconnection does not wait on 8883 first.
871
+ const FELL_BACK = new Map();
872
+ // The WebSocket endpoint of ep: relay.json's endpoints.mqtt_ws when it names the same host as ep.http
873
+ // over wss:// (ws:// only to loopback), else ep.ws. A relay that could name any host would send the
874
+ // login to it. Asked once per process and relay.
875
+ const WS_INFO = new Map();
876
+ async function wsEndpoint(ep) {
877
+ if (!WS_INFO.has(ep.http)) {
878
+ let url = ep.ws;
879
+ try {
880
+ const r = await http(`${ep.http}/relay.json`), w = new URL(r.body?.endpoints?.mqtt_ws), h = new URL(ep.http);
881
+ if (r.status === 200 && w.hostname === h.hostname && (w.protocol === 'wss:' || (w.protocol === 'ws:' && LOOPBACK.has(w.hostname)))) url = w.href;
882
+ } catch {}
883
+ WS_INFO.set(ep.http, url);
884
+ }
885
+ return WS_INFO.get(ep.http);
886
+ }
887
+
746
888
  class Link {
747
889
  constructor(relay, own) {
748
890
  this.relay = relay; this.own = own; this.client = null; this.subscribed = new Set(); this.refused = new Map(); // topic → when refused
@@ -775,8 +917,10 @@ export class Carrier {
775
917
  #mineMemo = null; #clocks = new Map();
776
918
 
777
919
  constructor({ identity, store, state, relay = DEFAULT_RELAY, endpoints = {}, retentionDays, clock = () => Math.floor(Date.now() / 1000),
778
- onEvent, keep, backoff = BACKOFF, tick = TICK, files }) {
779
- if (typeof identity !== 'function') throw new TypeError('identity: a function returning { secret, bundle }');
920
+ onEvent, keep, backoff = BACKOFF, tick = TICK, files, log, transport = 'auto' }) {
921
+ if (!TRANSPORTS.includes(transport)) throw new TypeError(`transport: ${TRANSPORTS.join(', ')}`);
922
+ this.transport = transport;
923
+ if (typeof identity !== 'function') throw new TypeError('identity: a function returning { sign, bundle }');
780
924
  if (typeof store !== 'string' || typeof state !== 'string') throw new TypeError('store, state: file paths (pathsFor(identityFile))');
781
925
  if (retentionDays !== undefined && !retentionOk(retentionDays)) throw new TypeError(`retentionDays: 1 to ${RETENTION_MAX_DAYS}`);
782
926
  // Not given: relay.json's at the first login to this agent's own relay may set it (#relayInfo).
@@ -789,13 +933,35 @@ export class Carrier {
789
933
  // Files received (#onFile): files, else beside the state as pathsFor names it (x.carrier.json → x.files).
790
934
  if (files !== undefined && typeof files !== 'string') throw new TypeError('files: a directory path (pathsFor(identityFile))');
791
935
  this.filesDir = resolve(files ?? state.replace(/(\.carrier)?\.json$/, '') + '.files');
936
+ // The inbox log: log, else beside the state as pathsFor names it (x.carrier.json → x.inbox.log); false: none.
937
+ if (log !== undefined && log !== false && typeof log !== 'string') throw new TypeError('log: a file path (pathsFor(identityFile)) or false');
938
+ this.logPath = log === false ? null : resolve(log ?? state.replace(/(\.carrier)?\.json$/, '') + '.inbox.log');
939
+ }
940
+
941
+ // Items given out (inbox, take), appended to the log before they are: a reader that loses its
942
+ // output reads them again (history). Under the lock, before the state drops them, so a failed
943
+ // write leaves them in the state; an item already logged (a crash before the state was saved) is
944
+ // not logged twice. Written whole to a fresh 0600 name, then renamed, as the state is.
945
+ #logOut(items) {
946
+ const path = this.logPath, add = items.filter((m) => !(typeof m?.label === 'string' && UNLOGGED.test(m.label)));
947
+ if (path === null || add.length === 0) return;
948
+ let lines = [];
949
+ try { lines = readFileSync(path, 'utf8').split('\n').filter((l) => l !== ''); } catch (e) { if (e.code !== 'ENOENT') throw e; }
950
+ const had = new Set(lines);
951
+ for (const m of add) { const l = JSON.stringify(m); if (!had.has(l)) { had.add(l); lines.push(l); } }
952
+ let bytes = lines.reduce((n, l) => n + Buffer.byteLength(l) + 1, 0), cut = 0;
953
+ while (lines.length - cut > 1 && (lines.length - cut > LOG_MAX || bytes > LOG_BYTES)) bytes -= Buffer.byteLength(lines[cut++]) + 1;
954
+ const tmp = join(dirname(path), `.${basename(path)}.${randomId()}.tmp`);
955
+ writeFileSync(tmp, lines.slice(cut).map((l) => `${l}\n`).join(''), { mode: 0o600, flag: 'wx' });
956
+ renameSync(tmp, path);
792
957
  }
793
958
 
794
959
  // ---- files, under the lock
795
960
 
796
- // The identity as of now: original and current DID, the current genesis and secret.
961
+ // The identity as of now: original and current DID, the current genesis, and sign(body), the
962
+ // only way anything here signs as it.
797
963
  #me(now) {
798
- const { secret, bundle } = this.identity();
964
+ const id = this.identity(), { bundle } = id, sign = (body) => signAs(id, body);
799
965
  let r;
800
966
  try { r = verify(chainOf(bundle), now); } catch (e) { fail('identity', `this agent's bundle does not verify: ${e.message}`); }
801
967
  const genesis = [bundle.genesis, ...bundle.rotations.map((x) => x.next_genesis)].find((g) => didOf(g) === r.did);
@@ -805,7 +971,7 @@ export class Carrier {
805
971
  for (let i = 0; i + 1 < r.chain.length; i++) {
806
972
  if (bundle.rotations.some((x) => x.body.id === r.chain[i] && x.body.next === r.chain[i + 1] && x.body.reason === 'recovery')) recovery = i;
807
973
  }
808
- return { did: r.chain[0], current_did: r.did, secret, genesis, bundle, chain: r.chain, recovery };
974
+ return { did: r.chain[0], current_did: r.did, sign, genesis, bundle, chain: r.chain, recovery };
809
975
  }
810
976
 
811
977
  // The state is saved before the store's held writes (store.mjs hold: a handshake's), so a crash
@@ -896,7 +1062,7 @@ export class Carrier {
896
1062
  #restore(st, store, me, did) {
897
1063
  const c = store.lookup(did);
898
1064
  if (!c || c.revoked || !c.pair_key) return null;
899
- const s = session({ me: { did: me.did, current_did: me.current_did, secret: me.secret }, peer: c, K: hexToBytes(c.pair_key), hold: this.retention });
1065
+ const s = session({ me: { did: me.did, current_did: me.current_did, sign: me.sign }, peer: c, K: hexToBytes(c.pair_key), hold: this.retention });
900
1066
  const d = st.peers[c.did]?.session;
901
1067
  // A session of an earlier pairing key belongs to a pairing that was replaced: start afresh.
902
1068
  if (d && d.pair === s.pair) loadSession(s, d);
@@ -1091,7 +1257,7 @@ export class Carrier {
1091
1257
  let n;
1092
1258
  try { n = parseBytes(bytes); } catch { return; }
1093
1259
  if (n === null || typeof n !== 'object' || typeof n.code !== 'string') return;
1094
- const note = { code: n.code.slice(0, 64), detail: typeof n.detail === 'string' ? n.detail.slice(0, 200) : '' };
1260
+ const note = { code: n.code.slice(0, 64), detail: typeof n.detail === 'string' ? n.detail.slice(0, 200) : '', ...(QUOTA_SIDES.has(n.side) && { side: n.side }) };
1095
1261
  // id: the packet id of the PUBLISH a refusal names (#publish), kept out of events.
1096
1262
  if (link.collect) link.collect.push(Number.isSafeInteger(n.id) ? { ...note, id: n.id } : note);
1097
1263
  else this.#emit({ type: 'notice', relay: link.relay, ...note });
@@ -1211,8 +1377,11 @@ export class Carrier {
1211
1377
  // A FILE_LABEL message from contact c, opened (r). The manifest is kept in the state (files,
1212
1378
  // under a key of the contact and the file's id), each chunk under filesDir/.partial/<key>/<i>
1213
1379
  // (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
1380
+ // filesDir/<contact>-<16 hex of SHA-256(original DID)>/<sha256[0..8]>-<name> (0600), and given to
1381
+ // inbox() as one item of type "file". The folder is the contact's alone, whatever its name
1382
+ // reduces to; a name taken already is never written over (linked in, or opened wx): the file
1383
+ // goes as <sha256[0..8]>-<n>-<name>, n from 2, and past FILE_COPIES it is dropped, file_exists.
1384
+ // Never opened, never made executable. Anything wrong with the message is counted in
1216
1385
  // dropped by its check, as a refused bundle is above; the envelope stays opened either way.
1217
1386
  // A chunk before its manifest (none: the sender sends the manifest first, in one login) is
1218
1387
  // dropped, file_chunk. The disk is written before the state: a crash between them leaves a
@@ -1262,14 +1431,26 @@ export class Carrier {
1262
1431
  rmSync(this.#partDir(key), { recursive: true, force: true });
1263
1432
  return drop(e);
1264
1433
  }
1265
- const dir = join(this.filesDir, safeName(c.name || c.did));
1434
+ const dir = join(this.filesDir, contactDir(c));
1266
1435
  mkdirSync(dir, { recursive: true, mode: 0o700 });
1267
1436
  chmodSync(this.filesDir, 0o700); chmodSync(dir, 0o700);
1268
- const path = join(dir, `${p.sha256.slice(0, 8)}-${p.name}`), tmp = join(dir, `.${randomId()}.tmp`);
1437
+ const tmp = join(dir, `.${randomId()}.tmp`);
1269
1438
  writeFileSync(tmp, bytes, { mode: 0o600, flag: 'wx' });
1270
- renameSync(tmp, path);
1439
+ let path = null;
1440
+ try {
1441
+ for (let n = 1; path === null && n <= FILE_COPIES; n++) {
1442
+ const at = join(dir, `${p.sha256.slice(0, 8)}-${n === 1 ? '' : `${n}-`}${p.name}`);
1443
+ try { linkSync(tmp, at); path = at; } catch (e) {
1444
+ if (e.code === 'EEXIST') continue;
1445
+ // No hard links here (FAT, some network file systems): written again, exclusively.
1446
+ if (!['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'EXDEV', 'ENOSYS'].includes(e.code)) throw e;
1447
+ try { writeFileSync(at, bytes, { mode: 0o600, flag: 'wx' }); path = at; } catch (e2) { if (e2.code !== 'EEXIST') throw e2; }
1448
+ }
1449
+ }
1450
+ } finally { rmSync(tmp, { force: true }); }
1271
1451
  delete st.files[key];
1272
1452
  rmSync(this.#partDir(key), { recursive: true, force: true });
1453
+ if (path === null) return drop(new MsgError('file_exists', `${p.name}: ${FILE_COPIES} files of that name and hash are in ${dir} already; not saved`));
1273
1454
  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
1455
  iat: r.body.iat, received: now, last_resort: r.last_resort };
1275
1456
  // Kept for inbox() as a message is (#onPeer), and so many at most.
@@ -1499,19 +1680,22 @@ export class Carrier {
1499
1680
  const c = store.lookup(res.did), K = hexToBytes(res.pair_key);
1500
1681
  // What checkAnswer replaced, put back if the reply cannot reach the answerer (#unpair).
1501
1682
  const undo = { contact: before[c.did] ?? null, peer: st.peers[c.did] ?? null };
1502
- const s = session({ me: { did: me.did, current_did: me.current_did, secret: me.secret }, peer: c, K });
1503
- const prekeys = s.in.prekeys.issue({ current_did: me.current_did, secret: me.secret }, s.pair, now);
1504
- const reply = buildReply({ answer_id: res.answer_id, identity: { secret: me.secret, genesis: me.genesis }, bundle: chainOf(me.bundle), kem_ct: ct, prekeys });
1683
+ const s = session({ me: { did: me.did, current_did: me.current_did, sign: me.sign }, peer: c, K });
1684
+ const prekeys = s.in.prekeys.issue({ current_did: me.current_did, sign: me.sign }, s.pair, now);
1685
+ const reply = buildReply({ answer_id: res.answer_id, identity: { sign: me.sign, genesis: me.genesis }, bundle: chainOf(me.bundle), kem_ct: ct, prekeys });
1505
1686
  const frame = seal(KIND.invite_reply, keys.key, keys.reply_topic, reply);
1506
- const entry = { relay: p.relay, topic: keys.reply_topic, kind: KIND.invite_reply, control: 'reply', peer: c.did, undo,
1687
+ const entry = { relay: p.relay, topic: keys.reply_topic, kind: KIND.invite_reply, control: 'reply', peer: c.did, undo, invite: nonce,
1507
1688
  needs: [topic(K, c.did, me.did, isoWeek(now))], exp: p.exp };
1508
1689
  if (frame.length > INVITE_BYTES) {
1509
1690
  return [this.#unpair(ctx, entry, { code: 'too_large', detail: `the reply is ${frame.length} bytes, more than an invite topic holds (${INVITE_BYTES}): this agent's chain is too long` })];
1510
1691
  }
1511
1692
  st.peers[c.did] = { session: dumpSession(s), announced: me.current_did, known: me.current_did, outbox: st.peers[c.did]?.outbox ?? [], prekeys_resend: false, prekeys_iat: now };
1512
1693
  this.#queue(st, { ...entry, bytes: frame });
1694
+ // Who answered this code (answeredBy): saved with the pairing, whoever reads the paired event.
1695
+ for (const [x, a] of Object.entries(st.answered)) if (!(a.exp > now)) delete st.answered[x];
1696
+ st.answered[nonce] = { did: c.did, exp: p.exp + DAY };
1513
1697
  this.#routes = new Map();
1514
- return [this.#note(st, now, { type: 'paired', did: c.did, name: c.name, current_did: c.current_did, rekeyed: res.rekeyed, fingerprint: wordsOf(res.pair_key) })];
1698
+ return [this.#note(st, now, { type: 'paired', did: c.did, name: c.name, current_did: c.current_did, rekeyed: res.rekeyed, fingerprint: wordsOf(res.pair_key), invite: nonce })];
1515
1699
  }
1516
1700
 
1517
1701
  // Alice: her reply will never reach the answerer (refused, too large, or its code expired while
@@ -1524,6 +1708,7 @@ export class Carrier {
1524
1708
  if (e.undo.contact) store.s.contacts[e.peer] = e.undo.contact; else delete store.s.contacts[e.peer];
1525
1709
  store.save();
1526
1710
  this.#restorePeer(st, e);
1711
+ if (e.invite) delete st.answered[e.invite];
1527
1712
  this.#routes = new Map();
1528
1713
  return this.#note(st, now, { type: 'pairing_failed', did: e.peer, name, code, detail });
1529
1714
  }
@@ -1575,7 +1760,7 @@ export class Carrier {
1575
1760
  // An entry written before `as` was kept: unknown, so the notice goes (#next `first`).
1576
1761
  const answered = waiting.find(([x]) => x === id)[1], held = answered.as ?? null;
1577
1762
  const c = renamed(store, store.lookup(res.did), answered);
1578
- const s = session({ me: { did: me.did, current_did: me.current_did, secret: me.secret }, peer: c, K: hexToBytes(res.pair_key) });
1763
+ const s = session({ me: { did: me.did, current_did: me.current_did, sign: me.sign }, peer: c, K: hexToBytes(res.pair_key) });
1579
1764
  const events = [this.#note(st, now, { type: 'paired', did: c.did, name: c.name, current_did: c.current_did, rekeyed: res.rekeyed, fingerprint: wordsOf(res.pair_key) })];
1580
1765
  try { acceptPrekeys(s, reply.prekeys, now); } catch (e) {
1581
1766
  if (!(e instanceof MsgError)) throw e;
@@ -1647,7 +1832,7 @@ export class Carrier {
1647
1832
  e.announced = me.current_did;
1648
1833
  e.noticed = now;
1649
1834
  e.notice_asked = false;
1650
- return this.#queue(st, { relay, topic: t, bytes: seal(KIND_NOTICE, noticeKey(K, me.did, c.did), t, { bundle: chainOf(me.bundle), proof: { body: proof, sig: sign(me.secret, proof) } }),
1835
+ return this.#queue(st, { relay, topic: t, bytes: seal(KIND_NOTICE, noticeKey(K, me.did, c.did), t, { bundle: chainOf(me.bundle), proof: { body: proof, sig: me.sign(proof) } }),
1651
1836
  kind: KIND_NOTICE, peer: c.did, control: 'notice' });
1652
1837
  }
1653
1838
  if (c.re_pair) {
@@ -1794,7 +1979,7 @@ export class Carrier {
1794
1979
  const back = r?.code === 'no_reader' && e.kind === KIND.message && e.item !== undefined;
1795
1980
  if (e.control === undefined || e.control === 'answer') this.#results.set(e.id, back ? { code: null, queued: noReader(this.#nameOf(e.peer)) } : r ?? { code: null }); // what a verb waits for
1796
1981
  this.#emit(back ? { type: 'queued', id: e.id, peer: e.peer, code: r.code, detail: r.detail }
1797
- : r ? { type: 'refused', id: e.id, peer: e.peer, control: e.control, code: r.code, detail: r.detail } : { type: 'sent', id: e.id, peer: e.peer, control: e.control });
1982
+ : r ? { type: 'refused', id: e.id, peer: e.peer, control: e.control, code: r.code, ...(r.side && { side: r.side }), detail: r.detail } : { type: 'sent', id: e.id, peer: e.peer, control: e.control });
1798
1983
  // A refusal stops this round: what follows would be refused alike (a quota, the rate brake),
1799
1984
  // and a control frame would be queued again at once. The next round retries. A mailbox
1800
1985
  // nobody holds stops only what goes to that contact (absent, #next).
@@ -1931,7 +2116,7 @@ export class Carrier {
1931
2116
  if (ch.relay !== relay) fail('challenge', `relay ${JSON.stringify(ch.relay)} is not this relay's name, ${relay}`);
1932
2117
  // Signed as built here, never as received; its typ is one no challenge signer produces (a SPEC
1933
2118
  // §5.2 challenge for this relay, got by a world from sign-challenge, logs in nobody).
1934
- const body = { v: LOGIN_V, typ: TYP_LOGIN, did: me.current_did, relay, nonce: ch.nonce }, sig = sign(me.secret, body);
2119
+ const body = { v: LOGIN_V, typ: TYP_LOGIN, did: me.current_did, relay, nonce: ch.nonce }, sig = me.sign(body);
1935
2120
  if (!verifySig(me.genesis.key, body, sig)) fail('identity', 'this agent\'s secret does not match its current genesis key');
1936
2121
  if (canonicalize(body) !== canonicalize(ch)) fail('challenge', 'not the login body this agent signs');
1937
2122
  let pow;
@@ -2004,8 +2189,21 @@ export class Carrier {
2004
2189
  const info = link.own && this.#ask ? this.#relayInfo(ep) : null;
2005
2190
  const creds = await this.#credentials(relay, ep);
2006
2191
  await info;
2192
+ // The transport (the header's "Transport"): auto tries ep.mqtt for PROBE_MS, then the WebSocket
2193
+ // endpoint, and keeps to it for the rest of the process (FELL_BACK). Only a dial that got no
2194
+ // CONNACK at all falls back: a refusal by name (its return code) is the relay's answer, on
2195
+ // either transport. Both are TLS; nothing falls back to a plain connection.
2196
+ const onPacket = (packet) => this.#onPacket(link, packet);
2197
+ const probe = this.transport === 'auto' && !FELL_BACK.has(ep.mqtt) && /^mqtts?:/.test(ep.mqtt);
2198
+ let url = this.transport === 'wss' ? await wsEndpoint(ep) : this.transport === 'auto' ? FELL_BACK.get(ep.mqtt) ?? ep.mqtt : ep.mqtt;
2007
2199
  // A cut connection is this client's own refusal: no POST /check may rename it.
2008
- try { await mqttConnect(ep.mqtt, creds, link, (packet) => this.#onPacket(link, packet)); } catch (e) { throw link.cut ?? await named(ep, creds, e); }
2200
+ try { await mqttConnect(url, creds, link, onPacket, probe ? PROBE_MS : CONNECT_MS); } catch (e) {
2201
+ if (!probe || link.cut || typeof e.code === 'number') throw link.cut ?? await named(ep, creds, e);
2202
+ url = await wsEndpoint(ep);
2203
+ try { await mqttConnect(url, creds, link, onPacket); } catch (e2) { throw link.cut ?? await named(ep, creds, e2); }
2204
+ FELL_BACK.set(ep.mqtt, url);
2205
+ this.#emit({ type: 'transport', relay, transport: 'wss', detail: `${ep.mqtt} gave no CONNACK within ${PROBE_MS / 1000} s (${e.message}): MQTT over WebSocket at ${url} for the rest of this process` });
2206
+ }
2009
2207
  // A close right after CONNACK (a cut in the same read) reached no listener of this connection.
2010
2208
  if (!link.client.connected) throw link.cut ?? new MsgError('connect', 'the relay closed the connection');
2011
2209
  // Deliveries are counted from here (quiet), not from before the login: a proof-of-work search
@@ -2185,6 +2383,25 @@ export class Carrier {
2185
2383
  return r.body.invite;
2186
2384
  }
2187
2385
 
2386
+ // A gift code redeemed at this agent's own relay (POST /gift, relay/gifts.mjs): the relay gets the
2387
+ // code's hash (short.mjs giftHash), never the code, with a login of its own; the identity logged
2388
+ // in becomes the operator whose pool is Pro. A malformed code is refused here, before any login.
2389
+ async redeemGift(text) {
2390
+ const hash = giftHash(text), ep = endpointOf(this.relay, this.endpoints);
2391
+ const creds = await this.#credentials(this.relay, ep);
2392
+ const r = await http(`${ep.http}/gift`, { method: 'POST', body: JSON.stringify({ username: creds.username, client_id: creds.clientId, password: creds.password, code_hash: hash }) });
2393
+ this.#clockFrom(this.relay, r);
2394
+ const check = typeof r.body?.check === 'string' ? r.body.check : null;
2395
+ if (r.status === 429) refuse('rate', `the relay ${this.relay} takes no more gift codes from this network for now (${relaySays(r.body?.detail)}): ${retryIn(r, 'up to an hour')}`, r);
2396
+ if ((r.status === 404 || r.status === 405) && check === null) refuse('gift', `the relay ${this.relay} takes no gift codes`, r);
2397
+ if (r.status !== 200) refuse('connect', `${this.relay}: ${statusWhy(r, 'POST /gift')}`, r);
2398
+ if (r.body?.ok !== true) refuse(GIFT_CHECKS.has(check) ? check : 'gift', `the relay refused the gift code (${relaySays(`${check}: ${r.body?.detail}`)})`, r);
2399
+ // A proof sent with this login was taken: the identity is stored there now, as after a session.
2400
+ if (creds.pow !== undefined) this.#locked(({ st }) => { (st.relays[this.relay] ??= { proven: false, claims: {} }).proven = true; });
2401
+ if (!Number.isSafeInteger(r.body.exp) || !Number.isSafeInteger(r.body.months)) refuse('connect', `${this.relay}: POST /gift answered ok without the new expiry: SIGELO_DEBUG=1 shows the answer`, r);
2402
+ return { exp: r.body.exp, months: r.body.months };
2403
+ }
2404
+
2188
2405
  async accept(text, opts = {}) {
2189
2406
  // Short or long by the input's shape, before either parser runs (short.mjs codeKind).
2190
2407
  const how = codeKind(text) === 'short' ? 'parked' : 'long';
@@ -2203,7 +2420,7 @@ export class Carrier {
2203
2420
  }
2204
2421
  const k = kemKey();
2205
2422
  try {
2206
- const answer = buildAnswer({ code, identity: { secret: me.secret, genesis: me.genesis }, bundle: chainOf(me.bundle), kem_pk: k.pk, prekeys: null });
2423
+ const answer = buildAnswer({ code, identity: { sign: me.sign, genesis: me.genesis }, bundle: chainOf(me.bundle), kem_pk: k.pk, prekeys: null });
2207
2424
  const keys = inviteKeys(code.secret), frame = seal(KIND.invite_answer, keys.key, keys.answer_topic, answer);
2208
2425
  // Checked before anything is stored: the relay would refuse it (quota_storage).
2209
2426
  if (frame.length > INVITE_BYTES) fail('too_large', `the answer is ${frame.length} bytes, more than an invite topic holds (${INVITE_BYTES}): this agent's chain is too long`);
@@ -2293,7 +2510,7 @@ export class Carrier {
2293
2510
  contacts: Object.values(s.contacts).map((c) => {
2294
2511
  const e = st.peers[c.did], pair = c.revoked || !c.pair_key ? null : pairId(hexToBytes(c.pair_key));
2295
2512
  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,
2513
+ re_pair: c.re_pair ?? null, fingerprint: c.revoked ? null : wordsOf(c.pair_key), pair, ours: store.oursOf(c, now), tier: store.tierOf(c, now), tier_by: c.tier_by ?? null,
2297
2514
  prekeys: pair !== null && theirPrekeys(c, e?.session, pair, now), waiting: e?.waiting ?? null };
2298
2515
  }),
2299
2516
  invites: Object.values(s.invites).filter((p) => p.exp > now).map((p) => ({ name: p.name, exp: p.exp, relay: p.relay })),
@@ -2306,7 +2523,8 @@ export class Carrier {
2306
2523
 
2307
2524
  async send(to, content, { label = '', local = false } = {}) {
2308
2525
  const [r] = await this.sendAll(to, [content], { label, local });
2309
- if (r.status === 'refused') fail(r.code, `refused (${r.detail})`);
2526
+ // side: whose quota a quota_storage is (relay/allowance.mjs), on the error too.
2527
+ if (r.status === 'refused') throw Object.assign(new MsgError(r.code, `refused (${r.detail})`), r.side && { side: r.side });
2310
2528
  return r;
2311
2529
  }
2312
2530
 
@@ -2358,7 +2576,7 @@ export class Carrier {
2358
2576
  const r = this.#results.get(id);
2359
2577
  this.#results.delete(id);
2360
2578
  // detail: the carrier's own words when it refused the message itself, else the relay's, quoted.
2361
- if (r?.code) return { status: 'refused', id, to: c.did, name: c.name, code: r.code, detail: r.local ? r.detail : relaySays(r.detail) };
2579
+ if (r?.code) return { status: 'refused', id, to: c.did, name: c.name, code: r.code, ...(r.side && { side: r.side }), detail: r.local ? r.detail : quotaWhy(r, c.name) ?? relaySays(r.detail) };
2362
2580
  if (!r || r.queued) return { status: 'queued', id, to: c.did, name: c.name, detail: r?.queued ?? 'waiting for the relay\'s acknowledgement: it goes at the next connection' };
2363
2581
  return { status: 'sent', id, to: c.did, name: c.name };
2364
2582
  });
@@ -2385,8 +2603,8 @@ export class Carrier {
2385
2603
  let ownDir;
2386
2604
  try { ownDir = realpathSync(dirname(own)); } catch { ownDir = dirname(own); }
2387
2605
  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`);
2606
+ if (real.startsWith(files + sep) || real === this.logPath || (dirname(real) === ownDir && (leaf.startsWith(`${basename(own)}.`) || leaf.includes('.local.')))) {
2607
+ fail('file', `${path} is one of this agent's identity files (key, contacts, state, files received, inbox log): not sent`);
2390
2608
  }
2391
2609
  try { bytes = readFileSync(real); } catch (e) { fail('file', `cannot read ${path}: ${e.code ?? e.message}`, { cause: e }); }
2392
2610
  if (bytes.length > MAX_FILE) fail('file_too_large', `${path} is ${bytes.length} bytes, at most ${MAX_FILE} (8 MiB) a file`);
@@ -2422,6 +2640,7 @@ export class Carrier {
2422
2640
  return this.#locked(({ now, store, st }) => {
2423
2641
  this.#sweepFiles(st, now);
2424
2642
  const pick = picks(store, now), messages = st.inbox.filter(pick);
2643
+ this.#logOut(messages);
2425
2644
  const out = { messages, events: st.events, dropped: st.dropped, ...(offline && { offline }) };
2426
2645
  st.inbox = st.inbox.filter((m) => !pick(m)); st.events = []; st.dropped = {};
2427
2646
  return out;
@@ -2437,22 +2656,46 @@ export class Carrier {
2437
2656
  return this.#locked(({ now, store, st }) => {
2438
2657
  const t = store.tiers(now), out = [], keep = [];
2439
2658
  for (const m of st.inbox) (pick(m, t.get(m.from) ?? 'friend') ? out : keep).push(m);
2659
+ this.#logOut(out);
2440
2660
  st.inbox = keep;
2441
2661
  return out;
2442
2662
  });
2443
2663
  }
2444
2664
 
2665
+ // The log as written (atomic renames: no lock needed), oldest first; since: unix seconds, by
2666
+ // `received`. A line that does not parse (a hand edit) is skipped, never the rest.
2667
+ history({ since = 0 } = {}) {
2668
+ if (!Number.isSafeInteger(since) || since < 0) throw new TypeError('since: unix seconds, a whole number');
2669
+ if (this.logPath === null) return { messages: [] };
2670
+ let text = '';
2671
+ try { text = readFileSync(this.logPath, 'utf8'); } catch (e) { if (e.code !== 'ENOENT') throw e; }
2672
+ const messages = [];
2673
+ for (const l of text.split('\n')) {
2674
+ if (l === '') continue;
2675
+ let m;
2676
+ try { m = JSON.parse(l); } catch { continue; }
2677
+ if (m !== null && typeof m === 'object' && (m.received ?? 0) >= since) messages.push(m);
2678
+ }
2679
+ return { messages };
2680
+ }
2681
+
2445
2682
  setTier(who, tier) { return this.#locked(({ now, store }) => store.setTier(who, tier, now)); }
2683
+ // The owner's tier for an original DID before it is a contact (an enrolled worker): store.mjs presetTier.
2684
+ presetTier(did, tier) { return this.#locked(({ now, store }) => store.presetTier(did, tier, now)); }
2685
+ // The original DID that paired through this agent's code `nonce` (its inviteNonce, readCode().nonce),
2686
+ // or null: none yet, or the code's life plus a day is over (enrol.mjs answers only that DID).
2687
+ answeredBy(nonce) { return this.#read(({ now, st }) => { const a = Object.hasOwn(st.answered, nonce) ? st.answered[nonce] : null; return a && a.exp > now ? a.did : null; }); }
2446
2688
 
2447
2689
  // 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.
2690
+ // here; → { did, tier, ours }, or null when it is no contact's.
2449
2691
  observe(bundle) {
2450
2692
  return this.#locked(({ now, store }) => {
2451
2693
  let r;
2452
2694
  try { r = verify(bundle, now); } catch (e) { fail('bundle', `REJECT: ${e.message}`); }
2453
2695
  const c = store.lookup(r.chain[0]);
2454
2696
  if (!c || c.revoked || c.did !== r.chain[0]) return null;
2455
- return { did: c.did, tier: store.observe(c.did, r, now) };
2697
+ const tier = store.observe(c.did, r, now);
2698
+ return { did: c.did, tier, ours: store.oursOf(store.lookup(c.did), now) };
2456
2699
  });
2457
2700
  }
2458
2701