sigelo-contact 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/test-carrier.mjs CHANGED
@@ -12,7 +12,10 @@
12
12
  // undone and reported; hostile hosts (an endless answer, a greedy proof of work, proof of work
13
13
  // asked again at every reconnection, redirects to a host inside, a 100 MB MQTT packet, a code
14
14
  // naming an address or a local name); a 502 refuses nothing and a delivered answer outlives a refusal for good; a slow packet
15
- // does not read as a drained queue; a thief's fork of 63 rotations loses to the owner's recovery;
15
+ // does not read as a drained queue; a thief's fork of 63 rotations loses to the owner's recovery,
16
+ // after which both sides hold the pairing key as burned (re_pair: only the notice goes, no new
17
+ // mailbox is claimed) until they pair again, and a thief holding the old key claims next week's
18
+ // mailboxes under it and gets nothing;
16
19
  // a notice whose chain ends at a key its sender does not hold is refused (notice_sig); a refused
17
20
  // first envelope gives its prekey back; 32 days with no bundle across heal without pairing again;
18
21
  // a carrier with onEvent keeps no plaintext at rest; one code accepted twice; an epoch outlives its
@@ -43,8 +46,8 @@ import { PassThrough } from 'node:stream';
43
46
  import { fileURLToPath, pathToFileURL } from 'node:url';
44
47
  import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
45
48
  import { connect } from 'mqtt';
46
- import { canonicalize, keygen, rotate, sign } from 'sigelo';
47
- import { Carrier, INVITE_BYTES, KIND_PREKEYS, LABEL_PREKEYS, MAX_PACKET, MAX_ROTATIONS, NOTICE_CHECKS, POW_SEARCHES, TYP_NOTICE, V as CARRIER_V, limitPackets, noticeKey, pathsFor, prekeysKey, seal, solvePow, unseal } from './carrier.mjs';
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';
48
51
  import { MAX_ENVELOPE, header, pad } from './envelope.mjs';
49
52
  import { V as STORE_V, answerId, buildAnswer, checkAnswer, checkReply, inviteKeys, makeInvite, parseInvite } from './invite.mjs';
50
53
  import { isoWeek, pairId, topic } from './kdf.mjs';
@@ -88,6 +91,13 @@ const report = () => {
88
91
  const ik = inviteKeys(unhex(d.invite.secret));
89
92
  ok(ik.answer_topic === d.invite.answer_topic && ik.reply_topic === d.invite.reply_topic && hexOf(ik.key) === d.invite.key, 'what the invite secret yields (invite.mjs)');
90
93
  ok(checkPrekeys(value('prekeys').prekeys, { did: B0.did, current_did: B0.did, current_key: B0.key }, d.pair.hex, F.t0 + 40).keys.length === 20, 'bob\'s bundle in the prekeys frame passes the sender\'s check');
94
+ {
95
+ // The recovery notice: its chain follows the recovery past the thief's B1 and ends at B2, whose
96
+ // key signs the proof. A receiver that followed B1 marks bob re_pair (the relay part below).
97
+ const n = value('notice_recovery'), r = verify(n.bundle, F.t0 + 300), B2 = F.identities.B2;
98
+ ok(r.did === B2.did && r.chain.join() === `${B0.did},${B2.did}` && F.recovery.body.reason === 'recovery' && verifySig(B2.key, n.proof.body, n.proof.sig),
99
+ 'the recovery notice: the recovery from B0 beats the thief\'s B1, the chain ends at B2, the proof verifies under B2\'s key');
100
+ }
91
101
  const sd = mkdtempSync(join(tmpdir(), 'sigelo-carrier-fixture-'));
92
102
  try {
93
103
  // alice's code from the fixture's inputs: its bytes, and a nonce that hashes all of them.
@@ -132,8 +142,13 @@ const HOST = 'relay.test', DAY = 86400, CREATED = '2026-10-01T00:00:00Z';
132
142
  const dir = mkdtempSync(join(tmpdir(), 'sigelo-carrier-'));
133
143
  let now = Date.parse('2026-10-11T12:00:00Z') / 1000; // a Sunday, ISO week 2026-W41
134
144
  const lines = [];
145
+ // The scenarios below are written against a free tier of 7 days and 256 KB: the client's default
146
+ // retention (carrier.mjs RETENTION_DAYS) and the relay's free tier until 2026-10-14. Both have since
147
+ // grown (14 days, 512 KB); pinning the old ones here (TEST_FREE, and make's retentionDays) keeps
148
+ // each scenario's expiry and too_large at the client's own window, whatever the defaults.
149
+ const TEST_FREE = { ...TIERS.free, retentionDays: 7, maxMessage: 256 * 1024 };
135
150
  const cfg = { host: HOST, db: join(dir, 'relay.db'), tcpPort: 0, httpPort: 0, loginRate: 100000, verifyBudget: 1e9, clock: () => now, diskUsed: () => 0.1,
136
- log: (l) => lines.push(l), policy: (ctx) => relayPolicy(ctx, { pow: { bits: 8, loadBits: 12, loadPerHour: 1000 }, freeQueue: 64 * 1024 * 1024 }) };
151
+ log: (l) => lines.push(l), policy: (ctx) => relayPolicy(ctx, { pow: { bits: 8, loadBits: 12, loadPerHour: 1000 }, freeQueue: 64 * 1024 * 1024, tiers: { free: TEST_FREE, pro: TIERS.pro } }) };
137
152
  let relay = await startRelay(cfg);
138
153
  const endpoints = { [HOST]: { mqtt: `mqtt://127.0.0.1:${relay.ports.tcp}`, http: `http://127.0.0.1:${relay.ports.http}` } };
139
154
 
@@ -166,11 +181,14 @@ const events = {};
166
181
  const make = (a, extra = {}) => {
167
182
  events[a.label] = [];
168
183
  return new Carrier({ identity: () => ({ secret: a.secret, bundle: a.bundle }), ...pathsFor(join(dir, `${a.label}.local.json`)), relay: HOST, endpoints,
169
- clock: () => now, onEvent: (e) => events[a.label].push(e), keep: true, backoff: [100, 400], ...extra });
184
+ clock: () => now, onEvent: (e) => events[a.label].push(e), keep: true, backoff: [100, 400], retentionDays: 7, ...extra });
170
185
  };
171
186
  const seen = (who, f) => events[who].filter(f);
172
187
  const texts = (who) => seen(who, (e) => e.type === 'message').map((e) => e.content);
173
188
  const stateOf = (a) => JSON.parse(readFileSync(pathsFor(join(dir, `${a.label}.local.json`)).state, 'utf8'));
189
+ // The contact's re_pair as the carrier's contacts() lists it.
190
+ const marked = (carrier, peer) => carrier.contacts().contacts.find((c) => c.did === peer.original)?.re_pair;
191
+ const claimsOf = (a) => Object.keys(stateOf(a).relays[HOST]?.claims ?? {});
174
192
  const editState = (a, f) => { const file = pathsFor(join(dir, `${a.label}.local.json`)).state, s = JSON.parse(readFileSync(file, 'utf8')); f(s); writeFileSync(file, JSON.stringify(s)); };
175
193
  const oneTimeLeft = (holder, peer) => stateOf(holder).peers[peer.original].session.in.prekeys.oneTime.length;
176
194
  const q = (sql, ...p) => relay.db.raw.prepare(sql).all(...p);
@@ -896,13 +914,25 @@ try {
896
914
  const thief = make(T), heldBy = (x) => storeOf(x).contacts[A.original];
897
915
  ok((await thief.send('bob', say('from the thief'))).status === 'sent' && await until(() => texts('bob').includes('from the thief')), 'the thief, holding alice\'s key and files, rotates 63 times and writes to bob');
898
916
  ok(bob.contacts().contacts.find((c) => c.did === A.original).current_did === T.did && heldBy(B).rotations.length === 64, 'bob follows the thief\'s chain, 64 rotations: nothing offline can tell it from alice\'s');
917
+ // A message alice queued for bob before the recovery, as a send that returned `queued` leaves
918
+ // it: that send has exited, so only her inbox can tell her it never went.
919
+ const QUEUED = 'queued-before-the-recovery';
920
+ editState(A, (s) => s.peers[B.original].outbox.push({ id: QUEUED, label: '', content: say('queued before the recovery') }));
899
921
  recoverAgent(A);
900
922
  const recovered = A.did;
901
923
  secrets.add(recovered);
902
- ok((await alice.send('bob', say('after recovery'))).status === 'sent' && await until(() => texts('bob').includes('after recovery')), 'alice recovers and writes under her recovered key');
903
- ok(bob.contacts().contacts.find((c) => c.did === A.original).current_did === recovered, 'bob\'s store merged both chains: the recovery wins (SPEC §7.1)');
924
+ // The thief copied K with the key: after the recovery both sides hold it as burned (re_pair).
925
+ ok(marked(alice, B) === 'own_recovery' && storeOf(A).contacts[B.original].re_pair === 'own_recovery', 'alice recovers: her store marks bob re_pair, own_recovery, before any connection');
926
+ await refuses(() => alice.send('bob', 'after recovery'), 're_pair', 'and she sends him nothing under the old K');
927
+ const afterRecovery = (await alice.inbox()).events;
928
+ ok(afterRecovery.some((e) => e.type === 're_pair' && e.did === B.original && e.re_pair === 'own_recovery'), 'her next inbox says so');
929
+ ok(afterRecovery.some((e) => e.type === 'refused' && e.id === QUEUED && e.peer === B.original && e.code === 're_pair')
930
+ && stateOf(A).peers[B.original].outbox.length === 0 && seen('alice', (e) => e.type === 'refused' && e.id === QUEUED).length === 1,
931
+ 'and that the message queued for him before the recovery was refused, unsent (a refused event, code re_pair)');
932
+ ok(await until(() => heldBy(B).current_did === recovered), 'her rotation notice still goes: bob\'s store merged both chains, the recovery wins (SPEC §7.1)');
904
933
  ok(heldBy(B).rotations.length === 2, `and keeps the chain followed: her first rotation and the recovery, the thief's fork gone (${heldBy(B).rotations.length})`);
905
- ok(seen('bob', (e) => e.type === 'message' && e.content === 'after recovery')[0]?.current_did === recovered, 'her message is signed by the recovered key');
934
+ ok(marked(bob, A) === 'contact_recovery' && seen('bob', (e) => e.type === 'rotated' && e.current_did === recovered && e.re_pair === 'contact_recovery').length === 1,
935
+ 'bob marks alice re_pair, contact_recovery, and his rotated event says so');
906
936
  // She rotates again. First a notice from whoever holds K, with a copy of that rotation whose
907
937
  // signature is not valid ahead of the real one: refused, and bob's record left as it was.
908
938
  rotateAgent(A);
@@ -917,30 +947,55 @@ try {
917
947
  ok(await until(() => seen('bob', (e) => e.type === 'dropped' && e.check === 'bundle' && /two rotations on one edge/.test(e.detail)).length === 1), 'a notice with two rotations on one edge, the first not valid: refused');
918
948
  ok(heldBy(B).current_did === recovered && heldBy(B).rotations.length === 2, 'and bob\'s record is as it was');
919
949
  }
920
- ok((await alice.send('bob', say('rotated after recovery'))).status === 'sent' && await until(() => texts('bob').includes('rotated after recovery')), 'her own notice follows: her next message arrives');
921
- ok(heldBy(B).current_did === A.did && heldBy(B).rotations.length === 3, 'bob follows her rotation after the recovery');
950
+ await alice.inbox();
951
+ ok(await until(() => heldBy(B).current_did === A.did) && heldBy(B).rotations.length === 3 && heldBy(B).re_pair === 'contact_recovery', 'her own notice follows: bob follows her rotation after the recovery, the mark kept');
922
952
  await refuses(() => thief.send('bob', 'thief again'), 'bundle', 'the relay, which kept alice\'s recovery, refuses the thief\'s login');
923
- ok((await bob.send('alice', say('to the recovered key'))).status === 'sent', 'bob answers');
924
- ok((await alice.inbox()).messages.some((m) => m.content === 'to the recovered key'), 'alice reads it: her fresh prekeys followed her notice');
953
+ await refuses(() => bob.send('alice', 'to the recovered key'), 're_pair', 'bob sends nothing to alice under the old K either');
925
954
  }
926
955
 
927
956
  // ================================================================ pairing again replaces K
928
957
  {
929
958
  // The thief also copied K, and with it every later mailbox topic of the pair, which it can
930
- // claim first from any identity. A recovery does not change K; pairing again does: a code
931
- // between two contacts keeps the contact and replaces K, and its topics with it.
932
- const K0 = storeOf(A).contacts[B.original].pair_key;
959
+ // claim first from any identity. A recovery does not change K, so neither side claims a new
960
+ // mailbox under it (re_pair); pairing again does: a code between two contacts keeps the
961
+ // contact, replaces K, and its topics with it, and clears the mark. A week passes first.
962
+ const K0 = storeOf(A).contacts[B.original].pair_key, K0b = Buffer.from(K0, 'hex');
963
+ now += 7 * DAY;
964
+ await bob.sync();
965
+ await alice.inbox();
966
+ const ahead = isoWeek(now + 7 * DAY), squat = [topic(K0b, B.original, A.original, ahead), topic(K0b, A.original, B.original, ahead)];
967
+ ok(!squat.some((t) => claimsOf(A).includes(t) || claimsOf(B).includes(t)), 'a week after the recovery, neither has claimed next week\'s mailboxes under the burned K');
968
+ const squatter = await rawClient(agent('squatter')), squatted = [], takenBefore = seen('alice', (e) => e.code === 'mailbox_taken').length;
969
+ squatter.on('message', (t) => { if (squat.includes(t)) squatted.push(t); });
970
+ // The SUBACK's codes: MQTT.js hands back the topics asked, at the QoS asked, when one is refused.
971
+ const claim = (topics) => new Promise((resolve) => squatter.subscribe(topics, { qos: 1 }, (_err, _subs, packet) => resolve(packet?.granted ?? [])));
972
+ ok((await claim(squat)).join() === '1,1', 'the thief, holding K0, claims both of them first: the relay cannot tell (the live test\'s squat)');
933
973
  const code = (await alice.invite({ name: 'bob again' })).code;
934
- ok((await bob.accept(code, { name: 'alice again', wait: 0.3 })).status === 'waiting', 'bob answers a new code from alice, his contact already');
974
+ ok((await bob.accept(code, { name: 'alice', wait: 0.3 })).status === 'waiting', 'bob answers a new code from alice, his contact already');
935
975
  const a1 = await alice.inbox();
936
976
  ok(a1.events.some((e) => e.type === 'paired' && e.did === B.original && e.rekeyed === true), 'alice: the same contact, re-keyed');
937
977
  ok(await until(() => seen('bob', (e) => e.type === 'paired' && e.did === A.original && e.rekeyed === true).length === 1), 'bob: the same, on reading her reply');
938
978
  const K1 = storeOf(A).contacts[B.original].pair_key;
939
979
  ok(K1 !== K0 && K1 === storeOf(B).contacts[A.original].pair_key, 'both hold a new K, unknown to whoever copied the old one');
940
980
  ok(alice.contacts().contacts.filter((c) => c.did === B.original).map((c) => c.name).join() === 'bob', 'one contact, its name kept');
981
+ ok(marked(alice, B) === null && marked(bob, A) === null, 'and neither marks the other any more: the new K is not burned');
941
982
  await alice.inbox(); // bob's prekeys for the new pairing
942
983
  ok((await alice.send('bob', say('under the new K'))).status === 'sent' && await until(() => texts('bob').includes('under the new K')), 'alice writes under the new K, bob reads it');
984
+ ok(seen('bob', (e) => e.type === 'message' && e.content === 'under the new K')[0]?.current_did === A.did, 'signed by her key after the recovery');
943
985
  ok((await bob.send('alice', say('back under the new K'))).status === 'sent' && (await alice.inbox()).messages.some((m) => m.content === 'back under the new K'), 'and back');
986
+ // Next week's mailboxes of the pair are now K1's, held ahead by the pair: a thief with K0 cannot
987
+ // derive them, and one that learnt them could not claim them.
988
+ const K1b = Buffer.from(K1, 'hex'), theirs = [topic(K1b, B.original, A.original, ahead), topic(K1b, A.original, B.original, ahead)];
989
+ ok(await until(() => claimsOf(A).includes(theirs[0]) && claimsOf(B).includes(theirs[1])), 'next week\'s mailboxes under the new K are already claimed, each by its reader');
990
+ const refused = await claim(theirs);
991
+ ok(refused.join() === '128,128', `claimed by anyone else: refused (mailbox_taken; SUBACK ${refused.join()})`);
992
+ now += 7 * DAY;
993
+ await alice.inbox();
994
+ ok((await bob.send('alice', say('next week, under the new K'))).status === 'sent' && (await alice.inbox()).messages.some((m) => m.content === 'next week, under the new K'),
995
+ 'a week later bob writes in that week\'s mailbox and alice reads it');
996
+ await sleep(300);
997
+ squatter.end(true);
998
+ ok(squatted.length === 0 && seen('alice', (e) => e.code === 'mailbox_taken').length === takenBefore, `the thief's mailboxes under K0 got nothing (${squatted.length}), and alice never met mailbox_taken`);
944
999
  }
945
1000
 
946
1001
  // ================================================================ the MCP tools: the same verbs
@@ -1054,7 +1109,7 @@ try {
1054
1109
  // A re-key, the store's write failing after the state's: the reply the state kept names the
1055
1110
  // code's reply topic, and is put back before the answer runs again; its K never goes out.
1056
1111
  const K0 = storeOf(Ro).contacts[Sa.original].pair_key;
1057
- ok((await saul.accept((await rosa.invite({ name: 'saul again' })).code, { name: 'rosa again', wait: 0.3 })).status === 'waiting', 'saul answers a fresh code of hers: a re-key');
1112
+ ok((await saul.accept((await rosa.invite({ name: 'saul again' })).code, { name: 'rosa', wait: 0.3 })).status === 'waiting', 'saul answers a fresh code of hers: a re-key');
1058
1113
  f = failRenameOnce(files(Ro).store, (x) => { const c = JSON.parse(x).contacts[Sa.original]; return Boolean(c) && c.pair_key !== K0; });
1059
1114
  await rosa.inbox();
1060
1115
  f.restore();
@@ -1115,8 +1170,11 @@ try {
1115
1170
  recoverAgent(O);
1116
1171
  const recovered = O.did;
1117
1172
  secrets.add(recovered);
1118
- ok((await odile.send('piet', say('odile recovered'))).status === 'sent' && (await piet.inbox()).messages.some((m) => m.content === 'odile recovered' && m.current_did === recovered)
1119
- && storeOf(Pi).contacts[O.original].current_did === recovered, 'within that hour odile recovers: her notice, bringing the recovery, is checked all the same, and piet reads her');
1173
+ await refuses(() => odile.send('piet', 'odile recovered'), 're_pair', 'within that hour odile recovers: she writes nothing to piet under the old K');
1174
+ await odile.inbox();
1175
+ await piet.inbox();
1176
+ ok(storeOf(Pi).contacts[O.original].current_did === recovered && storeOf(Pi).contacts[O.original].re_pair === 'contact_recovery',
1177
+ 'her notice, bringing the recovery, is checked all the same: piet follows it, and marks her re_pair');
1120
1178
  t += 3601;
1121
1179
  await publish(mal, tp(), junk(NOTICE_CHECKS + 2));
1122
1180
  mal.end(true);
@@ -1137,16 +1195,20 @@ try {
1137
1195
  await quill.inbox(); await rhea.inbox(); await quill.inbox();
1138
1196
  ok((await quill.send('rhea', 'hello')).status === 'sent' && (await rhea.inbox()).messages.length === 1, 'quill and rhea pair and talk');
1139
1197
  // Day 15: quill's epoch is past 7 days, so this message begins one, in an ISO week rhea, away
1140
- // since day 0, never claimed. The relay drops it, and now says so: before, quill was told
1141
- // "sent", and every later message of that epoch failed epoch_unknown at rhea.
1198
+ // since day 0, never claimed. The relay drops it, and says so: before, quill was told "sent",
1199
+ // and every later message of that epoch failed epoch_unknown at rhea. Then it was refused,
1200
+ // lost; now it stays queued at quill's, unsealed, and goes once rhea is back.
1142
1201
  t += 15 * DAY;
1143
- await refuses(() => quill.send('rhea', 'day 15'), 'no_reader', 'day 15, to a mailbox rhea has not claimed: refused no_reader, not "sent"');
1202
+ const d15 = await quill.send('rhea', 'day 15');
1203
+ ok(d15.status === 'queued' && /does not hold its mailbox/.test(d15.detail) && stateOf(Q).peers[Rh.original].outbox.map((x) => x.content).join() === 'day 15',
1204
+ `day 15, to a mailbox rhea has not claimed: queued, kept in quill's outbox, not "sent" and not lost (${d15.status}: ${d15.detail})`);
1144
1205
  t += DAY;
1145
1206
  await rhea.inbox(); // back: she claims the weeks around now
1146
1207
  const st5 = [];
1147
1208
  for (let i = 0; i < 5; i++) { t += 3600; st5.push((await quill.send('rhea', `after return ${i}`)).status); }
1148
1209
  const box3 = await rhea.inbox();
1149
- ok(st5.every((x) => x === 'sent') && box3.messages.length === 5 && !box3.dropped.epoch_unknown, `the next five begin a new epoch and arrive (${st5.join()}; ${box3.messages.length} read, dropped ${JSON.stringify(box3.dropped)})`);
1210
+ ok(st5.every((x) => x === 'sent') && box3.messages.map((m) => m.content).join() === 'day 15,after return 0,after return 1,after return 2,after return 3,after return 4' && !box3.dropped.epoch_unknown,
1211
+ `the kept one goes first, then the next five, in a new epoch (${st5.join()}; ${box3.messages.length} read, dropped ${JSON.stringify(box3.dropped)})`);
1150
1212
  const contents = (box) => box.messages.map((m) => m.content).join();
1151
1213
  const carrying = () => stateOf(Q).peers[Rh.original].session.out.epoch.carry;
1152
1214
  // A relay that acknowledges an epoch's first envelope and throws it away: the next carries the
@@ -1217,21 +1279,22 @@ try {
1217
1279
  ok(JSON.parse(ottoFile()).inbox.length === 0 && !ottoFile().includes('hello otto'), 'otto took it by onEvent: his state file holds no message, in plaintext or otherwise');
1218
1280
  // otto is away 22 days, longer than he claims ahead: each of piper's sends begins an epoch the
1219
1281
  // relay refuses (no_reader). Before, each burned one of otto's one-time prekeys for good: after
1220
- // twenty, every epoch began on his last-resort key.
1282
+ // twenty, every epoch began on his last-resort key. Each message stays queued in her outbox.
1221
1283
  t += 22 * DAY;
1222
1284
  // Her own weekly bundle went just before (state edited): else it goes first, is refused
1223
- // no_reader as well, and her messages are refused unsealed, beginning no epoch at all.
1285
+ // no_reader as well, and her messages wait unsealed, beginning no epoch at all.
1224
1286
  editState(Pi, (x) => { x.peers[O.original].session.in.prekeys.replaced = t; });
1225
1287
  const used0 = outOf().used.length, refusals = [];
1226
- for (let i = 0; i < 3; i++) { t += 600; refusals.push(await piper.send('otto', `try ${i}`).then(() => 'sent', (e) => e.check)); }
1288
+ for (let i = 0; i < 3; i++) { t += 600; refusals.push(await piper.send('otto', `try ${i}`).then((r) => r.status, (e) => e.check)); }
1227
1289
  const out = outOf();
1228
- ok(refusals.join() === 'no_reader,no_reader,no_reader' && out.used.length === used0 && out.returned.length === 1,
1229
- `three sends refused no_reader: no prekey burned, the one each began on put back (${refusals.join()}; used ${used0} → ${out.used.length}, returned ${out.returned.length})`);
1290
+ ok(refusals.join() === 'queued,queued,queued' && out.used.length === used0 && out.returned.length === 1 && stateOf(Pi).peers[O.original].outbox.length === 3,
1291
+ `three sends to a mailbox nobody holds: queued, kept unsealed; no prekey burned, the one the first began on put back (${refusals.join()}; used ${used0} → ${out.used.length}, returned ${out.returned.length})`);
1230
1292
  t += 600;
1231
1293
  await otto.inbox(); await piper.inbox();
1294
+ ok(stateOf(Pi).peers[O.original].outbox.length === 0, 'otto back: piper\'s next inbox sends the three');
1232
1295
  const back = texts('otto').length;
1233
- ok((await piper.send('otto', 'after return')).status === 'sent' && (await otto.inbox()) && texts('otto').length === back + 1
1234
- && seen('otto', (e) => e.type === 'message' && e.content === 'after return')[0]?.last_resort === false, 'otto back: piper\'s next message begins an epoch on that one-time key, not the last-resort one');
1296
+ ok((await piper.send('otto', 'after return')).status === 'sent' && (await otto.inbox()) && texts('otto').slice(back).join() === 'try 0,try 1,try 2,after return'
1297
+ && seen('otto', (e) => e.type === 'message' && e.content === 'try 0')[0]?.last_resort === false, `otto reads them in order: they begin an epoch on that one-time key, not the last-resort one (${texts('otto').slice(back).join()})`);
1235
1298
  // 32 days in which neither runs: both bundles held are past their 31 days. Before, neither side
1236
1299
  // could send its fresh bundle (it went inside an envelope, which needs an epoch, which needs
1237
1300
  // the other's bundle): every send answered "queued" for good. Now bundles travel in frames.
@@ -1545,7 +1608,7 @@ try {
1545
1608
  ok(hugo.contacts().contacts.length === 10, 'hugo pairs with ten contacts');
1546
1609
  let subscribes = 0;
1547
1610
  const braked = (ctx) => {
1548
- const p = relayPolicy(ctx, { pow: { bits: 8, loadBits: 12, loadPerHour: 1000 }, freeQueue: 64 * 1024 * 1024, tiers: { free: { ...TIERS.free, mailboxes: 1000 }, pro: TIERS.pro }, rate: { claim: { perSecond: 1, burst: 20 } } });
1611
+ const p = relayPolicy(ctx, { pow: { bits: 8, loadBits: 12, loadPerHour: 1000 }, freeQueue: 64 * 1024 * 1024, tiers: { free: { ...TEST_FREE, mailboxes: 1000 }, pro: TIERS.pro }, rate: { claim: { perSecond: 1, burst: 20 } } });
1549
1612
  const rate = p.rate;
1550
1613
  p.rate = (x) => { if (x.kind === 'subscribe') subscribes++; return rate(x); };
1551
1614
  return p;
@@ -1576,12 +1639,119 @@ try {
1576
1639
  await relay12.close();
1577
1640
  }
1578
1641
 
1642
+ // ================================================================ the 0.1.3 live re-test (2026-10-14)
1643
+ {
1644
+ // Its own relay and clock. connect.html's order: ines invites, jon accepts while she is offline
1645
+ // (waiting), ines runs inbox (paired), then send. Jon's mailbox for the pairing needs K, which
1646
+ // only her reply carries: until jon's agent reads it, nobody holds that mailbox (no_reader).
1647
+ let t = now;
1648
+ const relayL = await startRelay({ ...cfg, db: join(dir, 'live.db'), tcpPort: 0, httpPort: 0, clock: () => t, log: () => {} });
1649
+ const epL = { [HOST]: { mqtt: `mqtt://127.0.0.1:${relayL.ports.tcp}`, http: `http://127.0.0.1:${relayL.ports.http}` } };
1650
+ const In = agent('isla'), Jo = agent('jude'), ines = make(In, { endpoints: epL, clock: () => t }), jon = make(Jo, { endpoints: epL, clock: () => t });
1651
+ const code1 = (await ines.invite({ name: 'jon' })).code, prefix = In.original.slice('did:sigelo:'.length, 'did:sigelo:'.length + 8);
1652
+ ok((await jon.accept(code1, { wait: 0.3 })).status === 'waiting' && jon.contacts().answers[0]?.name === prefix,
1653
+ `L1: accept without --name names the inviter by its DID's first digits (${jon.contacts().answers[0]?.name})`);
1654
+ ok((await ines.inbox()).events.some((e) => e.type === 'paired' && e.name === 'jon'), 'M1: ines\'s inbox pairs');
1655
+ const hello = await ines.send('jon', say('hello jon'));
1656
+ ok(hello.status === 'queued' && /jon's agent does not hold its mailbox for this pairing yet/.test(hello.detail) && stateOf(In).peers[Jo.original].outbox.length === 1,
1657
+ `M1: her first send is queued, kept in her outbox, and says why: jon's agent, not hers (${hello.status}: ${hello.detail})`);
1658
+ const hi = await jon.send(prefix, say('hi ines'));
1659
+ ok(hi.status === 'sent' && jon.contacts().contacts.map((c) => c.name).join() === prefix, `M1: jon's first send after accept reads her reply first, pairs and goes (${hi.status})`);
1660
+ const ib = await ines.inbox();
1661
+ ok(ib.messages.map((m) => m.content).join() === 'hi ines' && stateOf(In).peers[Jo.original].outbox.length === 0, 'M1: ines\'s next inbox reads him and sends her kept message');
1662
+ ok((await jon.inbox()).messages.map((m) => m.content).join() === 'hello jon', 'M1: jon reads it');
1663
+ await refuses(() => make(agent('noor'), { endpoints: epL, clock: () => t }).send('nobody', 'x'), 'not_contact', 'a name nobody answered stays not_contact');
1664
+
1665
+ // L1: on a re-pair, the name accept is given wins over the name kept.
1666
+ const code2 = (await ines.invite({ name: 'jonny' })).code;
1667
+ ok((await jon.accept(code2, { name: 'ines', wait: 0.3 })).status === 'waiting', 'L1: jon answers a new code of ines\'s, naming her');
1668
+ await refuses(() => jon.send('ines', 'too soon'), 'not_paired', 'M1: a send to the name of an answer the inviter has not read yet says so, by name');
1669
+ await ines.inbox();
1670
+ const jp = await jon.send('ines', say('re-paired'));
1671
+ ok(jp.status === 'sent' && jon.contacts().contacts.map((c) => c.name).join() === 'ines', `L1: once paired again, she is "ines" on his side (${jon.contacts().contacts.map((c) => c.name).join()})`);
1672
+ ok((await ines.inbox()).messages.some((m) => m.content === 're-paired') && ines.contacts().contacts.map((c) => c.name).join() === 'jon', 'L1: on hers he keeps his name: invite --name names new contacts only');
1673
+
1674
+ // L4: a code answered before is refused at once, not after the whole wait.
1675
+ const Ka = agent('kai'), kai = make(Ka, { endpoints: epL, clock: () => t }), t0 = Date.now();
1676
+ await refuses(() => kai.accept(code1, { wait: 10 }), 'mailbox_taken', 'L4: a replayed code');
1677
+ ok(Date.now() - t0 < 6000, `L4: refused in ${Date.now() - t0} ms, not after the 10 s wait`);
1678
+
1679
+ // H1: a thief copies phone's identity and files, writes to vps (an MCP agent), rotates, writes
1680
+ // twice more; the relay holds the last back. Then phone recovers from its genesis.
1681
+ const mcp = await import(pathToFileURL(join(HERE, '..', 'integrations', 'mcp', 'contact.mjs')).href);
1682
+ const id = await import(pathToFileURL(join(HERE, '..', 'adapters', 'moadim', 'sigelo-agent.ts')).href);
1683
+ const tools = await mcp.load({ installed: false, id, env: { SIGELO_RELAY: HOST, SIGELO_RELAY_ENDPOINTS: JSON.stringify(epL) }, clock: () => t });
1684
+ const vFile = join(dir, 'vps.local.json');
1685
+ id.init(vFile, keygen({ seed: seed('vps recovery'), recovery: 'sha256:' + '0'.repeat(64) }).key);
1686
+ const vDid = id.chainOf(id.load(vFile))[0], h = tools.handlers, vInbox = async () => JSON.parse((await h.sigelo_inbox({}, vFile)).text);
1687
+ secrets.add(vDid);
1688
+ const Ph = agent('phone'), phone = make(Ph, { endpoints: epL, clock: () => t });
1689
+ await h.sigelo_accept({ code: (await phone.invite({ name: 'vps' })).code, name: 'phone', wait: 1 }, vFile);
1690
+ await phone.inbox(); await vInbox(); await phone.inbox();
1691
+ ok((await phone.send('vps', say('from the phone'))).status === 'sent' && (await vInbox()).messages.some((m) => m.content === 'from the phone'), 'H1: phone and vps (MCP) pair and talk');
1692
+ const T = { ...Ph, label: 'phone thief', bundle: structuredClone(Ph.bundle) };
1693
+ for (const k of ['store', 'state']) copyFileSync(pathsFor(join(dir, 'phone.local.json'))[k], pathsFor(join(dir, 'phone thief.local.json'))[k]);
1694
+ const thief = make(T, { endpoints: epL, clock: () => t });
1695
+ ok((await thief.send('vps', say('THIEF before recovery'))).status === 'sent', 'H1: the thief writes under the copied key');
1696
+ rotateAgent(T);
1697
+ secrets.add(T.did);
1698
+ ok((await thief.send('vps', say('THIEF after rotating'))).status === 'sent', 'H1: rotates, and writes again under its own key');
1699
+ ok((await thief.send('vps', say('THIEF late'))).status === 'sent', 'H1: and once more');
1700
+ const late = relayL.db.raw.prepare('SELECT id, topic, payload FROM messages WHERE account = ? ORDER BY seq DESC LIMIT 1').get(accountOf(vDid));
1701
+ relayL.db.raw.prepare('DELETE FROM messages WHERE id = ?').run(late.id);
1702
+ const R = keygen({ seed: seed('phone recovered'), recovery: Ph.bundle.genesis.recovery, created: CREATED, nonce: seed('phone recovered nonce').slice(0, 16) });
1703
+ Ph.bundle.rotations = [rotate({ genesis: Ph.bundle.genesis, next_genesis: R.genesis, iat: t - 60, reason: 'recovery', secret: seed('phone recovery') })];
1704
+ Ph.secret = R.secret; Ph.did = R.did;
1705
+ secrets.add(R.did);
1706
+ await phone.inbox(); // the recovered chain logs in; its notice goes to vps
1707
+ const vb = await vInbox();
1708
+ ok(!vb.messages.some((m) => /THIEF/.test(m.content)), `H1: vps, in one sigelo_inbox after the recovery, delivers none of the thief's messages (${vb.messages.map((m) => m.content).join() || 'none'})`);
1709
+ const refusedNow = vb.events.filter((e) => e.type === 'refused' && e.code === 're_pair' && e.from === Ph.original).map((e) => e.current_did);
1710
+ ok(refusedNow.length === 2 && refusedNow.includes(Ph.original) && refusedNow.includes(T.did),
1711
+ `H1: both are reported refused, re_pair, with the key each was signed by: the recovered-from key and the thief's (${refusedNow.join()})`);
1712
+ const rot = vb.events.find((e) => e.type === 'rotated' && e.re_pair === 'contact_recovery');
1713
+ ok(rot?.current_did === R.did && rot.overruled.includes(Ph.original) && rot.overruled.includes(T.did) && !rot.overruled.includes(R.did),
1714
+ 'H1: the recovery\'s rotated event names the DIDs it overruled');
1715
+ const mal = await rawClient(agent('mallory'), epL);
1716
+ await publish(mal, late.topic, late.payload);
1717
+ mal.end(true);
1718
+ const vb2 = await vInbox();
1719
+ ok(vb2.messages.length === 0 && vb2.events.some((e) => e.type === 'refused' && e.code === 're_pair' && e.from === Ph.original && e.current_did === undefined) && !vb2.dropped.from,
1720
+ `H1: the one the relay held back, delivered after the recovery: refused re_pair too, not dropped as "from" (${JSON.stringify(vb2.events.map((e) => e.type + ':' + (e.code ?? '')))})`);
1721
+
1722
+ // The retention: relay.json's at the agent's own relay, unless told; 14 when it says nothing.
1723
+ ok(retentionOf({ limits: { free: { retention_days: 14 } } }) === 14 && retentionOf({ limits: { free: { retention_days: 91 } } }) === null && retentionOf({ limits: { free: { retention_days: '14' } } }) === null && retentionOf(null) === null,
1724
+ 'retentionOf: whole days, 1 to 90, else nothing');
1725
+ const info = createServer(async (req, res) => {
1726
+ if (req.url === '/relay.json') { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify({ limits: { free: { retention_days: 21 } } })); return; }
1727
+ const r = await fetch(`${epL[HOST].http}${req.url}`);
1728
+ res.writeHead(r.status, { 'content-type': 'application/json' });
1729
+ res.end(Buffer.from(await r.arrayBuffer()));
1730
+ });
1731
+ await new Promise((r) => info.listen(0, '127.0.0.1', r));
1732
+ const epI = { [HOST]: { mqtt: epL[HOST].mqtt, http: `http://127.0.0.1:${info.address().port}` } };
1733
+ const asked = make(agent('luz'), { endpoints: epI, clock: () => t, retentionDays: undefined });
1734
+ ok(asked.retentionDays === 14, `the default before any login: 14 days (${asked.retentionDays})`);
1735
+ await asked.inbox();
1736
+ ok(asked.retentionDays === 21, `after its first login: relay.json's 21 (${asked.retentionDays})`);
1737
+ const told = make(agent('mia'), { endpoints: epI, clock: () => t, retentionDays: 7 });
1738
+ await told.inbox();
1739
+ const none = make(agent('ned'), { endpoints: epL, clock: () => t, retentionDays: undefined });
1740
+ await none.inbox();
1741
+ ok(told.retentionDays === 7 && none.retentionDays === 14, `told 7 (SIGELO_RELAY_RETENTION_DAYS): 7 (${told.retentionDays}); a relay with no relay.json: 14 (${none.retentionDays})`);
1742
+ info.closeAllConnections();
1743
+ await new Promise((r) => info.close(r));
1744
+ await relayL.close();
1745
+ }
1746
+
1579
1747
  // ================================================================ forget
1580
1748
  const claimsBefore = q('SELECT count(*) AS n FROM claims WHERE account = ? AND topic LIKE ?', accountOf(B.original), 'm/%')[0].n;
1581
1749
  const f = await bob.forget(A.original);
1582
1750
  ok(f.revoked === true && f.released === true && f.did === A.original, 'bob forgets alice: revoked, and his mailboxes for her given up');
1583
1751
  ok(q('SELECT count(*) AS n FROM claims WHERE account = ? AND topic LIKE ?', accountOf(B.original), 'm/%')[0].n < claimsBefore, 'the relay holds fewer of bob\'s mailboxes');
1584
- await refuses(() => alice.send('bob', say('after forget')), 'no_reader', 'alice writes on: the relay tells her nobody holds that mailbox now');
1752
+ const af = await alice.send('bob', say('after forget'));
1753
+ ok(af.status === 'queued' && /bob's agent does not hold its mailbox/.test(af.detail) && alice.contacts().contacts.find((c) => c.did === B.original).queued === 1,
1754
+ `alice writes on: nobody holds that mailbox now, so it stays queued with her, and contacts says so (${af.status})`);
1585
1755
  await sleep(500);
1586
1756
  ok(!texts('bob').includes('after forget') && q('SELECT count(*) AS n FROM messages WHERE account = ?', accountOf(B.original))[0].n === 0, 'nobody reads it, and nothing is queued for bob');
1587
1757
  await refuses(() => bob.send('alice', 'x'), 'not_contact', 'bob cannot write to a forgotten contact by name');