sigelo-contact 0.1.14 → 0.1.21

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.
Files changed (51) hide show
  1. package/README.md +13 -10
  2. package/call.mjs +831 -0
  3. package/carrier.mjs +1013 -112
  4. package/control.mjs +81 -22
  5. package/device.mjs +1 -1
  6. package/enrol.mjs +214 -35
  7. package/gen-carrier.mjs +4 -4
  8. package/gen-device.mjs +2 -2
  9. package/gen-envelope.mjs +3 -3
  10. package/gen-invite.mjs +3 -3
  11. package/gen-short.mjs +3 -3
  12. package/group.mjs +28 -9
  13. package/invite.mjs +63 -13
  14. package/kdf.mjs +1 -1
  15. package/link.mjs +1 -1
  16. package/package.json +34 -7
  17. package/page.mjs +1018 -81
  18. package/photo.mjs +37 -0
  19. package/platform-node.mjs +110 -13
  20. package/prekeys.mjs +10 -2
  21. package/public.mjs +93 -0
  22. package/relays.mjs +1 -1
  23. package/restore.mjs +3 -3
  24. package/rtc-web.mjs +109 -0
  25. package/short.mjs +19 -3
  26. package/store.mjs +126 -10
  27. package/test-carrier.mjs +121 -18
  28. package/test-device.mjs +1 -1
  29. package/test-enrol.mjs +123 -8
  30. package/test-envelope.mjs +16 -3
  31. package/test-file.mjs +5 -5
  32. package/test-group.mjs +48 -7
  33. package/test-invite.mjs +15 -2
  34. package/test-link.mjs +6 -6
  35. package/test-platform.mjs +5 -5
  36. package/test-presence.mjs +5 -5
  37. package/test-push.mjs +136 -0
  38. package/test-relay-lane.mjs +323 -0
  39. package/test-short.mjs +35 -12
  40. package/test-tier.mjs +6 -6
  41. package/test-transfer-web.mjs +313 -0
  42. package/test-transfer.mjs +51 -11
  43. package/test-voice.mjs +161 -0
  44. package/test-ws.mjs +5 -5
  45. package/transfer-engine.mjs +858 -0
  46. package/transfer-node.mjs +254 -641
  47. package/transfer-web.mjs +80 -0
  48. package/transfer.mjs +25 -6
  49. package/voice-web.mjs +113 -0
  50. package/voice.mjs +70 -0
  51. package/words-lock.mjs +25 -10
package/store.mjs CHANGED
@@ -2,11 +2,12 @@
2
2
  // The contact store of sigelo-invite/0: one JSON file per identity. Contacts are keyed by the
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
- // { v, self, invites: { nonce: { secret, exp, name, peer, relay } },
5
+ // { v, self, invites: { nonce: { secret, exp, name, peer, relay, short?, short_exp?, renew? } },
6
6
  // accepts: { answer id: { secret, code_did, exp, name, relay, kem_sk, as, named?, tier? } },
7
7
  // contacts: { original DID: { name, did, current_did, current_key, revoked, chain, rotations, relay, pair_key, re_pair?,
8
8
  // tier, tier_by, operator_exp?, link?, presence? } },
9
- // preset?: { original DID: tier } }
9
+ // preset?: { original DID: tier },
10
+ // renew?: { series id: { name, ttl, relay, n, used: [{ short, did, name, at }], due?, claim?, retry?, error? } } }
10
11
  // invites: codes this owner handed out, keyed by inviteNonce(code bytes); peer: the original DID of
11
12
  // the contact a re-key code is for, null on a new contact's code. accepts: codes this owner
12
13
  // answered, keyed by answerId(answer). re_pair: "own_recovery" or "contact_recovery" once a recovery
@@ -32,6 +33,20 @@
32
33
  // presence: true when the owner lets this contact see whether this agent is online (setPresence; off
33
34
  // by default, design/transfer.md §8 T0). An own agent (ours, or tier own) always sees it: presenceOf.
34
35
  // Kept by a re-pair, a merge and a rename, as the tier is.
36
+ // short, short_exp: the short code parked for an invite of mine (carrier.mjs invite) and the relay's
37
+ // exp of it, so a cancel by the short code finds the invite and the state shows it. renew (an invite's
38
+ // series id, and the series in `renew`): a one-person code that renews itself:
39
+ // when its invite is taken (answered, well or not) the series is due, and the
40
+ // carrier parks a fresh code for it (carrier.mjs #renewDue) with the series' name (numbered: n), ttl
41
+ // and relay (null: the defaults). used: the codes of it that were used, the latest RENEW_USED. claim:
42
+ // when a process began a renewal (two processes of one identity park one code); retry, error: a
43
+ // renewal that failed, tried again from retry. Cancelling the current code (cancelInvite) ends the
44
+ // series; so does its code running out unused (purged with it, as nothing is due).
45
+ // publics: { code nonce: { secret, exp, name, relay, short, cap, open, paused, words, day, n, chats,
46
+ // requests: { answer id: { id, did, current_did, words, received, exp, answer } }, seen: { answer id: exp } } }:
47
+ // this owner's public codes (sigelo-public/0, public.mjs), with the pairing requests waiting for
48
+ // approval and the answer ids seen (replays dropped). An accept of a public code has public: true,
49
+ // and words when the joiner was given the inviter's four words; its exp is the request's (7 days).
35
50
  // The file holds one-time secrets, Bob's one-time key and
36
51
  // pairing keys, so it is written 0600. Two simultaneous writers still need the integrator's lock.
37
52
  import { utf8ToBytes } from '@noble/hashes/utils.js';
@@ -45,6 +60,8 @@ const UTF8 = new TextDecoder('utf-8', { ignoreBOM: true });
45
60
  export const OPERATOR_CTX = 'sigelo-relay/operator';
46
61
  // The longest name rename() gives a contact, in characters.
47
62
  export const NAME_MAX = 64;
63
+ // Renewing codes: seconds a process's claim on a due series holds; the codes used kept per series.
64
+ export const RENEW_CLAIM = 120, RENEW_USED = 10;
48
65
  // What a record keeps of its tier through admit (a re-pair, a merged notice).
49
66
  const TIER_KEYS = ['tier', 'tier_by', 'operator_exp', 'link', 'presence'];
50
67
  // A recovery key used and replaced still governs every node up to its retirement (SPEC §7.2), and
@@ -178,6 +195,15 @@ export class Contacts {
178
195
  return { did, tier, preset: true };
179
196
  }
180
197
 
198
+ // A new contact's name, unique among the live ones (the agent-setup feedback, point 9: two contacts with one
199
+ // name, and send <name> refused both): taken, it gets the first free numeric suffix, name-2, name-3…
200
+ freeName(name, did) {
201
+ if (typeof name !== 'string') return name;
202
+ const taken = (n) => Object.values(this.s.contacts).some((x) => !x.revoked && x.did !== did && x.name === n);
203
+ if (!taken(name)) return name;
204
+ for (let i = 2; ; i++) { const n = `${[...name].slice(0, NAME_MAX - String(i).length - 1).join('')}-${i}`; if (!taken(n)) return n; }
205
+ }
206
+
181
207
  /**
182
208
  * The owner's name for a contact (who: a name or any DID of its chain): 1 to NAME_MAX characters,
183
209
  * trimmed, no control characters, and no other live contact's (name_taken: a name two contacts
@@ -190,6 +216,7 @@ export class Contacts {
190
216
  const c = this.#find(who), to = name.trim();
191
217
  if (Object.values(this.s.contacts).some((x) => !x.revoked && x.did !== c.did && x.name === to)) fail('name_taken', `another contact is called ${JSON.stringify(to)}`);
192
218
  c.name = to;
219
+ delete c.name_from; // the human's name: never replaced by the one the contact tells (carrier.mjs "Names")
193
220
  this.save();
194
221
  return { did: c.did, name: to };
195
222
  }
@@ -230,7 +257,7 @@ export class Contacts {
230
257
  }
231
258
 
232
259
  // A fresh temporary name each time, created exclusively: a leftover or planted "<path>.tmp" (a
233
- // wider mode, a symlink) is never written through. As adapters/moadim/sigelo-agent.ts save().
260
+ // wider mode, a symlink) is never written through. As apps/agent/sigelo-agent.ts save().
234
261
  save() {
235
262
  if (this.held) { this.dirty = true; return; }
236
263
  this.files.write(this.path, utf8ToBytes(JSON.stringify(this.s, null, 2)));
@@ -258,10 +285,22 @@ export class Contacts {
258
285
  for (const k of ['invites', 'accepts']) {
259
286
  for (const [nonce, p] of Object.entries(this.s[k])) {
260
287
  if (p.exp > now) continue;
261
- if (k === 'accepts') (this.gone ??= []).push({ id: nonce, code_did: p.code_did, name: p.name, exp: p.exp, relay: p.relay });
288
+ if (k === 'accepts') (this.gone ??= []).push({ id: nonce, code_did: p.code_did, name: p.name, exp: p.exp, relay: p.relay, ...(p.public && { public: true }) });
262
289
  delete this.s[k][nonce]; n++;
263
290
  }
264
291
  }
292
+ // Public codes past their exp go; requests and seen answer ids past theirs.
293
+ for (const [nonce, p] of Object.entries(this.s.publics ?? {})) {
294
+ if (p.exp <= now) { delete this.s.publics[nonce]; n++; continue; }
295
+ for (const [id, q] of Object.entries(p.requests)) if (q.exp <= now) { delete p.requests[id]; n++; }
296
+ for (const [id, exp] of Object.entries(p.seen)) if (exp <= now) { delete p.seen[id]; n++; }
297
+ }
298
+ // A series with no current code and nothing due is over (its code ran out unused).
299
+ for (const id of Object.keys(this.s.renew ?? {})) {
300
+ if (this.s.renew[id].due || Object.values(this.s.invites).some((p) => p.renew === id)) continue;
301
+ delete this.s.renew[id]; n++;
302
+ }
303
+ if (this.s.renew && Object.keys(this.s.renew).length === 0) delete this.s.renew;
265
304
  return n;
266
305
  }
267
306
 
@@ -291,14 +330,57 @@ export class Contacts {
291
330
  * null and peer = a DID of the known contact it is for: an answer from anyone else fails
292
331
  * challenge_did, as sigelo-pair pins its challenge to one DID.
293
332
  */
294
- addInvite(code, name, now, peer = null) {
333
+ addInvite(code, name, now, peer = null, renew = null) {
295
334
  let pin = null;
296
335
  if (name === null) {
297
336
  const c = this.lookup(peer) ?? fail('not_contact', `a re-key code names the contact it is for; ${JSON.stringify(peer)} is not one`);
298
337
  if (c.revoked) fail('revoked', `${c.did} was revoked by this owner`);
299
338
  pin = c.did;
300
339
  } else if (peer !== null) fail('name', 'a new contact\'s code is for whoever holds it: no peer');
301
- return this.#add('invites', code.nonce, { secret: hex(code.secret), exp: code.exp, name, peer: pin, relay: code.relay }, now, TTL_MAX);
340
+ // renew: { id } to continue a series (gone: it was cancelled), { id, start: { name, ttl, relay } } to begin one.
341
+ if (renew !== null) {
342
+ if (pin !== null || typeof renew?.id !== 'string') fail('renew', 'a renewing code is a new contact\'s, with a series id');
343
+ if (!renew.start && !this.load().s.renew?.[renew.id]) fail('challenge_unknown', 'this renewing code was cancelled');
344
+ }
345
+ const nonce = this.#add('invites', code.nonce, { secret: hex(code.secret), exp: code.exp, name, peer: pin, relay: code.relay, ...(renew && { renew: renew.id }) }, now, TTL_MAX);
346
+ if (renew?.start) { (this.s.renew ??= {})[renew.id] = { name: renew.start.name ?? null, ttl: renew.start.ttl ?? null, relay: renew.start.relay ?? null, n: 1, used: [] }; this.save(); }
347
+ return nonce;
348
+ }
349
+
350
+ /** The short code parked for invite nonce (carrier.mjs invite), and the relay's exp of it. */
351
+ setShort(nonce, short, short_exp) {
352
+ const p = this.load().s.invites[nonce] ?? fail('challenge_unknown', 'no pending invite with this nonce');
353
+ p.short = short; p.short_exp = short_exp; this.save();
354
+ }
355
+
356
+ /** The renewing series due now (taken, not claimed by a process in the last RENEW_CLAIM s, past retry), claimed. */
357
+ renewClaim(now, peek = false) {
358
+ const out = [];
359
+ for (const [id, x] of Object.entries(this.load().s.renew ?? {})) {
360
+ if (!x.due || x.claim > now - RENEW_CLAIM || x.retry > now) continue;
361
+ if (!peek) x.claim = now;
362
+ out.push({ id, name: x.name, ttl: x.ttl, relay: x.relay, n: x.n });
363
+ }
364
+ if (out.length > 0 && !peek) this.save();
365
+ return out;
366
+ }
367
+ /** A fresh code parked for series id: no longer due. */
368
+ renewDone(id) {
369
+ const x = this.load().s.renew?.[id];
370
+ if (!x) return;
371
+ x.n++; delete x.due; delete x.claim; delete x.retry; delete x.error; this.save();
372
+ }
373
+ /** A renewal that failed: tried again from retry (unix seconds); why, shown in the state. */
374
+ renewFailed(id, why, retry) {
375
+ const x = this.load().s.renew?.[id];
376
+ if (!x) return;
377
+ x.retry = retry; x.error = why; delete x.claim; this.save();
378
+ }
379
+ /** Who used a code of series id (the pairing it made). */
380
+ renewUsed(id, use) {
381
+ const x = this.load().s.renew?.[id];
382
+ if (!x) return;
383
+ x.used = [...x.used, use].slice(-RENEW_USED); this.save();
302
384
  }
303
385
 
304
386
  /**
@@ -311,9 +393,37 @@ export class Contacts {
311
393
  * named: he chose the name (accept --name), so a re-pair renames the known contact (the carrier).
312
394
  * tier: he chose the tier (accept --tier): the contact is filed with it (invite.mjs checkReply).
313
395
  */
314
- addAccept(code, id, name, now, kem_sk = null, as = null, named = false, tier = null) {
396
+ addAccept(code, id, name, now, kem_sk = null, as = null, named = false, tier = null, extra = {}) {
315
397
  if (tier !== null && !TIERS.includes(tier)) fail('tier', `a tier is ${TIERS.join(', ')}; not ${JSON.stringify(tier)}`);
316
- 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 }), ...(tier && { tier }) }, now, TTL_MAX + SKEW);
398
+ 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 }), ...(tier && { tier }), ...extra }, now, TTL_MAX + SKEW);
399
+ }
400
+
401
+ /** A public code of mine (makeInvite version 2): kept until its exp or Revoke. → its nonce. */
402
+ addPublic(code, { name, cap, open, words }, now) {
403
+ checkTime(now);
404
+ if (name !== null && typeof name !== 'string') fail('name', 'a string, or null');
405
+ this.load(); this.#purge(now);
406
+ (this.s.publics ??= {})[code.nonce] = { secret: hex(code.secret), exp: code.exp, name, relay: code.relay, short: null, cap, open: open === true, paused: false, words, day: 0, n: 0, chats: 0, requests: {}, seen: {} };
407
+ this.save();
408
+ return code.nonce;
409
+ }
410
+ /** The public code with this nonce, its PUB code, its id (nonce) or the hash its PUB code is parked under, or null. → [nonce, entry]. */
411
+ findPublic(key, hashOf = () => null) {
412
+ for (const [nonce, p] of Object.entries(this.load().s.publics ?? {})) {
413
+ if (nonce === key || (p.short !== null && (p.short === key || hashOf(p.short) === key))) return [nonce, p];
414
+ }
415
+ return null;
416
+ }
417
+ /** The public code a request waits under → [nonce, entry, request] or null. */
418
+ findRequest(id) {
419
+ for (const [nonce, p] of Object.entries(this.load().s.publics ?? {})) if (typeof id === 'string' && Object.hasOwn(p.requests, id)) return [nonce, p, p.requests[id]];
420
+ return null;
421
+ }
422
+ /** The owner's Revoke: the code goes here (the relay's tombstone is the carrier's). */
423
+ dropPublic(nonce) {
424
+ if (!Object.hasOwn(this.load().s.publics ?? {}, nonce)) fail('challenge_unknown', 'no public code of this owner with this id');
425
+ delete this.s.publics[nonce];
426
+ this.save();
317
427
  }
318
428
 
319
429
  /** Single use: the entry is deleted, and the file saved, before any check runs on the message naming it. */
@@ -322,6 +432,8 @@ export class Contacts {
322
432
  this.load();
323
433
  const p = typeof nonce === 'string' && Object.hasOwn(this.s[kind], nonce) ? { ...this.s[kind][nonce], nonce } : null;
324
434
  if (p) delete this.s[kind][nonce];
435
+ // A renewing code used, well or not: its series is due a fresh one (carrier.mjs #renewDue).
436
+ if (kind === 'invites' && p?.renew && this.s.renew?.[p.renew]) this.s.renew[p.renew].due = true;
325
437
  if (this.#purge(now) || p) this.save();
326
438
  return p;
327
439
  }
@@ -329,7 +441,11 @@ export class Contacts {
329
441
  /** The owner withdraws a code not yet answered (nonce = code.nonce). */
330
442
  cancelInvite(nonce) {
331
443
  if (typeof nonce !== 'string' || !Object.hasOwn(this.load().s.invites, nonce)) fail('challenge_unknown', 'no pending invite with this nonce');
332
- delete this.s.invites[nonce]; this.save();
444
+ const series = this.s.invites[nonce].renew;
445
+ delete this.s.invites[nonce];
446
+ // A renewing code cancelled: no fresh one after it.
447
+ if (series && this.s.renew) { delete this.s.renew[series]; if (Object.keys(this.s.renew).length === 0) delete this.s.renew; }
448
+ this.save();
333
449
  }
334
450
 
335
451
  // Every contact whose chain shares a DID with `chain`. admit lets at most one exist.
@@ -421,7 +537,7 @@ export class Contacts {
421
537
  const kept = old ? Object.fromEntries(TIER_KEYS.filter((k) => Object.hasOwn(old, k)).map((k) => [k, old[k]])) : {};
422
538
  const pre = !old && TIERS.includes(this.s.preset?.[r.chain[0]]) ? { tier: this.s.preset[r.chain[0]], tier_by: 'owner' } : {};
423
539
  if (this.s.preset) delete this.s.preset[r.chain[0]];
424
- const c = { name: old?.name ?? name, did: r.chain[0], current_did: r.did, current_key: keyOf(bundle, rotations, r.did), revoked: false, chain: r.chain, rotations, ...kept, ...pre, ...fields };
540
+ const c = { name: old?.name ?? this.freeName(name, r.chain[0]), did: r.chain[0], current_did: r.did, current_key: keyOf(bundle, rotations, r.did), revoked: false, chain: r.chain, rotations, ...kept, ...pre, ...fields };
425
541
  if (fields.tier !== undefined && !TIERS.includes(fields.tier)) fail('tier', `a tier is ${TIERS.join(', ')}`);
426
542
  this.s.contacts[c.did] = c;
427
543
  // Attestations the bundle carried (none at a pairing today: chains only), then the tier.
package/test-carrier.mjs CHANGED
@@ -31,8 +31,8 @@
31
31
  // brake, and what it refused asked again an hour later, not sooner; a full disk between the
32
32
  // handshake's two files, on either side, heals at the next delivery; notices from whoever holds K:
33
33
  // one refused is not checked again, past NOTICE_CHECKS an hour none is, a recovery still is.
34
- // node contact/test-carrier.mjs → ALL PASS (n)
35
- // The relay is its own AGPL package, absent from this one's export: SIGELO_RELAY_DIR, else ../relay;
34
+ // node apps/contact/test-carrier.mjs → ALL PASS (n)
35
+ // The relay is its own AGPL package, absent from this one's export: SIGELO_RELAY_DIR, else ../../relay;
36
36
  // without it only the fixture part runs, and the run says SKIP for the rest.
37
37
  import { spawnSync } from 'node:child_process';
38
38
  import { createHash, randomBytes } from 'node:crypto';
@@ -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, retentionOf, seal, solvePow, unseal } from './carrier.mjs';
50
+ import { Carrier, INVITE_BYTES, KIND_PREKEYS, LABEL_PREKEYS, MAX_PACKET, MAX_ROTATIONS, NOTICE_CHECKS, POW_COST, POW_MAX, POW_MAX_OTHER, POW_SEARCHES, SEEN_LABEL, BUSY_LABEL, BUSY_TTL_S, TYP_NOTICE, V as CARRIER_V, limitPackets, noticeKey, pathsFor, powCost, 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';
@@ -122,21 +122,23 @@ const report = () => {
122
122
  } finally { rmSync(sd, { recursive: true, force: true }); }
123
123
  }
124
124
 
125
- const RELAY_DIR = process.env.SIGELO_RELAY_DIR ?? join(HERE, '..', 'relay');
125
+ const RELAY_DIR = process.env.SIGELO_RELAY_DIR ?? join(HERE, '..', '..', 'relay');
126
126
  if (!existsSync(join(RELAY_DIR, 'server.mjs'))) {
127
127
  report();
128
- console.log(`ALL PASS (${count}): the fixture part; SKIP the rest, no relay checkout beside contact/ (the relay is its own AGPL package): set SIGELO_RELAY_DIR`);
128
+ console.log(`ALL PASS (${count}): the fixture part; SKIP the rest, no relay checkout beside apps/contact/ (the relay is its own AGPL package): set SIGELO_RELAY_DIR`);
129
129
  process.exit(0);
130
130
  }
131
131
  const { startRelay } = await import(pathToFileURL(join(RELAY_DIR, 'server.mjs')).href);
132
132
  const { TIERS, relayPolicy } = await import(pathToFileURL(join(RELAY_DIR, 'allowance.mjs')).href);
133
+ const relayPow = await import(pathToFileURL(join(RELAY_DIR, 'pow.mjs')).href);
133
134
 
134
135
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
135
136
  const until = async (cond, ms = 8000) => { const end = Date.now() + ms; while (Date.now() < end) { if (cond()) return true; await sleep(20); } return cond(); };
136
137
  const refuses = async (f, check, what) => {
137
138
  try { await f(); ok(false, `${what}: accepted, expected ${check}`); } catch (e) { ok(e.check === check, `${what}: ${e.check ?? 'exception'} (${e.message}), expected ${check}`); }
138
139
  };
139
- setTimeout(() => { console.log(`FAIL the run did not finish in 300 s (${count} checks so far)`); process.exit(1); }, 300000).unref();
140
+ // A phone-class machine needs about 300 s for the whole run; the deadline catches a hang, not a slow device.
141
+ setTimeout(() => { console.log(`FAIL the run did not finish in 600 s (${count} checks so far)`); process.exit(1); }, 600000).unref();
140
142
 
141
143
  const HOST = 'relay.test', DAY = 86400, CREATED = '2026-10-01T00:00:00Z';
142
144
  const dir = mkdtempSync(join(tmpdir(), 'sigelo-carrier-'));
@@ -148,7 +150,7 @@ const lines = [];
148
150
  // each scenario's expiry and too_large at the client's own window, whatever the defaults.
149
151
  const TEST_FREE = { ...TIERS.free, retentionDays: 7, maxMessage: 256 * 1024 };
150
152
  const cfg = { host: HOST, db: join(dir, 'relay.db'), tcpPort: 0, httpPort: 0, loginRate: 100000, verifyBudget: 1e9, clock: () => now, diskUsed: () => 0.1,
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 } }) };
153
+ log: (l) => lines.push(l), policy: (ctx) => relayPolicy(ctx, { pow: { bits: 2, loadBits: 4, loadPerHour: 1000, cost: { m: 8, t: 1, p: 1 } }, freeQueue: 64 * 1024 * 1024, tiers: { free: TEST_FREE, pro: TIERS.pro } }) };
152
154
  let relay = await startRelay(cfg);
153
155
  const endpoints = { [HOST]: { mqtt: `mqtt://127.0.0.1:${relay.ports.tcp}`, http: `http://127.0.0.1:${relay.ports.http}` } };
154
156
 
@@ -196,9 +198,9 @@ const accountOf = (d) => createHash('sha256').update(d, 'utf8').digest('hex');
196
198
  // A plain MQTT client logged in as `a` (the relay lets anyone logged in write to any mailbox): a
197
199
  // hostile writer, or the relay replaying what it holds.
198
200
  async function rawClient(a, ep = endpoints) {
199
- const base = ep[HOST].http, { challenge: ch, pow_bits } = await (await fetch(`${base}/challenge?did=${encodeURIComponent(a.did)}`)).json();
201
+ const base = ep[HOST].http, { challenge: ch, pow_bits, pow: fn } = await (await fetch(`${base}/challenge?did=${encodeURIComponent(a.did)}`)).json();
200
202
  const sig = sign(a.secret, { v: 'sigelo-relay/0', typ: 'relay-login', did: a.did, relay: HOST, nonce: ch.nonce });
201
- const password = canonicalize({ v: 'sigelo-relay/0', nonce: ch.nonce, sig, bundle: a.bundle, pow: await solvePow(HOST, a.original, ch.nonce, pow_bits) });
203
+ const password = canonicalize({ v: 'sigelo-relay/0', nonce: ch.nonce, sig, bundle: a.bundle, pow: await solvePow(HOST, a.original, ch.nonce, pow_bits, Infinity, undefined, powCost(fn)) });
202
204
  return new Promise((resolve, reject) => {
203
205
  const c = connect(ep[HOST].mqtt, { protocolVersion: 4, clean: false, clientId: 's' + accountOf(a.original).slice(0, 24), username: a.did, password, reconnectPeriod: 0 });
204
206
  c.once('connect', () => resolve(c)); c.once('error', reject);
@@ -359,7 +361,8 @@ try {
359
361
  // ================================================================ a host a stranger's code names
360
362
  {
361
363
  // One HTTP server playing two hostile relays: /flood answers GET /challenge with endless
362
- // chunks and no Content-Length; /greedy answers a well-formed challenge asking 24 bits.
364
+ // chunks and no Content-Length; /greedy answers a well-formed challenge asking 24 bits; /sha one
365
+ // asking 4 bits of sigelo-relay-pow/0 (SHA-256), which this client no longer computes.
363
366
  let flooded = 0;
364
367
  const fake = createServer((req, res) => {
365
368
  const url = new URL(req.url, 'http://x');
@@ -371,6 +374,9 @@ try {
371
374
  } else if (url.pathname === '/greedy/challenge') {
372
375
  res.writeHead(200, { 'content-type': 'application/json' });
373
376
  res.end(JSON.stringify({ challenge: { v: 'sigelo-relay/0', typ: 'relay-login', did: url.searchParams.get('did'), relay: 'greedy.test', nonce: randomBytes(32).toString('base64url') }, pow_bits: 24 }));
377
+ } else if (url.pathname === '/sha/challenge') {
378
+ res.writeHead(200, { 'content-type': 'application/json' });
379
+ res.end(JSON.stringify({ challenge: { v: 'sigelo-relay/0', typ: 'relay-login', did: url.searchParams.get('did'), relay: 'sha.test', nonce: randomBytes(32).toString('base64url') }, pow_bits: 4, pow: { v: 0, alg: 'sha256' } }));
374
380
  } else { res.writeHead(404); res.end(); }
375
381
  });
376
382
  await new Promise((r) => fake.listen(0, '127.0.0.1', r));
@@ -382,6 +388,8 @@ try {
382
388
  const Y = agent('yuri'), yuri = make(Y, { endpoints: { ...endpoints, 'greedy.test': { mqtt: nowhere, http: `${base}/greedy` } } });
383
389
  const code = makeInvite({ did: A.did, relay: 'greedy.test', now }).text;
384
390
  await refuses(() => yuri.accept(code, { wait: 0.3 }), 'pow', 'a relay other than the agent\'s own asking 24 bits');
391
+ const Z = agent('zora'), zora = make(Z, { endpoints: { ...endpoints, 'sha.test': { mqtt: nowhere, http: `${base}/sha` } } });
392
+ await refuses(() => zora.accept(makeInvite({ did: A.did, relay: 'sha.test', now }).text, { wait: 0.3 }), 'pow', 'a relay asking 4 bits of a proof of work this client does not compute (SHA-256, sigelo-relay-pow/0)');
385
393
  ok(yuri.contacts().answers.length === 0 && stateOf(Y).pending.length === 0, 'is refused for good: the answer is withdrawn, so no later round dials that host for it');
386
394
  // A code naming an address or a local name, neither the agent's own relay nor configured:
387
395
  // refused before anything is stored or dialled.
@@ -492,7 +500,7 @@ try {
492
500
  if (name === 'hop2.test' && what === 'check') { checks.push(req.method); res.writeHead(307, { location: `${there}/admin/action` }); res.end(); return; }
493
501
  if (what !== 'challenge') { res.writeHead(404); res.end(); return; }
494
502
  res.writeHead(200, { 'content-type': 'application/json' });
495
- res.end(JSON.stringify({ challenge: { v: 'sigelo-relay/0', typ: 'relay-login', did: url.searchParams.get('did'), relay: name, nonce: randomBytes(32).toString('base64url') }, pow_bits: name === 'loop.test' ? 4 : 0 }));
503
+ res.end(JSON.stringify({ challenge: { v: 'sigelo-relay/0', typ: 'relay-login', did: url.searchParams.get('did'), relay: name, nonce: randomBytes(32).toString('base64url') }, pow_bits: name === 'loop.test' ? 4 : 0, pow: { v: 1, alg: 'argon2id', m: 8, t: 1, p: 1 } }));
496
504
  });
497
505
  await new Promise((r) => http.listen(0, '127.0.0.1', r));
498
506
  const base = `http://127.0.0.1:${http.address().port}`, nowhere = 'mqtt://127.0.0.1:9';
@@ -567,7 +575,7 @@ try {
567
575
  res.writeHead(what === 'challenge' || what === 'check' ? 200 : 404, { 'content-type': 'application/json' });
568
576
  if (what === 'check') { req.resume(); req.on('end', () => res.end('{"ok":true}')); return; }
569
577
  if (what !== 'challenge') { res.end(); return; }
570
- res.end(JSON.stringify({ challenge: { v: 'sigelo-relay/0', typ: 'relay-login', did: url.searchParams.get('did'), relay: 'mute.test', nonce: randomBytes(32).toString('base64url') }, pow_bits: 4 }));
578
+ res.end(JSON.stringify({ challenge: { v: 'sigelo-relay/0', typ: 'relay-login', did: url.searchParams.get('did'), relay: 'mute.test', nonce: randomBytes(32).toString('base64url') }, pow_bits: 4, pow: { v: 1, alg: 'argon2id', m: 8, t: 1, p: 1 } }));
571
579
  });
572
580
  await new Promise((r) => http.listen(0, '127.0.0.1', r));
573
581
  const M = agent('mia'), mia = make(M, { relay: 'mute.test', transport: 'mqtts', endpoints: { 'mute.test': { mqtt: `mqtt://127.0.0.1:${mute.port}`, http: `http://127.0.0.1:${http.address().port}/mute.test` } } });
@@ -743,6 +751,78 @@ try {
743
751
  await refuses(() => alice.send('bob', 1.5), 'body', 'send a float');
744
752
  await refuses(() => alice.send('bob', 'x', { label: LABEL_PREKEYS }), 'body', 'send under the carrier\'s own label');
745
753
 
754
+ // ================================================================ seen receipts (the header's): inside the envelope, never an inbox message
755
+ {
756
+ const bobAt = () => alice.contacts().contacts.find((x) => x.did === B.original);
757
+ await refuses(() => alice.send('bob', { seen: 1 }, { label: SEEN_LABEL }), 'body', 'send under the seen receipts\' label (seen() only)');
758
+ ok(bobAt().seen_upto === null && bobAt().seen_peer === false, 'no receipt yet: seen_upto null, seen_peer false');
759
+ const r = await bob.seen(A.original, now);
760
+ const got = await alice.inbox();
761
+ ok(r.status === 'sent' && got.messages.length === 0 && bobAt().seen_upto === now && bobAt().seen_peer === true
762
+ && events.alice.some((e) => e.type === 'seen' && e.from === B.original && e.upto === now), 'seen(): a receipt goes; alice files it (seen_upto, seen_peer, event seen), no inbox message');
763
+ await bob.seen(A.original, now - 5);
764
+ await alice.inbox();
765
+ ok(bobAt().seen_upto === now && !alice.history({ since: 0 }).messages.some((m) => m.label === SEEN_LABEL), 'an older receipt keeps the highest; none in the log');
766
+ await refuses(() => bob.seen(A.original, 1.5), 'body', 'a receipt\'s time not whole seconds');
767
+ }
768
+
769
+ // ================================================================ busy marks (the header's): inside the envelope, never a message
770
+ {
771
+ const aliceAt = () => bob.contacts().contacts.find((x) => x.did === A.original), busyEv = () => events.bob.filter((e) => e.type === 'busy');
772
+ await refuses(() => alice.send('bob', { busy: true }, { label: BUSY_LABEL }), 'body', 'send under the busy marks\' label (busy() only)');
773
+ const sk = await bob.busy(A.original, true);
774
+ ok(sk.status === 'skipped' && stateOf(B).peers[A.original].outbox.length === 0 && bob.contacts().contacts.find((x) => x.did === A.original).busy_peer === false,
775
+ `busy(): skipped to a contact that never said it takes them (alice sent no receipt: ${sk.status})`);
776
+ ok(alice.contacts().contacts.find((x) => x.did === B.original).busy_peer === true, 'bob\'s seen receipt said busy: true: alice has him as busy_peer');
777
+ const e0 = busyEv().length, m0 = events.bob.filter((e) => e.type === 'message').length;
778
+ const r = await alice.busy('bob', true), got = await bob.inbox();
779
+ ok(r.status === 'sent' && got.messages.length === 0 && aliceAt().busy === true && busyEv().length === e0 + 1 && busyEv().at(-1).on === true && busyEv().at(-1).from === A.original
780
+ && events.bob.filter((e) => e.type === 'message').length === m0 && !bob.history({ since: 0 }).messages.some((m) => m.label === BUSY_LABEL),
781
+ 'busy(true): sent; bob files it (contacts busy, event busy), no inbox message, no event message, nothing in the log');
782
+ await alice.busy('bob', false);
783
+ await bob.inbox();
784
+ ok(aliceAt().busy === false && busyEv().at(-1).on === false, 'busy(false): off at once');
785
+ await alice.busy('bob', true);
786
+ await bob.inbox();
787
+ const was = aliceAt().busy;
788
+ await alice.send('bob', say('the reply'));
789
+ const rep = (await bob.inbox()).messages;
790
+ ok(was === true && rep.length === 1 && aliceAt().busy === false, 'a message from alice ends her busy mark (her reply is here)');
791
+ await alice.busy('bob', true);
792
+ await bob.inbox();
793
+ const on = aliceAt().busy;
794
+ now += BUSY_TTL_S + 1;
795
+ ok(on === true && aliceAt().busy === false, `a mark not refreshed lapses after BUSY_TTL_S (${BUSY_TTL_S} s)`);
796
+ const q = await alice.busy('bob', true, { local: true });
797
+ now += BUSY_TTL_S + 1;
798
+ const e1 = busyEv().length;
799
+ await alice.inbox();
800
+ await bob.inbox();
801
+ ok(q.status === 'queued' && stateOf(A).peers[B.original].outbox.length === 0 && busyEv().length === e1 && aliceAt().busy === false, 'a mark queued past its expires: dropped unsent');
802
+ }
803
+
804
+ // ================================================================ read marks (0.1.19): what an agent's reader took, marked by code
805
+ {
806
+ const aliceAt = () => bob.contacts().contacts.find((x) => x.did === A.original), sentBy = (r) => r.map((x) => `${x.to === A.original ? 'alice' : x.to}@${x.upto - now}:${x.status ?? x.error}`).join();
807
+ await alice.send('bob', say('read me'));
808
+ const [m1] = (await bob.inbox()).messages;
809
+ const r1 = await bob.read([m1]), r2 = await bob.read([m1]);
810
+ await alice.inbox();
811
+ const at1 = alice.contacts().contacts.find((x) => x.did === B.original).seen_upto;
812
+ ok(sentBy(r1) === 'alice@0:sent' && r2.length === 0 && at1 === m1.iat, `read(): the first mark to a contact not known to read them goes, once; a second read of the same sends none (${sentBy(r1)} | ${sentBy(r2)})`);
813
+ now += 10;
814
+ await alice.send('bob', say('and me'));
815
+ const [m2] = (await bob.inbox()).messages;
816
+ const r3 = await bob.read([m2, { ...m2, iat: m2.iat + 5, group: { gid: 'g' } }, { from: A.original }]);
817
+ ok(r3.length === 0 && aliceAt().seen_peer === false, 'read(): no more to one that never sent a receipt (the app\'s rule); group items and ones without iat: never');
818
+ await alice.seen(B.original, now);
819
+ await bob.inbox();
820
+ const r4 = await bob.read([m2]);
821
+ ok(aliceAt().seen_peer === true && sentBy(r4) === 'alice@0:sent', `read(): once theirs came, each newer one goes (${sentBy(r4)})`);
822
+ const r5 = await bob.read([m1, m2]);
823
+ ok(r5.length === 0, 'read(): an older or the same message again: nothing');
824
+ }
825
+
746
826
  // ================================================================ several messages, one login
747
827
  {
748
828
  const logins = () => seen('alice', (e) => e.type === 'connected').length, l0 = logins();
@@ -984,8 +1064,22 @@ try {
984
1064
  fake.closeAllConnections();
985
1065
  await new Promise((r) => fake.close(r));
986
1066
  }
987
- ok(await solvePow('relay.test', A.original, 'n', 8) === await solvePow('relay.test', A.original, 'n', 8), 'the proof of work is deterministic');
988
- ok(await solvePow('relay.test', A.original, 'n', 48, Date.now() + 200) === null, 'and stops at its deadline, before the challenge would expire');
1067
+ {
1068
+ // The proof of work (relay/pow.mjs, sigelo-relay-pow/1): the relay's own solver finds the same c,
1069
+ // at a test cost here (8 KiB, 1 pass); 0 bits evaluate nothing.
1070
+ const T = { m: 8, t: 1, p: 1 }, nonce = 'n'.repeat(43);
1071
+ const c = await solvePow('relay.test', A.original, nonce, 6, Infinity, undefined, T);
1072
+ ok(c === await solvePow('relay.test', A.original, nonce, 6, Infinity, undefined, T) && c === await relayPow.solve('relay.test', A.original, nonce, 6, T),
1073
+ `the proof of work is deterministic, and the relay's (c = ${c} at 6 bits)`);
1074
+ ok(await solvePow('relay.test', A.original, 'n', 48, Date.now() + 200) === null && await solvePow('relay.test', A.original, nonce, 0, Infinity, () => { throw new Error('evaluated'); }) === '0',
1075
+ 'and stops at its deadline, before the challenge would expire; 0 bits: "0", nothing evaluated');
1076
+ ok(POW_MAX === relayPow.POW_BITS + 4 && POW_MAX_OTHER === relayPow.POW_BITS && JSON.stringify(POW_COST) === JSON.stringify(relayPow.ARGON),
1077
+ `the client spends at most the relay's base + 4 (${POW_MAX}) at its own relay, the base (${POW_MAX_OTHER}) at another, at the relay's cost`);
1078
+ const fn = { v: 1, alg: 'argon2id', m: 65536, t: 3, p: 1 };
1079
+ ok(JSON.stringify(powCost(fn)) === '{"m":65536,"t":3,"p":1}' && JSON.stringify(powCost({ ...fn, m: 8, t: 1 })) === '{"m":8,"t":1,"p":1}'
1080
+ && [undefined, null, { ...fn, v: 0 }, { ...fn, alg: 'sha256' }, { ...fn, m: 131072 }, { ...fn, t: 4 }, { ...fn, p: 2 }, { ...fn, m: 4 }, { ...fn, extra: 1 }, { v: 1, alg: 'argon2id', m: 65536, t: 3 }].every((x) => powCost(x) === null),
1081
+ 'the function a challenge states: Argon2id v1 at up to 64 MiB, 3 passes, 1 lane is computed (less too); anything else, or nothing, is refused');
1082
+ }
989
1083
 
990
1084
  // ================================================================ a thief's rotation loses to recovery
991
1085
  {
@@ -1089,10 +1183,10 @@ try {
1089
1183
  // ================================================================ the MCP tools: the same verbs
1090
1184
  {
1091
1185
  const mcp = await import(pathToFileURL(join(HERE, '..', 'integrations', 'mcp', 'contact.mjs')).href);
1092
- const id = await import(pathToFileURL(join(HERE, '..', 'adapters', 'moadim', 'sigelo-agent.ts')).href);
1186
+ const id = await import(pathToFileURL(join(HERE, '..', 'agent', 'sigelo-agent.ts')).href);
1093
1187
  const env = { SIGELO_RELAY: HOST, SIGELO_RELAY_ENDPOINTS: JSON.stringify(endpoints) };
1094
1188
  const tools = await mcp.load({ installed: false, id, env, clock: () => now });
1095
- ok(tools && tools.tools.map(([n]) => n).join() === 'sigelo_invite,sigelo_accept,sigelo_contacts,sigelo_set_tier,sigelo_presence,sigelo_send,sigelo_send_file,sigelo_inbox,sigelo_forget_contact,sigelo_links,sigelo_group,sigelo_transfer,sigelo_history', 'the MCP module lists the thirteen tools');
1189
+ ok(tools && tools.tools.map(([n]) => n).join() === 'sigelo_invite,sigelo_accept,sigelo_contacts,sigelo_set_tier,sigelo_presence,sigelo_send,sigelo_send_file,sigelo_inbox,sigelo_forget_contact,sigelo_links,sigelo_group,sigelo_transfer,sigelo_wait_for_message,sigelo_reply,sigelo_enrol,sigelo_enrol_finish,sigelo_public,sigelo_history', 'the MCP module lists the eighteen tools');
1096
1190
  ok(tools.tools.every(([, d, s]) => typeof d === 'string' && s.type === 'object' && s.additionalProperties === false && s.properties.identity), 'each with a closed schema and the profile argument');
1097
1191
  const daveFile = join(dir, 'dave.local.json');
1098
1192
  id.init(daveFile, keygen({ seed: seed('dave recovery'), recovery: 'sha256:' + '0'.repeat(64) }).key);
@@ -1380,6 +1474,15 @@ try {
1380
1474
  const out = outOf();
1381
1475
  ok(refusals.join() === 'queued,queued,queued' && out.used.length === used0 && out.returned.length === 1 && stateOf(Pi).peers[O.original].outbox.length === 3,
1382
1476
  `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})`);
1477
+ // send's expires (a remote control's request or pushed state, apps/contact/control.mjs TTL): past it the
1478
+ // message leaves the outbox unsent, so a contact away does not come back to a backlog of them.
1479
+ await refuses(() => piper.send('otto', 'x', { expires: 'soon' }), 'body', 'send expires not unix seconds → body');
1480
+ const xr = await piper.send('otto', 'short-lived', { expires: t + 300 });
1481
+ const four = stateOf(Pi).peers[O.original].outbox.length;
1482
+ t += 600;
1483
+ await piper.inbox();
1484
+ ok(xr.status === 'queued' && four === 4 && stateOf(Pi).peers[O.original].outbox.length === 3 && !JSON.stringify(stateOf(Pi)).includes('short-lived'),
1485
+ `a message sent with expires, queued (nobody holds the mailbox): past it, dropped from the outbox unsent (${xr.status}, ${four} → ${stateOf(Pi).peers[O.original].outbox.length})`);
1383
1486
  t += 600;
1384
1487
  await otto.inbox(); await piper.inbox();
1385
1488
  ok(stateOf(Pi).peers[O.original].outbox.length === 0, 'otto back: piper\'s next inbox sends the three');
@@ -1699,7 +1802,7 @@ try {
1699
1802
  ok(hugo.contacts().contacts.length === 10, 'hugo pairs with ten contacts');
1700
1803
  let subscribes = 0;
1701
1804
  const braked = (ctx) => {
1702
- 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 } } });
1805
+ const p = relayPolicy(ctx, { pow: { bits: 2, loadBits: 4, loadPerHour: 1000, cost: { m: 8, t: 1, p: 1 } }, freeQueue: 64 * 1024 * 1024, tiers: { free: { ...TEST_FREE, mailboxes: 1000 }, pro: TIERS.pro }, rate: { claim: { perSecond: 1, burst: 20 } } });
1703
1806
  const rate = p.rate;
1704
1807
  p.rate = (x) => { if (x.kind === 'subscribe') subscribes++; return rate(x); };
1705
1808
  return p;
@@ -1771,7 +1874,7 @@ try {
1771
1874
  // H1: a thief copies phone's identity and files, writes to vps (an MCP agent), rotates, writes
1772
1875
  // twice more; the relay holds the last back. Then phone recovers from its genesis.
1773
1876
  const mcp = await import(pathToFileURL(join(HERE, '..', 'integrations', 'mcp', 'contact.mjs')).href);
1774
- const id = await import(pathToFileURL(join(HERE, '..', 'adapters', 'moadim', 'sigelo-agent.ts')).href);
1877
+ const id = await import(pathToFileURL(join(HERE, '..', 'agent', 'sigelo-agent.ts')).href);
1775
1878
  const tools = await mcp.load({ installed: false, id, env: { SIGELO_RELAY: HOST, SIGELO_RELAY_ENDPOINTS: JSON.stringify(epL) }, clock: () => t });
1776
1879
  const vFile = join(dir, 'vps.local.json');
1777
1880
  id.init(vFile, keygen({ seed: seed('vps recovery'), recovery: 'sha256:' + '0'.repeat(64) }).key);
package/test-device.mjs CHANGED
@@ -7,7 +7,7 @@
7
7
  // errors and rotation; zbarimg on the same PNGs when it is on PATH; and UNLOGGED (carrier.mjs).
8
8
  // D3: the seat in the signed list (validity, epoch monotonic, stale seats), sealed snapshots (seal,
9
9
  // open, tamper, wrong K, the size path).
10
- // node contact/test-device.mjs → ALL PASS (n)
10
+ // node apps/contact/test-device.mjs → ALL PASS (n)
11
11
  import { execFileSync, spawnSync } from 'node:child_process';
12
12
  import { createHash, hkdfSync, randomBytes } from 'node:crypto';
13
13
  import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';