sigelo-contact 0.1.2 → 0.1.4
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 +10 -8
- package/carrier.mjs +242 -48
- package/fixtures/carrier-v0.json +113 -1
- package/gen-carrier.mjs +14 -6
- package/package.json +2 -2
- package/store.mjs +8 -5
- package/test-carrier.mjs +202 -32
package/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
<!-- SPDX-License-Identifier: MIT -->
|
|
2
2
|
# sigelo-contact
|
|
3
3
|
|
|
4
|
-
Two agents swap a one-line code
|
|
4
|
+
Two agents swap a one-line code, then send each other end-to-end encrypted
|
|
5
5
|
messages through a relay that holds them while one is offline and cannot read them. Each checks
|
|
6
6
|
the other's sigelo chain offline; a key rotation keeps the contact. MIT; the relay,
|
|
7
7
|
[sigelo-relay](https://github.com/csigelo/sigelo-relay), is AGPL-3.0.
|
|
@@ -9,21 +9,23 @@ the other's sigelo chain offline; a key rotation keeps the contact. MIT; the rel
|
|
|
9
9
|
```sh
|
|
10
10
|
sigelo-agent invite --name bob # alice: one-time code, 24 hours
|
|
11
11
|
sigelo-agent accept <code> --name alice # bob: checks alice offline, pairs
|
|
12
|
-
sigelo-agent send bob "hello" # sent, or
|
|
12
|
+
sigelo-agent send bob "hello" # sent, or queued until bob's agent connects
|
|
13
13
|
seq 3 | sigelo-agent send bob - --lines # one message a line, one login
|
|
14
14
|
sigelo-agent inbox # what came since last time
|
|
15
15
|
```
|
|
16
16
|
|
|
17
17
|
Also `contacts`, `forget <did>`, and all as MCP tools
|
|
18
|
-
([`integrations/mcp/contact.mjs`](../integrations/mcp/contact.mjs))
|
|
18
|
+
([`integrations/mcp/contact.mjs`](../integrations/mcp/contact.mjs)).
|
|
19
19
|
Each verb logs in once (a relay allows 30 a minute per network).
|
|
20
|
-
The first login proves work (
|
|
20
|
+
The first login proves work (5 to 60 s on a phone). `SIGELO_RELAY` names the relay for new codes
|
|
21
21
|
(default `relay.sigelo.ai`); a Pro reader sets `SIGELO_RELAY_RETENTION_DAYS=90`. State sits
|
|
22
22
|
beside the identity file (0600); messages wait there in plaintext until `inbox` takes them.
|
|
23
23
|
`carrier.mjs`'s header is its API; with `onEvent`, nothing is kept.
|
|
24
24
|
|
|
25
25
|
## Tests
|
|
26
26
|
|
|
27
|
+
Node 22.18 or newer; tested on 24.
|
|
28
|
+
|
|
27
29
|
```sh
|
|
28
30
|
node test-invite.mjs && node test-envelope.mjs
|
|
29
31
|
node test-carrier.mjs # with ../relay, on loopback
|
|
@@ -55,7 +57,8 @@ Each regenerates byte for byte from seeds (`gen-*.mjs`); refusals name their che
|
|
|
55
57
|
reads a reply, each envelope repeats the encapsulation: a reader offline past retention loses
|
|
56
58
|
those messages, not the epoch. Prekeys travel under `K`, replaced weekly.
|
|
57
59
|
5. **Rotation**: the rotated agent sends each contact its chain under `K`, proven by its new key,
|
|
58
|
-
until the contact
|
|
60
|
+
until the contact confirms it, so recovery beats a thief (SPEC §7.1). After a recovery both
|
|
61
|
+
mark the pairing `re_pair`: only that notice goes under `K` until a new code replaces it.
|
|
59
62
|
6. **Relay login**: a signed `{v:"sigelo-relay/0", typ:"relay-login", did, relay, nonce}`, a
|
|
60
63
|
type no challenge signer produces.
|
|
61
64
|
|
|
@@ -67,8 +70,7 @@ Key agreement is hybrid post-quantum (X25519 + ML-KEM-768), as in Signal and Sim
|
|
|
67
70
|
(signed).
|
|
68
71
|
- Heal inside an epoch after a key theft (no double ratchet): a stolen state file reads what
|
|
69
72
|
contacts write until the next weekly prekey replacement.
|
|
70
|
-
-
|
|
71
|
-
|
|
72
|
-
with an epoch's key agreement loses what follows until fresh prekeys restart it.
|
|
73
|
+
- Confirm delivery (the relay acknowledges, not the contact): a relay withholding an epoch's key
|
|
74
|
+
agreement loses what follows until fresh prekeys restart it.
|
|
73
75
|
- Check where a stranger's relay resolves: only its name is checked.
|
|
74
76
|
- Push, groups, direct delivery, a second carrier (version 2), unsend.
|
package/carrier.mjs
CHANGED
|
@@ -10,14 +10,15 @@
|
|
|
10
10
|
// await c.send(to, content, { label }) → { status: 'sent' | 'queued', … }, or throws the relay's code
|
|
11
11
|
// await c.sendAll(to, contents, { label }) → one result each ('refused' with its code), one login
|
|
12
12
|
// await c.inbox({ wait }) → { messages, events, dropped, offline? }: all are taken (messages: those kept)
|
|
13
|
-
// await c.forget(did) → { name, did, revoked: true, released }
|
|
13
|
+
// await c.forget(did) → { name, did, revoked: true, released, offline? }
|
|
14
14
|
// await c.start(), c.sync(), c.stop() stay connected, reconnecting with backoff; events reach onEvent
|
|
15
15
|
//
|
|
16
16
|
// identity() → { secret, bundle }: the agent's current secret key and SPEC §8 bundle, read again at
|
|
17
17
|
// every operation, so a rotation made by another process is seen at once. store: the contact store
|
|
18
18
|
// (store.mjs); state: this file's own JSON (sessions, outbox, inbox), both 0600 and written under one
|
|
19
19
|
// lock file, `<state>.lock`. pathsFor(identityFile) names both beside the identity file. onEvent(e):
|
|
20
|
-
// each event as it happens, messages included
|
|
20
|
+
// each event as it happens, messages included, and `pow` / `pow_done` around a proof-of-work search
|
|
21
|
+
// (seconds to a minute on a phone: say so to the operator). keep: messages also wait in the state file for
|
|
21
22
|
// inbox(), in plaintext, until taken (INBOX_MAX at most: the oldest go, counted as inbox_full); by
|
|
22
23
|
// default only without onEvent, so a message onEvent took is not left at rest after the keys that
|
|
23
24
|
// opened it are gone (contacts.md §3: keys stolen today must not open yesterday's messages).
|
|
@@ -93,15 +94,41 @@
|
|
|
93
94
|
// on reading the notice, retires the prekeys it listed and sends fresh ones. The pairing key
|
|
94
95
|
// K stays: whoever copied the store can compute and claim later mailbox topics until the two
|
|
95
96
|
// pair again (invite and accept between existing contacts replace K: `rekeyed`).
|
|
97
|
+
// - After a recovery, K is burned on both sides (re_pair, in the contact store): the recovered
|
|
98
|
+
// agent marks every contact it paired with before the recovery (`own_recovery`, #markRecovered),
|
|
99
|
+
// and a contact marks it on merging a notice that brings a recovery it had not followed
|
|
100
|
+
// (`contact_recovery`). Toward a marked contact nothing goes but the rotation notice, and no
|
|
101
|
+
// new mailbox of the pair is claimed: a thief holding K claims weeks nobody writes in. A
|
|
102
|
+
// message queued for it before the mark is refused, and noted (`refused`, code re_pair). A new
|
|
103
|
+
// invite and accept replace K and clear the mark (store.admit writes the record afresh). A
|
|
104
|
+
// contact on sigelo-contact 0.1.2 follows the recovery but marks nothing and keeps writing
|
|
105
|
+
// under K, to weeks nobody may read but a thief: the recovered side pairs again at once.
|
|
106
|
+
// - Recovery beats key, for messages too: a contact's envelope signed by a DID that a recovery
|
|
107
|
+
// this agent follows has overruled (any DID of the contact's chain up to the node recovered
|
|
108
|
+
// from, or on a fork the recovery left) is refused, and noted (`refused`, code re_pair, `from`
|
|
109
|
+
// the contact): it may be the thief's. The relay delivers in the order written, so a thief's
|
|
110
|
+
// messages written before the owner recovered arrive before the recovery's notice, and were
|
|
111
|
+
// taken as the contact's. So a notice that brings a recovery checks again every message of
|
|
112
|
+
// that contact still waiting for inbox() against the chain it ends at (the recovery is not
|
|
113
|
+
// taken first: the relay alone decides what comes when), and one that arrives after it fails
|
|
114
|
+
// `from`, reported as re_pair. A message signed by the recovered-from key before the theft
|
|
115
|
+
// cannot be told from the thief's: refused alike; the owner writes again once paired again.
|
|
116
|
+
// What an earlier inbox() returned, or onEvent got, cannot be taken back: the `rotated` event
|
|
117
|
+
// of such a notice lists the DIDs it overruled (`overruled`).
|
|
96
118
|
// - Mailboxes: an agent holds the topics of every ISO week from `retention` ago to AHEAD (7 days,
|
|
97
119
|
// or its retention if shorter) ahead. The relay drops a publish to a topic nobody claimed (and
|
|
98
120
|
// says no_reader), so next week's topic must be claimed before a contact writes in it while
|
|
99
|
-
// this agent is offline.
|
|
100
|
-
//
|
|
101
|
-
//
|
|
102
|
-
//
|
|
103
|
-
//
|
|
104
|
-
//
|
|
121
|
+
// this agent is offline. An invitee's mailbox cannot be claimed before it reads the inviter's
|
|
122
|
+
// reply (the topic needs K, which the reply carries), so the inviter's first frames to it meet
|
|
123
|
+
// no_reader until the invitee next connects. A no_reader never loses a message: it stays queued
|
|
124
|
+
// here, unsealed (its epoch restarted when it began one, its prekey given back), with
|
|
125
|
+
// everything else to that contact until the next round, and goes at the next connection that
|
|
126
|
+
// finds the mailbox held (`queued`, the reason in its detail). Free tier: 14 days, 4 weeks
|
|
127
|
+
// (5 within 5 minutes of Monday 00:00 UTC), so 4 or 5 mailboxes per contact; Pro's 90 days:
|
|
128
|
+
// 14 or 15 (relay/allowance.mjs counts 15). A reader away longer than a week is told nothing of
|
|
129
|
+
// contacts writing in a week it did not claim: their messages wait on their side (no_reader).
|
|
130
|
+
// The retention: the constructor's, else relay.json's free tier at this agent's own relay
|
|
131
|
+
// (read once, at the first login), else RETENTION_DAYS. A Pro reader must say its 90 days
|
|
105
132
|
// (SIGELO_RELAY_RETENTION_DAYS): nothing tells the carrier its tier. A claim past its time is
|
|
106
133
|
// given up only once deliveries have stopped, so what is queued on it is read first. The relay
|
|
107
134
|
// brakes new claims (relay/allowance.mjs RATE.claim: 128 at once per identity, then 2 a second):
|
|
@@ -130,7 +157,8 @@ export const LABEL_PREKEYS = 'sigelo-msg/0 prekeys', KIND_NOTICE = 4, KIND_PREKE
|
|
|
130
157
|
// type of its own, never a SPEC §5.2 challenge: a world that passed the relay's nonce on as its own
|
|
131
158
|
// challenge would get the agent's relay login back from sign-challenge.
|
|
132
159
|
export const LOGIN_V = 'sigelo-relay/0', TYP_LOGIN = 'relay-login';
|
|
133
|
-
|
|
160
|
+
// RETENTION_DAYS: the relay's free tier (relay/allowance.mjs TIERS.free), when relay.json says nothing.
|
|
161
|
+
export const RETENTION_DAYS = 14, RETENTION_MAX_DAYS = 90, DAY = 86400, SKEW = 300, AHEAD = 7 * DAY;
|
|
134
162
|
// The relay closes a connection whose SUBSCRIBE holds more topics (relay/mailbox.mjs MAX_TOPICS).
|
|
135
163
|
const MAX_TOPICS = 128;
|
|
136
164
|
// An invite topic holds 4 messages and 64 KB (relay/mailbox.mjs INVITE_BYTES); a bundle at most 64
|
|
@@ -271,6 +299,14 @@ export function publicRelay(relay) {
|
|
|
271
299
|
return host.includes('.') && !IPV4_LIKE.test(host) && !LOCAL_NAME.test(host);
|
|
272
300
|
}
|
|
273
301
|
|
|
302
|
+
const retentionOk = (n) => Number.isSafeInteger(n) && n >= 1 && n <= RETENTION_MAX_DAYS;
|
|
303
|
+
|
|
304
|
+
/** The free tier's retention in days that a relay's relay.json states (limits.free.retention_days), or null. */
|
|
305
|
+
export function retentionOf(info) {
|
|
306
|
+
const n = info?.limits?.free?.retention_days;
|
|
307
|
+
return retentionOk(n) ? n : null;
|
|
308
|
+
}
|
|
309
|
+
|
|
274
310
|
/** SIGELO_RELAY (the relay new invites name), SIGELO_RELAY_ENDPOINTS (JSON, as endpointOf), SIGELO_RELAY_RETENTION_DAYS. */
|
|
275
311
|
export function optionsFromEnv(env = process.env) {
|
|
276
312
|
const o = {};
|
|
@@ -280,7 +316,7 @@ export function optionsFromEnv(env = process.env) {
|
|
|
280
316
|
}
|
|
281
317
|
if (env.SIGELO_RELAY_RETENTION_DAYS) {
|
|
282
318
|
const n = Number(env.SIGELO_RELAY_RETENTION_DAYS);
|
|
283
|
-
if (!
|
|
319
|
+
if (!retentionOk(n)) fail('relay', `SIGELO_RELAY_RETENTION_DAYS: whole days, 1 to ${RETENTION_MAX_DAYS} (the reader's tier)`);
|
|
284
320
|
o.retentionDays = n;
|
|
285
321
|
}
|
|
286
322
|
return o;
|
|
@@ -512,6 +548,24 @@ async function http(url, init = {}) {
|
|
|
512
548
|
// Text a relay writes reaches the operator, and perhaps a model, inside this client's messages:
|
|
513
549
|
// quoted and cut short, so it reads as data.
|
|
514
550
|
const relaySays = (s) => `the relay says ${JSON.stringify(String(s ?? '').slice(0, 200))}`;
|
|
551
|
+
// A refusal's words without its check: a verb that adds to them keeps one "check: " in front.
|
|
552
|
+
const reason = (e) => (e instanceof MsgError && e.message.startsWith(`${e.check}: `) ? e.message.slice(e.check.length + 2) : e.message);
|
|
553
|
+
// Why nothing goes to a contact marked re_pair (the header's "After a recovery").
|
|
554
|
+
const rePairWhy = (c) => (c.re_pair === 'contact_recovery'
|
|
555
|
+
? `${c.name} recovered its identity after a theft: the pairing key may be the thief's; pair again (invite, accept) before writing`
|
|
556
|
+
: `this agent recovered its identity: the pairing key with ${c.name} may be the thief's; pair again (invite, and ${c.name}'s operator accepts the code) before writing`);
|
|
557
|
+
|
|
558
|
+
// A re-pair keeps a known contact's name (store.admit), unless the owner named the answer
|
|
559
|
+
// (`accept --name`): then that name. The inviter's `invite --name` names a new contact only: the
|
|
560
|
+
// code may be answered by anyone, and a re-key code's name is the contact's own. → the contact.
|
|
561
|
+
function renamed(store, c, entry) {
|
|
562
|
+
if (entry.named === true && c.name !== entry.name) { c.name = entry.name; store.save(); }
|
|
563
|
+
return c;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// Why messages to a contact wait after a no_reader (the header's "Mailboxes"): its agent has not
|
|
567
|
+
// claimed the mailbox they go to, not this one.
|
|
568
|
+
const noReader = (name) => `${name}'s agent does not hold its mailbox for this pairing yet (it has not run inbox since the pairing, or has been away longer than a week): kept here, it goes at your next inbox or send once ${name}'s agent has connected`;
|
|
515
569
|
|
|
516
570
|
// MQTT 3.1.1 says only "bad user name or password": POST /check with the same credentials names
|
|
517
571
|
// the failing check (relay/auth.mjs).
|
|
@@ -606,13 +660,16 @@ class Link {
|
|
|
606
660
|
export class Carrier {
|
|
607
661
|
#links = new Map(); #work = Promise.resolve(); #busy = 0; #lastWork = 0; #routes = new Map(); #results = new Map();
|
|
608
662
|
#claimed = new Set(); #refusedTopics = new Map(); #handshakes = new Map(); #soon = new Set();
|
|
609
|
-
#started = false; #tick = null; #timers = new Map(); #attempts = new Map(); #connecting = new Set(); #powFails = new Map();
|
|
663
|
+
#started = false; #tick = null; #timers = new Map(); #attempts = new Map(); #connecting = new Set(); #powFails = new Map(); #ask = false;
|
|
610
664
|
|
|
611
|
-
constructor({ identity, store, state, relay = DEFAULT_RELAY, endpoints = {}, retentionDays
|
|
665
|
+
constructor({ identity, store, state, relay = DEFAULT_RELAY, endpoints = {}, retentionDays, clock = () => Math.floor(Date.now() / 1000),
|
|
612
666
|
onEvent, keep, backoff = BACKOFF, tick = TICK }) {
|
|
613
667
|
if (typeof identity !== 'function') throw new TypeError('identity: a function returning { secret, bundle }');
|
|
614
668
|
if (typeof store !== 'string' || typeof state !== 'string') throw new TypeError('store, state: file paths (pathsFor(identityFile))');
|
|
615
|
-
if (
|
|
669
|
+
if (retentionDays !== undefined && !retentionOk(retentionDays)) throw new TypeError(`retentionDays: 1 to ${RETENTION_MAX_DAYS}`);
|
|
670
|
+
// Not given: relay.json's at the first login to this agent's own relay may set it (#relayInfo).
|
|
671
|
+
this.#ask = retentionDays === undefined;
|
|
672
|
+
retentionDays ??= RETENTION_DAYS;
|
|
616
673
|
if (onEvent !== undefined && typeof onEvent !== 'function') throw new TypeError('onEvent: a function');
|
|
617
674
|
if (keep !== undefined && typeof keep !== 'boolean') throw new TypeError('keep: true or false');
|
|
618
675
|
Object.assign(this, { identity, storePath: store, statePath: state, relay, endpoints, retention: retentionDays * DAY, clock, onEvent: onEvent ?? (() => {}),
|
|
@@ -627,7 +684,13 @@ export class Carrier {
|
|
|
627
684
|
let r;
|
|
628
685
|
try { r = verify(chainOf(bundle), now); } catch (e) { fail('identity', `this agent's bundle does not verify: ${e.message}`); }
|
|
629
686
|
const genesis = [bundle.genesis, ...bundle.rotations.map((x) => x.next_genesis)].find((g) => didOf(g) === r.did);
|
|
630
|
-
|
|
687
|
+
// The last edge of the chain followed that a recovery rotation took (-1: none): chain[recovery]
|
|
688
|
+
// is the node the owner recovered from (#markRecovered).
|
|
689
|
+
let recovery = -1;
|
|
690
|
+
for (let i = 0; i + 1 < r.chain.length; i++) {
|
|
691
|
+
if (bundle.rotations.some((x) => x.body.id === r.chain[i] && x.body.next === r.chain[i + 1] && x.body.reason === 'recovery')) recovery = i;
|
|
692
|
+
}
|
|
693
|
+
return { did: r.chain[0], current_did: r.did, secret, genesis, bundle, chain: r.chain, recovery };
|
|
631
694
|
}
|
|
632
695
|
|
|
633
696
|
// The state is saved before the store's held writes (store.mjs hold: a handshake's), so a crash
|
|
@@ -636,6 +699,9 @@ export class Carrier {
|
|
|
636
699
|
return withLock(this.statePath, () => {
|
|
637
700
|
const now = checkNow(this.clock()), me = this.#me(now);
|
|
638
701
|
const ctx = { now, me, store: new Contacts(this.storePath, me.did), st: loadState(this.statePath, me.did) };
|
|
702
|
+
// Before anything reads the store: a recovery made by another process (sigelo-agent recover)
|
|
703
|
+
// is seen at once. The store's marks are written first; the state keeps the events.
|
|
704
|
+
if (this.#markRecovered(ctx)) saveState(this.statePath, ctx.st);
|
|
639
705
|
const out = fn(ctx);
|
|
640
706
|
if (write) { saveState(this.statePath, ctx.st); ctx.store.commit(); }
|
|
641
707
|
return out;
|
|
@@ -644,6 +710,27 @@ export class Carrier {
|
|
|
644
710
|
#locked(fn) { return this.#with(true, fn); }
|
|
645
711
|
#read(fn) { return this.#with(false, fn); }
|
|
646
712
|
|
|
713
|
+
// This agent recovered after it last told a contact of its keys (`announced`: a DID at or before
|
|
714
|
+
// the node it recovered from, or one the recovery dropped, or none known): K and the session sat
|
|
715
|
+
// in the files a thief copied with the key. The contact is marked re_pair, `own_recovery` (the
|
|
716
|
+
// header's "After a recovery"), and the next inbox says so. A contact paired after the recovery
|
|
717
|
+
// was announced a later DID: not marked.
|
|
718
|
+
#markRecovered({ now, me, store, st }) {
|
|
719
|
+
if (me.recovery < 0) return false;
|
|
720
|
+
const marked = [];
|
|
721
|
+
for (const c of Object.values(store.load().s.contacts)) {
|
|
722
|
+
if (c.revoked || !c.pair_key || c.re_pair) continue;
|
|
723
|
+
const e = st.peers[c.did];
|
|
724
|
+
if (e && me.chain.indexOf(e.announced) > me.recovery) continue;
|
|
725
|
+
c.re_pair = 'own_recovery';
|
|
726
|
+
marked.push(c);
|
|
727
|
+
}
|
|
728
|
+
if (marked.length === 0) return false;
|
|
729
|
+
store.save();
|
|
730
|
+
for (const c of marked) this.#note(st, now, { type: 're_pair', did: c.did, name: c.name, re_pair: c.re_pair });
|
|
731
|
+
return true;
|
|
732
|
+
}
|
|
733
|
+
|
|
647
734
|
// announced: the current DID this agent last sent its rotation notice for, noticed: when; known:
|
|
648
735
|
// the current DID of this agent's the contact last said it holds (a prekeys frame's `known`;
|
|
649
736
|
// pairing: the one it checked); notice_asked: that was another one, so the notice goes again.
|
|
@@ -729,7 +816,8 @@ export class Carrier {
|
|
|
729
816
|
const add = (x) => { if (!seen.has(x.topic)) { seen.add(x.topic); out.push(x); } };
|
|
730
817
|
for (const p of Object.values(store.s.invites)) if (p.relay === relay && p.exp > now) add({ topic: inviteKeys(hexToBytes(p.secret)).answer_topic });
|
|
731
818
|
for (const p of Object.values(store.s.accepts)) if (p.relay === relay && p.exp > now) add({ topic: inviteKeys(hexToBytes(p.secret)).reply_topic });
|
|
732
|
-
|
|
819
|
+
// No new mailbox under a burned K (re_pair): those held run out at their time (#refresh).
|
|
820
|
+
const contacts = this.#liveContacts(store, relay).filter((c) => !c.re_pair).map((c) => ({ did: c.did, K: hexToBytes(c.pair_key) }));
|
|
733
821
|
const weeks = this.#weeks(now), at = Math.max(0, weeks.findIndex((w) => w.week === isoWeek(now)));
|
|
734
822
|
for (const w of [...weeks.slice(at), ...weeks.slice(0, at).reverse()]) {
|
|
735
823
|
for (const c of contacts) add({ topic: topic(c.K, c.did, me.did, w.week), peer: c.did, until: w.until });
|
|
@@ -761,15 +849,18 @@ export class Carrier {
|
|
|
761
849
|
|
|
762
850
|
#resolve(store, to) {
|
|
763
851
|
if (typeof to !== 'string' || to === '') fail('not_contact', 'name a contact: its DID or its name');
|
|
852
|
+
let c;
|
|
764
853
|
if (to.startsWith('did:sigelo:')) {
|
|
765
|
-
|
|
854
|
+
c = store.lookup(to) ?? fail('not_contact', `${to} is not a contact`);
|
|
766
855
|
if (c.revoked) fail('revoked', `${c.did} was revoked by this owner`);
|
|
767
|
-
|
|
856
|
+
} else {
|
|
857
|
+
const hits = this.#liveContacts(store).filter((x) => x.name === to);
|
|
858
|
+
if (hits.length === 0) fail('not_contact', `no contact named ${JSON.stringify(to)}`);
|
|
859
|
+
if (hits.length > 1) fail('name', `${hits.length} contacts are named ${JSON.stringify(to)}: use the DID`);
|
|
860
|
+
c = hits[0];
|
|
768
861
|
}
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
if (hits.length > 1) fail('name', `${hits.length} contacts are named ${JSON.stringify(to)}: use the DID`);
|
|
772
|
-
return hits[0];
|
|
862
|
+
if (c.re_pair) fail('re_pair', rePairWhy(c));
|
|
863
|
+
return c;
|
|
773
864
|
}
|
|
774
865
|
|
|
775
866
|
// ---- incoming
|
|
@@ -867,7 +958,18 @@ export class Carrier {
|
|
|
867
958
|
const s = this.#restore(st, store, me, did) ?? fail('not_contact', 'no live pairing with the writer of this topic');
|
|
868
959
|
// Bytes 2 to 18 are the epoch id (envelope.mjs "Layout"); a frame too short fails open() below.
|
|
869
960
|
const begins = !s.in.epochs.has(hex(bytes.subarray(2, 18)));
|
|
870
|
-
|
|
961
|
+
let r;
|
|
962
|
+
try { r = open(s, bytes, t, now); } catch (e) { // checks by name; the session is unchanged when one fails
|
|
963
|
+
// Not signed as the contact's current DID, after a recovery of the contact's this agent
|
|
964
|
+
// followed: a key the recovery overruled, maybe the thief's (the header's "Recovery beats
|
|
965
|
+
// key"). Refused and noted, and no bundle is owed for it (`from`'s known_due): nothing goes
|
|
966
|
+
// under this K. The claimed DID is unverified: not echoed.
|
|
967
|
+
if (e instanceof MsgError && e.check === 'from' && s.peer.re_pair === 'contact_recovery') {
|
|
968
|
+
return [this.#note(st, now, { type: 'refused', from: s.peer.did, name: s.peer.name, code: 're_pair',
|
|
969
|
+
detail: `a message not signed by ${s.peer.name}'s key after its recovery: maybe the thief's, not delivered` })];
|
|
970
|
+
}
|
|
971
|
+
throw e;
|
|
972
|
+
}
|
|
871
973
|
const c = s.peer, events = [];
|
|
872
974
|
// The writer's epochs begin here again: a bundle owed for one that could not (RESYNC) is not.
|
|
873
975
|
if (begins) this.#entry(st, did).resync_due = false;
|
|
@@ -994,7 +1096,8 @@ export class Carrier {
|
|
|
994
1096
|
if (p.body.did !== r.did || p.body.pair !== pairId(K)) fail('notice_sig', 'the proof names another DID than the chain ends at, or another pairing');
|
|
995
1097
|
if (!verifySig(keyOf(bundle, bundle.rotations, r.did), p.body, p.sig)) fail('notice_sig', 'the proof does not verify under the key the chain ends at');
|
|
996
1098
|
const before = structuredClone(c);
|
|
997
|
-
|
|
1099
|
+
// A mark stays with the record through a merge (admit writes it afresh); a new pairing clears it.
|
|
1100
|
+
const a = store.admit(bundle, r, null, { relay: c.relay, pair_key: c.pair_key, ...(c.re_pair && { re_pair: c.re_pair }) }, now);
|
|
998
1101
|
// admit writes every rotation either side held. The store keeps only those followed(); a
|
|
999
1102
|
// merged chain too long to keep puts the record back as it was. Held rotations come first, so
|
|
1000
1103
|
// on an edge both hold, the one this store followed before stays. store.mjs has no verb for
|
|
@@ -1007,14 +1110,37 @@ export class Carrier {
|
|
|
1007
1110
|
throw e;
|
|
1008
1111
|
}
|
|
1009
1112
|
merged.rotations = kept;
|
|
1113
|
+
// A recovery this store had not followed: the key it superseded, and the files a thief copied
|
|
1114
|
+
// with it, held K. Burned here too (the header's "After a recovery").
|
|
1115
|
+
const held = new Set(before.rotations.map(canonicalize));
|
|
1116
|
+
const recovered = kept.some((x) => x.body.reason === 'recovery' && !held.has(canonicalize(x)));
|
|
1117
|
+
if (recovered) merged.re_pair ??= 'contact_recovery';
|
|
1010
1118
|
store.save();
|
|
1119
|
+
const overruled = recovered ? this.#overrule(st, now, merged, kept, before.chain) : [];
|
|
1011
1120
|
if (a.current_did === c.current_did) return [];
|
|
1012
1121
|
// The contact's old key, and perhaps its state with the prekeys we listed, may be a thief's:
|
|
1013
1122
|
// list fresh ones only. retire() keeps the old secrets until they expire, for epochs begun.
|
|
1014
1123
|
const s = this.#restore(st, store, me, c.did);
|
|
1015
1124
|
if (s) { s.in.prekeys.retire(now); this.#persist(st, s); }
|
|
1016
1125
|
this.#entry(st, c.did).prekeys_resend = true;
|
|
1017
|
-
return [this.#note(st, now, { type: 'rotated', did: c.did, name: c.name, current_did: a.current_did })];
|
|
1126
|
+
return [this.#note(st, now, { type: 'rotated', did: c.did, name: c.name, current_did: a.current_did, ...(recovered && { re_pair: merged.re_pair, overruled }) })];
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
// A recovery of contact c was merged (kept: the rotation followed on each edge of c.chain). The
|
|
1130
|
+
// DIDs it overrules: those of the chain up to the last recovery's node, and those of the chain
|
|
1131
|
+
// held before that it left. Messages of c's still waiting for inbox() signed by one of them are
|
|
1132
|
+
// taken out and noted refused (the header's "Recovery beats key"). → the DIDs overruled.
|
|
1133
|
+
#overrule(st, now, c, kept, before) {
|
|
1134
|
+
const last = kept.findLastIndex((x) => x.body.reason === 'recovery'), honest = new Set(c.chain.slice(last + 1));
|
|
1135
|
+
const overruled = [...new Set([...c.chain, ...before])].filter((d) => !honest.has(d));
|
|
1136
|
+
const out = st.inbox.filter((m) => m.from === c.did && !honest.has(m.current_did));
|
|
1137
|
+
if (out.length === 0) return overruled;
|
|
1138
|
+
st.inbox = st.inbox.filter((m) => !out.includes(m));
|
|
1139
|
+
for (const m of out) {
|
|
1140
|
+
this.#note(st, now, { type: 'refused', from: c.did, name: c.name, current_did: m.current_did, iat: m.iat, code: 're_pair',
|
|
1141
|
+
detail: `signed by ${m.current_did}, a key ${c.name}'s recovery overruled: maybe the thief's, not delivered` });
|
|
1142
|
+
}
|
|
1143
|
+
return overruled;
|
|
1018
1144
|
}
|
|
1019
1145
|
|
|
1020
1146
|
// Alice: an answer to one of her codes. checkAnswer runs sigelo-pair's checks in its order and
|
|
@@ -1126,8 +1252,8 @@ export class Carrier {
|
|
|
1126
1252
|
}
|
|
1127
1253
|
spend(id);
|
|
1128
1254
|
// An entry written before `as` was kept: unknown, so the notice goes (#next `first`).
|
|
1129
|
-
const
|
|
1130
|
-
const c = store.lookup(res.did);
|
|
1255
|
+
const answered = waiting.find(([x]) => x === id)[1], held = answered.as ?? null;
|
|
1256
|
+
const c = renamed(store, store.lookup(res.did), answered);
|
|
1131
1257
|
const s = session({ me: { did: me.did, current_did: me.current_did, secret: me.secret }, peer: c, K: hexToBytes(res.pair_key) });
|
|
1132
1258
|
const events = [this.#note(st, now, { type: 'paired', did: c.did, name: c.name, current_did: c.current_did, rekeyed: res.rekeyed })];
|
|
1133
1259
|
try { acceptPrekeys(s, reply.prekeys, now); } catch (e) {
|
|
@@ -1154,8 +1280,8 @@ export class Carrier {
|
|
|
1154
1280
|
}
|
|
1155
1281
|
st.pending = st.pending.filter((p) => p.exp === undefined || p.exp > now);
|
|
1156
1282
|
// Nothing goes to a contact whose mailbox nobody held at this round's last publish to it
|
|
1157
|
-
// (no_reader): it would be refused alike. Its
|
|
1158
|
-
//
|
|
1283
|
+
// (no_reader): it would be refused alike. Its frames wait for the next round, its messages
|
|
1284
|
+
// unsealed in its outbox, so no epoch is begun (and no prekey spent) for nothing.
|
|
1159
1285
|
const absent = (did) => did !== undefined && link.absent.has(did);
|
|
1160
1286
|
const queued = st.pending.find((p) => p.relay === link.relay && (p.control === 'reply' || !absent(p.peer)) && (p.needs ?? []).every((t) => link.subscribed.has(t)));
|
|
1161
1287
|
if (queued) return queued;
|
|
@@ -1164,11 +1290,10 @@ export class Carrier {
|
|
|
1164
1290
|
const e = st.peers[c.did];
|
|
1165
1291
|
if (!e) continue;
|
|
1166
1292
|
if (absent(c.did)) {
|
|
1167
|
-
const detail =
|
|
1168
|
-
for (const item of e.outbox.
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
}
|
|
1293
|
+
const detail = noReader(c.name);
|
|
1294
|
+
for (const item of e.outbox) this.#results.set(item.id, { code: null, queued: detail });
|
|
1295
|
+
// Said once while it lasts (a CLI agent reads it in inbox()).
|
|
1296
|
+
if (e.outbox.length > 0 && e.waiting !== detail) { e.waiting = detail; this.#emit(this.#note(st, now, { type: 'waiting', did: c.did, name: c.name, detail })); }
|
|
1172
1297
|
continue;
|
|
1173
1298
|
}
|
|
1174
1299
|
const K = hexToBytes(c.pair_key), t = topic(K, me.did, c.did, isoWeek(now));
|
|
@@ -1180,7 +1305,8 @@ export class Carrier {
|
|
|
1180
1305
|
const ask = missing !== null && e.outbox.length > 0 && now - (e.asked ?? 0) >= DAY;
|
|
1181
1306
|
const resync = e.renew === true || (e.resync_due === true && now - (e.resync_at ?? 0) >= RESYNC);
|
|
1182
1307
|
const told = e.known_due === true && now - (e.prekeys_iat ?? 0) >= RESYNC;
|
|
1183
|
-
|
|
1308
|
+
// Under a burned K (re_pair) the notice alone goes: no bundle, no message.
|
|
1309
|
+
const bundle = !c.re_pair && (e.prekeys_resend || s.in.prekeys.due(now, me) || ask || resync || told);
|
|
1184
1310
|
// The rotation notice: after this agent's own rotation (announced), and again, at most every
|
|
1185
1311
|
// RESYNC, while the contact has not said it holds the current DID (known): before a frame
|
|
1186
1312
|
// signed by the current key goes (a bundle, an envelope), or when the contact's frame named
|
|
@@ -1203,6 +1329,15 @@ export class Carrier {
|
|
|
1203
1329
|
return this.#queue(st, { relay, topic: t, bytes: seal(KIND_NOTICE, noticeKey(K, me.did, c.did), t, { bundle: chainOf(me.bundle), proof: { body: proof, sig: sign(me.secret, proof) } }),
|
|
1204
1330
|
kind: KIND_NOTICE, peer: c.did, control: 'notice' });
|
|
1205
1331
|
}
|
|
1332
|
+
if (c.re_pair) {
|
|
1333
|
+
// Queued before the mark: refused here, unsealed. Noted too: the send that queued it has
|
|
1334
|
+
// exited, and its agent was told it goes at a later connection.
|
|
1335
|
+
for (const item of e.outbox.splice(0)) {
|
|
1336
|
+
this.#results.set(item.id, { code: 're_pair', detail: rePairWhy(c), local: true });
|
|
1337
|
+
this.#emit(this.#note(st, now, { type: 'refused', id: item.id, peer: c.did, name: c.name, code: 're_pair', detail: rePairWhy(c) }));
|
|
1338
|
+
}
|
|
1339
|
+
continue;
|
|
1340
|
+
}
|
|
1206
1341
|
if (bundle) {
|
|
1207
1342
|
// The contact refuses a bundle no newer than the one it holds (envelope.mjs acceptPrekeys),
|
|
1208
1343
|
// so two issued within one second get iat one apart (checkPrekeys allows SKEW ahead).
|
|
@@ -1225,8 +1360,11 @@ export class Carrier {
|
|
|
1225
1360
|
try {
|
|
1226
1361
|
const m = send(s, { label: item.label, content: item.content }, now);
|
|
1227
1362
|
e.outbox.shift();
|
|
1363
|
+
if (e.waiting === noReader(c.name)) e.waiting = null;
|
|
1228
1364
|
this.#persist(st, s);
|
|
1229
|
-
|
|
1365
|
+
// item: put back in the outbox if the relay says no_reader (#refused). Plaintext at rest
|
|
1366
|
+
// only as long as the outbox already kept it, until the PUBACK.
|
|
1367
|
+
return this.#queue(st, { id: item.id, relay, topic: m.topic, bytes: m.bytes, kind: KIND.message, n: m.n, peer: c.did, item });
|
|
1230
1368
|
} catch (err) {
|
|
1231
1369
|
if (!(err instanceof MsgError)) throw err;
|
|
1232
1370
|
if (err.check === 'prekeys') {
|
|
@@ -1272,9 +1410,16 @@ export class Carrier {
|
|
|
1272
1410
|
const s = this.#restore(st, store, me, e.peer);
|
|
1273
1411
|
if (s) { restartEpoch(s, unb64(e.bytes)); this.#persist(st, s); }
|
|
1274
1412
|
}
|
|
1413
|
+
// Nobody holds the contact's mailbox: the message goes back to the front of its outbox, to be
|
|
1414
|
+
// sealed again for the week it then goes in (the header's "Mailboxes"). Sealed bytes kept for
|
|
1415
|
+
// later could name a week whose mailbox the reader never claims again. An entry written by an
|
|
1416
|
+
// earlier version has no item: refused, as it was.
|
|
1417
|
+
if (e.kind === KIND.message && r.code === 'no_reader' && e.item) p.outbox.unshift(e.item);
|
|
1275
1418
|
return false;
|
|
1276
1419
|
}
|
|
1277
1420
|
|
|
1421
|
+
#nameOf(did) { try { return this.#read(({ store }) => store.lookup(did)?.name) ?? 'the contact'; } catch { return 'the contact'; } }
|
|
1422
|
+
|
|
1278
1423
|
async #throttle(link) {
|
|
1279
1424
|
for (;;) {
|
|
1280
1425
|
const t = Date.now();
|
|
@@ -1314,8 +1459,11 @@ export class Carrier {
|
|
|
1314
1459
|
this.#locked((ctx) => { if (!(r && this.#refused(ctx, e, r))) ctx.st.pending = ctx.st.pending.filter((p) => p.id !== e.id); });
|
|
1315
1460
|
if (r?.code === 'pow') { link.pow = true; link.closing = true; link.client.end(true); return; } // log in again, with the proof (#connect, #closed)
|
|
1316
1461
|
if (r?.code === 'no_reader' && e.peer !== undefined && e.control !== 'reply') link.absent.add(e.peer);
|
|
1317
|
-
|
|
1318
|
-
|
|
1462
|
+
// A message the relay had no reader for is back in its outbox (#refused): queued, not refused.
|
|
1463
|
+
const back = r?.code === 'no_reader' && e.kind === KIND.message && e.item !== undefined;
|
|
1464
|
+
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
|
|
1465
|
+
this.#emit(back ? { type: 'queued', id: e.id, peer: e.peer, code: r.code, detail: r.detail }
|
|
1466
|
+
: 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 });
|
|
1319
1467
|
// A refusal stops this round: what follows would be refused alike (a quota, the rate brake),
|
|
1320
1468
|
// and a control frame would be queued again at once. The next round retries. A mailbox
|
|
1321
1469
|
// nobody holds stops only what goes to that contact (absent, #next).
|
|
@@ -1474,14 +1622,35 @@ export class Carrier {
|
|
|
1474
1622
|
}
|
|
1475
1623
|
at.searches = [...recent, now];
|
|
1476
1624
|
});
|
|
1477
|
-
|
|
1625
|
+
const t0 = Date.now();
|
|
1626
|
+
if (bits > 0) this.#emit({ type: 'pow', relay, bits });
|
|
1627
|
+
pow = await solvePow(relay, me.did, ch.nonce, bits, t0 + POW_MS) ?? fail('pow', `no ${bits}-bit proof of work found within the challenge's 5 minutes on this machine: try again, or later (the relay raises it under load)`);
|
|
1628
|
+
if (bits > 0) this.#emit({ type: 'pow_done', relay, bits, ms: Date.now() - t0 });
|
|
1478
1629
|
}
|
|
1479
1630
|
const password = canonicalize({ v: LOGIN_V, nonce: ch.nonce, sig, bundle: loginBundle(me.bundle, relay), ...(pow !== undefined && { pow }) });
|
|
1480
1631
|
return { username: me.current_did, clientId: clientIdOf(me.did), password, pow };
|
|
1481
1632
|
}
|
|
1482
1633
|
|
|
1634
|
+
// How long this agent's own relay keeps a message on the free tier (relay.json, plan §11), when
|
|
1635
|
+
// the constructor was not told: asked once, beside the first login's challenge. Any failure (no
|
|
1636
|
+
// such file, a relay on loopback, a value out of range) keeps RETENTION_DAYS. Before the first
|
|
1637
|
+
// claim, so the weeks claimed behind (#weeks) follow it.
|
|
1638
|
+
async #relayInfo(ep) {
|
|
1639
|
+
this.#ask = false;
|
|
1640
|
+
try {
|
|
1641
|
+
const r = await http(`${ep.http}/relay.json`);
|
|
1642
|
+
const n = r.status === 200 ? retentionOf(r.body) : null;
|
|
1643
|
+
if (n !== null) this.retention = n * DAY;
|
|
1644
|
+
} catch {}
|
|
1645
|
+
}
|
|
1646
|
+
|
|
1647
|
+
get retentionDays() { return this.retention / DAY; }
|
|
1648
|
+
|
|
1483
1649
|
async #dial(relay) {
|
|
1484
|
-
const ep = endpointOf(relay, this.endpoints), link = new Link(relay, relay === this.relay)
|
|
1650
|
+
const ep = endpointOf(relay, this.endpoints), link = new Link(relay, relay === this.relay);
|
|
1651
|
+
const info = link.own && this.#ask ? this.#relayInfo(ep) : null;
|
|
1652
|
+
const creds = await this.#credentials(relay, ep);
|
|
1653
|
+
await info;
|
|
1485
1654
|
// A cut connection is this client's own refusal: no POST /check may rename it.
|
|
1486
1655
|
try { await mqttConnect(ep.mqtt, creds, link, (packet) => this.#onPacket(link, packet)); } catch (e) { throw link.cut ?? await named(ep, creds, e); }
|
|
1487
1656
|
// A close right after CONNACK (a cut in the same read) reached no listener of this connection.
|
|
@@ -1644,7 +1813,9 @@ export class Carrier {
|
|
|
1644
1813
|
// Checked before anything is stored: the relay would refuse it (quota_storage).
|
|
1645
1814
|
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`);
|
|
1646
1815
|
const id = answerId(answer);
|
|
1647
|
-
|
|
1816
|
+
// Unnamed: the code's DID's first digits ("z5esAbCd"), as operators shorten a DID. Named, the
|
|
1817
|
+
// name also replaces a known contact's on a re-pair (#onReply).
|
|
1818
|
+
store.addAccept(code, id, name ?? code.did.slice('did:sigelo:'.length, 'did:sigelo:'.length + 8), now, hex(k.secretKey), me.current_did, name !== undefined);
|
|
1648
1819
|
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 });
|
|
1649
1820
|
return { code, id, entry: entry.id };
|
|
1650
1821
|
} finally { k.secretKey.fill(0); }
|
|
@@ -1654,7 +1825,11 @@ export class Carrier {
|
|
|
1654
1825
|
this.#locked(({ now, store, st }) => { st.pending = st.pending.filter((p) => p.id !== entry); store.take('accepts', id, now); });
|
|
1655
1826
|
fail(check, why);
|
|
1656
1827
|
};
|
|
1657
|
-
|
|
1828
|
+
// Done early too once the reply topic or the answer is refused (a code answered before:
|
|
1829
|
+
// mailbox_taken), not after the whole wait.
|
|
1830
|
+
const reply = inviteKeys(code.secret).reply_topic;
|
|
1831
|
+
const settled = () => this.#handshakes.has(id) || this.#refusedTopics.has(reply) || Boolean(this.#results.get(entry)?.code);
|
|
1832
|
+
try { await this.#session([code.relay], { max: wait * 1000, until: settled }); } catch (e) {
|
|
1658
1833
|
// A relay other than this agent's own that refuses it for good would be dialled again at
|
|
1659
1834
|
// every connection, until the code expires, for an answer it never takes: and a stranger's
|
|
1660
1835
|
// code names it. Withdrawn only while it waits to go: an answer the relay holds keeps its
|
|
@@ -1669,9 +1844,9 @@ export class Carrier {
|
|
|
1669
1844
|
return 'withdrawn';
|
|
1670
1845
|
});
|
|
1671
1846
|
const why = { withdrawn: 'the answer is withdrawn', queued: 'the answer stays queued: it goes at the next connection', delivered: 'the relay holds the answer: the reply is read at a later connection' }[left];
|
|
1672
|
-
throw new MsgError(e.check ?? 'connect', `${e
|
|
1847
|
+
throw new MsgError(e.check ?? 'connect', `${reason(e)} (${why})`);
|
|
1673
1848
|
}
|
|
1674
|
-
const h = this.#handshakes.get(id), sent = this.#results.get(entry)
|
|
1849
|
+
const h = this.#handshakes.get(id), sent = this.#results.get(entry);
|
|
1675
1850
|
this.#handshakes.delete(id); this.#results.delete(entry);
|
|
1676
1851
|
if (h?.check) fail(h.check, h.detail);
|
|
1677
1852
|
if (h) return { status: 'connected', contact: h.contact };
|
|
@@ -1685,7 +1860,8 @@ export class Carrier {
|
|
|
1685
1860
|
return this.#read(({ now, store, st }) => {
|
|
1686
1861
|
const s = store.load().s;
|
|
1687
1862
|
return {
|
|
1688
|
-
contacts: Object.values(s.contacts).map((c) => ({ name: c.name, did: c.did, current_did: c.current_did, revoked: c.revoked, relay: c.relay, queued: st.peers[c.did]?.outbox.length ?? 0
|
|
1863
|
+
contacts: Object.values(s.contacts).map((c) => ({ name: c.name, did: c.did, current_did: c.current_did, revoked: c.revoked, relay: c.relay, queued: st.peers[c.did]?.outbox.length ?? 0,
|
|
1864
|
+
re_pair: c.re_pair ?? null })),
|
|
1689
1865
|
invites: Object.values(s.invites).filter((p) => p.exp > now).map((p) => ({ name: p.name, exp: p.exp, relay: p.relay })),
|
|
1690
1866
|
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 })),
|
|
1691
1867
|
};
|
|
@@ -1709,13 +1885,29 @@ export class Carrier {
|
|
|
1709
1885
|
if (content === undefined) fail('body', 'content is required');
|
|
1710
1886
|
try { canonicalize({ label, content }); } catch (e) { fail('body', `content is not canonical JSON (no floats): ${e.message}`); }
|
|
1711
1887
|
}
|
|
1888
|
+
// An answer of ours to `to`'s code waits for its reply (accept said `waiting`): the reply may be
|
|
1889
|
+
// at the relay now. One session reads it first, so `send` right after `accept` pairs (or, to a
|
|
1890
|
+
// contact already, re-pairs) and goes under the key the reply brings.
|
|
1891
|
+
const answered = this.#read(({ now, store }) => [...new Set(Object.values(store.load().s.accepts)
|
|
1892
|
+
.filter((p) => p.exp > now && (p.name === to || p.code_did === to)).map((p) => p.relay))]);
|
|
1893
|
+
if (answered.length > 0) {
|
|
1894
|
+
try { await this.#session(answered); } catch {}
|
|
1895
|
+
this.#routes = new Map();
|
|
1896
|
+
this.#read(({ now, store }) => {
|
|
1897
|
+
const s = store.load().s;
|
|
1898
|
+
if (!Object.values(s.contacts).some((c) => !c.revoked && c.pair_key && (c.name === to || c.chain.includes(to)))
|
|
1899
|
+
&& Object.values(s.accepts).some((p) => p.exp > now && (p.name === to || p.code_did === to))) {
|
|
1900
|
+
fail('not_paired', `${JSON.stringify(to)} is not paired yet: your answer to its code waits for the inviter's agent to connect and reply; send again once inbox reports "paired"`);
|
|
1901
|
+
}
|
|
1902
|
+
});
|
|
1903
|
+
}
|
|
1712
1904
|
const { ids, c } = this.#locked(({ store, st }) => {
|
|
1713
1905
|
const c = this.#resolve(store, to), outbox = this.#entry(st, c.did).outbox;
|
|
1714
1906
|
const ids = contents.map((content) => { const id = randomId(); outbox.push({ id, label, content }); return id; });
|
|
1715
1907
|
return { ids, c };
|
|
1716
1908
|
});
|
|
1717
1909
|
try { await this.#session([c.relay]); } catch (e) {
|
|
1718
|
-
throw new MsgError(e.check ?? 'connect', `${e
|
|
1910
|
+
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)`);
|
|
1719
1911
|
}
|
|
1720
1912
|
return ids.map((id) => {
|
|
1721
1913
|
const r = this.#results.get(id);
|
|
@@ -1734,7 +1926,7 @@ export class Carrier {
|
|
|
1734
1926
|
const inUse = this.#relaysInUse(), relays = inUse.length > 0 ? inUse : [this.relay];
|
|
1735
1927
|
try {
|
|
1736
1928
|
await this.#session(relays, wait > 0 ? { max: wait * 1000, until: () => this.#read(({ st }) => st.inbox.length > 0) } : {});
|
|
1737
|
-
} catch (e) { offline =
|
|
1929
|
+
} catch (e) { offline = e instanceof MsgError ? e.message : `connect: ${e.message}`; }
|
|
1738
1930
|
return this.#locked(({ st }) => {
|
|
1739
1931
|
const out = { messages: st.inbox, events: st.events, dropped: st.dropped, ...(offline && { offline }) };
|
|
1740
1932
|
st.inbox = []; st.events = []; st.dropped = {};
|
|
@@ -1750,9 +1942,11 @@ export class Carrier {
|
|
|
1750
1942
|
return c;
|
|
1751
1943
|
});
|
|
1752
1944
|
this.#routes = new Map();
|
|
1753
|
-
|
|
1945
|
+
// Revoked here whatever the relay says; offline: its mailboxes are given up at a later round.
|
|
1946
|
+
let offline = null;
|
|
1947
|
+
try { await this.#session([c.relay]); } catch (e) { offline = e instanceof MsgError ? e.message : `connect: ${e.message}`; }
|
|
1754
1948
|
const released = this.#read(({ st }) => !Object.values(st.relays[c.relay]?.claims ?? {}).some((x) => x.peer === c.did));
|
|
1755
|
-
return { name: c.name, did: c.did, revoked: true, released };
|
|
1949
|
+
return { name: c.name, did: c.did, revoked: true, released, ...(offline && { offline }) };
|
|
1756
1950
|
}
|
|
1757
1951
|
|
|
1758
1952
|
// ---- staying connected
|