sigelo-contact 0.1.6 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/carrier.mjs +435 -37
- package/enrol.mjs +402 -0
- package/file.mjs +113 -0
- package/invite.mjs +1 -1
- package/package.json +12 -3
- 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 +20 -0
- package/test-tier.mjs +240 -0
package/carrier.mjs
CHANGED
|
@@ -9,13 +9,32 @@
|
|
|
9
9
|
// await c.unpark(short) → the long code parked under a short one, taken from the relay (one use)
|
|
10
10
|
// await c.accept(code, { name, wait }) → { status: 'connected' | 'waiting' | 'pending', … } a long code or a short one
|
|
11
11
|
// (refused after a short code was fetched: .long, keepLong)
|
|
12
|
-
// c.
|
|
12
|
+
// await c.cancelInvite(code) → { cancelled, name }: an unanswered invite of this agent's withdrawn
|
|
13
|
+
// c.rename(who, name) the owner's name for a contact (store.mjs rename) → { did, name }
|
|
14
|
+
// c.contacts() → { contacts, invites, answers, failed } each contact with its four words (fingerprint),
|
|
15
|
+
// pair id, chain, tier (store.mjs: own, friend, quiet) and tier_by, prekeys: its
|
|
16
|
+
// bundle is here (false: messages wait for it), waiting: why they wait, or null;
|
|
13
17
|
// 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.
|
|
18
|
+
// await c.send(to, content, { label, local }) → { status: 'sent' | 'queued', … }, or throws the relay's code
|
|
19
|
+
// await c.sendAll(to, contents, { label, local }) → one result each ('refused' with its code), one login
|
|
20
|
+
// await c.sendFile(to, path, { local }) → { status, to, name, file: {id, name, size, sha256, chunks} }: a file of at most
|
|
21
|
+
// 8 MiB as FILE_LABEL messages (file.mjs), one login; throws as send does. Chunks
|
|
22
|
+
// queued wait in files/.out (0600), the state names them; gone once sent or refused.
|
|
23
|
+
// local (all three): no session, queued in the state file for a started carrier
|
|
24
|
+
// of the same identity elsewhere (a watcher), which sends it at its next sync()
|
|
25
|
+
// await c.inbox({ wait, tiers, local, paired }) → { messages, events, dropped, offline? }: all are taken (messages: those kept;
|
|
26
|
+
// tiers: only those from contacts of these tiers, the rest stay); local: no
|
|
27
|
+
// session, the state file only (a started carrier elsewhere is connected);
|
|
28
|
+
// paired: the wait also ends at a pairing (enrol.mjs)
|
|
29
|
+
// c.peek(), c.take(pick) the messages kept for inbox(), each with its sender's tier: read, or those
|
|
30
|
+
// pick(message, tier) chooses taken; no session (a started carrier's owner)
|
|
31
|
+
// c.setTier(who, tier) the owner's tier for a contact (store.mjs setTier) → { did, name, tier }
|
|
32
|
+
// c.observe(bundle) a contact's full bundle seen: its operator attestations (store.mjs observe)
|
|
33
|
+
// a file received whole is one item {type: "file", from, contact, name, size,
|
|
34
|
+
// sha256, path, …}, saved under `files` (pathsFor), never opened
|
|
17
35
|
// await c.forget(did) → { name, did, revoked: true, released, offline? }
|
|
18
36
|
// c.lastError the error behind the last offline of inbox or forget (SIGELO_DEBUG)
|
|
37
|
+
// c.clockOffset(), await c.checkClock() → { relay, offset, checked } | null: the relay's clock less this one's, seconds
|
|
19
38
|
// await c.start(), c.sync(), c.stop() stay connected, reconnecting with backoff; events reach onEvent
|
|
20
39
|
//
|
|
21
40
|
// identity() → { secret, bundle }: the agent's current secret key and SPEC §8 bundle, read again at
|
|
@@ -28,8 +47,9 @@
|
|
|
28
47
|
// default only without onEvent, so a message onEvent took is not left at rest after the keys that
|
|
29
48
|
// opened it are gone (contacts.md §3: keys stolen today must not open yesterday's messages).
|
|
30
49
|
// One connected carrier per identity: every process logs in with the identity's one MQTT client
|
|
31
|
-
// id, so a
|
|
32
|
-
//
|
|
50
|
+
// id, so a second login takes the session from a started carrier (the files stay sound under the
|
|
51
|
+
// lock; the started one reconnects with backoff). Beside one, use inbox and send with local: the
|
|
52
|
+
// state file only (sigelo-agent's one-owner rule, adapters/moadim/WATCH.md).
|
|
33
53
|
//
|
|
34
54
|
// What this adds to the wire, beside the envelope (envelope.mjs) and the invite (invite.mjs); the
|
|
35
55
|
// bytes are pinned in fixtures/carrier-v0.json (gen-carrier.mjs --check):
|
|
@@ -120,6 +140,18 @@
|
|
|
120
140
|
// cannot be told from the thief's: refused alike; the owner writes again once paired again.
|
|
121
141
|
// What an earlier inbox() returned, or onEvent got, cannot be taken back: the `rotated` event
|
|
122
142
|
// of such a notice lists the DIDs it overruled (`overruled`).
|
|
143
|
+
// - Operator hints (label OPERATOR_LABEL, a message like any other): an agent attested by
|
|
144
|
+
// operators (sigelo-relay/operator) tells each contact {hints: HMAC-SHA256(K, "sigelo-operator/0
|
|
145
|
+
// hint\n" ‖ its original DID ‖ "\n" ‖ operator DID)}, once per pairing and set of operators. A
|
|
146
|
+
// contact run by the same operator, or that operator itself, recognises one and answers {asks}
|
|
147
|
+
// (the same with "ask" and its own DID: it knows the operator's DID, an echo does not), and only
|
|
148
|
+
// then the agent sends {proof}: its chain with those attestations and their issuers, which the
|
|
149
|
+
// contact verifies (SPEC §9) and files (store.mjs observe): the contact's tier becomes own. A
|
|
150
|
+
// proof is taken only after asks of ours, at most NOTICE_CHECKS an hour, and only if its chain
|
|
151
|
+
// ends at the sender's current DID as held (store.mjs current_did). A renewed attestation is
|
|
152
|
+
// hinted and proved again; asks for the same operators go at most every RESYNC. A contact
|
|
153
|
+
// learns from the hints only which operator DIDs it guesses right (THREAT-MODEL §2.12). An
|
|
154
|
+
// agent on an older version gets the hints as messages with that label. send refuses the label.
|
|
123
155
|
// - Mailboxes: an agent holds the topics of every ISO week from `retention` ago to AHEAD (7 days,
|
|
124
156
|
// or its retention if shorter) ahead. The relay drops a publish to a topic nobody claimed (and
|
|
125
157
|
// says no_reader), so next week's topic must be claimed before a contact writes in it while
|
|
@@ -141,10 +173,11 @@
|
|
|
141
173
|
// round, so topics are asked in the order they matter (#want). A refused topic is asked again
|
|
142
174
|
// at the next hourly round (ASK_AGAIN).
|
|
143
175
|
import { createHash } from 'node:crypto';
|
|
144
|
-
import { closeSync, existsSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
145
|
-
import { basename, dirname, join } from 'node:path';
|
|
176
|
+
import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
177
|
+
import { basename, dirname, join, resolve, sep } from 'node:path';
|
|
146
178
|
import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
|
147
179
|
import { hkdf } from '@noble/hashes/hkdf.js';
|
|
180
|
+
import { hmac } from '@noble/hashes/hmac.js';
|
|
148
181
|
import { sha256 } from '@noble/hashes/sha2.js';
|
|
149
182
|
import { concatBytes, hexToBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils.js';
|
|
150
183
|
import { connect } from 'mqtt';
|
|
@@ -153,12 +186,14 @@ import { KIND, acceptPrekeys, expire, header, open, pad, prekeysMissing, restart
|
|
|
153
186
|
import { answerId, buildAnswer, buildReply, checkAnswer, checkReply, inviteKeys, keyOf, makeInvite, parseInvite } from './invite.mjs';
|
|
154
187
|
import { MsgError, checkNow, fail, hex, isoWeek, pairId, topic } from './kdf.mjs';
|
|
155
188
|
import { Prekeys, exact, kemDecapsulate, kemEncapsulate, kemKey } from './prekeys.mjs';
|
|
156
|
-
import { Contacts } from './store.mjs';
|
|
189
|
+
import { Contacts, OPERATOR_CTX, TIERS } from './store.mjs';
|
|
157
190
|
import { SHORT_TTL, codeHash, codeKind, fingerprint, formatShort, makeShort, normaliseShort } from './short.mjs';
|
|
191
|
+
import { FILE_LABEL, MAX_FILE, assemble, checkChunk, checkManifest, chunkHead, isManifest, safeName, splitFile } from './file.mjs';
|
|
158
192
|
|
|
159
193
|
export const V = 'sigelo-carrier/0';
|
|
160
194
|
export const DEFAULT_RELAY = 'relay.sigelo.ai', MQTT_PORT = 8883, NOTICE = '$sigelo/notice';
|
|
161
195
|
export const LABEL_PREKEYS = 'sigelo-msg/0 prekeys', KIND_NOTICE = 4, KIND_PREKEYS = 5, TYP_NOTICE = 'contact-notice';
|
|
196
|
+
export const OPERATOR_LABEL = 'sigelo-operator/0';
|
|
162
197
|
// The relay login (relay-plan §3 "Login"): the body GET /challenge answers and the agent signs. A
|
|
163
198
|
// type of its own, never a SPEC §5.2 challenge: a world that passed the relay's nonce on as its own
|
|
164
199
|
// challenge would get the agent's relay login back from sign-challenge.
|
|
@@ -193,6 +228,8 @@ const POISON_TRIES = 3;
|
|
|
193
228
|
// Events kept for the next inbox(): pairings, rotations, failed pairings. The oldest go first.
|
|
194
229
|
// Messages kept for it (keep), likewise.
|
|
195
230
|
const EVENTS_MAX = 1000, INBOX_MAX = 1000;
|
|
231
|
+
// Files arriving at once from one contact (#onFile): each holds up to 8 MiB of parts here.
|
|
232
|
+
const FILES_OPEN = 8;
|
|
196
233
|
// Half the relay's publish brake (20 a second, 200 at once): past it the relay refuses publishes
|
|
197
234
|
// ("rate"), and closes the connection after 500 refusals in a minute (every refused publish
|
|
198
235
|
// counts, a no_reader too).
|
|
@@ -262,6 +299,14 @@ const b64 = (b) => Buffer.from(b).toString('base64');
|
|
|
262
299
|
const unb64 = (s) => new Uint8Array(Buffer.from(s, 'base64'));
|
|
263
300
|
const randomId = () => hex(randomBytes(8));
|
|
264
301
|
const clientIdOf = (original) => 's' + createHash('sha256').update(original, 'utf8').digest('hex').slice(0, 24);
|
|
302
|
+
// Operators as hinted and proved: each with its attestation's expiry, so a renewal goes again.
|
|
303
|
+
const opKey = (mine, ops) => [...ops].sort().map((d) => `${d} ${mine.exp.get(d)}`).join();
|
|
304
|
+
// Whether a session as the state holds it (dumpSession) has a prekey bundle of contact c's that an
|
|
305
|
+
// epoch can begin on (envelope.mjs prekeysMissing): of this pairing, signed as c's current DID, unexpired.
|
|
306
|
+
const theirPrekeys = (c, d, pair, now) => {
|
|
307
|
+
const p = d?.pair === pair ? d.out.prekeys : null;
|
|
308
|
+
return Boolean(p) && p.did === c.current_did && now < p.exp;
|
|
309
|
+
};
|
|
265
310
|
// The four words of a pairing (short.mjs), from its pairing key as the store holds it (hex), or null.
|
|
266
311
|
const wordsOf = (pairKey) => (typeof pairKey === 'string' ? fingerprint(pairId(hexToBytes(pairKey))) : null);
|
|
267
312
|
// The refusals of POST /park this client names (relay/park.mjs, and the login's: auth.mjs).
|
|
@@ -269,10 +314,10 @@ const PARK_CHECKS = new Set(['park', 'park_taken', 'park_full', 'pow', ...LOGIN_
|
|
|
269
314
|
|
|
270
315
|
// ---------------------------------------------------------------- configuration
|
|
271
316
|
|
|
272
|
-
/** The contact store
|
|
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/. */
|
|
273
318
|
export function pathsFor(identityFile) {
|
|
274
319
|
const base = identityFile.replace(/\.json$/, '');
|
|
275
|
-
return { store: `${base}.contacts.json`, state: `${base}.carrier.json` };
|
|
320
|
+
return { store: `${base}.contacts.json`, state: `${base}.carrier.json`, files: `${base}.files` };
|
|
276
321
|
}
|
|
277
322
|
|
|
278
323
|
/**
|
|
@@ -421,6 +466,8 @@ function loadSession(s, d) {
|
|
|
421
466
|
|
|
422
467
|
const ZERO_EPOCH = new Uint8Array(16), FRAME_HEAD = 22, NONCE = 24;
|
|
423
468
|
/** The contact notice's key: HKDF-SHA256(K, salt "sigelo-notice/0", info = from ‖ "\n" ‖ to), original DIDs. */
|
|
469
|
+
// The header's "Operator hints": what `from` (an original DID) shows of operator `op`, as hex.
|
|
470
|
+
export const operatorHint = (K, kind, from, op) => hex(hmac(sha256, K, utf8ToBytes(`${OPERATOR_LABEL} ${kind}\n${from}\n${op}`)));
|
|
424
471
|
export const noticeKey = (K, from, to) => hkdf(sha256, K, utf8ToBytes('sigelo-notice/0'), utf8ToBytes(`${from}\n${to}`), 32);
|
|
425
472
|
/** The prekeys frame's key: HKDF-SHA256(K, salt "sigelo-prekeys/0", info = from ‖ "\n" ‖ to), original DIDs. */
|
|
426
473
|
export const prekeysKey = (K, from, to) => hkdf(sha256, K, utf8ToBytes('sigelo-prekeys/0'), utf8ToBytes(`${from}\n${to}`), 32);
|
|
@@ -532,11 +579,14 @@ export async function solvePow(host, original, nonce, bits, deadline = Infinity)
|
|
|
532
579
|
async function http(url, init = {}) {
|
|
533
580
|
let res;
|
|
534
581
|
const at = where(url), http = { url, method: init.method ?? 'GET' };
|
|
582
|
+
const t0 = Date.now();
|
|
535
583
|
try { res = await fetch(url, { ...init, redirect: 'manual', signal: AbortSignal.timeout(HTTP_MS) }); } catch (e) {
|
|
536
584
|
const why = e.name === 'TimeoutError' ? `no answer within ${HTTP_MS / 1000} s` : e.cause?.code ?? e.cause?.message ?? e.message;
|
|
537
585
|
fail('connect', `cannot reach the relay at ${at} (${why}): check the network and SIGELO_RELAY / SIGELO_RELAY_ENDPOINTS, then try again`, { cause: e, http });
|
|
538
586
|
}
|
|
539
587
|
http.status = res.status;
|
|
588
|
+
// The relay's clock (Date, whole seconds) and the round trip to it, for clockOffset.
|
|
589
|
+
const rtt = Date.now() - t0, date = Date.parse(res.headers.get('date') ?? '');
|
|
540
590
|
if ((res.status >= 300 && res.status < 400) || res.type === 'opaqueredirect') {
|
|
541
591
|
try { await res.body?.cancel(); } catch {}
|
|
542
592
|
fail('connect', `${at}: answered ${res.status}, a redirect, which this client does not follow`, { http });
|
|
@@ -562,7 +612,7 @@ async function http(url, init = {}) {
|
|
|
562
612
|
const after = Number(res.headers.get('retry-after'));
|
|
563
613
|
// What a refusal carries for SIGELO_DEBUG: the status and the start of the body as received.
|
|
564
614
|
http.body = new TextDecoder().decode(raw.subarray(0, 512));
|
|
565
|
-
return { status: res.status, body, retryAfter: Number.isSafeInteger(after) && after > 0 ? after : null, http };
|
|
615
|
+
return { status: res.status, body, retryAfter: Number.isSafeInteger(after) && after > 0 ? after : null, http, date: Number.isNaN(date) ? null : date, rtt };
|
|
566
616
|
}
|
|
567
617
|
|
|
568
618
|
// A URL as a refusal shows it: no query (it carries the DID), no code hash.
|
|
@@ -591,7 +641,7 @@ export function readCode(text, now, how = 'long') {
|
|
|
591
641
|
// stood for, so the refusal carries it (.long, and in its words). Not when the answer it made
|
|
592
642
|
// still stands (queued, or held by the relay: .kept) nor when the code was answered already.
|
|
593
643
|
export function keepLong(e, long) {
|
|
594
|
-
if (e?.kept || e?.check === 'mailbox_taken') return e;
|
|
644
|
+
if (e?.kept || e?.lapsed || e?.check === 'mailbox_taken') return e;
|
|
595
645
|
const k = new MsgError(e instanceof MsgError ? e.check : 'error', `${e instanceof Error ? reason(e) : String(e)}. The short code is used up; its long code: ${long} (keep this; accept it with the long code)`, { cause: e, http: e?.http });
|
|
596
646
|
k.long = long;
|
|
597
647
|
return k;
|
|
@@ -722,9 +772,10 @@ export class Carrier {
|
|
|
722
772
|
#links = new Map(); #work = Promise.resolve(); #busy = 0; #lastWork = 0; #routes = new Map(); #results = new Map();
|
|
723
773
|
#claimed = new Set(); #refusedTopics = new Map(); #handshakes = new Map(); #soon = new Set();
|
|
724
774
|
#started = false; #tick = null; #timers = new Map(); #attempts = new Map(); #connecting = new Set(); #powFails = new Map(); #ask = false;
|
|
775
|
+
#mineMemo = null; #clocks = new Map();
|
|
725
776
|
|
|
726
777
|
constructor({ identity, store, state, relay = DEFAULT_RELAY, endpoints = {}, retentionDays, clock = () => Math.floor(Date.now() / 1000),
|
|
727
|
-
onEvent, keep, backoff = BACKOFF, tick = TICK }) {
|
|
778
|
+
onEvent, keep, backoff = BACKOFF, tick = TICK, files }) {
|
|
728
779
|
if (typeof identity !== 'function') throw new TypeError('identity: a function returning { secret, bundle }');
|
|
729
780
|
if (typeof store !== 'string' || typeof state !== 'string') throw new TypeError('store, state: file paths (pathsFor(identityFile))');
|
|
730
781
|
if (retentionDays !== undefined && !retentionOk(retentionDays)) throw new TypeError(`retentionDays: 1 to ${RETENTION_MAX_DAYS}`);
|
|
@@ -735,6 +786,9 @@ export class Carrier {
|
|
|
735
786
|
if (keep !== undefined && typeof keep !== 'boolean') throw new TypeError('keep: true or false');
|
|
736
787
|
Object.assign(this, { identity, storePath: store, statePath: state, relay, endpoints, retention: retentionDays * DAY, clock, onEvent: onEvent ?? (() => {}),
|
|
737
788
|
keep: keep ?? onEvent === undefined, backoff, tick });
|
|
789
|
+
// Files received (#onFile): files, else beside the state as pathsFor names it (x.carrier.json → x.files).
|
|
790
|
+
if (files !== undefined && typeof files !== 'string') throw new TypeError('files: a directory path (pathsFor(identityFile))');
|
|
791
|
+
this.filesDir = resolve(files ?? state.replace(/(\.carrier)?\.json$/, '') + '.files');
|
|
738
792
|
}
|
|
739
793
|
|
|
740
794
|
// ---- files, under the lock
|
|
@@ -759,7 +813,7 @@ export class Carrier {
|
|
|
759
813
|
#with(write, fn) {
|
|
760
814
|
return withLock(this.statePath, () => {
|
|
761
815
|
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) };
|
|
816
|
+
const ctx = { now, me, store: new Contacts(this.storePath, me.did, { mine: () => this.#mine(me, now) }), st: loadState(this.statePath, me.did) };
|
|
763
817
|
// Before anything reads the store: a recovery made by another process (sigelo-agent recover)
|
|
764
818
|
// is seen at once. The store's marks are written first; the state keeps the events.
|
|
765
819
|
if (this.#markRecovered(ctx)) saveState(this.statePath, ctx.st);
|
|
@@ -773,6 +827,24 @@ export class Carrier {
|
|
|
773
827
|
}
|
|
774
828
|
#locked(fn) { return this.#with(true, fn); }
|
|
775
829
|
|
|
830
|
+
// For tiers (store.mjs): this agent's chain, and its operators: the issuers of the unexpired
|
|
831
|
+
// sigelo-relay/operator attestations its bundle carries that verify (operator DID → exp). Kept
|
|
832
|
+
// until the bundle changes or one of them expires.
|
|
833
|
+
#mine(me, now) {
|
|
834
|
+
const key = JSON.stringify([me.chain, me.bundle.attestations ?? [], me.bundle.issuers ?? []]), m = this.#mineMemo;
|
|
835
|
+
if (m && m.key === key && now < m.until) return m.value;
|
|
836
|
+
const operators = new Map();
|
|
837
|
+
try {
|
|
838
|
+
const r = verify({ ...me.bundle, bindings: [] }, now);
|
|
839
|
+
for (const [iss, bodies] of Object.entries(r.attestations)) {
|
|
840
|
+
for (const b of bodies) if (b.ctx === OPERATOR_CTX && !me.chain.includes(iss)) operators.set(iss, Math.max(operators.get(iss) ?? 0, b.exp));
|
|
841
|
+
}
|
|
842
|
+
} catch {}
|
|
843
|
+
const value = { chain: me.chain, operators: [...operators.keys()], exp: operators };
|
|
844
|
+
this.#mineMemo = { key, until: Math.min(Infinity, ...operators.values()), value };
|
|
845
|
+
return value;
|
|
846
|
+
}
|
|
847
|
+
|
|
776
848
|
// An answer that expired before the inviter's reply came: the accept said "waiting", so the next
|
|
777
849
|
// inbox (and contacts until then) says it failed, rather than nothing at all.
|
|
778
850
|
#lapse({ now, store, st }) {
|
|
@@ -1060,6 +1132,16 @@ export class Carrier {
|
|
|
1060
1132
|
st.dropped[e.check] = (st.dropped[e.check] ?? 0) + 1;
|
|
1061
1133
|
events.push({ type: 'dropped', check: e.check, detail: e.message });
|
|
1062
1134
|
}
|
|
1135
|
+
} else if (r.body.label === FILE_LABEL) {
|
|
1136
|
+
// A file's manifest or chunk (file.mjs): kept apart until the file is whole (#onFile).
|
|
1137
|
+
events.push(...this.#onFile(ctx, c, r, now));
|
|
1138
|
+
} else if (r.body.label === OPERATOR_LABEL) {
|
|
1139
|
+
// Operator hints, asks and proofs (the header): taken here, never an inbox message. One refused is counted.
|
|
1140
|
+
try { events.push(...this.#onOperator(ctx, c, r.body.content)); } catch (e) {
|
|
1141
|
+
if (!(e instanceof MsgError)) throw e;
|
|
1142
|
+
st.dropped[e.check] = (st.dropped[e.check] ?? 0) + 1;
|
|
1143
|
+
events.push({ type: 'dropped', check: e.check, detail: e.message });
|
|
1144
|
+
}
|
|
1063
1145
|
} else {
|
|
1064
1146
|
// last_resort: the epoch began on the last-resort prekey, which may serve many epochs: weaker
|
|
1065
1147
|
// forward secrecy (plan §3 "Prekeys"), and routine for a while after a rotation (#next).
|
|
@@ -1075,6 +1157,170 @@ export class Carrier {
|
|
|
1075
1157
|
return events;
|
|
1076
1158
|
}
|
|
1077
1159
|
|
|
1160
|
+
// The header's "Operator hints". Hints of contact c's operators: those this agent knows (its own
|
|
1161
|
+
// operators, or itself) are asked for, once per set. Asks: proofs of this agent's operators the
|
|
1162
|
+
// contact showed it knows, once per set. A proof: c's chain with operator attestations, filed.
|
|
1163
|
+
// Answers go first in c's outbox. → events: `tier` when c's tier changed.
|
|
1164
|
+
#onOperator({ now, me, store, st }, c, v) {
|
|
1165
|
+
const K = hexToBytes(c.pair_key), e = this.#entry(st, c.did), mine = this.#mine(me, now);
|
|
1166
|
+
const list = (x) => (Array.isArray(x) && x.length <= 8 && x.every((h) => typeof h === 'string') ? x : fail('operator', 'hints and asks: at most 8 strings'));
|
|
1167
|
+
if (v?.hints !== undefined) {
|
|
1168
|
+
const hints = list(v.hints), known = [...mine.operators, ...mine.chain].filter((d) => hints.includes(operatorHint(K, 'hint', c.did, d))).sort();
|
|
1169
|
+
// Again for the same operators at most every RESYNC: the contact hints anew once their
|
|
1170
|
+
// attestations are renewed (#next), and its proof must come again before the old one lapses.
|
|
1171
|
+
if (known.length > 0 && (e.op_asked !== known.join() || now - (e.op_asked_at ?? 0) >= RESYNC)) {
|
|
1172
|
+
e.op_asked = known.join(); e.op_asked_at = now;
|
|
1173
|
+
e.outbox.unshift({ id: randomId(), label: OPERATOR_LABEL, content: { asks: known.map((d) => operatorHint(K, 'ask', me.did, d)) } });
|
|
1174
|
+
}
|
|
1175
|
+
return [];
|
|
1176
|
+
}
|
|
1177
|
+
if (v?.asks !== undefined) {
|
|
1178
|
+
// Proved again once an attestation shown is renewed (its expiry is in the key).
|
|
1179
|
+
const asks = list(v.asks), shown = mine.operators.filter((d) => asks.includes(operatorHint(K, 'ask', c.did, d))).sort(), key = opKey(mine, shown);
|
|
1180
|
+
if (shown.length > 0 && e.op_proved !== key) {
|
|
1181
|
+
e.op_proved = key;
|
|
1182
|
+
const b = me.bundle, iss = new Set(shown);
|
|
1183
|
+
const proof = { v: b.v, typ: 'bundle', genesis: b.genesis, rotations: b.rotations, bindings: [],
|
|
1184
|
+
attestations: (b.attestations ?? []).filter((a) => a?.body?.ctx === OPERATOR_CTX && iss.has(a.body.iss)), issuers: (b.issuers ?? []).filter((g) => iss.has(didOf(g))) };
|
|
1185
|
+
e.outbox.unshift({ id: randomId(), label: OPERATOR_LABEL, content: { proof } });
|
|
1186
|
+
}
|
|
1187
|
+
return [];
|
|
1188
|
+
}
|
|
1189
|
+
if (v?.proof !== undefined) {
|
|
1190
|
+
// Only in answer to asks of ours, and so many an hour: each costs SPEC §9 (THREAT-MODEL §2.12).
|
|
1191
|
+
if (!e.op_asked) fail('operator', 'an operator proof nobody asked for');
|
|
1192
|
+
const recent = (e.op_checks ?? []).filter((x) => x > now - RESYNC);
|
|
1193
|
+
if (recent.length >= NOTICE_CHECKS) fail('operator_rate', `${recent.length} operator proofs of this contact checked within ${RESYNC} s, the most`);
|
|
1194
|
+
e.op_checks = [...recent, now];
|
|
1195
|
+
const p = v.proof;
|
|
1196
|
+
if (![p?.rotations, p?.attestations, p?.issuers].every(Array.isArray) || p.rotations.length > MAX_ROTATIONS || p.attestations.length > 8 || p.issuers.length > 8) {
|
|
1197
|
+
fail('operator', `an operator proof is a bundle of at most ${MAX_ROTATIONS} rotations, 8 attestations and 8 issuers`);
|
|
1198
|
+
}
|
|
1199
|
+
let r;
|
|
1200
|
+
try { r = verify(p, now); } catch (err) { fail('operator', `the contact's operator proof does not verify: ${err.message}`); }
|
|
1201
|
+
if (r.chain[0] !== c.did) fail('operator', 'the operator proof is not the chain of the contact that sent it');
|
|
1202
|
+
// store.observe refuses a chain that ends anywhere but the contact's current DID (current_did).
|
|
1203
|
+
const before = store.tierOf(c, now), after = store.observe(c.did, r, now);
|
|
1204
|
+
return after === before ? [] : [{ type: 'tier', did: c.did, name: c.name, tier: after }];
|
|
1205
|
+
}
|
|
1206
|
+
fail('operator', 'an operator message is {hints}, {asks} or {proof}');
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
// ---- files (file.mjs; design/human-ui-plan.md §4)
|
|
1210
|
+
|
|
1211
|
+
// A FILE_LABEL message from contact c, opened (r). The manifest is kept in the state (files,
|
|
1212
|
+
// under a key of the contact and the file's id), each chunk under filesDir/.partial/<key>/<i>
|
|
1213
|
+
// (0600, directories 0700); once all have come, the file is checked (size, SHA-256), saved as
|
|
1214
|
+
// filesDir/<contact>/<sha256[0..8]>-<name> (0600), and given to inbox() as one item of type
|
|
1215
|
+
// "file". Never opened, never made executable. Anything wrong with the message is counted in
|
|
1216
|
+
// dropped by its check, as a refused bundle is above; the envelope stays opened either way.
|
|
1217
|
+
// A chunk before its manifest (none: the sender sends the manifest first, in one login) is
|
|
1218
|
+
// dropped, file_chunk. The disk is written before the state: a crash between them leaves a
|
|
1219
|
+
// chunk that the delivery, unacknowledged, writes again.
|
|
1220
|
+
#onFile(ctx, c, r, now) {
|
|
1221
|
+
const { st } = ctx, content = r.body.content;
|
|
1222
|
+
st.files ??= {};
|
|
1223
|
+
const drop = (e) => {
|
|
1224
|
+
if (!(e instanceof MsgError)) throw e;
|
|
1225
|
+
st.dropped[e.check] = (st.dropped[e.check] ?? 0) + 1;
|
|
1226
|
+
return [{ type: 'dropped', check: e.check, detail: `a file from ${c.name}: ${e.message}` }];
|
|
1227
|
+
};
|
|
1228
|
+
const keyOf = (id) => hex(sha256(utf8ToBytes(`${c.did}\n${id}`)).subarray(0, 16));
|
|
1229
|
+
let key, p;
|
|
1230
|
+
try {
|
|
1231
|
+
if (isManifest(content)) {
|
|
1232
|
+
const m = checkManifest(content);
|
|
1233
|
+
key = keyOf(m.id);
|
|
1234
|
+
const had = st.files[key];
|
|
1235
|
+
if (had) {
|
|
1236
|
+
if (had.sha256 !== m.sha256 || had.size !== m.size) fail('file', 'a second manifest for one file id, with another content');
|
|
1237
|
+
return [];
|
|
1238
|
+
}
|
|
1239
|
+
// At most FILES_OPEN files arriving at once per contact: each holds up to 8 MiB here.
|
|
1240
|
+
if (Object.values(st.files).filter((x) => x.from === c.did).length >= FILES_OPEN) fail('file_busy', `${FILES_OPEN} files from this contact are incomplete already`);
|
|
1241
|
+
p = st.files[key] = { from: c.did, ...m, got: [], first: now };
|
|
1242
|
+
} else {
|
|
1243
|
+
const h = chunkHead(content);
|
|
1244
|
+
key = keyOf(h.id);
|
|
1245
|
+
p = st.files[key] ?? fail('file_chunk', 'a chunk of a file whose manifest has not come');
|
|
1246
|
+
const bytes = checkChunk(content, p);
|
|
1247
|
+
if (!p.got.includes(h.i)) {
|
|
1248
|
+
const dir = this.#partDir(key);
|
|
1249
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
1250
|
+
writeFileSync(join(dir, String(h.i)), bytes, { mode: 0o600 });
|
|
1251
|
+
p.got.push(h.i);
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
} catch (e) { return drop(e); }
|
|
1255
|
+
if (p.got.length < p.chunks) return [];
|
|
1256
|
+
// Whole: checked, saved, and the parts gone whatever the check said.
|
|
1257
|
+
let bytes;
|
|
1258
|
+
try {
|
|
1259
|
+
bytes = assemble(p, Array.from({ length: p.chunks }, (_, i) => readFileSync(join(this.#partDir(key), String(i)))));
|
|
1260
|
+
} catch (e) {
|
|
1261
|
+
delete st.files[key];
|
|
1262
|
+
rmSync(this.#partDir(key), { recursive: true, force: true });
|
|
1263
|
+
return drop(e);
|
|
1264
|
+
}
|
|
1265
|
+
const dir = join(this.filesDir, safeName(c.name || c.did));
|
|
1266
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
1267
|
+
chmodSync(this.filesDir, 0o700); chmodSync(dir, 0o700);
|
|
1268
|
+
const path = join(dir, `${p.sha256.slice(0, 8)}-${p.name}`), tmp = join(dir, `.${randomId()}.tmp`);
|
|
1269
|
+
writeFileSync(tmp, bytes, { mode: 0o600, flag: 'wx' });
|
|
1270
|
+
renameSync(tmp, path);
|
|
1271
|
+
delete st.files[key];
|
|
1272
|
+
rmSync(this.#partDir(key), { recursive: true, force: true });
|
|
1273
|
+
const item = { type: 'file', from: c.did, contact: c.name, current_did: r.body.from, label: FILE_LABEL, name: p.name, size: p.size, sha256: p.sha256, path,
|
|
1274
|
+
iat: r.body.iat, received: now, last_resort: r.last_resort };
|
|
1275
|
+
// Kept for inbox() as a message is (#onPeer), and so many at most.
|
|
1276
|
+
if (this.keep) {
|
|
1277
|
+
st.inbox.push(item);
|
|
1278
|
+
if (st.inbox.length > INBOX_MAX) { const n = st.inbox.length - INBOX_MAX; st.inbox.splice(0, n); st.dropped.inbox_full = (st.dropped.inbox_full ?? 0) + n; }
|
|
1279
|
+
}
|
|
1280
|
+
return [item];
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
#partDir(key) { return join(this.filesDir, '.partial', key); }
|
|
1284
|
+
|
|
1285
|
+
// A file's chunks wait in filesDir/.out/<item id>.json (0600, directory 0700), not in the state:
|
|
1286
|
+
// base64 in an outbox item, 8 MiB were rewritten with the state at every chunk sent. The outbox
|
|
1287
|
+
// item keeps { id, label, spool: true }. A contact's name never starts with a dot (safeName), so
|
|
1288
|
+
// .out is no contact's directory. Written under the lock with the items that name them.
|
|
1289
|
+
#spoolDir() { return join(this.filesDir, '.out'); }
|
|
1290
|
+
#spool(id, content) {
|
|
1291
|
+
const dir = this.#spoolDir();
|
|
1292
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
1293
|
+
chmodSync(this.filesDir, 0o700); chmodSync(dir, 0o700);
|
|
1294
|
+
writeFileSync(join(dir, `${id}.json`), JSON.stringify(content), { mode: 0o600, flag: 'wx' });
|
|
1295
|
+
}
|
|
1296
|
+
#spooled(id) {
|
|
1297
|
+
try { return JSON.parse(readFileSync(join(this.#spoolDir(), `${id}.json`), 'utf8')); } catch (e) {
|
|
1298
|
+
fail('file', `a queued part of a file is gone from ${this.#spoolDir()} (${e.code ?? e.message}): send the file again`);
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
// Spooled parts no outbox or pending entry names any more (sent, refused, forgotten): removed.
|
|
1302
|
+
#sweepSpool(st) {
|
|
1303
|
+
let names;
|
|
1304
|
+
try { names = readdirSync(this.#spoolDir()); } catch { return; }
|
|
1305
|
+
const held = new Set();
|
|
1306
|
+
for (const e of Object.values(st.peers)) for (const x of e.outbox ?? []) if (x.spool) held.add(x.id);
|
|
1307
|
+
for (const p of st.pending) if (p.item?.spool) held.add(p.item.id);
|
|
1308
|
+
for (const n of names) if (/^[0-9a-f]{16}\.json$/.test(n) && !held.has(n.slice(0, -5))) rmSync(join(this.#spoolDir(), n), { force: true });
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
// Files still incomplete after the retention (the relay has dropped whatever of them was left to
|
|
1312
|
+
// come): their parts go, counted file_incomplete, and inbox() says which.
|
|
1313
|
+
#sweepFiles(st, now) {
|
|
1314
|
+
for (const [key, p] of Object.entries(st.files ?? {})) {
|
|
1315
|
+
if (p.first + this.retention > now) continue;
|
|
1316
|
+
rmSync(this.#partDir(key), { recursive: true, force: true });
|
|
1317
|
+
delete st.files[key];
|
|
1318
|
+
st.dropped.file_incomplete = (st.dropped.file_incomplete ?? 0) + 1;
|
|
1319
|
+
this.#emit(this.#note(st, now, { type: 'dropped', check: 'file_incomplete', from: p.from,
|
|
1320
|
+
detail: `${p.name} (${p.size} bytes): ${p.got.length} of ${p.chunks} parts came within the retention; the rest will not: ask for it again` }));
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1078
1324
|
// A bundle from the contact was accepted into s (acceptPrekeys). want: it asked for ours, which
|
|
1079
1325
|
// goes unless one went within RESYNC (the header's "Prekeys").
|
|
1080
1326
|
#tookPrekeys(st, s, want, now) {
|
|
@@ -1430,10 +1676,16 @@ export class Carrier {
|
|
|
1430
1676
|
if (missing !== null) e.asked = now;
|
|
1431
1677
|
return this.#queue(st, { relay, topic: t, bytes: frame, kind: KIND_PREKEYS, peer: c.did, control: 'prekeys' });
|
|
1432
1678
|
}
|
|
1679
|
+
// This agent's operator hints, once per pairing and set of operators (#onOperator).
|
|
1680
|
+
const mine = this.#mine(me, now), ops = mine.operators, hinted = opKey(mine, ops);
|
|
1681
|
+
if (ops.length > 0 && e.op_hinted !== hinted) {
|
|
1682
|
+
e.op_hinted = hinted;
|
|
1683
|
+
e.outbox.unshift({ id: randomId(), label: OPERATOR_LABEL, content: { hints: [...ops].sort().map((d) => operatorHint(K, 'hint', me.did, d)) } });
|
|
1684
|
+
}
|
|
1433
1685
|
while (e.outbox.length > 0) {
|
|
1434
1686
|
const item = e.outbox[0];
|
|
1435
1687
|
try {
|
|
1436
|
-
const m = send(s, { label: item.label, content: item.content }, now);
|
|
1688
|
+
const m = send(s, { label: item.label, content: item.spool ? this.#spooled(item.id) : item.content }, now);
|
|
1437
1689
|
e.outbox.shift();
|
|
1438
1690
|
if (e.waiting === noReader(c.name)) e.waiting = null;
|
|
1439
1691
|
this.#persist(st, s);
|
|
@@ -1520,6 +1772,10 @@ export class Carrier {
|
|
|
1520
1772
|
}
|
|
1521
1773
|
|
|
1522
1774
|
async #flush(link) {
|
|
1775
|
+
try { await this.#flushing(link); } finally { try { this.#locked(({ st }) => this.#sweepSpool(st)); } catch {} }
|
|
1776
|
+
}
|
|
1777
|
+
|
|
1778
|
+
async #flushing(link) {
|
|
1523
1779
|
for (;;) {
|
|
1524
1780
|
if (!link.up) return;
|
|
1525
1781
|
const e = this.#locked((ctx) => this.#next(ctx, link));
|
|
@@ -1659,6 +1915,7 @@ export class Carrier {
|
|
|
1659
1915
|
const { me, proven } = this.#read(({ me, st }) => ({ me, proven: st.relays[relay]?.proven === true }));
|
|
1660
1916
|
const powMax = relay === this.relay ? POW_MAX : POW_MAX_OTHER;
|
|
1661
1917
|
const r = await http(`${ep.http}/challenge?did=${encodeURIComponent(me.current_did)}`);
|
|
1918
|
+
this.#clockFrom(relay, r);
|
|
1662
1919
|
if (r.status === 429) refuse('rate', `the relay ${relay} turned the login away: too many logins from this network (${relaySays(r.body?.error ?? r.body?.detail)}): ${retryIn(r, 'a minute')}, then try again`, r);
|
|
1663
1920
|
// Any other status is no answer about this agent (nginx says 502 while the relay restarts):
|
|
1664
1921
|
// `connect`, retried. `challenge`, which no retry fixes, is a 200 that is not this relay's
|
|
@@ -1714,6 +1971,7 @@ export class Carrier {
|
|
|
1714
1971
|
this.#ask = false;
|
|
1715
1972
|
try {
|
|
1716
1973
|
const r = await http(`${ep.http}/relay.json`);
|
|
1974
|
+
this.#clockFrom(this.relay, r);
|
|
1717
1975
|
const n = r.status === 200 ? retentionOf(r.body) : null;
|
|
1718
1976
|
if (n !== null) this.retention = n * DAY;
|
|
1719
1977
|
} catch {}
|
|
@@ -1721,6 +1979,26 @@ export class Carrier {
|
|
|
1721
1979
|
|
|
1722
1980
|
get retentionDays() { return this.retention / DAY; }
|
|
1723
1981
|
|
|
1982
|
+
// The relay's clock less this agent's (this.clock), in seconds, from an answer r of relay: its
|
|
1983
|
+
// Date header (whole seconds, so +0.5) taken as of the middle of the round trip.
|
|
1984
|
+
#clockFrom(relay, r) {
|
|
1985
|
+
if (r?.date == null) return;
|
|
1986
|
+
const now = this.clock();
|
|
1987
|
+
this.#clocks.set(relay, { offset: Math.round((r.date + 500 - r.rtt / 2) / 1000 - now), checked: now });
|
|
1988
|
+
}
|
|
1989
|
+
|
|
1990
|
+
/** { relay, offset, checked } as last measured at relay (a login, relay.json, a short code), or null. offset: seconds, relay minus local. */
|
|
1991
|
+
clockOffset(relay = this.relay) {
|
|
1992
|
+
const c = this.#clocks.get(relay);
|
|
1993
|
+
return c ? { relay, ...c } : null;
|
|
1994
|
+
}
|
|
1995
|
+
|
|
1996
|
+
/** Measures the offset now at this agent's own relay (GET /relay.json). → clockOffset(); throws as a relay that does not answer does. */
|
|
1997
|
+
async checkClock() {
|
|
1998
|
+
this.#clockFrom(this.relay, await http(`${endpointOf(this.relay, this.endpoints).http}/relay.json`));
|
|
1999
|
+
return this.clockOffset();
|
|
2000
|
+
}
|
|
2001
|
+
|
|
1724
2002
|
async #dial(relay) {
|
|
1725
2003
|
const ep = endpointOf(relay, this.endpoints), link = new Link(relay, relay === this.relay);
|
|
1726
2004
|
const info = link.own && this.#ask ? this.#relayInfo(ep) : null;
|
|
@@ -1915,7 +2193,8 @@ export class Carrier {
|
|
|
1915
2193
|
try { return await this.#answer(long, how, opts); } catch (e) { throw keepLong(e, long); }
|
|
1916
2194
|
}
|
|
1917
2195
|
|
|
1918
|
-
async #answer(text, how, { name, wait = 10 } = {}) {
|
|
2196
|
+
async #answer(text, how, { name, wait = 10, tier } = {}) {
|
|
2197
|
+
if (tier !== undefined && !TIERS.includes(tier)) fail('tier', `a tier is ${TIERS.join(', ')}; not ${JSON.stringify(tier)}`);
|
|
1919
2198
|
const { code, id, entry } = this.#locked(({ now, me, store, st }) => {
|
|
1920
2199
|
const code = readCode(text, now, how);
|
|
1921
2200
|
// This agent's own relay, and those its operator configured, are the operator's choice.
|
|
@@ -1931,7 +2210,7 @@ export class Carrier {
|
|
|
1931
2210
|
const id = answerId(answer);
|
|
1932
2211
|
// Unnamed: the code's DID's first digits ("z5esAbCd"), as operators shorten a DID. Named, the
|
|
1933
2212
|
// 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);
|
|
2213
|
+
store.addAccept(code, id, name ?? code.did.slice('did:sigelo:'.length, 'did:sigelo:'.length + 8), now, hex(k.secretKey), me.current_did, name !== undefined, tier ?? null);
|
|
1935
2214
|
const entry = this.#queue(st, { relay: code.relay, topic: keys.answer_topic, bytes: frame, kind: KIND.invite_answer, control: 'answer', needs: [keys.reply_topic], exp: code.exp });
|
|
1936
2215
|
return { code, id, entry: entry.id };
|
|
1937
2216
|
} finally { k.secretKey.fill(0); }
|
|
@@ -1944,7 +2223,8 @@ export class Carrier {
|
|
|
1944
2223
|
// Done early too once the reply topic or the answer is refused (a code answered before:
|
|
1945
2224
|
// mailbox_taken), not after the whole wait.
|
|
1946
2225
|
const reply = inviteKeys(code.secret).reply_topic;
|
|
1947
|
-
|
|
2226
|
+
// And once the code expires (#lapse): the answer is dead, so --wait does not run out first.
|
|
2227
|
+
const settled = () => this.#handshakes.has(id) || this.#refusedTopics.has(reply) || Boolean(this.#results.get(entry)?.code) || this.clock() >= code.exp;
|
|
1948
2228
|
try { await this.#session([code.relay], { max: wait * 1000, until: settled }); } catch (e) {
|
|
1949
2229
|
// A relay other than this agent's own that refuses it for good would be dialled again at
|
|
1950
2230
|
// every connection, until the code expires, for an answer it never takes: and a stranger's
|
|
@@ -1975,16 +2255,47 @@ export class Carrier {
|
|
|
1975
2255
|
: `the relay did not let this agent claim the reply topic (${relaySays(r.detail)})`);
|
|
1976
2256
|
}
|
|
1977
2257
|
if (sent?.code) drop(sent.code, `the relay refused the answer (${relaySays(sent.detail)})`);
|
|
2258
|
+
// The code expired during the wait: #lapse emitted pairing_failed (onEvent); the refusal says
|
|
2259
|
+
// it here, so the next inbox does not say it again. No long code to keep (keepLong): it is dead.
|
|
2260
|
+
const lapsed = this.#locked(({ now, store, st }) => {
|
|
2261
|
+
if (now < code.exp) return null;
|
|
2262
|
+
st.pending = st.pending.filter((p) => p.id !== entry); store.take('accepts', id, now);
|
|
2263
|
+
const at = new Date(code.exp * 1000).toISOString().replace('.000', '');
|
|
2264
|
+
const i = st.events.findIndex((e) => e.type === 'pairing_failed' && e.code === 'code_expired' && e.did === code.did && e.detail?.includes(at));
|
|
2265
|
+
return i >= 0 ? st.events.splice(i, 1)[0].detail : `the code expired at ${at} before the inviter's agent replied: ask the inviter for a new code`;
|
|
2266
|
+
});
|
|
2267
|
+
if (lapsed) throw Object.assign(new MsgError('code_expired', lapsed), { lapsed: true });
|
|
1978
2268
|
if (!sent) return { status: 'pending', did: code.did, relay: code.relay, detail: 'the answer has not reached the relay yet: it goes at the next connection' };
|
|
1979
2269
|
return { status: 'waiting', did: code.did, relay: code.relay, detail: 'answer delivered; the pairing completes when the inviter\'s agent next connects' };
|
|
1980
2270
|
}
|
|
1981
2271
|
|
|
2272
|
+
// An invite this agent made and nobody has answered, withdrawn: code, its long code (invite's
|
|
2273
|
+
// `code`). Its answer topic is given up at the next round; a short code parked for it leads to
|
|
2274
|
+
// nothing. → { cancelled: true, name }.
|
|
2275
|
+
async cancelInvite(code) {
|
|
2276
|
+
const { relay, name } = this.#locked(({ now, store }) => {
|
|
2277
|
+
const c = readCode(code, now), p = store.load().s.invites[c.nonce];
|
|
2278
|
+
store.cancelInvite(c.nonce);
|
|
2279
|
+
return { relay: c.relay, name: p.name };
|
|
2280
|
+
});
|
|
2281
|
+
this.#routes = new Map();
|
|
2282
|
+
if (this.#links.get(relay)?.up) this.#refreshSoon(relay);
|
|
2283
|
+
return { cancelled: true, name };
|
|
2284
|
+
}
|
|
2285
|
+
|
|
2286
|
+
/** The owner renames a contact (a name or any DID of its chain; store.mjs rename) → { did, name }. */
|
|
2287
|
+
rename(who, name) { return this.#locked(({ store }) => store.rename(who, name)); }
|
|
2288
|
+
|
|
1982
2289
|
contacts() {
|
|
1983
2290
|
return this.#read(({ now, store, st }) => {
|
|
1984
2291
|
const s = store.load().s;
|
|
1985
2292
|
return {
|
|
1986
|
-
contacts: Object.values(s.contacts).map((c) =>
|
|
1987
|
-
|
|
2293
|
+
contacts: Object.values(s.contacts).map((c) => {
|
|
2294
|
+
const e = st.peers[c.did], pair = c.revoked || !c.pair_key ? null : pairId(hexToBytes(c.pair_key));
|
|
2295
|
+
return { name: c.name, did: c.did, current_did: c.current_did, chain: c.chain, revoked: c.revoked, relay: c.relay, queued: e?.outbox.length ?? 0,
|
|
2296
|
+
re_pair: c.re_pair ?? null, fingerprint: c.revoked ? null : wordsOf(c.pair_key), pair, tier: store.tierOf(c, now), tier_by: c.tier_by ?? null,
|
|
2297
|
+
prekeys: pair !== null && theirPrekeys(c, e?.session, pair, now), waiting: e?.waiting ?? null };
|
|
2298
|
+
}),
|
|
1988
2299
|
invites: Object.values(s.invites).filter((p) => p.exp > now).map((p) => ({ name: p.name, exp: p.exp, relay: p.relay })),
|
|
1989
2300
|
answers: Object.values(s.accepts).filter((p) => p.exp > now).map((p) => ({ name: p.name, did: p.code_did, exp: p.exp, relay: p.relay })),
|
|
1990
2301
|
// Pairings that failed since the last inbox, which takes them as events.
|
|
@@ -1993,8 +2304,8 @@ export class Carrier {
|
|
|
1993
2304
|
});
|
|
1994
2305
|
}
|
|
1995
2306
|
|
|
1996
|
-
async send(to, content, { label = '' } = {}) {
|
|
1997
|
-
const [r] = await this.sendAll(to, [content], { label });
|
|
2307
|
+
async send(to, content, { label = '', local = false } = {}) {
|
|
2308
|
+
const [r] = await this.sendAll(to, [content], { label, local });
|
|
1998
2309
|
if (r.status === 'refused') fail(r.code, `refused (${r.detail})`);
|
|
1999
2310
|
return r;
|
|
2000
2311
|
}
|
|
@@ -2002,9 +2313,13 @@ export class Carrier {
|
|
|
2002
2313
|
// Several messages to one contact in one session: one login, where `send` costs one each (the
|
|
2003
2314
|
// relay allows 30 logins a minute per network). sent: the relay accepted it, and holds it for
|
|
2004
2315
|
// the contact's claim on the topic; queued: it goes at the next connection.
|
|
2005
|
-
async sendAll(to, contents, { label = '' } = {}) {
|
|
2316
|
+
async sendAll(to, contents, { label = '', local = false } = {}) { return this.#sendAll(to, contents, label, false, local); }
|
|
2317
|
+
|
|
2318
|
+
// spool: every content after the first waits on disk (#spool), as a file's chunks do. local: queued
|
|
2319
|
+
// only, for the started carrier of this identity in another process (inbox's local, for sending).
|
|
2320
|
+
async #sendAll(to, contents, label, spool, local = false) {
|
|
2006
2321
|
if (typeof label !== 'string') fail('body', 'label must be a string');
|
|
2007
|
-
if (label === LABEL_PREKEYS) fail('body', `the label ${JSON.stringify(
|
|
2322
|
+
if (label === LABEL_PREKEYS || label === OPERATOR_LABEL) fail('body', `the label ${JSON.stringify(label)} is the carrier's own`);
|
|
2008
2323
|
if (!Array.isArray(contents) || contents.length === 0) fail('body', 'at least one message');
|
|
2009
2324
|
for (const content of contents) {
|
|
2010
2325
|
if (content === undefined) fail('body', 'content is required');
|
|
@@ -2015,7 +2330,7 @@ export class Carrier {
|
|
|
2015
2330
|
// contact already, re-pairs) and goes under the key the reply brings.
|
|
2016
2331
|
const answered = this.#read(({ now, store }) => [...new Set(Object.values(store.load().s.accepts)
|
|
2017
2332
|
.filter((p) => p.exp > now && (p.name === to || p.code_did === to)).map((p) => p.relay))]);
|
|
2018
|
-
if (answered.length > 0) {
|
|
2333
|
+
if (answered.length > 0 && !local) {
|
|
2019
2334
|
try { await this.#session(answered); } catch {}
|
|
2020
2335
|
this.#routes = new Map();
|
|
2021
2336
|
this.#read(({ now, store }) => {
|
|
@@ -2028,9 +2343,14 @@ export class Carrier {
|
|
|
2028
2343
|
}
|
|
2029
2344
|
const { ids, c } = this.#locked(({ store, st }) => {
|
|
2030
2345
|
const c = this.#resolve(store, to), outbox = this.#entry(st, c.did).outbox;
|
|
2031
|
-
const ids = contents.map((content) => {
|
|
2346
|
+
const ids = contents.map((content, i) => {
|
|
2347
|
+
const id = randomId();
|
|
2348
|
+
if (spool && i > 0) { this.#spool(id, content); outbox.push({ id, label, spool: true }); } else outbox.push({ id, label, content });
|
|
2349
|
+
return id;
|
|
2350
|
+
});
|
|
2032
2351
|
return { ids, c };
|
|
2033
2352
|
});
|
|
2353
|
+
if (local) return ids.map((id) => ({ status: 'queued', id, to: c.did, name: c.name, detail: 'kept for the process that holds this identity\'s relay session: it sends it' }));
|
|
2034
2354
|
try { await this.#session([c.relay]); } catch (e) {
|
|
2035
2355
|
throw new MsgError(e.check ?? 'connect', `${reason(e)} (${ids.length === 1 ? 'the message stays' : `the ${ids.length} messages stay`} queued for ${c.name}: they go at the next connection)`, { cause: e, http: e.http });
|
|
2036
2356
|
}
|
|
@@ -2044,26 +2364,104 @@ export class Carrier {
|
|
|
2044
2364
|
});
|
|
2045
2365
|
}
|
|
2046
2366
|
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2367
|
+
// A file to a contact (file.mjs): its manifest and chunks in one sendAll, so one login. Read whole
|
|
2368
|
+
// first (at most MAX_FILE); this identity's own files (key, contacts, state, files received) are
|
|
2369
|
+
// refused, so a confused or misled agent cannot send its key. A refusal of any part throws as
|
|
2370
|
+
// send does: the contact gets no file, and what came of it there goes at its retention.
|
|
2371
|
+
async sendFile(to, path, { local = false } = {}) {
|
|
2372
|
+
if (typeof path !== 'string' || path === '') fail('file', 'a file path is required');
|
|
2373
|
+
let real, bytes;
|
|
2052
2374
|
try {
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2375
|
+
real = realpathSync(path);
|
|
2376
|
+
const s = statSync(real);
|
|
2377
|
+
if (!s.isFile()) fail('file', `${path} is not a regular file`);
|
|
2378
|
+
if (s.size > MAX_FILE) fail('file_too_large', `${path} is ${s.size} bytes, at most ${MAX_FILE} (8 MiB) a file`);
|
|
2379
|
+
} catch (e) {
|
|
2380
|
+
if (e instanceof MsgError) throw e;
|
|
2381
|
+
fail('file', `cannot read ${path}: ${e.code === 'ENOENT' ? 'no such file' : e.code ?? e.message}`, { cause: e });
|
|
2382
|
+
}
|
|
2383
|
+
// Beside the identity: its own files (x.*) and any profile's (*.local.*, sigelo-agent's pattern).
|
|
2384
|
+
const own = resolve(this.statePath.replace(/(\.carrier)?\.json$/, '')), files = (() => { try { return realpathSync(this.filesDir); } catch { return this.filesDir; } })();
|
|
2385
|
+
let ownDir;
|
|
2386
|
+
try { ownDir = realpathSync(dirname(own)); } catch { ownDir = dirname(own); }
|
|
2387
|
+
const leaf = basename(real);
|
|
2388
|
+
if (real.startsWith(files + sep) || (dirname(real) === ownDir && (leaf.startsWith(`${basename(own)}.`) || leaf.includes('.local.')))) {
|
|
2389
|
+
fail('file', `${path} is one of this agent's identity files (key, contacts, state, files received): not sent`);
|
|
2390
|
+
}
|
|
2391
|
+
try { bytes = readFileSync(real); } catch (e) { fail('file', `cannot read ${path}: ${e.code ?? e.message}`, { cause: e }); }
|
|
2392
|
+
if (bytes.length > MAX_FILE) fail('file_too_large', `${path} is ${bytes.length} bytes, at most ${MAX_FILE} (8 MiB) a file`);
|
|
2393
|
+
const { manifest, chunks } = splitFile(bytes, basename(real));
|
|
2394
|
+
const results = await this.#sendAll(to, [manifest, ...chunks], FILE_LABEL, true, local);
|
|
2395
|
+
const refused = results.find((x) => x.status === 'refused'), queued = results.find((x) => x.status === 'queued');
|
|
2396
|
+
if (refused) fail(refused.code, `refused (${refused.detail}): ${manifest.name} did not go whole; send it again once that is settled`);
|
|
2397
|
+
const { id, name, size, sha256: sum, chunks: n } = manifest;
|
|
2398
|
+
return { status: queued ? 'queued' : 'sent', to: results[0].to, name: results[0].name, file: { id, name, size, sha256: sum, chunks: n },
|
|
2399
|
+
...(queued && { detail: queued.detail }) };
|
|
2400
|
+
}
|
|
2401
|
+
|
|
2402
|
+
// tiers: only messages from contacts of these tiers are taken (and waited for); the rest stay for a
|
|
2403
|
+
// later inbox. Events are all taken. local: no session: what the state file holds, waited for by
|
|
2404
|
+
// reading it again, for a reader beside a started carrier of the same identity (a watcher), which
|
|
2405
|
+
// a session here would disconnect.
|
|
2406
|
+
async inbox({ wait = 0, tiers, local = false, paired = false } = {}) {
|
|
2407
|
+
const want = tiers === undefined ? null : new Set(tiers);
|
|
2408
|
+
if (want && ![...want].every((t) => TIERS.includes(t))) fail('tier', `tiers: some of ${TIERS.join(', ')}`);
|
|
2409
|
+
const picks = (store, now) => { const t = want && store.tiers(now); return (m) => !want || want.has(t.get(m.from) ?? 'friend'); };
|
|
2410
|
+
const ready = () => this.#read(({ now, store, st }) => st.inbox.some(picks(store, now)) || st.events.some((e) => e.type === 'pairing_failed' || (paired && e.type === 'paired')));
|
|
2411
|
+
let offline = null;
|
|
2412
|
+
if (local) {
|
|
2413
|
+
for (const end = Date.now() + wait * 1000; Date.now() < end && !ready();) await sleep(250);
|
|
2414
|
+
} else {
|
|
2415
|
+
// With nothing in use anywhere, this agent's own relay: an operator with no contacts logs in by
|
|
2416
|
+
// `inbox` before uploading its licence (relay/site/pro.md step 2), and proves its work there.
|
|
2417
|
+
const inUse = this.#relaysInUse(), relays = inUse.length > 0 ? inUse : [this.relay];
|
|
2418
|
+
try {
|
|
2419
|
+
await this.#session(relays, wait > 0 ? { max: wait * 1000, until: ready } : {});
|
|
2420
|
+
} catch (e) { this.lastError = e; offline = e instanceof MsgError ? e.message : `connect: ${e.message}`; }
|
|
2421
|
+
}
|
|
2422
|
+
return this.#locked(({ now, store, st }) => {
|
|
2423
|
+
this.#sweepFiles(st, now);
|
|
2424
|
+
const pick = picks(store, now), messages = st.inbox.filter(pick);
|
|
2425
|
+
const out = { messages, events: st.events, dropped: st.dropped, ...(offline && { offline }) };
|
|
2426
|
+
st.inbox = st.inbox.filter((m) => !pick(m)); st.events = []; st.dropped = {};
|
|
2427
|
+
return out;
|
|
2428
|
+
});
|
|
2429
|
+
}
|
|
2430
|
+
|
|
2431
|
+
peek() {
|
|
2432
|
+
return this.#read(({ now, store, st }) => { const t = store.tiers(now); return st.inbox.map((m) => ({ ...m, tier: t.get(m.from) ?? 'friend' })); });
|
|
2433
|
+
}
|
|
2434
|
+
|
|
2435
|
+
take(pick) {
|
|
2436
|
+
if (typeof pick !== 'function') throw new TypeError('take: a function (message, tier) → boolean');
|
|
2437
|
+
return this.#locked(({ now, store, st }) => {
|
|
2438
|
+
const t = store.tiers(now), out = [], keep = [];
|
|
2439
|
+
for (const m of st.inbox) (pick(m, t.get(m.from) ?? 'friend') ? out : keep).push(m);
|
|
2440
|
+
st.inbox = keep;
|
|
2058
2441
|
return out;
|
|
2059
2442
|
});
|
|
2060
2443
|
}
|
|
2061
2444
|
|
|
2445
|
+
setTier(who, tier) { return this.#locked(({ now, store }) => store.setTier(who, tier, now)); }
|
|
2446
|
+
|
|
2447
|
+
// A contact's full bundle, from wherever it came (the UI reads its local agents' files): verified
|
|
2448
|
+
// here; → { did, tier }, or null when it is no contact's.
|
|
2449
|
+
observe(bundle) {
|
|
2450
|
+
return this.#locked(({ now, store }) => {
|
|
2451
|
+
let r;
|
|
2452
|
+
try { r = verify(bundle, now); } catch (e) { fail('bundle', `REJECT: ${e.message}`); }
|
|
2453
|
+
const c = store.lookup(r.chain[0]);
|
|
2454
|
+
if (!c || c.revoked || c.did !== r.chain[0]) return null;
|
|
2455
|
+
return { did: c.did, tier: store.observe(c.did, r, now) };
|
|
2456
|
+
});
|
|
2457
|
+
}
|
|
2458
|
+
|
|
2062
2459
|
async forget(did) {
|
|
2063
2460
|
const c = this.#locked(({ store, st }) => {
|
|
2064
2461
|
const c = store.revoke(did);
|
|
2065
2462
|
delete st.peers[c.did];
|
|
2066
2463
|
st.pending = st.pending.filter((p) => p.peer !== c.did);
|
|
2464
|
+
this.#sweepSpool(st);
|
|
2067
2465
|
return c;
|
|
2068
2466
|
});
|
|
2069
2467
|
this.#routes = new Map();
|