sigelo-contact 0.1.3 → 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 +1 -1
- package/carrier.mjs +151 -29
- package/package.json +2 -2
- package/store.mjs +4 -3
- package/test-carrier.mjs +135 -18
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@ 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
|
```
|
package/carrier.mjs
CHANGED
|
@@ -103,15 +103,32 @@
|
|
|
103
103
|
// invite and accept replace K and clear the mark (store.admit writes the record afresh). A
|
|
104
104
|
// contact on sigelo-contact 0.1.2 follows the recovery but marks nothing and keeps writing
|
|
105
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`).
|
|
106
118
|
// - Mailboxes: an agent holds the topics of every ISO week from `retention` ago to AHEAD (7 days,
|
|
107
119
|
// or its retention if shorter) ahead. The relay drops a publish to a topic nobody claimed (and
|
|
108
120
|
// says no_reader), so next week's topic must be claimed before a contact writes in it while
|
|
109
|
-
// this agent is offline.
|
|
110
|
-
//
|
|
111
|
-
//
|
|
112
|
-
//
|
|
113
|
-
//
|
|
114
|
-
//
|
|
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
|
|
115
132
|
// (SIGELO_RELAY_RETENTION_DAYS): nothing tells the carrier its tier. A claim past its time is
|
|
116
133
|
// given up only once deliveries have stopped, so what is queued on it is read first. The relay
|
|
117
134
|
// brakes new claims (relay/allowance.mjs RATE.claim: 128 at once per identity, then 2 a second):
|
|
@@ -140,7 +157,8 @@ export const LABEL_PREKEYS = 'sigelo-msg/0 prekeys', KIND_NOTICE = 4, KIND_PREKE
|
|
|
140
157
|
// type of its own, never a SPEC §5.2 challenge: a world that passed the relay's nonce on as its own
|
|
141
158
|
// challenge would get the agent's relay login back from sign-challenge.
|
|
142
159
|
export const LOGIN_V = 'sigelo-relay/0', TYP_LOGIN = 'relay-login';
|
|
143
|
-
|
|
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;
|
|
144
162
|
// The relay closes a connection whose SUBSCRIBE holds more topics (relay/mailbox.mjs MAX_TOPICS).
|
|
145
163
|
const MAX_TOPICS = 128;
|
|
146
164
|
// An invite topic holds 4 messages and 64 KB (relay/mailbox.mjs INVITE_BYTES); a bundle at most 64
|
|
@@ -281,6 +299,14 @@ export function publicRelay(relay) {
|
|
|
281
299
|
return host.includes('.') && !IPV4_LIKE.test(host) && !LOCAL_NAME.test(host);
|
|
282
300
|
}
|
|
283
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
|
+
|
|
284
310
|
/** SIGELO_RELAY (the relay new invites name), SIGELO_RELAY_ENDPOINTS (JSON, as endpointOf), SIGELO_RELAY_RETENTION_DAYS. */
|
|
285
311
|
export function optionsFromEnv(env = process.env) {
|
|
286
312
|
const o = {};
|
|
@@ -290,7 +316,7 @@ export function optionsFromEnv(env = process.env) {
|
|
|
290
316
|
}
|
|
291
317
|
if (env.SIGELO_RELAY_RETENTION_DAYS) {
|
|
292
318
|
const n = Number(env.SIGELO_RELAY_RETENTION_DAYS);
|
|
293
|
-
if (!
|
|
319
|
+
if (!retentionOk(n)) fail('relay', `SIGELO_RELAY_RETENTION_DAYS: whole days, 1 to ${RETENTION_MAX_DAYS} (the reader's tier)`);
|
|
294
320
|
o.retentionDays = n;
|
|
295
321
|
}
|
|
296
322
|
return o;
|
|
@@ -529,6 +555,18 @@ const rePairWhy = (c) => (c.re_pair === 'contact_recovery'
|
|
|
529
555
|
? `${c.name} recovered its identity after a theft: the pairing key may be the thief's; pair again (invite, accept) before writing`
|
|
530
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`);
|
|
531
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`;
|
|
569
|
+
|
|
532
570
|
// MQTT 3.1.1 says only "bad user name or password": POST /check with the same credentials names
|
|
533
571
|
// the failing check (relay/auth.mjs).
|
|
534
572
|
async function named(ep, creds, err) {
|
|
@@ -622,13 +660,16 @@ class Link {
|
|
|
622
660
|
export class Carrier {
|
|
623
661
|
#links = new Map(); #work = Promise.resolve(); #busy = 0; #lastWork = 0; #routes = new Map(); #results = new Map();
|
|
624
662
|
#claimed = new Set(); #refusedTopics = new Map(); #handshakes = new Map(); #soon = new Set();
|
|
625
|
-
#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;
|
|
626
664
|
|
|
627
|
-
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),
|
|
628
666
|
onEvent, keep, backoff = BACKOFF, tick = TICK }) {
|
|
629
667
|
if (typeof identity !== 'function') throw new TypeError('identity: a function returning { secret, bundle }');
|
|
630
668
|
if (typeof store !== 'string' || typeof state !== 'string') throw new TypeError('store, state: file paths (pathsFor(identityFile))');
|
|
631
|
-
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;
|
|
632
673
|
if (onEvent !== undefined && typeof onEvent !== 'function') throw new TypeError('onEvent: a function');
|
|
633
674
|
if (keep !== undefined && typeof keep !== 'boolean') throw new TypeError('keep: true or false');
|
|
634
675
|
Object.assign(this, { identity, storePath: store, statePath: state, relay, endpoints, retention: retentionDays * DAY, clock, onEvent: onEvent ?? (() => {}),
|
|
@@ -917,7 +958,18 @@ export class Carrier {
|
|
|
917
958
|
const s = this.#restore(st, store, me, did) ?? fail('not_contact', 'no live pairing with the writer of this topic');
|
|
918
959
|
// Bytes 2 to 18 are the epoch id (envelope.mjs "Layout"); a frame too short fails open() below.
|
|
919
960
|
const begins = !s.in.epochs.has(hex(bytes.subarray(2, 18)));
|
|
920
|
-
|
|
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
|
+
}
|
|
921
973
|
const c = s.peer, events = [];
|
|
922
974
|
// The writer's epochs begin here again: a bundle owed for one that could not (RESYNC) is not.
|
|
923
975
|
if (begins) this.#entry(st, did).resync_due = false;
|
|
@@ -1064,13 +1116,31 @@ export class Carrier {
|
|
|
1064
1116
|
const recovered = kept.some((x) => x.body.reason === 'recovery' && !held.has(canonicalize(x)));
|
|
1065
1117
|
if (recovered) merged.re_pair ??= 'contact_recovery';
|
|
1066
1118
|
store.save();
|
|
1119
|
+
const overruled = recovered ? this.#overrule(st, now, merged, kept, before.chain) : [];
|
|
1067
1120
|
if (a.current_did === c.current_did) return [];
|
|
1068
1121
|
// The contact's old key, and perhaps its state with the prekeys we listed, may be a thief's:
|
|
1069
1122
|
// list fresh ones only. retire() keeps the old secrets until they expire, for epochs begun.
|
|
1070
1123
|
const s = this.#restore(st, store, me, c.did);
|
|
1071
1124
|
if (s) { s.in.prekeys.retire(now); this.#persist(st, s); }
|
|
1072
1125
|
this.#entry(st, c.did).prekeys_resend = true;
|
|
1073
|
-
return [this.#note(st, now, { type: 'rotated', did: c.did, name: c.name, current_did: a.current_did, ...(recovered && { re_pair: merged.re_pair }) })];
|
|
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;
|
|
1074
1144
|
}
|
|
1075
1145
|
|
|
1076
1146
|
// Alice: an answer to one of her codes. checkAnswer runs sigelo-pair's checks in its order and
|
|
@@ -1182,8 +1252,8 @@ export class Carrier {
|
|
|
1182
1252
|
}
|
|
1183
1253
|
spend(id);
|
|
1184
1254
|
// An entry written before `as` was kept: unknown, so the notice goes (#next `first`).
|
|
1185
|
-
const
|
|
1186
|
-
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);
|
|
1187
1257
|
const s = session({ me: { did: me.did, current_did: me.current_did, secret: me.secret }, peer: c, K: hexToBytes(res.pair_key) });
|
|
1188
1258
|
const events = [this.#note(st, now, { type: 'paired', did: c.did, name: c.name, current_did: c.current_did, rekeyed: res.rekeyed })];
|
|
1189
1259
|
try { acceptPrekeys(s, reply.prekeys, now); } catch (e) {
|
|
@@ -1210,8 +1280,8 @@ export class Carrier {
|
|
|
1210
1280
|
}
|
|
1211
1281
|
st.pending = st.pending.filter((p) => p.exp === undefined || p.exp > now);
|
|
1212
1282
|
// Nothing goes to a contact whose mailbox nobody held at this round's last publish to it
|
|
1213
|
-
// (no_reader): it would be refused alike. Its
|
|
1214
|
-
//
|
|
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.
|
|
1215
1285
|
const absent = (did) => did !== undefined && link.absent.has(did);
|
|
1216
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)));
|
|
1217
1287
|
if (queued) return queued;
|
|
@@ -1220,11 +1290,10 @@ export class Carrier {
|
|
|
1220
1290
|
const e = st.peers[c.did];
|
|
1221
1291
|
if (!e) continue;
|
|
1222
1292
|
if (absent(c.did)) {
|
|
1223
|
-
const detail =
|
|
1224
|
-
for (const item of e.outbox.
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
}
|
|
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 })); }
|
|
1228
1297
|
continue;
|
|
1229
1298
|
}
|
|
1230
1299
|
const K = hexToBytes(c.pair_key), t = topic(K, me.did, c.did, isoWeek(now));
|
|
@@ -1291,8 +1360,11 @@ export class Carrier {
|
|
|
1291
1360
|
try {
|
|
1292
1361
|
const m = send(s, { label: item.label, content: item.content }, now);
|
|
1293
1362
|
e.outbox.shift();
|
|
1363
|
+
if (e.waiting === noReader(c.name)) e.waiting = null;
|
|
1294
1364
|
this.#persist(st, s);
|
|
1295
|
-
|
|
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 });
|
|
1296
1368
|
} catch (err) {
|
|
1297
1369
|
if (!(err instanceof MsgError)) throw err;
|
|
1298
1370
|
if (err.check === 'prekeys') {
|
|
@@ -1338,9 +1410,16 @@ export class Carrier {
|
|
|
1338
1410
|
const s = this.#restore(st, store, me, e.peer);
|
|
1339
1411
|
if (s) { restartEpoch(s, unb64(e.bytes)); this.#persist(st, s); }
|
|
1340
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);
|
|
1341
1418
|
return false;
|
|
1342
1419
|
}
|
|
1343
1420
|
|
|
1421
|
+
#nameOf(did) { try { return this.#read(({ store }) => store.lookup(did)?.name) ?? 'the contact'; } catch { return 'the contact'; } }
|
|
1422
|
+
|
|
1344
1423
|
async #throttle(link) {
|
|
1345
1424
|
for (;;) {
|
|
1346
1425
|
const t = Date.now();
|
|
@@ -1380,8 +1459,11 @@ export class Carrier {
|
|
|
1380
1459
|
this.#locked((ctx) => { if (!(r && this.#refused(ctx, e, r))) ctx.st.pending = ctx.st.pending.filter((p) => p.id !== e.id); });
|
|
1381
1460
|
if (r?.code === 'pow') { link.pow = true; link.closing = true; link.client.end(true); return; } // log in again, with the proof (#connect, #closed)
|
|
1382
1461
|
if (r?.code === 'no_reader' && e.peer !== undefined && e.control !== 'reply') link.absent.add(e.peer);
|
|
1383
|
-
|
|
1384
|
-
|
|
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 });
|
|
1385
1467
|
// A refusal stops this round: what follows would be refused alike (a quota, the rate brake),
|
|
1386
1468
|
// and a control frame would be queued again at once. The next round retries. A mailbox
|
|
1387
1469
|
// nobody holds stops only what goes to that contact (absent, #next).
|
|
@@ -1549,8 +1631,26 @@ export class Carrier {
|
|
|
1549
1631
|
return { username: me.current_did, clientId: clientIdOf(me.did), password, pow };
|
|
1550
1632
|
}
|
|
1551
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
|
+
|
|
1552
1649
|
async #dial(relay) {
|
|
1553
|
-
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;
|
|
1554
1654
|
// A cut connection is this client's own refusal: no POST /check may rename it.
|
|
1555
1655
|
try { await mqttConnect(ep.mqtt, creds, link, (packet) => this.#onPacket(link, packet)); } catch (e) { throw link.cut ?? await named(ep, creds, e); }
|
|
1556
1656
|
// A close right after CONNACK (a cut in the same read) reached no listener of this connection.
|
|
@@ -1713,7 +1813,9 @@ export class Carrier {
|
|
|
1713
1813
|
// Checked before anything is stored: the relay would refuse it (quota_storage).
|
|
1714
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`);
|
|
1715
1815
|
const id = answerId(answer);
|
|
1716
|
-
|
|
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);
|
|
1717
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 });
|
|
1718
1820
|
return { code, id, entry: entry.id };
|
|
1719
1821
|
} finally { k.secretKey.fill(0); }
|
|
@@ -1723,7 +1825,11 @@ export class Carrier {
|
|
|
1723
1825
|
this.#locked(({ now, store, st }) => { st.pending = st.pending.filter((p) => p.id !== entry); store.take('accepts', id, now); });
|
|
1724
1826
|
fail(check, why);
|
|
1725
1827
|
};
|
|
1726
|
-
|
|
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) {
|
|
1727
1833
|
// A relay other than this agent's own that refuses it for good would be dialled again at
|
|
1728
1834
|
// every connection, until the code expires, for an answer it never takes: and a stranger's
|
|
1729
1835
|
// code names it. Withdrawn only while it waits to go: an answer the relay holds keeps its
|
|
@@ -1740,7 +1846,7 @@ export class Carrier {
|
|
|
1740
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];
|
|
1741
1847
|
throw new MsgError(e.check ?? 'connect', `${reason(e)} (${why})`);
|
|
1742
1848
|
}
|
|
1743
|
-
const h = this.#handshakes.get(id), sent = this.#results.get(entry)
|
|
1849
|
+
const h = this.#handshakes.get(id), sent = this.#results.get(entry);
|
|
1744
1850
|
this.#handshakes.delete(id); this.#results.delete(entry);
|
|
1745
1851
|
if (h?.check) fail(h.check, h.detail);
|
|
1746
1852
|
if (h) return { status: 'connected', contact: h.contact };
|
|
@@ -1779,6 +1885,22 @@ export class Carrier {
|
|
|
1779
1885
|
if (content === undefined) fail('body', 'content is required');
|
|
1780
1886
|
try { canonicalize({ label, content }); } catch (e) { fail('body', `content is not canonical JSON (no floats): ${e.message}`); }
|
|
1781
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
|
+
}
|
|
1782
1904
|
const { ids, c } = this.#locked(({ store, st }) => {
|
|
1783
1905
|
const c = this.#resolve(store, to), outbox = this.#entry(st, c.did).outbox;
|
|
1784
1906
|
const ids = contents.map((content) => { const id = randomId(); outbox.push({ id, label, content }); return id; });
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sigelo-contact",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.4",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Agent contacts for sigelo identities: invite codes, a contact store, end-to-end encrypted envelopes with hybrid post-quantum key agreement, and an MQTT carrier. Client code (MIT); the relay server is csigelo/sigelo-relay (AGPL-3.0).",
|
|
6
6
|
"keywords": [
|
|
@@ -75,6 +75,6 @@
|
|
|
75
75
|
"@noble/hashes": "^2.4.0",
|
|
76
76
|
"@noble/post-quantum": "^0.7.1",
|
|
77
77
|
"mqtt": "^5.16.0",
|
|
78
|
-
"sigelo": "^0.1.
|
|
78
|
+
"sigelo": "^0.1.4"
|
|
79
79
|
}
|
|
80
80
|
}
|
package/store.mjs
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// peer's ORIGINAL DID with every rotation seen, as accept/node/sigelo-pair.mjs keeps pairings, so
|
|
4
4
|
// a rotation keeps the contact and a recovery still beats a thief (SPEC §7.1).
|
|
5
5
|
// { v, self, invites: { nonce: { secret, exp, name, peer, relay } },
|
|
6
|
-
// accepts: { answer id: { secret, code_did, exp, name, relay, kem_sk, as } },
|
|
6
|
+
// accepts: { answer id: { secret, code_did, exp, name, relay, kem_sk, as, named? } },
|
|
7
7
|
// contacts: { original DID: { name, did, current_did, current_key, revoked, chain, rotations, relay, pair_key, re_pair? } } }
|
|
8
8
|
// invites: codes this owner handed out, keyed by inviteNonce(code bytes); peer: the original DID of
|
|
9
9
|
// the contact a re-key code is for, null on a new contact's code. accepts: codes this owner
|
|
@@ -97,9 +97,10 @@ export class Contacts {
|
|
|
97
97
|
* exactly as long as the pending answer: first reply, revoke, or expiry (at the next add or take).
|
|
98
98
|
* as: the current DID his answer's chain ends at, which the inviter files him under; he may
|
|
99
99
|
* rotate before the reply comes, and must then tell her (the carrier's rotation notice).
|
|
100
|
+
* named: he chose the name (accept --name), so a re-pair renames the known contact (the carrier).
|
|
100
101
|
*/
|
|
101
|
-
addAccept(code, id, name, now, kem_sk = null, as = null) {
|
|
102
|
-
return this.#add('accepts', id, { secret: hex(code.secret), code_did: code.did, exp: code.exp, name, relay: code.relay, kem_sk, as }, now, TTL_MAX + SKEW);
|
|
102
|
+
addAccept(code, id, name, now, kem_sk = null, as = null, named = false) {
|
|
103
|
+
return this.#add('accepts', id, { secret: hex(code.secret), code_did: code.did, exp: code.exp, name, relay: code.relay, kem_sk, as, ...(named && { named: true }) }, now, TTL_MAX + SKEW);
|
|
103
104
|
}
|
|
104
105
|
|
|
105
106
|
/** Single use: the entry is deleted, and the file saved, before any check runs on the message naming it. */
|
package/test-carrier.mjs
CHANGED
|
@@ -47,7 +47,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
|
47
47
|
import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
|
48
48
|
import { connect } from 'mqtt';
|
|
49
49
|
import { canonicalize, keygen, rotate, sign, verify, verifySig } from 'sigelo';
|
|
50
|
-
import { Carrier, INVITE_BYTES, KIND_PREKEYS, LABEL_PREKEYS, MAX_PACKET, MAX_ROTATIONS, NOTICE_CHECKS, POW_SEARCHES, TYP_NOTICE, V as CARRIER_V, limitPackets, noticeKey, pathsFor, prekeysKey, seal, solvePow, unseal } from './carrier.mjs';
|
|
50
|
+
import { Carrier, INVITE_BYTES, KIND_PREKEYS, LABEL_PREKEYS, MAX_PACKET, MAX_ROTATIONS, NOTICE_CHECKS, POW_SEARCHES, TYP_NOTICE, V as CARRIER_V, limitPackets, noticeKey, pathsFor, prekeysKey, retentionOf, seal, solvePow, unseal } from './carrier.mjs';
|
|
51
51
|
import { MAX_ENVELOPE, header, pad } from './envelope.mjs';
|
|
52
52
|
import { V as STORE_V, answerId, buildAnswer, checkAnswer, checkReply, inviteKeys, makeInvite, parseInvite } from './invite.mjs';
|
|
53
53
|
import { isoWeek, pairId, topic } from './kdf.mjs';
|
|
@@ -142,8 +142,13 @@ const HOST = 'relay.test', DAY = 86400, CREATED = '2026-10-01T00:00:00Z';
|
|
|
142
142
|
const dir = mkdtempSync(join(tmpdir(), 'sigelo-carrier-'));
|
|
143
143
|
let now = Date.parse('2026-10-11T12:00:00Z') / 1000; // a Sunday, ISO week 2026-W41
|
|
144
144
|
const lines = [];
|
|
145
|
+
// The scenarios below are written against a free tier of 7 days and 256 KB: the client's default
|
|
146
|
+
// retention (carrier.mjs RETENTION_DAYS) and the relay's free tier until 2026-10-14. Both have since
|
|
147
|
+
// grown (14 days, 512 KB); pinning the old ones here (TEST_FREE, and make's retentionDays) keeps
|
|
148
|
+
// each scenario's expiry and too_large at the client's own window, whatever the defaults.
|
|
149
|
+
const TEST_FREE = { ...TIERS.free, retentionDays: 7, maxMessage: 256 * 1024 };
|
|
145
150
|
const cfg = { host: HOST, db: join(dir, 'relay.db'), tcpPort: 0, httpPort: 0, loginRate: 100000, verifyBudget: 1e9, clock: () => now, diskUsed: () => 0.1,
|
|
146
|
-
log: (l) => lines.push(l), policy: (ctx) => relayPolicy(ctx, { pow: { bits: 8, loadBits: 12, loadPerHour: 1000 }, freeQueue: 64 * 1024 * 1024 }) };
|
|
151
|
+
log: (l) => lines.push(l), policy: (ctx) => relayPolicy(ctx, { pow: { bits: 8, loadBits: 12, loadPerHour: 1000 }, freeQueue: 64 * 1024 * 1024, tiers: { free: TEST_FREE, pro: TIERS.pro } }) };
|
|
147
152
|
let relay = await startRelay(cfg);
|
|
148
153
|
const endpoints = { [HOST]: { mqtt: `mqtt://127.0.0.1:${relay.ports.tcp}`, http: `http://127.0.0.1:${relay.ports.http}` } };
|
|
149
154
|
|
|
@@ -176,7 +181,7 @@ const events = {};
|
|
|
176
181
|
const make = (a, extra = {}) => {
|
|
177
182
|
events[a.label] = [];
|
|
178
183
|
return new Carrier({ identity: () => ({ secret: a.secret, bundle: a.bundle }), ...pathsFor(join(dir, `${a.label}.local.json`)), relay: HOST, endpoints,
|
|
179
|
-
clock: () => now, onEvent: (e) => events[a.label].push(e), keep: true, backoff: [100, 400], ...extra });
|
|
184
|
+
clock: () => now, onEvent: (e) => events[a.label].push(e), keep: true, backoff: [100, 400], retentionDays: 7, ...extra });
|
|
180
185
|
};
|
|
181
186
|
const seen = (who, f) => events[who].filter(f);
|
|
182
187
|
const texts = (who) => seen(who, (e) => e.type === 'message').map((e) => e.content);
|
|
@@ -966,7 +971,7 @@ try {
|
|
|
966
971
|
const claim = (topics) => new Promise((resolve) => squatter.subscribe(topics, { qos: 1 }, (_err, _subs, packet) => resolve(packet?.granted ?? [])));
|
|
967
972
|
ok((await claim(squat)).join() === '1,1', 'the thief, holding K0, claims both of them first: the relay cannot tell (the live test\'s squat)');
|
|
968
973
|
const code = (await alice.invite({ name: 'bob again' })).code;
|
|
969
|
-
ok((await bob.accept(code, { name: 'alice
|
|
974
|
+
ok((await bob.accept(code, { name: 'alice', wait: 0.3 })).status === 'waiting', 'bob answers a new code from alice, his contact already');
|
|
970
975
|
const a1 = await alice.inbox();
|
|
971
976
|
ok(a1.events.some((e) => e.type === 'paired' && e.did === B.original && e.rekeyed === true), 'alice: the same contact, re-keyed');
|
|
972
977
|
ok(await until(() => seen('bob', (e) => e.type === 'paired' && e.did === A.original && e.rekeyed === true).length === 1), 'bob: the same, on reading her reply');
|
|
@@ -1104,7 +1109,7 @@ try {
|
|
|
1104
1109
|
// A re-key, the store's write failing after the state's: the reply the state kept names the
|
|
1105
1110
|
// code's reply topic, and is put back before the answer runs again; its K never goes out.
|
|
1106
1111
|
const K0 = storeOf(Ro).contacts[Sa.original].pair_key;
|
|
1107
|
-
ok((await saul.accept((await rosa.invite({ name: 'saul again' })).code, { name: 'rosa
|
|
1112
|
+
ok((await saul.accept((await rosa.invite({ name: 'saul again' })).code, { name: 'rosa', wait: 0.3 })).status === 'waiting', 'saul answers a fresh code of hers: a re-key');
|
|
1108
1113
|
f = failRenameOnce(files(Ro).store, (x) => { const c = JSON.parse(x).contacts[Sa.original]; return Boolean(c) && c.pair_key !== K0; });
|
|
1109
1114
|
await rosa.inbox();
|
|
1110
1115
|
f.restore();
|
|
@@ -1190,16 +1195,20 @@ try {
|
|
|
1190
1195
|
await quill.inbox(); await rhea.inbox(); await quill.inbox();
|
|
1191
1196
|
ok((await quill.send('rhea', 'hello')).status === 'sent' && (await rhea.inbox()).messages.length === 1, 'quill and rhea pair and talk');
|
|
1192
1197
|
// Day 15: quill's epoch is past 7 days, so this message begins one, in an ISO week rhea, away
|
|
1193
|
-
// since day 0, never claimed. The relay drops it, and
|
|
1194
|
-
//
|
|
1198
|
+
// since day 0, never claimed. The relay drops it, and says so: before, quill was told "sent",
|
|
1199
|
+
// and every later message of that epoch failed epoch_unknown at rhea. Then it was refused,
|
|
1200
|
+
// lost; now it stays queued at quill's, unsealed, and goes once rhea is back.
|
|
1195
1201
|
t += 15 * DAY;
|
|
1196
|
-
|
|
1202
|
+
const d15 = await quill.send('rhea', 'day 15');
|
|
1203
|
+
ok(d15.status === 'queued' && /does not hold its mailbox/.test(d15.detail) && stateOf(Q).peers[Rh.original].outbox.map((x) => x.content).join() === 'day 15',
|
|
1204
|
+
`day 15, to a mailbox rhea has not claimed: queued, kept in quill's outbox, not "sent" and not lost (${d15.status}: ${d15.detail})`);
|
|
1197
1205
|
t += DAY;
|
|
1198
1206
|
await rhea.inbox(); // back: she claims the weeks around now
|
|
1199
1207
|
const st5 = [];
|
|
1200
1208
|
for (let i = 0; i < 5; i++) { t += 3600; st5.push((await quill.send('rhea', `after return ${i}`)).status); }
|
|
1201
1209
|
const box3 = await rhea.inbox();
|
|
1202
|
-
ok(st5.every((x) => x === 'sent') && box3.messages.
|
|
1210
|
+
ok(st5.every((x) => x === 'sent') && box3.messages.map((m) => m.content).join() === 'day 15,after return 0,after return 1,after return 2,after return 3,after return 4' && !box3.dropped.epoch_unknown,
|
|
1211
|
+
`the kept one goes first, then the next five, in a new epoch (${st5.join()}; ${box3.messages.length} read, dropped ${JSON.stringify(box3.dropped)})`);
|
|
1203
1212
|
const contents = (box) => box.messages.map((m) => m.content).join();
|
|
1204
1213
|
const carrying = () => stateOf(Q).peers[Rh.original].session.out.epoch.carry;
|
|
1205
1214
|
// A relay that acknowledges an epoch's first envelope and throws it away: the next carries the
|
|
@@ -1270,21 +1279,22 @@ try {
|
|
|
1270
1279
|
ok(JSON.parse(ottoFile()).inbox.length === 0 && !ottoFile().includes('hello otto'), 'otto took it by onEvent: his state file holds no message, in plaintext or otherwise');
|
|
1271
1280
|
// otto is away 22 days, longer than he claims ahead: each of piper's sends begins an epoch the
|
|
1272
1281
|
// relay refuses (no_reader). Before, each burned one of otto's one-time prekeys for good: after
|
|
1273
|
-
// twenty, every epoch began on his last-resort key.
|
|
1282
|
+
// twenty, every epoch began on his last-resort key. Each message stays queued in her outbox.
|
|
1274
1283
|
t += 22 * DAY;
|
|
1275
1284
|
// Her own weekly bundle went just before (state edited): else it goes first, is refused
|
|
1276
|
-
// no_reader as well, and her messages
|
|
1285
|
+
// no_reader as well, and her messages wait unsealed, beginning no epoch at all.
|
|
1277
1286
|
editState(Pi, (x) => { x.peers[O.original].session.in.prekeys.replaced = t; });
|
|
1278
1287
|
const used0 = outOf().used.length, refusals = [];
|
|
1279
|
-
for (let i = 0; i < 3; i++) { t += 600; refusals.push(await piper.send('otto', `try ${i}`).then(() =>
|
|
1288
|
+
for (let i = 0; i < 3; i++) { t += 600; refusals.push(await piper.send('otto', `try ${i}`).then((r) => r.status, (e) => e.check)); }
|
|
1280
1289
|
const out = outOf();
|
|
1281
|
-
ok(refusals.join() === '
|
|
1282
|
-
`three sends
|
|
1290
|
+
ok(refusals.join() === 'queued,queued,queued' && out.used.length === used0 && out.returned.length === 1 && stateOf(Pi).peers[O.original].outbox.length === 3,
|
|
1291
|
+
`three sends to a mailbox nobody holds: queued, kept unsealed; no prekey burned, the one the first began on put back (${refusals.join()}; used ${used0} → ${out.used.length}, returned ${out.returned.length})`);
|
|
1283
1292
|
t += 600;
|
|
1284
1293
|
await otto.inbox(); await piper.inbox();
|
|
1294
|
+
ok(stateOf(Pi).peers[O.original].outbox.length === 0, 'otto back: piper\'s next inbox sends the three');
|
|
1285
1295
|
const back = texts('otto').length;
|
|
1286
|
-
ok((await piper.send('otto', 'after return')).status === 'sent' && (await otto.inbox()) && texts('otto').
|
|
1287
|
-
&& seen('otto', (e) => e.type === 'message' && e.content === '
|
|
1296
|
+
ok((await piper.send('otto', 'after return')).status === 'sent' && (await otto.inbox()) && texts('otto').slice(back).join() === 'try 0,try 1,try 2,after return'
|
|
1297
|
+
&& seen('otto', (e) => e.type === 'message' && e.content === 'try 0')[0]?.last_resort === false, `otto reads them in order: they begin an epoch on that one-time key, not the last-resort one (${texts('otto').slice(back).join()})`);
|
|
1288
1298
|
// 32 days in which neither runs: both bundles held are past their 31 days. Before, neither side
|
|
1289
1299
|
// could send its fresh bundle (it went inside an envelope, which needs an epoch, which needs
|
|
1290
1300
|
// the other's bundle): every send answered "queued" for good. Now bundles travel in frames.
|
|
@@ -1598,7 +1608,7 @@ try {
|
|
|
1598
1608
|
ok(hugo.contacts().contacts.length === 10, 'hugo pairs with ten contacts');
|
|
1599
1609
|
let subscribes = 0;
|
|
1600
1610
|
const braked = (ctx) => {
|
|
1601
|
-
const p = relayPolicy(ctx, { pow: { bits: 8, loadBits: 12, loadPerHour: 1000 }, freeQueue: 64 * 1024 * 1024, tiers: { free: { ...
|
|
1611
|
+
const p = relayPolicy(ctx, { pow: { bits: 8, loadBits: 12, loadPerHour: 1000 }, freeQueue: 64 * 1024 * 1024, tiers: { free: { ...TEST_FREE, mailboxes: 1000 }, pro: TIERS.pro }, rate: { claim: { perSecond: 1, burst: 20 } } });
|
|
1602
1612
|
const rate = p.rate;
|
|
1603
1613
|
p.rate = (x) => { if (x.kind === 'subscribe') subscribes++; return rate(x); };
|
|
1604
1614
|
return p;
|
|
@@ -1629,12 +1639,119 @@ try {
|
|
|
1629
1639
|
await relay12.close();
|
|
1630
1640
|
}
|
|
1631
1641
|
|
|
1642
|
+
// ================================================================ the 0.1.3 live re-test (2026-10-14)
|
|
1643
|
+
{
|
|
1644
|
+
// Its own relay and clock. connect.html's order: ines invites, jon accepts while she is offline
|
|
1645
|
+
// (waiting), ines runs inbox (paired), then send. Jon's mailbox for the pairing needs K, which
|
|
1646
|
+
// only her reply carries: until jon's agent reads it, nobody holds that mailbox (no_reader).
|
|
1647
|
+
let t = now;
|
|
1648
|
+
const relayL = await startRelay({ ...cfg, db: join(dir, 'live.db'), tcpPort: 0, httpPort: 0, clock: () => t, log: () => {} });
|
|
1649
|
+
const epL = { [HOST]: { mqtt: `mqtt://127.0.0.1:${relayL.ports.tcp}`, http: `http://127.0.0.1:${relayL.ports.http}` } };
|
|
1650
|
+
const In = agent('isla'), Jo = agent('jude'), ines = make(In, { endpoints: epL, clock: () => t }), jon = make(Jo, { endpoints: epL, clock: () => t });
|
|
1651
|
+
const code1 = (await ines.invite({ name: 'jon' })).code, prefix = In.original.slice('did:sigelo:'.length, 'did:sigelo:'.length + 8);
|
|
1652
|
+
ok((await jon.accept(code1, { wait: 0.3 })).status === 'waiting' && jon.contacts().answers[0]?.name === prefix,
|
|
1653
|
+
`L1: accept without --name names the inviter by its DID's first digits (${jon.contacts().answers[0]?.name})`);
|
|
1654
|
+
ok((await ines.inbox()).events.some((e) => e.type === 'paired' && e.name === 'jon'), 'M1: ines\'s inbox pairs');
|
|
1655
|
+
const hello = await ines.send('jon', say('hello jon'));
|
|
1656
|
+
ok(hello.status === 'queued' && /jon's agent does not hold its mailbox for this pairing yet/.test(hello.detail) && stateOf(In).peers[Jo.original].outbox.length === 1,
|
|
1657
|
+
`M1: her first send is queued, kept in her outbox, and says why: jon's agent, not hers (${hello.status}: ${hello.detail})`);
|
|
1658
|
+
const hi = await jon.send(prefix, say('hi ines'));
|
|
1659
|
+
ok(hi.status === 'sent' && jon.contacts().contacts.map((c) => c.name).join() === prefix, `M1: jon's first send after accept reads her reply first, pairs and goes (${hi.status})`);
|
|
1660
|
+
const ib = await ines.inbox();
|
|
1661
|
+
ok(ib.messages.map((m) => m.content).join() === 'hi ines' && stateOf(In).peers[Jo.original].outbox.length === 0, 'M1: ines\'s next inbox reads him and sends her kept message');
|
|
1662
|
+
ok((await jon.inbox()).messages.map((m) => m.content).join() === 'hello jon', 'M1: jon reads it');
|
|
1663
|
+
await refuses(() => make(agent('noor'), { endpoints: epL, clock: () => t }).send('nobody', 'x'), 'not_contact', 'a name nobody answered stays not_contact');
|
|
1664
|
+
|
|
1665
|
+
// L1: on a re-pair, the name accept is given wins over the name kept.
|
|
1666
|
+
const code2 = (await ines.invite({ name: 'jonny' })).code;
|
|
1667
|
+
ok((await jon.accept(code2, { name: 'ines', wait: 0.3 })).status === 'waiting', 'L1: jon answers a new code of ines\'s, naming her');
|
|
1668
|
+
await refuses(() => jon.send('ines', 'too soon'), 'not_paired', 'M1: a send to the name of an answer the inviter has not read yet says so, by name');
|
|
1669
|
+
await ines.inbox();
|
|
1670
|
+
const jp = await jon.send('ines', say('re-paired'));
|
|
1671
|
+
ok(jp.status === 'sent' && jon.contacts().contacts.map((c) => c.name).join() === 'ines', `L1: once paired again, she is "ines" on his side (${jon.contacts().contacts.map((c) => c.name).join()})`);
|
|
1672
|
+
ok((await ines.inbox()).messages.some((m) => m.content === 're-paired') && ines.contacts().contacts.map((c) => c.name).join() === 'jon', 'L1: on hers he keeps his name: invite --name names new contacts only');
|
|
1673
|
+
|
|
1674
|
+
// L4: a code answered before is refused at once, not after the whole wait.
|
|
1675
|
+
const Ka = agent('kai'), kai = make(Ka, { endpoints: epL, clock: () => t }), t0 = Date.now();
|
|
1676
|
+
await refuses(() => kai.accept(code1, { wait: 10 }), 'mailbox_taken', 'L4: a replayed code');
|
|
1677
|
+
ok(Date.now() - t0 < 6000, `L4: refused in ${Date.now() - t0} ms, not after the 10 s wait`);
|
|
1678
|
+
|
|
1679
|
+
// H1: a thief copies phone's identity and files, writes to vps (an MCP agent), rotates, writes
|
|
1680
|
+
// twice more; the relay holds the last back. Then phone recovers from its genesis.
|
|
1681
|
+
const mcp = await import(pathToFileURL(join(HERE, '..', 'integrations', 'mcp', 'contact.mjs')).href);
|
|
1682
|
+
const id = await import(pathToFileURL(join(HERE, '..', 'adapters', 'moadim', 'sigelo-agent.ts')).href);
|
|
1683
|
+
const tools = await mcp.load({ installed: false, id, env: { SIGELO_RELAY: HOST, SIGELO_RELAY_ENDPOINTS: JSON.stringify(epL) }, clock: () => t });
|
|
1684
|
+
const vFile = join(dir, 'vps.local.json');
|
|
1685
|
+
id.init(vFile, keygen({ seed: seed('vps recovery'), recovery: 'sha256:' + '0'.repeat(64) }).key);
|
|
1686
|
+
const vDid = id.chainOf(id.load(vFile))[0], h = tools.handlers, vInbox = async () => JSON.parse((await h.sigelo_inbox({}, vFile)).text);
|
|
1687
|
+
secrets.add(vDid);
|
|
1688
|
+
const Ph = agent('phone'), phone = make(Ph, { endpoints: epL, clock: () => t });
|
|
1689
|
+
await h.sigelo_accept({ code: (await phone.invite({ name: 'vps' })).code, name: 'phone', wait: 1 }, vFile);
|
|
1690
|
+
await phone.inbox(); await vInbox(); await phone.inbox();
|
|
1691
|
+
ok((await phone.send('vps', say('from the phone'))).status === 'sent' && (await vInbox()).messages.some((m) => m.content === 'from the phone'), 'H1: phone and vps (MCP) pair and talk');
|
|
1692
|
+
const T = { ...Ph, label: 'phone thief', bundle: structuredClone(Ph.bundle) };
|
|
1693
|
+
for (const k of ['store', 'state']) copyFileSync(pathsFor(join(dir, 'phone.local.json'))[k], pathsFor(join(dir, 'phone thief.local.json'))[k]);
|
|
1694
|
+
const thief = make(T, { endpoints: epL, clock: () => t });
|
|
1695
|
+
ok((await thief.send('vps', say('THIEF before recovery'))).status === 'sent', 'H1: the thief writes under the copied key');
|
|
1696
|
+
rotateAgent(T);
|
|
1697
|
+
secrets.add(T.did);
|
|
1698
|
+
ok((await thief.send('vps', say('THIEF after rotating'))).status === 'sent', 'H1: rotates, and writes again under its own key');
|
|
1699
|
+
ok((await thief.send('vps', say('THIEF late'))).status === 'sent', 'H1: and once more');
|
|
1700
|
+
const late = relayL.db.raw.prepare('SELECT id, topic, payload FROM messages WHERE account = ? ORDER BY seq DESC LIMIT 1').get(accountOf(vDid));
|
|
1701
|
+
relayL.db.raw.prepare('DELETE FROM messages WHERE id = ?').run(late.id);
|
|
1702
|
+
const R = keygen({ seed: seed('phone recovered'), recovery: Ph.bundle.genesis.recovery, created: CREATED, nonce: seed('phone recovered nonce').slice(0, 16) });
|
|
1703
|
+
Ph.bundle.rotations = [rotate({ genesis: Ph.bundle.genesis, next_genesis: R.genesis, iat: t - 60, reason: 'recovery', secret: seed('phone recovery') })];
|
|
1704
|
+
Ph.secret = R.secret; Ph.did = R.did;
|
|
1705
|
+
secrets.add(R.did);
|
|
1706
|
+
await phone.inbox(); // the recovered chain logs in; its notice goes to vps
|
|
1707
|
+
const vb = await vInbox();
|
|
1708
|
+
ok(!vb.messages.some((m) => /THIEF/.test(m.content)), `H1: vps, in one sigelo_inbox after the recovery, delivers none of the thief's messages (${vb.messages.map((m) => m.content).join() || 'none'})`);
|
|
1709
|
+
const refusedNow = vb.events.filter((e) => e.type === 'refused' && e.code === 're_pair' && e.from === Ph.original).map((e) => e.current_did);
|
|
1710
|
+
ok(refusedNow.length === 2 && refusedNow.includes(Ph.original) && refusedNow.includes(T.did),
|
|
1711
|
+
`H1: both are reported refused, re_pair, with the key each was signed by: the recovered-from key and the thief's (${refusedNow.join()})`);
|
|
1712
|
+
const rot = vb.events.find((e) => e.type === 'rotated' && e.re_pair === 'contact_recovery');
|
|
1713
|
+
ok(rot?.current_did === R.did && rot.overruled.includes(Ph.original) && rot.overruled.includes(T.did) && !rot.overruled.includes(R.did),
|
|
1714
|
+
'H1: the recovery\'s rotated event names the DIDs it overruled');
|
|
1715
|
+
const mal = await rawClient(agent('mallory'), epL);
|
|
1716
|
+
await publish(mal, late.topic, late.payload);
|
|
1717
|
+
mal.end(true);
|
|
1718
|
+
const vb2 = await vInbox();
|
|
1719
|
+
ok(vb2.messages.length === 0 && vb2.events.some((e) => e.type === 'refused' && e.code === 're_pair' && e.from === Ph.original && e.current_did === undefined) && !vb2.dropped.from,
|
|
1720
|
+
`H1: the one the relay held back, delivered after the recovery: refused re_pair too, not dropped as "from" (${JSON.stringify(vb2.events.map((e) => e.type + ':' + (e.code ?? '')))})`);
|
|
1721
|
+
|
|
1722
|
+
// The retention: relay.json's at the agent's own relay, unless told; 14 when it says nothing.
|
|
1723
|
+
ok(retentionOf({ limits: { free: { retention_days: 14 } } }) === 14 && retentionOf({ limits: { free: { retention_days: 91 } } }) === null && retentionOf({ limits: { free: { retention_days: '14' } } }) === null && retentionOf(null) === null,
|
|
1724
|
+
'retentionOf: whole days, 1 to 90, else nothing');
|
|
1725
|
+
const info = createServer(async (req, res) => {
|
|
1726
|
+
if (req.url === '/relay.json') { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify({ limits: { free: { retention_days: 21 } } })); return; }
|
|
1727
|
+
const r = await fetch(`${epL[HOST].http}${req.url}`);
|
|
1728
|
+
res.writeHead(r.status, { 'content-type': 'application/json' });
|
|
1729
|
+
res.end(Buffer.from(await r.arrayBuffer()));
|
|
1730
|
+
});
|
|
1731
|
+
await new Promise((r) => info.listen(0, '127.0.0.1', r));
|
|
1732
|
+
const epI = { [HOST]: { mqtt: epL[HOST].mqtt, http: `http://127.0.0.1:${info.address().port}` } };
|
|
1733
|
+
const asked = make(agent('luz'), { endpoints: epI, clock: () => t, retentionDays: undefined });
|
|
1734
|
+
ok(asked.retentionDays === 14, `the default before any login: 14 days (${asked.retentionDays})`);
|
|
1735
|
+
await asked.inbox();
|
|
1736
|
+
ok(asked.retentionDays === 21, `after its first login: relay.json's 21 (${asked.retentionDays})`);
|
|
1737
|
+
const told = make(agent('mia'), { endpoints: epI, clock: () => t, retentionDays: 7 });
|
|
1738
|
+
await told.inbox();
|
|
1739
|
+
const none = make(agent('ned'), { endpoints: epL, clock: () => t, retentionDays: undefined });
|
|
1740
|
+
await none.inbox();
|
|
1741
|
+
ok(told.retentionDays === 7 && none.retentionDays === 14, `told 7 (SIGELO_RELAY_RETENTION_DAYS): 7 (${told.retentionDays}); a relay with no relay.json: 14 (${none.retentionDays})`);
|
|
1742
|
+
info.closeAllConnections();
|
|
1743
|
+
await new Promise((r) => info.close(r));
|
|
1744
|
+
await relayL.close();
|
|
1745
|
+
}
|
|
1746
|
+
|
|
1632
1747
|
// ================================================================ forget
|
|
1633
1748
|
const claimsBefore = q('SELECT count(*) AS n FROM claims WHERE account = ? AND topic LIKE ?', accountOf(B.original), 'm/%')[0].n;
|
|
1634
1749
|
const f = await bob.forget(A.original);
|
|
1635
1750
|
ok(f.revoked === true && f.released === true && f.did === A.original, 'bob forgets alice: revoked, and his mailboxes for her given up');
|
|
1636
1751
|
ok(q('SELECT count(*) AS n FROM claims WHERE account = ? AND topic LIKE ?', accountOf(B.original), 'm/%')[0].n < claimsBefore, 'the relay holds fewer of bob\'s mailboxes');
|
|
1637
|
-
|
|
1752
|
+
const af = await alice.send('bob', say('after forget'));
|
|
1753
|
+
ok(af.status === 'queued' && /bob's agent does not hold its mailbox/.test(af.detail) && alice.contacts().contacts.find((c) => c.did === B.original).queued === 1,
|
|
1754
|
+
`alice writes on: nobody holds that mailbox now, so it stays queued with her, and contacts says so (${af.status})`);
|
|
1638
1755
|
await sleep(500);
|
|
1639
1756
|
ok(!texts('bob').includes('after forget') && q('SELECT count(*) AS n FROM messages WHERE account = ?', accountOf(B.original))[0].n === 0, 'nobody reads it, and nothing is queued for bob');
|
|
1640
1757
|
await refuses(() => bob.send('alice', 'x'), 'not_contact', 'bob cannot write to a forgotten contact by name');
|