sigelo-contact 0.1.6 → 0.1.8
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/README.md +22 -20
- package/carrier.mjs +626 -72
- package/enrol.mjs +406 -0
- package/envelope.mjs +4 -4
- package/file.mjs +113 -0
- package/invite.mjs +5 -5
- package/kdf.mjs +6 -0
- package/package.json +13 -3
- package/prekeys.mjs +4 -4
- package/short.mjs +23 -0
- package/store.mjs +129 -9
- package/test-carrier.mjs +28 -1
- package/test-enrol.mjs +240 -0
- package/test-file.mjs +231 -0
- package/test-short.mjs +52 -1
- package/test-tier.mjs +240 -0
- package/test-ws.mjs +237 -0
package/carrier.mjs
CHANGED
|
@@ -3,23 +3,45 @@
|
|
|
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
|
-
// c.
|
|
14
|
+
// await c.cancelInvite(code) → { cancelled, name }: an unanswered invite of this agent's withdrawn
|
|
15
|
+
// c.rename(who, name) the owner's name for a contact (store.mjs rename) → { did, name }
|
|
16
|
+
// c.contacts() → { contacts, invites, answers, failed } each contact with its four words (fingerprint),
|
|
17
|
+
// pair id, chain, tier (store.mjs: own, friend, quiet) and tier_by, prekeys: its
|
|
18
|
+
// bundle is here (false: messages wait for it), waiting: why they wait, or null;
|
|
13
19
|
// failed: pairing_failed events (code_expired: an answer that outlived its code) until inbox
|
|
14
|
-
// await c.send(to, content, { label })
|
|
15
|
-
// await c.sendAll(to, contents, { label }) → one result each ('refused' with its code), one login
|
|
16
|
-
// await c.
|
|
20
|
+
// await c.send(to, content, { label, local }) → { status: 'sent' | 'queued', … }, or throws the relay's code
|
|
21
|
+
// await c.sendAll(to, contents, { label, local }) → one result each ('refused' with its code), one login
|
|
22
|
+
// await c.sendFile(to, path, { local }) → { status, to, name, file: {id, name, size, sha256, chunks} }: a file of at most
|
|
23
|
+
// 8 MiB as FILE_LABEL messages (file.mjs), one login; throws as send does. Chunks
|
|
24
|
+
// queued wait in files/.out (0600), the state names them; gone once sent or refused.
|
|
25
|
+
// local (all three): no session, queued in the state file for a started carrier
|
|
26
|
+
// of the same identity elsewhere (a watcher), which sends it at its next sync()
|
|
27
|
+
// await c.inbox({ wait, tiers, local, paired }) → { messages, events, dropped, offline? }: all are taken (messages: those kept;
|
|
28
|
+
// tiers: only those from contacts of these tiers, the rest stay); local: no
|
|
29
|
+
// session, the state file only (a started carrier elsewhere is connected);
|
|
30
|
+
// paired: the wait also ends at a pairing (enrol.mjs)
|
|
31
|
+
// c.peek(), c.take(pick) the messages kept for inbox(), each with its sender's tier: read, or those
|
|
32
|
+
// pick(message, tier) chooses taken; no session (a started carrier's owner)
|
|
33
|
+
// c.setTier(who, tier) the owner's tier for a contact (store.mjs setTier) → { did, name, tier }
|
|
34
|
+
// c.observe(bundle) a contact's full bundle seen: its operator attestations (store.mjs observe)
|
|
35
|
+
// a file received whole is one item {type: "file", from, contact, name, size,
|
|
36
|
+
// sha256, path, …}, saved under `files` (pathsFor), never opened
|
|
17
37
|
// await c.forget(did) → { name, did, revoked: true, released, offline? }
|
|
18
38
|
// c.lastError the error behind the last offline of inbox or forget (SIGELO_DEBUG)
|
|
39
|
+
// c.clockOffset(), await c.checkClock() → { relay, offset, checked } | null: the relay's clock less this one's, seconds
|
|
19
40
|
// await c.start(), c.sync(), c.stop() stay connected, reconnecting with backoff; events reach onEvent
|
|
20
41
|
//
|
|
21
|
-
// identity() → {
|
|
22
|
-
//
|
|
42
|
+
// identity() → { sign, bundle }: the agent's signer for its current key (sign(body) → the SPEC §3
|
|
43
|
+
// signature; sigelo-agent-keys.ts) and its SPEC §8 bundle, read again at every operation, so a
|
|
44
|
+
// rotation made by another process is seen at once. { secret, bundle }, the seed itself, still works. store: the contact store
|
|
23
45
|
// (store.mjs); state: this file's own JSON (sessions, outbox, inbox), both 0600 and written under one
|
|
24
46
|
// lock file, `<state>.lock`. pathsFor(identityFile) names both beside the identity file. onEvent(e):
|
|
25
47
|
// each event as it happens, messages included, and `pow` / `pow_done` around a proof-of-work search
|
|
@@ -28,8 +50,17 @@
|
|
|
28
50
|
// default only without onEvent, so a message onEvent took is not left at rest after the keys that
|
|
29
51
|
// opened it are gone (contacts.md §3: keys stolen today must not open yesterday's messages).
|
|
30
52
|
// One connected carrier per identity: every process logs in with the identity's one MQTT client
|
|
31
|
-
// id, so a
|
|
32
|
-
//
|
|
53
|
+
// id, so a second login takes the session from a started carrier (the files stay sound under the
|
|
54
|
+
// lock; the started one reconnects with backoff). Beside one, use inbox and send with local: the
|
|
55
|
+
// state file only (sigelo-agent's one-owner rule, adapters/moadim/WATCH.md).
|
|
56
|
+
//
|
|
57
|
+
// Transport (transport, or SIGELO_RELAY_TRANSPORT): "auto" (the default), 8883 for PROBE_MS, then
|
|
58
|
+
// 443 for the rest of the process, so a network that lets only HTTPS out needs no setting; "mqtts",
|
|
59
|
+
// MQTT over TLS on 8883 only; "wss", MQTT over WebSocket on 443 only (wss://host/mqtt, or
|
|
60
|
+
// 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
|
|
61
|
+
// and the WebSocket dial by HTTP CONNECT, unless NO_PROXY (or no_proxy) names the host (proxyFor);
|
|
62
|
+
// MQTT on 8883 never goes through it. Certificates are checked as without a proxy, so
|
|
63
|
+
// NODE_EXTRA_CA_CERTS works the same. The event { type: "transport" } says when auto fell back.
|
|
33
64
|
//
|
|
34
65
|
// What this adds to the wire, beside the envelope (envelope.mjs) and the invite (invite.mjs); the
|
|
35
66
|
// bytes are pinned in fixtures/carrier-v0.json (gen-carrier.mjs --check):
|
|
@@ -120,6 +151,18 @@
|
|
|
120
151
|
// cannot be told from the thief's: refused alike; the owner writes again once paired again.
|
|
121
152
|
// What an earlier inbox() returned, or onEvent got, cannot be taken back: the `rotated` event
|
|
122
153
|
// of such a notice lists the DIDs it overruled (`overruled`).
|
|
154
|
+
// - Operator hints (label OPERATOR_LABEL, a message like any other): an agent attested by
|
|
155
|
+
// operators (sigelo-relay/operator) tells each contact {hints: HMAC-SHA256(K, "sigelo-operator/0
|
|
156
|
+
// hint\n" ‖ its original DID ‖ "\n" ‖ operator DID)}, once per pairing and set of operators. A
|
|
157
|
+
// contact run by the same operator, or that operator itself, recognises one and answers {asks}
|
|
158
|
+
// (the same with "ask" and its own DID: it knows the operator's DID, an echo does not), and only
|
|
159
|
+
// then the agent sends {proof}: its chain with those attestations and their issuers, which the
|
|
160
|
+
// contact verifies (SPEC §9) and files (store.mjs observe): the contact's tier becomes own. A
|
|
161
|
+
// proof is taken only after asks of ours, at most NOTICE_CHECKS an hour, and only if its chain
|
|
162
|
+
// ends at the sender's current DID as held (store.mjs current_did). A renewed attestation is
|
|
163
|
+
// hinted and proved again; asks for the same operators go at most every RESYNC. A contact
|
|
164
|
+
// learns from the hints only which operator DIDs it guesses right (THREAT-MODEL §2.12). An
|
|
165
|
+
// agent on an older version gets the hints as messages with that label. send refuses the label.
|
|
123
166
|
// - Mailboxes: an agent holds the topics of every ISO week from `retention` ago to AHEAD (7 days,
|
|
124
167
|
// or its retention if shorter) ahead. The relay drops a publish to a topic nobody claimed (and
|
|
125
168
|
// says no_reader), so next week's topic must be claimed before a contact writes in it while
|
|
@@ -141,24 +184,30 @@
|
|
|
141
184
|
// round, so topics are asked in the order they matter (#want). A refused topic is asked again
|
|
142
185
|
// at the next hourly round (ASK_AGAIN).
|
|
143
186
|
import { createHash } from 'node:crypto';
|
|
144
|
-
import {
|
|
145
|
-
import {
|
|
187
|
+
import { request as httpRequest } from 'node:http';
|
|
188
|
+
import { Agent as HttpsAgent, request as httpsRequest } from 'node:https';
|
|
189
|
+
import { connect as tlsConnect } from 'node:tls';
|
|
190
|
+
import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
191
|
+
import { basename, dirname, join, resolve, sep } from 'node:path';
|
|
146
192
|
import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
|
147
193
|
import { hkdf } from '@noble/hashes/hkdf.js';
|
|
194
|
+
import { hmac } from '@noble/hashes/hmac.js';
|
|
148
195
|
import { sha256 } from '@noble/hashes/sha2.js';
|
|
149
196
|
import { concatBytes, hexToBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils.js';
|
|
150
197
|
import { connect } from 'mqtt';
|
|
151
|
-
import { canonicalize, commitmentOf, did as didOf, parseBytes,
|
|
198
|
+
import { canonicalize, commitmentOf, did as didOf, parseBytes, verify, verifySig } from 'sigelo';
|
|
152
199
|
import { KIND, acceptPrekeys, expire, header, open, pad, prekeysMissing, restartEpoch, send, session, unpad } from './envelope.mjs';
|
|
153
200
|
import { answerId, buildAnswer, buildReply, checkAnswer, checkReply, inviteKeys, keyOf, makeInvite, parseInvite } from './invite.mjs';
|
|
154
|
-
import { MsgError, checkNow, fail, hex, isoWeek, pairId, topic } from './kdf.mjs';
|
|
201
|
+
import { MsgError, checkNow, fail, hex, isoWeek, pairId, signAs, topic } from './kdf.mjs';
|
|
155
202
|
import { Prekeys, exact, kemDecapsulate, kemEncapsulate, kemKey } from './prekeys.mjs';
|
|
156
|
-
import { Contacts } from './store.mjs';
|
|
157
|
-
import { SHORT_TTL, codeHash, codeKind, fingerprint, formatShort, makeShort, normaliseShort } from './short.mjs';
|
|
203
|
+
import { Contacts, OPERATOR_CTX, TIERS } from './store.mjs';
|
|
204
|
+
import { SHORT_TTL, codeHash, codeKind, fingerprint, formatShort, giftHash, makeShort, normaliseShort } from './short.mjs';
|
|
205
|
+
import { FILE_LABEL, MAX_FILE, assemble, checkChunk, checkManifest, chunkHead, isManifest, safeName, splitFile } from './file.mjs';
|
|
158
206
|
|
|
159
207
|
export const V = 'sigelo-carrier/0';
|
|
160
208
|
export const DEFAULT_RELAY = 'relay.sigelo.ai', MQTT_PORT = 8883, NOTICE = '$sigelo/notice';
|
|
161
209
|
export const LABEL_PREKEYS = 'sigelo-msg/0 prekeys', KIND_NOTICE = 4, KIND_PREKEYS = 5, TYP_NOTICE = 'contact-notice';
|
|
210
|
+
export const OPERATOR_LABEL = 'sigelo-operator/0';
|
|
162
211
|
// The relay login (relay-plan §3 "Login"): the body GET /challenge answers and the agent signs. A
|
|
163
212
|
// type of its own, never a SPEC §5.2 challenge: a world that passed the relay's nonce on as its own
|
|
164
213
|
// challenge would get the agent's relay login back from sign-challenge.
|
|
@@ -193,12 +242,21 @@ const POISON_TRIES = 3;
|
|
|
193
242
|
// Events kept for the next inbox(): pairings, rotations, failed pairings. The oldest go first.
|
|
194
243
|
// Messages kept for it (keep), likewise.
|
|
195
244
|
const EVENTS_MAX = 1000, INBOX_MAX = 1000;
|
|
245
|
+
// Files arriving at once from one contact (#onFile): each holds up to 8 MiB of parts here.
|
|
246
|
+
const FILES_OPEN = 8;
|
|
196
247
|
// Half the relay's publish brake (20 a second, 200 at once): past it the relay refuses publishes
|
|
197
248
|
// ("rate"), and closes the connection after 500 refusals in a minute (every refused publish
|
|
198
249
|
// counts, a no_reader too).
|
|
199
250
|
const RATE = { perSecond: 10, burst: 100 };
|
|
200
251
|
// Milliseconds. QUIET: no delivery for this long after connecting = the relay's queue is drained.
|
|
201
252
|
const QUIET = 400, DRAIN = 4000, ACK_MS = 15000, CONNECT_MS = 15000, HTTP_MS = 15000, HTTP_MAX = 65536;
|
|
253
|
+
// transport "auto": MQTT over TLS gets this long to answer the CONNECT before the dial goes to MQTT
|
|
254
|
+
// over WebSocket on 443. A network that lets only HTTPS out drops 8883 rather than refusing it.
|
|
255
|
+
export const PROBE_MS = 5000;
|
|
256
|
+
export const TRANSPORTS = ['mqtts', 'wss', 'auto'];
|
|
257
|
+
// The WebSocket endpoint, as relay.json names it (relay/server.mjs WS_PATH) and as a relay with
|
|
258
|
+
// none is reached: on its HTTPS host.
|
|
259
|
+
export const WS_PATH = '/mqtt';
|
|
202
260
|
// MQTT.js buffers a packet whole before handing it over, up to MQTT's 256 MB (its own size check
|
|
203
261
|
// applies only to protocol version 5), and a code can name any host: a packet longer than the
|
|
204
262
|
// largest a relay forwards (relay/server.mjs MAX_FRAME: a 1 MB message and its header) cuts the
|
|
@@ -262,36 +320,108 @@ const b64 = (b) => Buffer.from(b).toString('base64');
|
|
|
262
320
|
const unb64 = (s) => new Uint8Array(Buffer.from(s, 'base64'));
|
|
263
321
|
const randomId = () => hex(randomBytes(8));
|
|
264
322
|
const clientIdOf = (original) => 's' + createHash('sha256').update(original, 'utf8').digest('hex').slice(0, 24);
|
|
323
|
+
// Operators as hinted and proved: each with its attestation's expiry, so a renewal goes again.
|
|
324
|
+
const opKey = (mine, ops) => [...ops].sort().map((d) => `${d} ${mine.exp.get(d)}`).join();
|
|
325
|
+
// Whether a session as the state holds it (dumpSession) has a prekey bundle of contact c's that an
|
|
326
|
+
// epoch can begin on (envelope.mjs prekeysMissing): of this pairing, signed as c's current DID, unexpired.
|
|
327
|
+
const theirPrekeys = (c, d, pair, now) => {
|
|
328
|
+
const p = d?.pair === pair ? d.out.prekeys : null;
|
|
329
|
+
return Boolean(p) && p.did === c.current_did && now < p.exp;
|
|
330
|
+
};
|
|
265
331
|
// The four words of a pairing (short.mjs), from its pairing key as the store holds it (hex), or null.
|
|
266
332
|
const wordsOf = (pairKey) => (typeof pairKey === 'string' ? fingerprint(pairId(hexToBytes(pairKey))) : null);
|
|
267
333
|
// The refusals of POST /park this client names (relay/park.mjs, and the login's: auth.mjs).
|
|
268
334
|
const PARK_CHECKS = new Set(['park', 'park_taken', 'park_full', 'pow', ...LOGIN_CHECKS]);
|
|
335
|
+
// The refusals of POST /gift this client names (relay/gifts.mjs, allowance.mjs, operator.mjs, and the login's).
|
|
336
|
+
const GIFT_CHECKS = new Set(['gift', 'gift_member', 'gift_term', 'pow', ...LOGIN_CHECKS]);
|
|
269
337
|
|
|
270
338
|
// ---------------------------------------------------------------- configuration
|
|
271
339
|
|
|
272
|
-
/** The contact store
|
|
340
|
+
/** 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/. */
|
|
273
341
|
export function pathsFor(identityFile) {
|
|
274
342
|
const base = identityFile.replace(/\.json$/, '');
|
|
275
|
-
return { store: `${base}.contacts.json`, state: `${base}.carrier.json` };
|
|
343
|
+
return { store: `${base}.contacts.json`, state: `${base}.carrier.json`, files: `${base}.files` };
|
|
276
344
|
}
|
|
277
345
|
|
|
278
346
|
/**
|
|
279
|
-
* Where relay "host[:port]" is reached: MQTT over TLS on port (8883), HTTPS on 443
|
|
280
|
-
* { [relay]: { mqtt, http } } overrides, e.g. a relay
|
|
281
|
-
*
|
|
347
|
+
* Where relay "host[:port]" is reached: MQTT over TLS on port (8883), HTTPS on 443, MQTT over
|
|
348
|
+
* WebSocket at wss://host/mqtt. endpoints: { [relay]: { mqtt, http, ws? } } overrides, e.g. a relay
|
|
349
|
+
* on loopback: mqtt may be mqtts:// or wss://, ws wss:// (by default the http origin at /mqtt);
|
|
350
|
+
* plain mqtt://, ws:// and http:// only to a loopback address, so nothing leaves the machine in clear.
|
|
282
351
|
*/
|
|
283
352
|
export function endpointOf(relay, endpoints = {}) {
|
|
284
353
|
const o = endpoints && Object.hasOwn(endpoints, relay) ? endpoints[relay] : null;
|
|
285
354
|
if (!o) {
|
|
286
355
|
const [host, port] = relay.split(':');
|
|
287
|
-
return { mqtt: `mqtts://${host}:${port ?? MQTT_PORT}`, http: `https://${host}` };
|
|
356
|
+
return { mqtt: `mqtts://${host}:${port ?? MQTT_PORT}`, http: `https://${host}`, ws: `wss://${host}${WS_PATH}` };
|
|
288
357
|
}
|
|
289
|
-
|
|
358
|
+
const check = (k, ok) => {
|
|
290
359
|
let u;
|
|
291
360
|
try { u = new URL(o[k]); } catch { fail('relay', `${relay}: endpoints.${k} is not a URL`); }
|
|
292
|
-
|
|
361
|
+
const [secure, plain] = ok.find(([sec, pl]) => u.protocol === sec || u.protocol === pl) ?? ok[0];
|
|
362
|
+
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)`);
|
|
363
|
+
};
|
|
364
|
+
check('mqtt', [['mqtts:', 'mqtt:'], ['wss:', 'ws:']]);
|
|
365
|
+
check('http', [['https:', 'http:']]);
|
|
366
|
+
const http = o.http.replace(/\/+$/, '');
|
|
367
|
+
if (o.ws !== undefined) check('ws', [['wss:', 'ws:']]);
|
|
368
|
+
return { mqtt: o.mqtt, http, ws: o.ws ?? http.replace(/^http/, 'ws') + WS_PATH };
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* The HTTP CONNECT proxy for url (https: or wss:), from HTTPS_PROXY or https_proxy, unless NO_PROXY
|
|
373
|
+
* (or no_proxy) names its host: "*", a name (its subdomains too; a leading "." or "*." the same), an
|
|
374
|
+
* address, each with an optional :port. → a URL, or null. Only an http:// proxy; TLS to the relay
|
|
375
|
+
* runs inside the tunnel, verified as without one (NODE_EXTRA_CA_CERTS included).
|
|
376
|
+
*/
|
|
377
|
+
export function proxyFor(url, env = process.env) {
|
|
378
|
+
const u = new URL(url);
|
|
379
|
+
const raw = env.HTTPS_PROXY || env.https_proxy;
|
|
380
|
+
if ((u.protocol !== 'https:' && u.protocol !== 'wss:') || !raw) return null;
|
|
381
|
+
const host = u.hostname.replace(/^\[|\]$/g, '').toLowerCase(), port = u.port || '443';
|
|
382
|
+
for (const e of String(env.NO_PROXY || env.no_proxy || '').toLowerCase().split(/[\s,]+/).filter(Boolean)) {
|
|
383
|
+
if (e === '*') return null;
|
|
384
|
+
const m = /^\[([^\]]+)\](?::(\d+))?$/.exec(e) ?? (e.split(':').length === 2 ? /^([^:]+):(\d+)$/.exec(e) : null);
|
|
385
|
+
const name = (m ? m[1] : e).replace(/^\*?\./, '.'), p = m?.[2];
|
|
386
|
+
if (p && p !== port) continue;
|
|
387
|
+
if (name.startsWith('.') ? host.endsWith(name) || host === name.slice(1) : host === name || host.endsWith(`.${name}`)) return null;
|
|
388
|
+
}
|
|
389
|
+
let p;
|
|
390
|
+
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'); }
|
|
391
|
+
if (p.protocol !== 'http:') fail('connect', `HTTPS_PROXY: ${p.protocol}// proxies are not supported; want http://host:port (HTTP CONNECT)`);
|
|
392
|
+
return p;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// An https.Agent whose every connection is a tunnel through proxy (HTTP CONNECT host:port), with
|
|
396
|
+
// TLS to the relay inside it: for the HTTP calls (http) and for MQTT over WebSocket (ws's agent).
|
|
397
|
+
class Tunnel extends HttpsAgent {
|
|
398
|
+
constructor(proxy) { super({ keepAlive: false }); this.proxy = proxy; }
|
|
399
|
+
createConnection(options, cb) {
|
|
400
|
+
const p = this.proxy, host = options.host.includes(':') ? `[${options.host}]` : options.host, target = `${host}:${options.port || 443}`;
|
|
401
|
+
const auth = p.username ? { 'proxy-authorization': `Basic ${Buffer.from(`${decodeURIComponent(p.username)}:${decodeURIComponent(p.password)}`).toString('base64')}` } : {};
|
|
402
|
+
const req = httpRequest({ host: p.hostname.replace(/^\[|\]$/g, ''), port: p.port || 80, method: 'CONNECT', path: target, agent: false, headers: { host: target, ...auth } });
|
|
403
|
+
req.setTimeout(HTTP_MS, () => req.destroy(new Error(`no answer within ${HTTP_MS / 1000} s`)));
|
|
404
|
+
req.once('connect', (res, sock) => {
|
|
405
|
+
req.setTimeout(0);
|
|
406
|
+
if (res.statusCode !== 200) { sock.destroy(); return cb(new Error(`the proxy ${p.host} answered ${res.statusCode} to CONNECT ${target}`)); }
|
|
407
|
+
cb(null, tlsConnect({ ...options, socket: sock, servername: options.servername || options.host }));
|
|
408
|
+
});
|
|
409
|
+
req.once('error', (e) => cb(new Error(`the proxy ${p.host}: ${e.code ?? e.message}`)));
|
|
410
|
+
req.end();
|
|
293
411
|
}
|
|
294
|
-
|
|
412
|
+
}
|
|
413
|
+
const tunnelFor = (url) => { const p = proxyFor(url); return p ? new Tunnel(p) : null; };
|
|
414
|
+
|
|
415
|
+
// An HTTPS request through a tunnel, answered in the shape of fetch's Response as http() reads it.
|
|
416
|
+
function viaTunnel(url, init, agent) {
|
|
417
|
+
return new Promise((resolve, reject) => {
|
|
418
|
+
const body = init.body === undefined ? undefined : Buffer.from(init.body);
|
|
419
|
+
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) => {
|
|
420
|
+
resolve({ status: res.statusCode, type: 'basic', body: res, headers: { get: (k) => { const v = res.headers[k.toLowerCase()]; return v === undefined ? null : String(v); } } });
|
|
421
|
+
});
|
|
422
|
+
req.once('error', (e) => reject(Object.assign(new Error(e.message), { cause: e })));
|
|
423
|
+
req.end(body);
|
|
424
|
+
});
|
|
295
425
|
}
|
|
296
426
|
|
|
297
427
|
/**
|
|
@@ -317,7 +447,7 @@ export function retentionOf(info) {
|
|
|
317
447
|
return retentionOk(n) ? n : null;
|
|
318
448
|
}
|
|
319
449
|
|
|
320
|
-
/** SIGELO_RELAY (the relay new invites name), SIGELO_RELAY_ENDPOINTS (JSON, as endpointOf), SIGELO_RELAY_RETENTION_DAYS. */
|
|
450
|
+
/** SIGELO_RELAY (the relay new invites name), SIGELO_RELAY_ENDPOINTS (JSON, as endpointOf), SIGELO_RELAY_RETENTION_DAYS, SIGELO_RELAY_TRANSPORT. */
|
|
321
451
|
export function optionsFromEnv(env = process.env) {
|
|
322
452
|
const o = {};
|
|
323
453
|
if (env.SIGELO_RELAY) o.relay = env.SIGELO_RELAY;
|
|
@@ -329,6 +459,10 @@ export function optionsFromEnv(env = process.env) {
|
|
|
329
459
|
if (!retentionOk(n)) fail('relay', `SIGELO_RELAY_RETENTION_DAYS: whole days, 1 to ${RETENTION_MAX_DAYS} (the reader's tier)`);
|
|
330
460
|
o.retentionDays = n;
|
|
331
461
|
}
|
|
462
|
+
if (env.SIGELO_RELAY_TRANSPORT) {
|
|
463
|
+
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)`);
|
|
464
|
+
o.transport = env.SIGELO_RELAY_TRANSPORT;
|
|
465
|
+
}
|
|
332
466
|
return o;
|
|
333
467
|
}
|
|
334
468
|
|
|
@@ -421,6 +555,8 @@ function loadSession(s, d) {
|
|
|
421
555
|
|
|
422
556
|
const ZERO_EPOCH = new Uint8Array(16), FRAME_HEAD = 22, NONCE = 24;
|
|
423
557
|
/** The contact notice's key: HKDF-SHA256(K, salt "sigelo-notice/0", info = from ‖ "\n" ‖ to), original DIDs. */
|
|
558
|
+
// The header's "Operator hints": what `from` (an original DID) shows of operator `op`, as hex.
|
|
559
|
+
export const operatorHint = (K, kind, from, op) => hex(hmac(sha256, K, utf8ToBytes(`${OPERATOR_LABEL} ${kind}\n${from}\n${op}`)));
|
|
424
560
|
export const noticeKey = (K, from, to) => hkdf(sha256, K, utf8ToBytes('sigelo-notice/0'), utf8ToBytes(`${from}\n${to}`), 32);
|
|
425
561
|
/** The prekeys frame's key: HKDF-SHA256(K, salt "sigelo-prekeys/0", info = from ‖ "\n" ‖ to), original DIDs. */
|
|
426
562
|
export const prekeysKey = (K, from, to) => hkdf(sha256, K, utf8ToBytes('sigelo-prekeys/0'), utf8ToBytes(`${from}\n${to}`), 32);
|
|
@@ -532,13 +668,19 @@ export async function solvePow(host, original, nonce, bits, deadline = Infinity)
|
|
|
532
668
|
async function http(url, init = {}) {
|
|
533
669
|
let res;
|
|
534
670
|
const at = where(url), http = { url, method: init.method ?? 'GET' };
|
|
535
|
-
|
|
671
|
+
const t0 = Date.now();
|
|
672
|
+
try {
|
|
673
|
+
const agent = tunnelFor(url);
|
|
674
|
+
res = agent ? await viaTunnel(url, { ...init, signal: AbortSignal.timeout(HTTP_MS) }, agent) : await fetch(url, { ...init, redirect: 'manual', signal: AbortSignal.timeout(HTTP_MS) });
|
|
675
|
+
} catch (e) {
|
|
536
676
|
const why = e.name === 'TimeoutError' ? `no answer within ${HTTP_MS / 1000} s` : e.cause?.code ?? e.cause?.message ?? e.message;
|
|
537
677
|
fail('connect', `cannot reach the relay at ${at} (${why}): check the network and SIGELO_RELAY / SIGELO_RELAY_ENDPOINTS, then try again`, { cause: e, http });
|
|
538
678
|
}
|
|
539
679
|
http.status = res.status;
|
|
680
|
+
// The relay's clock (Date, whole seconds) and the round trip to it, for clockOffset.
|
|
681
|
+
const rtt = Date.now() - t0, date = Date.parse(res.headers.get('date') ?? '');
|
|
540
682
|
if ((res.status >= 300 && res.status < 400) || res.type === 'opaqueredirect') {
|
|
541
|
-
try { await res.body?.cancel(); } catch {}
|
|
683
|
+
try { await (res.body?.cancel?.() ?? res.body?.destroy?.()); } catch {}
|
|
542
684
|
fail('connect', `${at}: answered ${res.status}, a redirect, which this client does not follow`, { http });
|
|
543
685
|
}
|
|
544
686
|
if (Number(res.headers.get('content-length') ?? 0) > HTTP_MAX) fail('connect', `${at}: answer over ${HTTP_MAX} bytes`, { http });
|
|
@@ -562,7 +704,7 @@ async function http(url, init = {}) {
|
|
|
562
704
|
const after = Number(res.headers.get('retry-after'));
|
|
563
705
|
// What a refusal carries for SIGELO_DEBUG: the status and the start of the body as received.
|
|
564
706
|
http.body = new TextDecoder().decode(raw.subarray(0, 512));
|
|
565
|
-
return { status: res.status, body, retryAfter: Number.isSafeInteger(after) && after > 0 ? after : null, http };
|
|
707
|
+
return { status: res.status, body, retryAfter: Number.isSafeInteger(after) && after > 0 ? after : null, http, date: Number.isNaN(date) ? null : date, rtt };
|
|
566
708
|
}
|
|
567
709
|
|
|
568
710
|
// A URL as a refusal shows it: no query (it carries the DID), no code hash.
|
|
@@ -591,12 +733,18 @@ export function readCode(text, now, how = 'long') {
|
|
|
591
733
|
// stood for, so the refusal carries it (.long, and in its words). Not when the answer it made
|
|
592
734
|
// still stands (queued, or held by the relay: .kept) nor when the code was answered already.
|
|
593
735
|
export function keepLong(e, long) {
|
|
594
|
-
if (e?.kept || e?.check === 'mailbox_taken') return e;
|
|
736
|
+
if (e?.kept || e?.lapsed || e?.check === 'mailbox_taken') return e;
|
|
595
737
|
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 });
|
|
596
738
|
k.long = long;
|
|
597
739
|
return k;
|
|
598
740
|
}
|
|
599
741
|
|
|
742
|
+
// Whose quota a quota_storage refusal is (relay/allowance.mjs `side`), in this client's words: a
|
|
743
|
+
// contact whose own queue is full, or whose operator's Pro lapsed, must not read as a broken relay.
|
|
744
|
+
const QUOTA_SIDES = new Set(['reader', 'sender', 'relay']);
|
|
745
|
+
const quotaWhy = (r, name) => (r.code !== 'quota_storage' ? null
|
|
746
|
+
: 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)})`
|
|
747
|
+
: 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);
|
|
600
748
|
// Text a relay writes reaches the operator, and perhaps a model, inside this client's messages:
|
|
601
749
|
// quoted and cut short, so it reads as data.
|
|
602
750
|
const relaySays = (s) => `the relay says ${JSON.stringify(String(s ?? '').slice(0, 200))}`;
|
|
@@ -670,10 +818,13 @@ export function limitPackets(stream, max, cut) {
|
|
|
670
818
|
});
|
|
671
819
|
}
|
|
672
820
|
|
|
673
|
-
|
|
821
|
+
// url: mqtts://, or wss:// (MQTT over WebSocket: through the HTTPS proxy when one applies, proxyFor;
|
|
822
|
+
// a frame over the largest packet, its fixed header included, refused by ws before it is held).
|
|
823
|
+
function mqttConnect(url, creds, link, onPacket, timeout = CONNECT_MS) {
|
|
674
824
|
return new Promise((resolve, reject) => {
|
|
825
|
+
const agent = /^wss?:/.test(url) ? tunnelFor(url) : null;
|
|
675
826
|
const client = connect(url, { protocolVersion: 4, clean: false, clientId: creds.clientId, username: creds.username, password: Buffer.from(creds.password, 'utf8'),
|
|
676
|
-
reconnectPeriod: 0, connectTimeout:
|
|
827
|
+
reconnectPeriod: 0, connectTimeout: timeout, keepalive: 60, resubscribe: false, wsOptions: { maxPayload: MAX_PACKET + 5, perMessageDeflate: false, ...(agent && { agent }) } });
|
|
677
828
|
link.client = client;
|
|
678
829
|
// connect() has built the socket and nothing has arrived yet. The cut is permanent at a relay
|
|
679
830
|
// other than this agent's own (#retry, accept): it would send the same packet again.
|
|
@@ -693,6 +844,25 @@ function mqttConnect(url, creds, link, onPacket) {
|
|
|
693
844
|
});
|
|
694
845
|
}
|
|
695
846
|
|
|
847
|
+
// transport "auto": the WebSocket endpoint each MQTT endpoint fell back to, for the process lifetime,
|
|
848
|
+
// so a reconnection does not wait on 8883 first.
|
|
849
|
+
const FELL_BACK = new Map();
|
|
850
|
+
// The WebSocket endpoint of ep: relay.json's endpoints.mqtt_ws when it names the same host as ep.http
|
|
851
|
+
// over wss:// (ws:// only to loopback), else ep.ws. A relay that could name any host would send the
|
|
852
|
+
// login to it. Asked once per process and relay.
|
|
853
|
+
const WS_INFO = new Map();
|
|
854
|
+
async function wsEndpoint(ep) {
|
|
855
|
+
if (!WS_INFO.has(ep.http)) {
|
|
856
|
+
let url = ep.ws;
|
|
857
|
+
try {
|
|
858
|
+
const r = await http(`${ep.http}/relay.json`), w = new URL(r.body?.endpoints?.mqtt_ws), h = new URL(ep.http);
|
|
859
|
+
if (r.status === 200 && w.hostname === h.hostname && (w.protocol === 'wss:' || (w.protocol === 'ws:' && LOOPBACK.has(w.hostname)))) url = w.href;
|
|
860
|
+
} catch {}
|
|
861
|
+
WS_INFO.set(ep.http, url);
|
|
862
|
+
}
|
|
863
|
+
return WS_INFO.get(ep.http);
|
|
864
|
+
}
|
|
865
|
+
|
|
696
866
|
class Link {
|
|
697
867
|
constructor(relay, own) {
|
|
698
868
|
this.relay = relay; this.own = own; this.client = null; this.subscribed = new Set(); this.refused = new Map(); // topic → when refused
|
|
@@ -722,10 +892,13 @@ export class Carrier {
|
|
|
722
892
|
#links = new Map(); #work = Promise.resolve(); #busy = 0; #lastWork = 0; #routes = new Map(); #results = new Map();
|
|
723
893
|
#claimed = new Set(); #refusedTopics = new Map(); #handshakes = new Map(); #soon = new Set();
|
|
724
894
|
#started = false; #tick = null; #timers = new Map(); #attempts = new Map(); #connecting = new Set(); #powFails = new Map(); #ask = false;
|
|
895
|
+
#mineMemo = null; #clocks = new Map();
|
|
725
896
|
|
|
726
897
|
constructor({ identity, store, state, relay = DEFAULT_RELAY, endpoints = {}, retentionDays, clock = () => Math.floor(Date.now() / 1000),
|
|
727
|
-
onEvent, keep, backoff = BACKOFF, tick = TICK }) {
|
|
728
|
-
if (
|
|
898
|
+
onEvent, keep, backoff = BACKOFF, tick = TICK, files, transport = 'auto' }) {
|
|
899
|
+
if (!TRANSPORTS.includes(transport)) throw new TypeError(`transport: ${TRANSPORTS.join(', ')}`);
|
|
900
|
+
this.transport = transport;
|
|
901
|
+
if (typeof identity !== 'function') throw new TypeError('identity: a function returning { sign, bundle }');
|
|
729
902
|
if (typeof store !== 'string' || typeof state !== 'string') throw new TypeError('store, state: file paths (pathsFor(identityFile))');
|
|
730
903
|
if (retentionDays !== undefined && !retentionOk(retentionDays)) throw new TypeError(`retentionDays: 1 to ${RETENTION_MAX_DAYS}`);
|
|
731
904
|
// Not given: relay.json's at the first login to this agent's own relay may set it (#relayInfo).
|
|
@@ -735,13 +908,17 @@ export class Carrier {
|
|
|
735
908
|
if (keep !== undefined && typeof keep !== 'boolean') throw new TypeError('keep: true or false');
|
|
736
909
|
Object.assign(this, { identity, storePath: store, statePath: state, relay, endpoints, retention: retentionDays * DAY, clock, onEvent: onEvent ?? (() => {}),
|
|
737
910
|
keep: keep ?? onEvent === undefined, backoff, tick });
|
|
911
|
+
// Files received (#onFile): files, else beside the state as pathsFor names it (x.carrier.json → x.files).
|
|
912
|
+
if (files !== undefined && typeof files !== 'string') throw new TypeError('files: a directory path (pathsFor(identityFile))');
|
|
913
|
+
this.filesDir = resolve(files ?? state.replace(/(\.carrier)?\.json$/, '') + '.files');
|
|
738
914
|
}
|
|
739
915
|
|
|
740
916
|
// ---- files, under the lock
|
|
741
917
|
|
|
742
|
-
// The identity as of now: original and current DID, the current genesis and
|
|
918
|
+
// The identity as of now: original and current DID, the current genesis, and sign(body), the
|
|
919
|
+
// only way anything here signs as it.
|
|
743
920
|
#me(now) {
|
|
744
|
-
const
|
|
921
|
+
const id = this.identity(), { bundle } = id, sign = (body) => signAs(id, body);
|
|
745
922
|
let r;
|
|
746
923
|
try { r = verify(chainOf(bundle), now); } catch (e) { fail('identity', `this agent's bundle does not verify: ${e.message}`); }
|
|
747
924
|
const genesis = [bundle.genesis, ...bundle.rotations.map((x) => x.next_genesis)].find((g) => didOf(g) === r.did);
|
|
@@ -751,7 +928,7 @@ export class Carrier {
|
|
|
751
928
|
for (let i = 0; i + 1 < r.chain.length; i++) {
|
|
752
929
|
if (bundle.rotations.some((x) => x.body.id === r.chain[i] && x.body.next === r.chain[i + 1] && x.body.reason === 'recovery')) recovery = i;
|
|
753
930
|
}
|
|
754
|
-
return { did: r.chain[0], current_did: r.did,
|
|
931
|
+
return { did: r.chain[0], current_did: r.did, sign, genesis, bundle, chain: r.chain, recovery };
|
|
755
932
|
}
|
|
756
933
|
|
|
757
934
|
// The state is saved before the store's held writes (store.mjs hold: a handshake's), so a crash
|
|
@@ -759,7 +936,7 @@ export class Carrier {
|
|
|
759
936
|
#with(write, fn) {
|
|
760
937
|
return withLock(this.statePath, () => {
|
|
761
938
|
const now = checkNow(this.clock()), me = this.#me(now);
|
|
762
|
-
const ctx = { now, me, store: new Contacts(this.storePath, me.did), st: loadState(this.statePath, me.did) };
|
|
939
|
+
const ctx = { now, me, store: new Contacts(this.storePath, me.did, { mine: () => this.#mine(me, now) }), st: loadState(this.statePath, me.did) };
|
|
763
940
|
// Before anything reads the store: a recovery made by another process (sigelo-agent recover)
|
|
764
941
|
// is seen at once. The store's marks are written first; the state keeps the events.
|
|
765
942
|
if (this.#markRecovered(ctx)) saveState(this.statePath, ctx.st);
|
|
@@ -773,6 +950,24 @@ export class Carrier {
|
|
|
773
950
|
}
|
|
774
951
|
#locked(fn) { return this.#with(true, fn); }
|
|
775
952
|
|
|
953
|
+
// For tiers (store.mjs): this agent's chain, and its operators: the issuers of the unexpired
|
|
954
|
+
// sigelo-relay/operator attestations its bundle carries that verify (operator DID → exp). Kept
|
|
955
|
+
// until the bundle changes or one of them expires.
|
|
956
|
+
#mine(me, now) {
|
|
957
|
+
const key = JSON.stringify([me.chain, me.bundle.attestations ?? [], me.bundle.issuers ?? []]), m = this.#mineMemo;
|
|
958
|
+
if (m && m.key === key && now < m.until) return m.value;
|
|
959
|
+
const operators = new Map();
|
|
960
|
+
try {
|
|
961
|
+
const r = verify({ ...me.bundle, bindings: [] }, now);
|
|
962
|
+
for (const [iss, bodies] of Object.entries(r.attestations)) {
|
|
963
|
+
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));
|
|
964
|
+
}
|
|
965
|
+
} catch {}
|
|
966
|
+
const value = { chain: me.chain, operators: [...operators.keys()], exp: operators };
|
|
967
|
+
this.#mineMemo = { key, until: Math.min(Infinity, ...operators.values()), value };
|
|
968
|
+
return value;
|
|
969
|
+
}
|
|
970
|
+
|
|
776
971
|
// An answer that expired before the inviter's reply came: the accept said "waiting", so the next
|
|
777
972
|
// inbox (and contacts until then) says it failed, rather than nothing at all.
|
|
778
973
|
#lapse({ now, store, st }) {
|
|
@@ -824,7 +1019,7 @@ export class Carrier {
|
|
|
824
1019
|
#restore(st, store, me, did) {
|
|
825
1020
|
const c = store.lookup(did);
|
|
826
1021
|
if (!c || c.revoked || !c.pair_key) return null;
|
|
827
|
-
const s = session({ me: { did: me.did, current_did: me.current_did,
|
|
1022
|
+
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 });
|
|
828
1023
|
const d = st.peers[c.did]?.session;
|
|
829
1024
|
// A session of an earlier pairing key belongs to a pairing that was replaced: start afresh.
|
|
830
1025
|
if (d && d.pair === s.pair) loadSession(s, d);
|
|
@@ -1019,7 +1214,7 @@ export class Carrier {
|
|
|
1019
1214
|
let n;
|
|
1020
1215
|
try { n = parseBytes(bytes); } catch { return; }
|
|
1021
1216
|
if (n === null || typeof n !== 'object' || typeof n.code !== 'string') return;
|
|
1022
|
-
const note = { code: n.code.slice(0, 64), detail: typeof n.detail === 'string' ? n.detail.slice(0, 200) : '' };
|
|
1217
|
+
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 }) };
|
|
1023
1218
|
// id: the packet id of the PUBLISH a refusal names (#publish), kept out of events.
|
|
1024
1219
|
if (link.collect) link.collect.push(Number.isSafeInteger(n.id) ? { ...note, id: n.id } : note);
|
|
1025
1220
|
else this.#emit({ type: 'notice', relay: link.relay, ...note });
|
|
@@ -1060,6 +1255,16 @@ export class Carrier {
|
|
|
1060
1255
|
st.dropped[e.check] = (st.dropped[e.check] ?? 0) + 1;
|
|
1061
1256
|
events.push({ type: 'dropped', check: e.check, detail: e.message });
|
|
1062
1257
|
}
|
|
1258
|
+
} else if (r.body.label === FILE_LABEL) {
|
|
1259
|
+
// A file's manifest or chunk (file.mjs): kept apart until the file is whole (#onFile).
|
|
1260
|
+
events.push(...this.#onFile(ctx, c, r, now));
|
|
1261
|
+
} else if (r.body.label === OPERATOR_LABEL) {
|
|
1262
|
+
// Operator hints, asks and proofs (the header): taken here, never an inbox message. One refused is counted.
|
|
1263
|
+
try { events.push(...this.#onOperator(ctx, c, r.body.content)); } catch (e) {
|
|
1264
|
+
if (!(e instanceof MsgError)) throw e;
|
|
1265
|
+
st.dropped[e.check] = (st.dropped[e.check] ?? 0) + 1;
|
|
1266
|
+
events.push({ type: 'dropped', check: e.check, detail: e.message });
|
|
1267
|
+
}
|
|
1063
1268
|
} else {
|
|
1064
1269
|
// last_resort: the epoch began on the last-resort prekey, which may serve many epochs: weaker
|
|
1065
1270
|
// forward secrecy (plan §3 "Prekeys"), and routine for a while after a rotation (#next).
|
|
@@ -1075,6 +1280,170 @@ export class Carrier {
|
|
|
1075
1280
|
return events;
|
|
1076
1281
|
}
|
|
1077
1282
|
|
|
1283
|
+
// The header's "Operator hints". Hints of contact c's operators: those this agent knows (its own
|
|
1284
|
+
// operators, or itself) are asked for, once per set. Asks: proofs of this agent's operators the
|
|
1285
|
+
// contact showed it knows, once per set. A proof: c's chain with operator attestations, filed.
|
|
1286
|
+
// Answers go first in c's outbox. → events: `tier` when c's tier changed.
|
|
1287
|
+
#onOperator({ now, me, store, st }, c, v) {
|
|
1288
|
+
const K = hexToBytes(c.pair_key), e = this.#entry(st, c.did), mine = this.#mine(me, now);
|
|
1289
|
+
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'));
|
|
1290
|
+
if (v?.hints !== undefined) {
|
|
1291
|
+
const hints = list(v.hints), known = [...mine.operators, ...mine.chain].filter((d) => hints.includes(operatorHint(K, 'hint', c.did, d))).sort();
|
|
1292
|
+
// Again for the same operators at most every RESYNC: the contact hints anew once their
|
|
1293
|
+
// attestations are renewed (#next), and its proof must come again before the old one lapses.
|
|
1294
|
+
if (known.length > 0 && (e.op_asked !== known.join() || now - (e.op_asked_at ?? 0) >= RESYNC)) {
|
|
1295
|
+
e.op_asked = known.join(); e.op_asked_at = now;
|
|
1296
|
+
e.outbox.unshift({ id: randomId(), label: OPERATOR_LABEL, content: { asks: known.map((d) => operatorHint(K, 'ask', me.did, d)) } });
|
|
1297
|
+
}
|
|
1298
|
+
return [];
|
|
1299
|
+
}
|
|
1300
|
+
if (v?.asks !== undefined) {
|
|
1301
|
+
// Proved again once an attestation shown is renewed (its expiry is in the key).
|
|
1302
|
+
const asks = list(v.asks), shown = mine.operators.filter((d) => asks.includes(operatorHint(K, 'ask', c.did, d))).sort(), key = opKey(mine, shown);
|
|
1303
|
+
if (shown.length > 0 && e.op_proved !== key) {
|
|
1304
|
+
e.op_proved = key;
|
|
1305
|
+
const b = me.bundle, iss = new Set(shown);
|
|
1306
|
+
const proof = { v: b.v, typ: 'bundle', genesis: b.genesis, rotations: b.rotations, bindings: [],
|
|
1307
|
+
attestations: (b.attestations ?? []).filter((a) => a?.body?.ctx === OPERATOR_CTX && iss.has(a.body.iss)), issuers: (b.issuers ?? []).filter((g) => iss.has(didOf(g))) };
|
|
1308
|
+
e.outbox.unshift({ id: randomId(), label: OPERATOR_LABEL, content: { proof } });
|
|
1309
|
+
}
|
|
1310
|
+
return [];
|
|
1311
|
+
}
|
|
1312
|
+
if (v?.proof !== undefined) {
|
|
1313
|
+
// Only in answer to asks of ours, and so many an hour: each costs SPEC §9 (THREAT-MODEL §2.12).
|
|
1314
|
+
if (!e.op_asked) fail('operator', 'an operator proof nobody asked for');
|
|
1315
|
+
const recent = (e.op_checks ?? []).filter((x) => x > now - RESYNC);
|
|
1316
|
+
if (recent.length >= NOTICE_CHECKS) fail('operator_rate', `${recent.length} operator proofs of this contact checked within ${RESYNC} s, the most`);
|
|
1317
|
+
e.op_checks = [...recent, now];
|
|
1318
|
+
const p = v.proof;
|
|
1319
|
+
if (![p?.rotations, p?.attestations, p?.issuers].every(Array.isArray) || p.rotations.length > MAX_ROTATIONS || p.attestations.length > 8 || p.issuers.length > 8) {
|
|
1320
|
+
fail('operator', `an operator proof is a bundle of at most ${MAX_ROTATIONS} rotations, 8 attestations and 8 issuers`);
|
|
1321
|
+
}
|
|
1322
|
+
let r;
|
|
1323
|
+
try { r = verify(p, now); } catch (err) { fail('operator', `the contact's operator proof does not verify: ${err.message}`); }
|
|
1324
|
+
if (r.chain[0] !== c.did) fail('operator', 'the operator proof is not the chain of the contact that sent it');
|
|
1325
|
+
// store.observe refuses a chain that ends anywhere but the contact's current DID (current_did).
|
|
1326
|
+
const before = store.tierOf(c, now), after = store.observe(c.did, r, now);
|
|
1327
|
+
return after === before ? [] : [{ type: 'tier', did: c.did, name: c.name, tier: after }];
|
|
1328
|
+
}
|
|
1329
|
+
fail('operator', 'an operator message is {hints}, {asks} or {proof}');
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
// ---- files (file.mjs; design/human-ui-plan.md §4)
|
|
1333
|
+
|
|
1334
|
+
// A FILE_LABEL message from contact c, opened (r). The manifest is kept in the state (files,
|
|
1335
|
+
// under a key of the contact and the file's id), each chunk under filesDir/.partial/<key>/<i>
|
|
1336
|
+
// (0600, directories 0700); once all have come, the file is checked (size, SHA-256), saved as
|
|
1337
|
+
// filesDir/<contact>/<sha256[0..8]>-<name> (0600), and given to inbox() as one item of type
|
|
1338
|
+
// "file". Never opened, never made executable. Anything wrong with the message is counted in
|
|
1339
|
+
// dropped by its check, as a refused bundle is above; the envelope stays opened either way.
|
|
1340
|
+
// A chunk before its manifest (none: the sender sends the manifest first, in one login) is
|
|
1341
|
+
// dropped, file_chunk. The disk is written before the state: a crash between them leaves a
|
|
1342
|
+
// chunk that the delivery, unacknowledged, writes again.
|
|
1343
|
+
#onFile(ctx, c, r, now) {
|
|
1344
|
+
const { st } = ctx, content = r.body.content;
|
|
1345
|
+
st.files ??= {};
|
|
1346
|
+
const drop = (e) => {
|
|
1347
|
+
if (!(e instanceof MsgError)) throw e;
|
|
1348
|
+
st.dropped[e.check] = (st.dropped[e.check] ?? 0) + 1;
|
|
1349
|
+
return [{ type: 'dropped', check: e.check, detail: `a file from ${c.name}: ${e.message}` }];
|
|
1350
|
+
};
|
|
1351
|
+
const keyOf = (id) => hex(sha256(utf8ToBytes(`${c.did}\n${id}`)).subarray(0, 16));
|
|
1352
|
+
let key, p;
|
|
1353
|
+
try {
|
|
1354
|
+
if (isManifest(content)) {
|
|
1355
|
+
const m = checkManifest(content);
|
|
1356
|
+
key = keyOf(m.id);
|
|
1357
|
+
const had = st.files[key];
|
|
1358
|
+
if (had) {
|
|
1359
|
+
if (had.sha256 !== m.sha256 || had.size !== m.size) fail('file', 'a second manifest for one file id, with another content');
|
|
1360
|
+
return [];
|
|
1361
|
+
}
|
|
1362
|
+
// At most FILES_OPEN files arriving at once per contact: each holds up to 8 MiB here.
|
|
1363
|
+
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`);
|
|
1364
|
+
p = st.files[key] = { from: c.did, ...m, got: [], first: now };
|
|
1365
|
+
} else {
|
|
1366
|
+
const h = chunkHead(content);
|
|
1367
|
+
key = keyOf(h.id);
|
|
1368
|
+
p = st.files[key] ?? fail('file_chunk', 'a chunk of a file whose manifest has not come');
|
|
1369
|
+
const bytes = checkChunk(content, p);
|
|
1370
|
+
if (!p.got.includes(h.i)) {
|
|
1371
|
+
const dir = this.#partDir(key);
|
|
1372
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
1373
|
+
writeFileSync(join(dir, String(h.i)), bytes, { mode: 0o600 });
|
|
1374
|
+
p.got.push(h.i);
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
} catch (e) { return drop(e); }
|
|
1378
|
+
if (p.got.length < p.chunks) return [];
|
|
1379
|
+
// Whole: checked, saved, and the parts gone whatever the check said.
|
|
1380
|
+
let bytes;
|
|
1381
|
+
try {
|
|
1382
|
+
bytes = assemble(p, Array.from({ length: p.chunks }, (_, i) => readFileSync(join(this.#partDir(key), String(i)))));
|
|
1383
|
+
} catch (e) {
|
|
1384
|
+
delete st.files[key];
|
|
1385
|
+
rmSync(this.#partDir(key), { recursive: true, force: true });
|
|
1386
|
+
return drop(e);
|
|
1387
|
+
}
|
|
1388
|
+
const dir = join(this.filesDir, safeName(c.name || c.did));
|
|
1389
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
1390
|
+
chmodSync(this.filesDir, 0o700); chmodSync(dir, 0o700);
|
|
1391
|
+
const path = join(dir, `${p.sha256.slice(0, 8)}-${p.name}`), tmp = join(dir, `.${randomId()}.tmp`);
|
|
1392
|
+
writeFileSync(tmp, bytes, { mode: 0o600, flag: 'wx' });
|
|
1393
|
+
renameSync(tmp, path);
|
|
1394
|
+
delete st.files[key];
|
|
1395
|
+
rmSync(this.#partDir(key), { recursive: true, force: true });
|
|
1396
|
+
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,
|
|
1397
|
+
iat: r.body.iat, received: now, last_resort: r.last_resort };
|
|
1398
|
+
// Kept for inbox() as a message is (#onPeer), and so many at most.
|
|
1399
|
+
if (this.keep) {
|
|
1400
|
+
st.inbox.push(item);
|
|
1401
|
+
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; }
|
|
1402
|
+
}
|
|
1403
|
+
return [item];
|
|
1404
|
+
}
|
|
1405
|
+
|
|
1406
|
+
#partDir(key) { return join(this.filesDir, '.partial', key); }
|
|
1407
|
+
|
|
1408
|
+
// A file's chunks wait in filesDir/.out/<item id>.json (0600, directory 0700), not in the state:
|
|
1409
|
+
// base64 in an outbox item, 8 MiB were rewritten with the state at every chunk sent. The outbox
|
|
1410
|
+
// item keeps { id, label, spool: true }. A contact's name never starts with a dot (safeName), so
|
|
1411
|
+
// .out is no contact's directory. Written under the lock with the items that name them.
|
|
1412
|
+
#spoolDir() { return join(this.filesDir, '.out'); }
|
|
1413
|
+
#spool(id, content) {
|
|
1414
|
+
const dir = this.#spoolDir();
|
|
1415
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
1416
|
+
chmodSync(this.filesDir, 0o700); chmodSync(dir, 0o700);
|
|
1417
|
+
writeFileSync(join(dir, `${id}.json`), JSON.stringify(content), { mode: 0o600, flag: 'wx' });
|
|
1418
|
+
}
|
|
1419
|
+
#spooled(id) {
|
|
1420
|
+
try { return JSON.parse(readFileSync(join(this.#spoolDir(), `${id}.json`), 'utf8')); } catch (e) {
|
|
1421
|
+
fail('file', `a queued part of a file is gone from ${this.#spoolDir()} (${e.code ?? e.message}): send the file again`);
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
// Spooled parts no outbox or pending entry names any more (sent, refused, forgotten): removed.
|
|
1425
|
+
#sweepSpool(st) {
|
|
1426
|
+
let names;
|
|
1427
|
+
try { names = readdirSync(this.#spoolDir()); } catch { return; }
|
|
1428
|
+
const held = new Set();
|
|
1429
|
+
for (const e of Object.values(st.peers)) for (const x of e.outbox ?? []) if (x.spool) held.add(x.id);
|
|
1430
|
+
for (const p of st.pending) if (p.item?.spool) held.add(p.item.id);
|
|
1431
|
+
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 });
|
|
1432
|
+
}
|
|
1433
|
+
|
|
1434
|
+
// Files still incomplete after the retention (the relay has dropped whatever of them was left to
|
|
1435
|
+
// come): their parts go, counted file_incomplete, and inbox() says which.
|
|
1436
|
+
#sweepFiles(st, now) {
|
|
1437
|
+
for (const [key, p] of Object.entries(st.files ?? {})) {
|
|
1438
|
+
if (p.first + this.retention > now) continue;
|
|
1439
|
+
rmSync(this.#partDir(key), { recursive: true, force: true });
|
|
1440
|
+
delete st.files[key];
|
|
1441
|
+
st.dropped.file_incomplete = (st.dropped.file_incomplete ?? 0) + 1;
|
|
1442
|
+
this.#emit(this.#note(st, now, { type: 'dropped', check: 'file_incomplete', from: p.from,
|
|
1443
|
+
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` }));
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1078
1447
|
// A bundle from the contact was accepted into s (acceptPrekeys). want: it asked for ours, which
|
|
1079
1448
|
// goes unless one went within RESYNC (the header's "Prekeys").
|
|
1080
1449
|
#tookPrekeys(st, s, want, now) {
|
|
@@ -1253,9 +1622,9 @@ export class Carrier {
|
|
|
1253
1622
|
const c = store.lookup(res.did), K = hexToBytes(res.pair_key);
|
|
1254
1623
|
// What checkAnswer replaced, put back if the reply cannot reach the answerer (#unpair).
|
|
1255
1624
|
const undo = { contact: before[c.did] ?? null, peer: st.peers[c.did] ?? null };
|
|
1256
|
-
const s = session({ me: { did: me.did, current_did: me.current_did,
|
|
1257
|
-
const prekeys = s.in.prekeys.issue({ current_did: me.current_did,
|
|
1258
|
-
const reply = buildReply({ answer_id: res.answer_id, identity: {
|
|
1625
|
+
const s = session({ me: { did: me.did, current_did: me.current_did, sign: me.sign }, peer: c, K });
|
|
1626
|
+
const prekeys = s.in.prekeys.issue({ current_did: me.current_did, sign: me.sign }, s.pair, now);
|
|
1627
|
+
const reply = buildReply({ answer_id: res.answer_id, identity: { sign: me.sign, genesis: me.genesis }, bundle: chainOf(me.bundle), kem_ct: ct, prekeys });
|
|
1259
1628
|
const frame = seal(KIND.invite_reply, keys.key, keys.reply_topic, reply);
|
|
1260
1629
|
const entry = { relay: p.relay, topic: keys.reply_topic, kind: KIND.invite_reply, control: 'reply', peer: c.did, undo,
|
|
1261
1630
|
needs: [topic(K, c.did, me.did, isoWeek(now))], exp: p.exp };
|
|
@@ -1329,7 +1698,7 @@ export class Carrier {
|
|
|
1329
1698
|
// An entry written before `as` was kept: unknown, so the notice goes (#next `first`).
|
|
1330
1699
|
const answered = waiting.find(([x]) => x === id)[1], held = answered.as ?? null;
|
|
1331
1700
|
const c = renamed(store, store.lookup(res.did), answered);
|
|
1332
|
-
const s = session({ me: { did: me.did, current_did: me.current_did,
|
|
1701
|
+
const s = session({ me: { did: me.did, current_did: me.current_did, sign: me.sign }, peer: c, K: hexToBytes(res.pair_key) });
|
|
1333
1702
|
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) })];
|
|
1334
1703
|
try { acceptPrekeys(s, reply.prekeys, now); } catch (e) {
|
|
1335
1704
|
if (!(e instanceof MsgError)) throw e;
|
|
@@ -1401,7 +1770,7 @@ export class Carrier {
|
|
|
1401
1770
|
e.announced = me.current_did;
|
|
1402
1771
|
e.noticed = now;
|
|
1403
1772
|
e.notice_asked = false;
|
|
1404
|
-
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(
|
|
1773
|
+
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) } }),
|
|
1405
1774
|
kind: KIND_NOTICE, peer: c.did, control: 'notice' });
|
|
1406
1775
|
}
|
|
1407
1776
|
if (c.re_pair) {
|
|
@@ -1430,10 +1799,16 @@ export class Carrier {
|
|
|
1430
1799
|
if (missing !== null) e.asked = now;
|
|
1431
1800
|
return this.#queue(st, { relay, topic: t, bytes: frame, kind: KIND_PREKEYS, peer: c.did, control: 'prekeys' });
|
|
1432
1801
|
}
|
|
1802
|
+
// This agent's operator hints, once per pairing and set of operators (#onOperator).
|
|
1803
|
+
const mine = this.#mine(me, now), ops = mine.operators, hinted = opKey(mine, ops);
|
|
1804
|
+
if (ops.length > 0 && e.op_hinted !== hinted) {
|
|
1805
|
+
e.op_hinted = hinted;
|
|
1806
|
+
e.outbox.unshift({ id: randomId(), label: OPERATOR_LABEL, content: { hints: [...ops].sort().map((d) => operatorHint(K, 'hint', me.did, d)) } });
|
|
1807
|
+
}
|
|
1433
1808
|
while (e.outbox.length > 0) {
|
|
1434
1809
|
const item = e.outbox[0];
|
|
1435
1810
|
try {
|
|
1436
|
-
const m = send(s, { label: item.label, content: item.content }, now);
|
|
1811
|
+
const m = send(s, { label: item.label, content: item.spool ? this.#spooled(item.id) : item.content }, now);
|
|
1437
1812
|
e.outbox.shift();
|
|
1438
1813
|
if (e.waiting === noReader(c.name)) e.waiting = null;
|
|
1439
1814
|
this.#persist(st, s);
|
|
@@ -1520,6 +1895,10 @@ export class Carrier {
|
|
|
1520
1895
|
}
|
|
1521
1896
|
|
|
1522
1897
|
async #flush(link) {
|
|
1898
|
+
try { await this.#flushing(link); } finally { try { this.#locked(({ st }) => this.#sweepSpool(st)); } catch {} }
|
|
1899
|
+
}
|
|
1900
|
+
|
|
1901
|
+
async #flushing(link) {
|
|
1523
1902
|
for (;;) {
|
|
1524
1903
|
if (!link.up) return;
|
|
1525
1904
|
const e = this.#locked((ctx) => this.#next(ctx, link));
|
|
@@ -1538,7 +1917,7 @@ export class Carrier {
|
|
|
1538
1917
|
const back = r?.code === 'no_reader' && e.kind === KIND.message && e.item !== undefined;
|
|
1539
1918
|
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
|
|
1540
1919
|
this.#emit(back ? { type: 'queued', id: e.id, peer: e.peer, code: r.code, detail: r.detail }
|
|
1541
|
-
: 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 });
|
|
1920
|
+
: 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 });
|
|
1542
1921
|
// A refusal stops this round: what follows would be refused alike (a quota, the rate brake),
|
|
1543
1922
|
// and a control frame would be queued again at once. The next round retries. A mailbox
|
|
1544
1923
|
// nobody holds stops only what goes to that contact (absent, #next).
|
|
@@ -1659,6 +2038,7 @@ export class Carrier {
|
|
|
1659
2038
|
const { me, proven } = this.#read(({ me, st }) => ({ me, proven: st.relays[relay]?.proven === true }));
|
|
1660
2039
|
const powMax = relay === this.relay ? POW_MAX : POW_MAX_OTHER;
|
|
1661
2040
|
const r = await http(`${ep.http}/challenge?did=${encodeURIComponent(me.current_did)}`);
|
|
2041
|
+
this.#clockFrom(relay, r);
|
|
1662
2042
|
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);
|
|
1663
2043
|
// Any other status is no answer about this agent (nginx says 502 while the relay restarts):
|
|
1664
2044
|
// `connect`, retried. `challenge`, which no retry fixes, is a 200 that is not this relay's
|
|
@@ -1674,7 +2054,7 @@ export class Carrier {
|
|
|
1674
2054
|
if (ch.relay !== relay) fail('challenge', `relay ${JSON.stringify(ch.relay)} is not this relay's name, ${relay}`);
|
|
1675
2055
|
// Signed as built here, never as received; its typ is one no challenge signer produces (a SPEC
|
|
1676
2056
|
// §5.2 challenge for this relay, got by a world from sign-challenge, logs in nobody).
|
|
1677
|
-
const body = { v: LOGIN_V, typ: TYP_LOGIN, did: me.current_did, relay, nonce: ch.nonce }, sig = sign(
|
|
2057
|
+
const body = { v: LOGIN_V, typ: TYP_LOGIN, did: me.current_did, relay, nonce: ch.nonce }, sig = me.sign(body);
|
|
1678
2058
|
if (!verifySig(me.genesis.key, body, sig)) fail('identity', 'this agent\'s secret does not match its current genesis key');
|
|
1679
2059
|
if (canonicalize(body) !== canonicalize(ch)) fail('challenge', 'not the login body this agent signs');
|
|
1680
2060
|
let pow;
|
|
@@ -1714,6 +2094,7 @@ export class Carrier {
|
|
|
1714
2094
|
this.#ask = false;
|
|
1715
2095
|
try {
|
|
1716
2096
|
const r = await http(`${ep.http}/relay.json`);
|
|
2097
|
+
this.#clockFrom(this.relay, r);
|
|
1717
2098
|
const n = r.status === 200 ? retentionOf(r.body) : null;
|
|
1718
2099
|
if (n !== null) this.retention = n * DAY;
|
|
1719
2100
|
} catch {}
|
|
@@ -1721,13 +2102,46 @@ export class Carrier {
|
|
|
1721
2102
|
|
|
1722
2103
|
get retentionDays() { return this.retention / DAY; }
|
|
1723
2104
|
|
|
2105
|
+
// The relay's clock less this agent's (this.clock), in seconds, from an answer r of relay: its
|
|
2106
|
+
// Date header (whole seconds, so +0.5) taken as of the middle of the round trip.
|
|
2107
|
+
#clockFrom(relay, r) {
|
|
2108
|
+
if (r?.date == null) return;
|
|
2109
|
+
const now = this.clock();
|
|
2110
|
+
this.#clocks.set(relay, { offset: Math.round((r.date + 500 - r.rtt / 2) / 1000 - now), checked: now });
|
|
2111
|
+
}
|
|
2112
|
+
|
|
2113
|
+
/** { relay, offset, checked } as last measured at relay (a login, relay.json, a short code), or null. offset: seconds, relay minus local. */
|
|
2114
|
+
clockOffset(relay = this.relay) {
|
|
2115
|
+
const c = this.#clocks.get(relay);
|
|
2116
|
+
return c ? { relay, ...c } : null;
|
|
2117
|
+
}
|
|
2118
|
+
|
|
2119
|
+
/** Measures the offset now at this agent's own relay (GET /relay.json). → clockOffset(); throws as a relay that does not answer does. */
|
|
2120
|
+
async checkClock() {
|
|
2121
|
+
this.#clockFrom(this.relay, await http(`${endpointOf(this.relay, this.endpoints).http}/relay.json`));
|
|
2122
|
+
return this.clockOffset();
|
|
2123
|
+
}
|
|
2124
|
+
|
|
1724
2125
|
async #dial(relay) {
|
|
1725
2126
|
const ep = endpointOf(relay, this.endpoints), link = new Link(relay, relay === this.relay);
|
|
1726
2127
|
const info = link.own && this.#ask ? this.#relayInfo(ep) : null;
|
|
1727
2128
|
const creds = await this.#credentials(relay, ep);
|
|
1728
2129
|
await info;
|
|
2130
|
+
// The transport (the header's "Transport"): auto tries ep.mqtt for PROBE_MS, then the WebSocket
|
|
2131
|
+
// endpoint, and keeps to it for the rest of the process (FELL_BACK). Only a dial that got no
|
|
2132
|
+
// CONNACK at all falls back: a refusal by name (its return code) is the relay's answer, on
|
|
2133
|
+
// either transport. Both are TLS; nothing falls back to a plain connection.
|
|
2134
|
+
const onPacket = (packet) => this.#onPacket(link, packet);
|
|
2135
|
+
const probe = this.transport === 'auto' && !FELL_BACK.has(ep.mqtt) && /^mqtts?:/.test(ep.mqtt);
|
|
2136
|
+
let url = this.transport === 'wss' ? await wsEndpoint(ep) : this.transport === 'auto' ? FELL_BACK.get(ep.mqtt) ?? ep.mqtt : ep.mqtt;
|
|
1729
2137
|
// A cut connection is this client's own refusal: no POST /check may rename it.
|
|
1730
|
-
try { await mqttConnect(
|
|
2138
|
+
try { await mqttConnect(url, creds, link, onPacket, probe ? PROBE_MS : CONNECT_MS); } catch (e) {
|
|
2139
|
+
if (!probe || link.cut || typeof e.code === 'number') throw link.cut ?? await named(ep, creds, e);
|
|
2140
|
+
url = await wsEndpoint(ep);
|
|
2141
|
+
try { await mqttConnect(url, creds, link, onPacket); } catch (e2) { throw link.cut ?? await named(ep, creds, e2); }
|
|
2142
|
+
FELL_BACK.set(ep.mqtt, url);
|
|
2143
|
+
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` });
|
|
2144
|
+
}
|
|
1731
2145
|
// A close right after CONNACK (a cut in the same read) reached no listener of this connection.
|
|
1732
2146
|
if (!link.client.connected) throw link.cut ?? new MsgError('connect', 'the relay closed the connection');
|
|
1733
2147
|
// Deliveries are counted from here (quiet), not from before the login: a proof-of-work search
|
|
@@ -1907,6 +2321,25 @@ export class Carrier {
|
|
|
1907
2321
|
return r.body.invite;
|
|
1908
2322
|
}
|
|
1909
2323
|
|
|
2324
|
+
// A gift code redeemed at this agent's own relay (POST /gift, relay/gifts.mjs): the relay gets the
|
|
2325
|
+
// code's hash (short.mjs giftHash), never the code, with a login of its own; the identity logged
|
|
2326
|
+
// in becomes the operator whose pool is Pro. A malformed code is refused here, before any login.
|
|
2327
|
+
async redeemGift(text) {
|
|
2328
|
+
const hash = giftHash(text), ep = endpointOf(this.relay, this.endpoints);
|
|
2329
|
+
const creds = await this.#credentials(this.relay, ep);
|
|
2330
|
+
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 }) });
|
|
2331
|
+
this.#clockFrom(this.relay, r);
|
|
2332
|
+
const check = typeof r.body?.check === 'string' ? r.body.check : null;
|
|
2333
|
+
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);
|
|
2334
|
+
if ((r.status === 404 || r.status === 405) && check === null) refuse('gift', `the relay ${this.relay} takes no gift codes`, r);
|
|
2335
|
+
if (r.status !== 200) refuse('connect', `${this.relay}: ${statusWhy(r, 'POST /gift')}`, r);
|
|
2336
|
+
if (r.body?.ok !== true) refuse(GIFT_CHECKS.has(check) ? check : 'gift', `the relay refused the gift code (${relaySays(`${check}: ${r.body?.detail}`)})`, r);
|
|
2337
|
+
// A proof sent with this login was taken: the identity is stored there now, as after a session.
|
|
2338
|
+
if (creds.pow !== undefined) this.#locked(({ st }) => { (st.relays[this.relay] ??= { proven: false, claims: {} }).proven = true; });
|
|
2339
|
+
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);
|
|
2340
|
+
return { exp: r.body.exp, months: r.body.months };
|
|
2341
|
+
}
|
|
2342
|
+
|
|
1910
2343
|
async accept(text, opts = {}) {
|
|
1911
2344
|
// Short or long by the input's shape, before either parser runs (short.mjs codeKind).
|
|
1912
2345
|
const how = codeKind(text) === 'short' ? 'parked' : 'long';
|
|
@@ -1915,7 +2348,8 @@ export class Carrier {
|
|
|
1915
2348
|
try { return await this.#answer(long, how, opts); } catch (e) { throw keepLong(e, long); }
|
|
1916
2349
|
}
|
|
1917
2350
|
|
|
1918
|
-
async #answer(text, how, { name, wait = 10 } = {}) {
|
|
2351
|
+
async #answer(text, how, { name, wait = 10, tier } = {}) {
|
|
2352
|
+
if (tier !== undefined && !TIERS.includes(tier)) fail('tier', `a tier is ${TIERS.join(', ')}; not ${JSON.stringify(tier)}`);
|
|
1919
2353
|
const { code, id, entry } = this.#locked(({ now, me, store, st }) => {
|
|
1920
2354
|
const code = readCode(text, now, how);
|
|
1921
2355
|
// This agent's own relay, and those its operator configured, are the operator's choice.
|
|
@@ -1924,14 +2358,14 @@ export class Carrier {
|
|
|
1924
2358
|
}
|
|
1925
2359
|
const k = kemKey();
|
|
1926
2360
|
try {
|
|
1927
|
-
const answer = buildAnswer({ code, identity: {
|
|
2361
|
+
const answer = buildAnswer({ code, identity: { sign: me.sign, genesis: me.genesis }, bundle: chainOf(me.bundle), kem_pk: k.pk, prekeys: null });
|
|
1928
2362
|
const keys = inviteKeys(code.secret), frame = seal(KIND.invite_answer, keys.key, keys.answer_topic, answer);
|
|
1929
2363
|
// Checked before anything is stored: the relay would refuse it (quota_storage).
|
|
1930
2364
|
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`);
|
|
1931
2365
|
const id = answerId(answer);
|
|
1932
2366
|
// Unnamed: the code's DID's first digits ("z5esAbCd"), as operators shorten a DID. Named, the
|
|
1933
2367
|
// name also replaces a known contact's on a re-pair (#onReply).
|
|
1934
|
-
store.addAccept(code, id, name ?? code.did.slice('did:sigelo:'.length, 'did:sigelo:'.length + 8), now, hex(k.secretKey), me.current_did, name !== undefined);
|
|
2368
|
+
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);
|
|
1935
2369
|
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 });
|
|
1936
2370
|
return { code, id, entry: entry.id };
|
|
1937
2371
|
} finally { k.secretKey.fill(0); }
|
|
@@ -1944,7 +2378,8 @@ export class Carrier {
|
|
|
1944
2378
|
// Done early too once the reply topic or the answer is refused (a code answered before:
|
|
1945
2379
|
// mailbox_taken), not after the whole wait.
|
|
1946
2380
|
const reply = inviteKeys(code.secret).reply_topic;
|
|
1947
|
-
|
|
2381
|
+
// And once the code expires (#lapse): the answer is dead, so --wait does not run out first.
|
|
2382
|
+
const settled = () => this.#handshakes.has(id) || this.#refusedTopics.has(reply) || Boolean(this.#results.get(entry)?.code) || this.clock() >= code.exp;
|
|
1948
2383
|
try { await this.#session([code.relay], { max: wait * 1000, until: settled }); } catch (e) {
|
|
1949
2384
|
// A relay other than this agent's own that refuses it for good would be dialled again at
|
|
1950
2385
|
// every connection, until the code expires, for an answer it never takes: and a stranger's
|
|
@@ -1975,16 +2410,47 @@ export class Carrier {
|
|
|
1975
2410
|
: `the relay did not let this agent claim the reply topic (${relaySays(r.detail)})`);
|
|
1976
2411
|
}
|
|
1977
2412
|
if (sent?.code) drop(sent.code, `the relay refused the answer (${relaySays(sent.detail)})`);
|
|
2413
|
+
// The code expired during the wait: #lapse emitted pairing_failed (onEvent); the refusal says
|
|
2414
|
+
// it here, so the next inbox does not say it again. No long code to keep (keepLong): it is dead.
|
|
2415
|
+
const lapsed = this.#locked(({ now, store, st }) => {
|
|
2416
|
+
if (now < code.exp) return null;
|
|
2417
|
+
st.pending = st.pending.filter((p) => p.id !== entry); store.take('accepts', id, now);
|
|
2418
|
+
const at = new Date(code.exp * 1000).toISOString().replace('.000', '');
|
|
2419
|
+
const i = st.events.findIndex((e) => e.type === 'pairing_failed' && e.code === 'code_expired' && e.did === code.did && e.detail?.includes(at));
|
|
2420
|
+
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`;
|
|
2421
|
+
});
|
|
2422
|
+
if (lapsed) throw Object.assign(new MsgError('code_expired', lapsed), { lapsed: true });
|
|
1978
2423
|
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' };
|
|
1979
2424
|
return { status: 'waiting', did: code.did, relay: code.relay, detail: 'answer delivered; the pairing completes when the inviter\'s agent next connects' };
|
|
1980
2425
|
}
|
|
1981
2426
|
|
|
2427
|
+
// An invite this agent made and nobody has answered, withdrawn: code, its long code (invite's
|
|
2428
|
+
// `code`). Its answer topic is given up at the next round; a short code parked for it leads to
|
|
2429
|
+
// nothing. → { cancelled: true, name }.
|
|
2430
|
+
async cancelInvite(code) {
|
|
2431
|
+
const { relay, name } = this.#locked(({ now, store }) => {
|
|
2432
|
+
const c = readCode(code, now), p = store.load().s.invites[c.nonce];
|
|
2433
|
+
store.cancelInvite(c.nonce);
|
|
2434
|
+
return { relay: c.relay, name: p.name };
|
|
2435
|
+
});
|
|
2436
|
+
this.#routes = new Map();
|
|
2437
|
+
if (this.#links.get(relay)?.up) this.#refreshSoon(relay);
|
|
2438
|
+
return { cancelled: true, name };
|
|
2439
|
+
}
|
|
2440
|
+
|
|
2441
|
+
/** The owner renames a contact (a name or any DID of its chain; store.mjs rename) → { did, name }. */
|
|
2442
|
+
rename(who, name) { return this.#locked(({ store }) => store.rename(who, name)); }
|
|
2443
|
+
|
|
1982
2444
|
contacts() {
|
|
1983
2445
|
return this.#read(({ now, store, st }) => {
|
|
1984
2446
|
const s = store.load().s;
|
|
1985
2447
|
return {
|
|
1986
|
-
contacts: Object.values(s.contacts).map((c) =>
|
|
1987
|
-
|
|
2448
|
+
contacts: Object.values(s.contacts).map((c) => {
|
|
2449
|
+
const e = st.peers[c.did], pair = c.revoked || !c.pair_key ? null : pairId(hexToBytes(c.pair_key));
|
|
2450
|
+
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,
|
|
2451
|
+
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,
|
|
2452
|
+
prekeys: pair !== null && theirPrekeys(c, e?.session, pair, now), waiting: e?.waiting ?? null };
|
|
2453
|
+
}),
|
|
1988
2454
|
invites: Object.values(s.invites).filter((p) => p.exp > now).map((p) => ({ name: p.name, exp: p.exp, relay: p.relay })),
|
|
1989
2455
|
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 })),
|
|
1990
2456
|
// Pairings that failed since the last inbox, which takes them as events.
|
|
@@ -1993,18 +2459,23 @@ export class Carrier {
|
|
|
1993
2459
|
});
|
|
1994
2460
|
}
|
|
1995
2461
|
|
|
1996
|
-
async send(to, content, { label = '' } = {}) {
|
|
1997
|
-
const [r] = await this.sendAll(to, [content], { label });
|
|
1998
|
-
|
|
2462
|
+
async send(to, content, { label = '', local = false } = {}) {
|
|
2463
|
+
const [r] = await this.sendAll(to, [content], { label, local });
|
|
2464
|
+
// side: whose quota a quota_storage is (relay/allowance.mjs), on the error too.
|
|
2465
|
+
if (r.status === 'refused') throw Object.assign(new MsgError(r.code, `refused (${r.detail})`), r.side && { side: r.side });
|
|
1999
2466
|
return r;
|
|
2000
2467
|
}
|
|
2001
2468
|
|
|
2002
2469
|
// Several messages to one contact in one session: one login, where `send` costs one each (the
|
|
2003
2470
|
// relay allows 30 logins a minute per network). sent: the relay accepted it, and holds it for
|
|
2004
2471
|
// the contact's claim on the topic; queued: it goes at the next connection.
|
|
2005
|
-
async sendAll(to, contents, { label = '' } = {}) {
|
|
2472
|
+
async sendAll(to, contents, { label = '', local = false } = {}) { return this.#sendAll(to, contents, label, false, local); }
|
|
2473
|
+
|
|
2474
|
+
// spool: every content after the first waits on disk (#spool), as a file's chunks do. local: queued
|
|
2475
|
+
// only, for the started carrier of this identity in another process (inbox's local, for sending).
|
|
2476
|
+
async #sendAll(to, contents, label, spool, local = false) {
|
|
2006
2477
|
if (typeof label !== 'string') fail('body', 'label must be a string');
|
|
2007
|
-
if (label === LABEL_PREKEYS) fail('body', `the label ${JSON.stringify(
|
|
2478
|
+
if (label === LABEL_PREKEYS || label === OPERATOR_LABEL) fail('body', `the label ${JSON.stringify(label)} is the carrier's own`);
|
|
2008
2479
|
if (!Array.isArray(contents) || contents.length === 0) fail('body', 'at least one message');
|
|
2009
2480
|
for (const content of contents) {
|
|
2010
2481
|
if (content === undefined) fail('body', 'content is required');
|
|
@@ -2015,7 +2486,7 @@ export class Carrier {
|
|
|
2015
2486
|
// contact already, re-pairs) and goes under the key the reply brings.
|
|
2016
2487
|
const answered = this.#read(({ now, store }) => [...new Set(Object.values(store.load().s.accepts)
|
|
2017
2488
|
.filter((p) => p.exp > now && (p.name === to || p.code_did === to)).map((p) => p.relay))]);
|
|
2018
|
-
if (answered.length > 0) {
|
|
2489
|
+
if (answered.length > 0 && !local) {
|
|
2019
2490
|
try { await this.#session(answered); } catch {}
|
|
2020
2491
|
this.#routes = new Map();
|
|
2021
2492
|
this.#read(({ now, store }) => {
|
|
@@ -2028,9 +2499,14 @@ export class Carrier {
|
|
|
2028
2499
|
}
|
|
2029
2500
|
const { ids, c } = this.#locked(({ store, st }) => {
|
|
2030
2501
|
const c = this.#resolve(store, to), outbox = this.#entry(st, c.did).outbox;
|
|
2031
|
-
const ids = contents.map((content) => {
|
|
2502
|
+
const ids = contents.map((content, i) => {
|
|
2503
|
+
const id = randomId();
|
|
2504
|
+
if (spool && i > 0) { this.#spool(id, content); outbox.push({ id, label, spool: true }); } else outbox.push({ id, label, content });
|
|
2505
|
+
return id;
|
|
2506
|
+
});
|
|
2032
2507
|
return { ids, c };
|
|
2033
2508
|
});
|
|
2509
|
+
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' }));
|
|
2034
2510
|
try { await this.#session([c.relay]); } catch (e) {
|
|
2035
2511
|
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 });
|
|
2036
2512
|
}
|
|
@@ -2038,32 +2514,110 @@ export class Carrier {
|
|
|
2038
2514
|
const r = this.#results.get(id);
|
|
2039
2515
|
this.#results.delete(id);
|
|
2040
2516
|
// detail: the carrier's own words when it refused the message itself, else the relay's, quoted.
|
|
2041
|
-
if (r?.code) return { status: 'refused', id, to: c.did, name: c.name, code: r.code, detail: r.local ? r.detail : relaySays(r.detail) };
|
|
2517
|
+
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) };
|
|
2042
2518
|
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' };
|
|
2043
2519
|
return { status: 'sent', id, to: c.did, name: c.name };
|
|
2044
2520
|
});
|
|
2045
2521
|
}
|
|
2046
2522
|
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2523
|
+
// A file to a contact (file.mjs): its manifest and chunks in one sendAll, so one login. Read whole
|
|
2524
|
+
// first (at most MAX_FILE); this identity's own files (key, contacts, state, files received) are
|
|
2525
|
+
// refused, so a confused or misled agent cannot send its key. A refusal of any part throws as
|
|
2526
|
+
// send does: the contact gets no file, and what came of it there goes at its retention.
|
|
2527
|
+
async sendFile(to, path, { local = false } = {}) {
|
|
2528
|
+
if (typeof path !== 'string' || path === '') fail('file', 'a file path is required');
|
|
2529
|
+
let real, bytes;
|
|
2052
2530
|
try {
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2531
|
+
real = realpathSync(path);
|
|
2532
|
+
const s = statSync(real);
|
|
2533
|
+
if (!s.isFile()) fail('file', `${path} is not a regular file`);
|
|
2534
|
+
if (s.size > MAX_FILE) fail('file_too_large', `${path} is ${s.size} bytes, at most ${MAX_FILE} (8 MiB) a file`);
|
|
2535
|
+
} catch (e) {
|
|
2536
|
+
if (e instanceof MsgError) throw e;
|
|
2537
|
+
fail('file', `cannot read ${path}: ${e.code === 'ENOENT' ? 'no such file' : e.code ?? e.message}`, { cause: e });
|
|
2538
|
+
}
|
|
2539
|
+
// Beside the identity: its own files (x.*) and any profile's (*.local.*, sigelo-agent's pattern).
|
|
2540
|
+
const own = resolve(this.statePath.replace(/(\.carrier)?\.json$/, '')), files = (() => { try { return realpathSync(this.filesDir); } catch { return this.filesDir; } })();
|
|
2541
|
+
let ownDir;
|
|
2542
|
+
try { ownDir = realpathSync(dirname(own)); } catch { ownDir = dirname(own); }
|
|
2543
|
+
const leaf = basename(real);
|
|
2544
|
+
if (real.startsWith(files + sep) || (dirname(real) === ownDir && (leaf.startsWith(`${basename(own)}.`) || leaf.includes('.local.')))) {
|
|
2545
|
+
fail('file', `${path} is one of this agent's identity files (key, contacts, state, files received): not sent`);
|
|
2546
|
+
}
|
|
2547
|
+
try { bytes = readFileSync(real); } catch (e) { fail('file', `cannot read ${path}: ${e.code ?? e.message}`, { cause: e }); }
|
|
2548
|
+
if (bytes.length > MAX_FILE) fail('file_too_large', `${path} is ${bytes.length} bytes, at most ${MAX_FILE} (8 MiB) a file`);
|
|
2549
|
+
const { manifest, chunks } = splitFile(bytes, basename(real));
|
|
2550
|
+
const results = await this.#sendAll(to, [manifest, ...chunks], FILE_LABEL, true, local);
|
|
2551
|
+
const refused = results.find((x) => x.status === 'refused'), queued = results.find((x) => x.status === 'queued');
|
|
2552
|
+
if (refused) fail(refused.code, `refused (${refused.detail}): ${manifest.name} did not go whole; send it again once that is settled`);
|
|
2553
|
+
const { id, name, size, sha256: sum, chunks: n } = manifest;
|
|
2554
|
+
return { status: queued ? 'queued' : 'sent', to: results[0].to, name: results[0].name, file: { id, name, size, sha256: sum, chunks: n },
|
|
2555
|
+
...(queued && { detail: queued.detail }) };
|
|
2556
|
+
}
|
|
2557
|
+
|
|
2558
|
+
// tiers: only messages from contacts of these tiers are taken (and waited for); the rest stay for a
|
|
2559
|
+
// later inbox. Events are all taken. local: no session: what the state file holds, waited for by
|
|
2560
|
+
// reading it again, for a reader beside a started carrier of the same identity (a watcher), which
|
|
2561
|
+
// a session here would disconnect.
|
|
2562
|
+
async inbox({ wait = 0, tiers, local = false, paired = false } = {}) {
|
|
2563
|
+
const want = tiers === undefined ? null : new Set(tiers);
|
|
2564
|
+
if (want && ![...want].every((t) => TIERS.includes(t))) fail('tier', `tiers: some of ${TIERS.join(', ')}`);
|
|
2565
|
+
const picks = (store, now) => { const t = want && store.tiers(now); return (m) => !want || want.has(t.get(m.from) ?? 'friend'); };
|
|
2566
|
+
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')));
|
|
2567
|
+
let offline = null;
|
|
2568
|
+
if (local) {
|
|
2569
|
+
for (const end = Date.now() + wait * 1000; Date.now() < end && !ready();) await sleep(250);
|
|
2570
|
+
} else {
|
|
2571
|
+
// With nothing in use anywhere, this agent's own relay: an operator with no contacts logs in by
|
|
2572
|
+
// `inbox` before uploading its licence (relay/site/pro.md step 2), and proves its work there.
|
|
2573
|
+
const inUse = this.#relaysInUse(), relays = inUse.length > 0 ? inUse : [this.relay];
|
|
2574
|
+
try {
|
|
2575
|
+
await this.#session(relays, wait > 0 ? { max: wait * 1000, until: ready } : {});
|
|
2576
|
+
} catch (e) { this.lastError = e; offline = e instanceof MsgError ? e.message : `connect: ${e.message}`; }
|
|
2577
|
+
}
|
|
2578
|
+
return this.#locked(({ now, store, st }) => {
|
|
2579
|
+
this.#sweepFiles(st, now);
|
|
2580
|
+
const pick = picks(store, now), messages = st.inbox.filter(pick);
|
|
2581
|
+
const out = { messages, events: st.events, dropped: st.dropped, ...(offline && { offline }) };
|
|
2582
|
+
st.inbox = st.inbox.filter((m) => !pick(m)); st.events = []; st.dropped = {};
|
|
2583
|
+
return out;
|
|
2584
|
+
});
|
|
2585
|
+
}
|
|
2586
|
+
|
|
2587
|
+
peek() {
|
|
2588
|
+
return this.#read(({ now, store, st }) => { const t = store.tiers(now); return st.inbox.map((m) => ({ ...m, tier: t.get(m.from) ?? 'friend' })); });
|
|
2589
|
+
}
|
|
2590
|
+
|
|
2591
|
+
take(pick) {
|
|
2592
|
+
if (typeof pick !== 'function') throw new TypeError('take: a function (message, tier) → boolean');
|
|
2593
|
+
return this.#locked(({ now, store, st }) => {
|
|
2594
|
+
const t = store.tiers(now), out = [], keep = [];
|
|
2595
|
+
for (const m of st.inbox) (pick(m, t.get(m.from) ?? 'friend') ? out : keep).push(m);
|
|
2596
|
+
st.inbox = keep;
|
|
2058
2597
|
return out;
|
|
2059
2598
|
});
|
|
2060
2599
|
}
|
|
2061
2600
|
|
|
2601
|
+
setTier(who, tier) { return this.#locked(({ now, store }) => store.setTier(who, tier, now)); }
|
|
2602
|
+
|
|
2603
|
+
// A contact's full bundle, from wherever it came (the UI reads its local agents' files): verified
|
|
2604
|
+
// here; → { did, tier }, or null when it is no contact's.
|
|
2605
|
+
observe(bundle) {
|
|
2606
|
+
return this.#locked(({ now, store }) => {
|
|
2607
|
+
let r;
|
|
2608
|
+
try { r = verify(bundle, now); } catch (e) { fail('bundle', `REJECT: ${e.message}`); }
|
|
2609
|
+
const c = store.lookup(r.chain[0]);
|
|
2610
|
+
if (!c || c.revoked || c.did !== r.chain[0]) return null;
|
|
2611
|
+
return { did: c.did, tier: store.observe(c.did, r, now) };
|
|
2612
|
+
});
|
|
2613
|
+
}
|
|
2614
|
+
|
|
2062
2615
|
async forget(did) {
|
|
2063
2616
|
const c = this.#locked(({ store, st }) => {
|
|
2064
2617
|
const c = store.revoke(did);
|
|
2065
2618
|
delete st.peers[c.did];
|
|
2066
2619
|
st.pending = st.pending.filter((p) => p.peer !== c.did);
|
|
2620
|
+
this.#sweepSpool(st);
|
|
2067
2621
|
return c;
|
|
2068
2622
|
});
|
|
2069
2623
|
this.#routes = new Map();
|