sigelo-contact 0.1.13 → 0.1.20

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 +727 -0
  3. package/carrier.mjs +1204 -137
  4. package/control.mjs +81 -22
  5. package/device.mjs +1 -1
  6. package/enrol.mjs +239 -43
  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 +616 -0
  13. package/invite.mjs +63 -13
  14. package/kdf.mjs +1 -1
  15. package/link.mjs +24 -16
  16. package/package.json +49 -7
  17. package/page.mjs +1172 -70
  18. package/photo.mjs +37 -0
  19. package/platform-node.mjs +125 -18
  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 +95 -0
  25. package/short.mjs +31 -3
  26. package/store.mjs +147 -12
  27. package/test-carrier.mjs +138 -21
  28. package/test-device.mjs +1 -1
  29. package/test-enrol.mjs +157 -8
  30. package/test-envelope.mjs +16 -3
  31. package/test-file.mjs +5 -5
  32. package/test-group.mjs +413 -0
  33. package/test-invite.mjs +15 -2
  34. package/test-link.mjs +11 -8
  35. package/test-platform.mjs +5 -5
  36. package/test-presence.mjs +169 -0
  37. package/test-push.mjs +136 -0
  38. package/test-relay-lane.mjs +248 -0
  39. package/test-short.mjs +38 -12
  40. package/test-tier.mjs +6 -6
  41. package/test-transfer-web.mjs +246 -0
  42. package/test-transfer.mjs +463 -0
  43. package/test-voice.mjs +158 -0
  44. package/test-ws.mjs +5 -5
  45. package/transfer-engine.mjs +800 -0
  46. package/transfer-node.mjs +449 -0
  47. package/transfer-web.mjs +80 -0
  48. package/transfer.mjs +388 -0
  49. package/voice-web.mjs +113 -0
  50. package/voice.mjs +65 -0
  51. package/words-lock.mjs +115 -0
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
- // tier, tier_by, operator_exp?, link? } },
9
- // preset?: { original DID: tier } }
8
+ // tier, tier_by, operator_exp?, link?, presence? } },
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
@@ -29,6 +30,23 @@
29
30
  // set own (link_tier). ended: {id, by, at} on a contact a link's end revoked (revoke(did, ended)), and
30
31
  // relink: {id, until}, the one-use permit a NEW link leaves on it (design/links.md §7.1a): the pairing
31
32
  // through that link's code is admitted, the record written afresh. Forgotten by hand: no ended, never.
33
+ // presence: true when the owner lets this contact see whether this agent is online (setPresence; off
34
+ // by default, design/transfer.md §8 T0). An own agent (ours, or tier own) always sees it: presenceOf.
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).
32
50
  // The file holds one-time secrets, Bob's one-time key and
33
51
  // pairing keys, so it is written 0600. Two simultaneous writers still need the integrator's lock.
34
52
  import { utf8ToBytes } from '@noble/hashes/utils.js';
@@ -42,8 +60,10 @@ const UTF8 = new TextDecoder('utf-8', { ignoreBOM: true });
42
60
  export const OPERATOR_CTX = 'sigelo-relay/operator';
43
61
  // The longest name rename() gives a contact, in characters.
44
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;
45
65
  // What a record keeps of its tier through admit (a re-pair, a merged notice).
46
- const TIER_KEYS = ['tier', 'tier_by', 'operator_exp', 'link'];
66
+ const TIER_KEYS = ['tier', 'tier_by', 'operator_exp', 'link', 'presence'];
47
67
  // A recovery key used and replaced still governs every node up to its retirement (SPEC §7.2), and
48
68
  // no offline verifier tells its thief from its owner (THREAT-MODEL §2.5a). A known contact's record
49
69
  // remembers: its chain holds the recovery rotation that retired the key. → commitment → JCS of that
@@ -125,6 +145,22 @@ export class Contacts {
125
145
  return { did: c.did, name: c.name, tier: this.tierOf(c, now), ours: this.oursOf(c, now) };
126
146
  }
127
147
 
148
+ /** What contact c sees of this agent's presence: "own" (an own agent: always), "allow" (the owner's choice), or "deny" (the default). */
149
+ presenceOf(c, now) { return this.oursOf(c, now) || this.tierOf(c, now) === 'own' ? 'own' : c.presence === true ? 'allow' : 'deny'; }
150
+
151
+ /**
152
+ * The owner's choice for a contact (a name or any DID of its chain): may it see whether this agent
153
+ * is online. An own agent always may (presence_own). → { did, name, presence: presenceOf }.
154
+ */
155
+ setPresence(who, allow, now) {
156
+ if (typeof allow !== 'boolean') fail('presence', 'allow: true or false');
157
+ const c = this.#find(who);
158
+ if (!allow && this.presenceOf(c, now) === 'own') fail('presence_own', `${c.name} is your own agent (${this.oursOf(c, now) ? 'yours by key' : 'tier own'}): own agents always see each other's presence`);
159
+ if (allow) c.presence = true; else delete c.presence;
160
+ this.save();
161
+ return { did: c.did, name: c.name, presence: this.presenceOf(c, now) };
162
+ }
163
+
128
164
  /**
129
165
  * The link record of a contact (who: a name or any DID of its chain), link.mjs's: an object
130
166
  * {id, purpose, linked_by, expires, tier, prior?}, or null to drop it (prior: its tier and tier_by
@@ -159,6 +195,15 @@ export class Contacts {
159
195
  return { did, tier, preset: true };
160
196
  }
161
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
+
162
207
  /**
163
208
  * The owner's name for a contact (who: a name or any DID of its chain): 1 to NAME_MAX characters,
164
209
  * trimmed, no control characters, and no other live contact's (name_taken: a name two contacts
@@ -171,6 +216,7 @@ export class Contacts {
171
216
  const c = this.#find(who), to = name.trim();
172
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)}`);
173
218
  c.name = to;
219
+ delete c.name_from; // the human's name: never replaced by the one the contact tells (carrier.mjs "Names")
174
220
  this.save();
175
221
  return { did: c.did, name: to };
176
222
  }
@@ -211,7 +257,7 @@ export class Contacts {
211
257
  }
212
258
 
213
259
  // A fresh temporary name each time, created exclusively: a leftover or planted "<path>.tmp" (a
214
- // 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().
215
261
  save() {
216
262
  if (this.held) { this.dirty = true; return; }
217
263
  this.files.write(this.path, utf8ToBytes(JSON.stringify(this.s, null, 2)));
@@ -239,10 +285,22 @@ export class Contacts {
239
285
  for (const k of ['invites', 'accepts']) {
240
286
  for (const [nonce, p] of Object.entries(this.s[k])) {
241
287
  if (p.exp > now) continue;
242
- 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 }) });
243
289
  delete this.s[k][nonce]; n++;
244
290
  }
245
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;
246
304
  return n;
247
305
  }
248
306
 
@@ -272,14 +330,57 @@ export class Contacts {
272
330
  * null and peer = a DID of the known contact it is for: an answer from anyone else fails
273
331
  * challenge_did, as sigelo-pair pins its challenge to one DID.
274
332
  */
275
- addInvite(code, name, now, peer = null) {
333
+ addInvite(code, name, now, peer = null, renew = null) {
276
334
  let pin = null;
277
335
  if (name === null) {
278
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`);
279
337
  if (c.revoked) fail('revoked', `${c.did} was revoked by this owner`);
280
338
  pin = c.did;
281
339
  } else if (peer !== null) fail('name', 'a new contact\'s code is for whoever holds it: no peer');
282
- 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();
283
384
  }
284
385
 
285
386
  /**
@@ -292,9 +393,37 @@ export class Contacts {
292
393
  * named: he chose the name (accept --name), so a re-pair renames the known contact (the carrier).
293
394
  * tier: he chose the tier (accept --tier): the contact is filed with it (invite.mjs checkReply).
294
395
  */
295
- 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 = {}) {
296
397
  if (tier !== null && !TIERS.includes(tier)) fail('tier', `a tier is ${TIERS.join(', ')}; not ${JSON.stringify(tier)}`);
297
- 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();
298
427
  }
299
428
 
300
429
  /** Single use: the entry is deleted, and the file saved, before any check runs on the message naming it. */
@@ -303,6 +432,8 @@ export class Contacts {
303
432
  this.load();
304
433
  const p = typeof nonce === 'string' && Object.hasOwn(this.s[kind], nonce) ? { ...this.s[kind][nonce], nonce } : null;
305
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;
306
437
  if (this.#purge(now) || p) this.save();
307
438
  return p;
308
439
  }
@@ -310,7 +441,11 @@ export class Contacts {
310
441
  /** The owner withdraws a code not yet answered (nonce = code.nonce). */
311
442
  cancelInvite(nonce) {
312
443
  if (typeof nonce !== 'string' || !Object.hasOwn(this.load().s.invites, nonce)) fail('challenge_unknown', 'no pending invite with this nonce');
313
- 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();
314
449
  }
315
450
 
316
451
  // Every contact whose chain shares a DID with `chain`. admit lets at most one exist.
@@ -402,7 +537,7 @@ export class Contacts {
402
537
  const kept = old ? Object.fromEntries(TIER_KEYS.filter((k) => Object.hasOwn(old, k)).map((k) => [k, old[k]])) : {};
403
538
  const pre = !old && TIERS.includes(this.s.preset?.[r.chain[0]]) ? { tier: this.s.preset[r.chain[0]], tier_by: 'owner' } : {};
404
539
  if (this.s.preset) delete this.s.preset[r.chain[0]];
405
- 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 };
406
541
  if (fields.tier !== undefined && !TIERS.includes(fields.tier)) fail('tier', `a tier is ${TIERS.join(', ')}`);
407
542
  this.s.contacts[c.did] = c;
408
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';
@@ -523,7 +531,7 @@ try {
523
531
  });
524
532
  let uNow = now;
525
533
  const U = agent('una'), una = make(U, { clock: () => uNow, endpoints: { ...endpoints, 'loop.test': { mqtt: `mqtt://127.0.0.1:${loop.port}`, http: `${base}/loop.test` } } });
526
- const powErrors = () => seen('una', (e) => e.type === 'error' && e.check === 'pow' && /searches at loop\.test within 24 hours/.test(e.detail)).length;
534
+ const powErrors = () => seen('una', (e) => e.type === 'error' && e.check === 'pow' && /setup paused at loop\.test: 3 proof-of-work searches today/.test(e.detail)).length;
527
535
  ok((await una.accept(makeInvite({ did: A.did, relay: 'loop.test', now, ttl: 7 * DAY }).text, { wait: 0.3 })).status === 'waiting' && searches === 1, `una answers a code naming loop.test: one search (${searches}), the answer delivered`);
528
536
  await una.start();
529
537
  ok(await until(() => powErrors() === 1, 30000), 'started, una stops at loop.test with pow, the searches of the day spent');
@@ -536,6 +544,19 @@ try {
536
544
  ok(await until(() => powErrors() === 3, 30000), '24 hours later, una searches again, and stops again');
537
545
  await sleep(1500);
538
546
  ok(searches === 2 * POW_SEARCHES, `${searches} searches in all, ${POW_SEARCHES} in each 24 hours`);
547
+ // design/profiles.md §6: the cap is the automatic retries'. Its refusal names the next automatic try;
548
+ // one the human starts (Try now) is never refused: past the cap it asks (pow_confirm), then goes.
549
+ const cap = seen('una', (e) => e.type === 'error' && e.check === 'pow').at(-1);
550
+ ok(Number.isSafeInteger(cap?.next) && cap.next > uNow && cap.detail.includes(`Next automatic try at ${new Date(cap.next * 1000).toISOString().slice(11, 16)} UTC`),
551
+ `the capped refusal (automatic) carries the next automatic try, and says it (${cap?.detail})`);
552
+ let asked;
553
+ try { await una.tryNow(); asked = { check: 'accepted' }; } catch (e) { asked = e; }
554
+ ok(asked.check === 'pow_confirm' && asked.message.endsWith('Fourth setup at this relay (loop.test) today, up to 2 minutes. Go on?') && searches === 2 * POW_SEARCHES,
555
+ `Try now past the cap: asked (pow_confirm), no search yet (${asked.check}: ${asked.message}; ${searches} searches)`);
556
+ await una.tryNow({ confirmed: true }).catch(() => {});
557
+ ok(await until(() => searches === 2 * POW_SEARCHES + 1, 10000), `confirmed: the search goes, past the day's cap (${searches})`);
558
+ await sleep(1500);
559
+ ok(searches === 2 * POW_SEARCHES + 1, `and the automatic retries after it stay capped (${searches} searches)`);
539
560
  await una.stop();
540
561
  loop.close();
541
562
  inside.close();
@@ -554,7 +575,7 @@ try {
554
575
  res.writeHead(what === 'challenge' || what === 'check' ? 200 : 404, { 'content-type': 'application/json' });
555
576
  if (what === 'check') { req.resume(); req.on('end', () => res.end('{"ok":true}')); return; }
556
577
  if (what !== 'challenge') { res.end(); return; }
557
- 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 } }));
558
579
  });
559
580
  await new Promise((r) => http.listen(0, '127.0.0.1', r));
560
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` } } });
@@ -730,6 +751,78 @@ try {
730
751
  await refuses(() => alice.send('bob', 1.5), 'body', 'send a float');
731
752
  await refuses(() => alice.send('bob', 'x', { label: LABEL_PREKEYS }), 'body', 'send under the carrier\'s own label');
732
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
+
733
826
  // ================================================================ several messages, one login
734
827
  {
735
828
  const logins = () => seen('alice', (e) => e.type === 'connected').length, l0 = logins();
@@ -971,8 +1064,22 @@ try {
971
1064
  fake.closeAllConnections();
972
1065
  await new Promise((r) => fake.close(r));
973
1066
  }
974
- ok(await solvePow('relay.test', A.original, 'n', 8) === await solvePow('relay.test', A.original, 'n', 8), 'the proof of work is deterministic');
975
- 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
+ }
976
1083
 
977
1084
  // ================================================================ a thief's rotation loses to recovery
978
1085
  {
@@ -1076,10 +1183,10 @@ try {
1076
1183
  // ================================================================ the MCP tools: the same verbs
1077
1184
  {
1078
1185
  const mcp = await import(pathToFileURL(join(HERE, '..', 'integrations', 'mcp', 'contact.mjs')).href);
1079
- 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);
1080
1187
  const env = { SIGELO_RELAY: HOST, SIGELO_RELAY_ENDPOINTS: JSON.stringify(endpoints) };
1081
1188
  const tools = await mcp.load({ installed: false, id, env, clock: () => now });
1082
- ok(tools && tools.tools.map(([n]) => n).join() === 'sigelo_invite,sigelo_accept,sigelo_contacts,sigelo_set_tier,sigelo_send,sigelo_send_file,sigelo_inbox,sigelo_forget_contact,sigelo_links,sigelo_history', 'the MCP module lists the ten 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');
1083
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');
1084
1191
  const daveFile = join(dir, 'dave.local.json');
1085
1192
  id.init(daveFile, keygen({ seed: seed('dave recovery'), recovery: 'sha256:' + '0'.repeat(64) }).key);
@@ -1367,6 +1474,15 @@ try {
1367
1474
  const out = outOf();
1368
1475
  ok(refusals.join() === 'queued,queued,queued' && out.used.length === used0 && out.returned.length === 1 && stateOf(Pi).peers[O.original].outbox.length === 3,
1369
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})`);
1370
1486
  t += 600;
1371
1487
  await otto.inbox(); await piper.inbox();
1372
1488
  ok(stateOf(Pi).peers[O.original].outbox.length === 0, 'otto back: piper\'s next inbox sends the three');
@@ -1686,7 +1802,7 @@ try {
1686
1802
  ok(hugo.contacts().contacts.length === 10, 'hugo pairs with ten contacts');
1687
1803
  let subscribes = 0;
1688
1804
  const braked = (ctx) => {
1689
- 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 } } });
1690
1806
  const rate = p.rate;
1691
1807
  p.rate = (x) => { if (x.kind === 'subscribe') subscribes++; return rate(x); };
1692
1808
  return p;
@@ -1703,12 +1819,13 @@ try {
1703
1819
  await hugo90.start();
1704
1820
  ok(await until(() => held().size === 20 && subscribes >= 128), `started, hugo asks for his topics: 20 claimed (${held().size}), ${subscribes} asked`);
1705
1821
  await sleep(500);
1706
- ok(subscribes === 128 && connects() === 1, `one SUBSCRIBE of 128 and no more: the round stops at the brake, the rest wait (${subscribes} asked, ${connects()} connection)`);
1822
+ // Beside the 128 mailboxes, one presence topic per contact (carrier.mjs "Presence"): a subscribe, never a claim.
1823
+ ok(subscribes === 128 + Ps.length && connects() === 1, `one SUBSCRIBE of 128 mailboxes and no more, and the ten presence topics: the claims stop at the brake, the rest wait (${subscribes} asked, ${connects()} connection)`);
1707
1824
  const h1 = held();
1708
1825
  ok([...mailboxes(W), ...mailboxes(ahead)].every((x) => h1.has(x)), 'the 20 claimed: this week\'s mailbox and next week\'s of each of the ten contacts');
1709
1826
  t += 600;
1710
1827
  await hugo90.sync();
1711
- ok(subscribes === 128 && held().size === 20, `a round 10 minutes later asks for nothing refused (${subscribes} asked)`);
1828
+ ok(subscribes === 128 + Ps.length && held().size === 20, `a round 10 minutes later asks for nothing refused (${subscribes} asked)`);
1712
1829
  t += 3000;
1713
1830
  await hugo90.sync();
1714
1831
  const h2 = held();
@@ -1757,7 +1874,7 @@ try {
1757
1874
  // H1: a thief copies phone's identity and files, writes to vps (an MCP agent), rotates, writes
1758
1875
  // twice more; the relay holds the last back. Then phone recovers from its genesis.
1759
1876
  const mcp = await import(pathToFileURL(join(HERE, '..', 'integrations', 'mcp', 'contact.mjs')).href);
1760
- 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);
1761
1878
  const tools = await mcp.load({ installed: false, id, env: { SIGELO_RELAY: HOST, SIGELO_RELAY_ENDPOINTS: JSON.stringify(epL) }, clock: () => t });
1762
1879
  const vFile = join(dir, 'vps.local.json');
1763
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';