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
@@ -0,0 +1,169 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Presence (carrier.mjs "Presence", design/transfer.md §8 T0): the store part first (off by default,
3
+ // allow and deny, own agents always, kept through a re-pair); then, with the relay checkout beside
4
+ // apps/contact/ (SIGELO_RELAY_DIR, else ../../relay), on a loopback relay: a started carrier's marker is
5
+ // read by an allowed contact and by its own agents, never by a denied one; a stop and a cut
6
+ // connection are the relay's offline with its time; a reconnection is online again; a deny clears
7
+ // what the contact sees.
8
+ // node apps/contact/test-presence.mjs → ALL PASS (n)
9
+ import { createHash } from 'node:crypto';
10
+ import { existsSync, mkdtempSync, rmSync } from 'node:fs';
11
+ import { tmpdir } from 'node:os';
12
+ import { dirname, join } from 'node:path';
13
+ import { fileURLToPath, pathToFileURL } from 'node:url';
14
+ import { attest, keygen, verify } from 'sigelo';
15
+ import { Contacts, OPERATOR_CTX } from './store.mjs';
16
+
17
+ const HERE = dirname(fileURLToPath(import.meta.url));
18
+ let count = 0;
19
+ const fails = [];
20
+ const ok = (cond, what) => { count++; if (!cond) fails.push(what); };
21
+ const checkOf = (f) => { try { f(); return 'accepted'; } catch (e) { return e.check ?? `exception ${e.constructor.name}: ${e.message}`; } };
22
+ const report = () => {
23
+ for (const f of fails) console.log('FAIL ' + f);
24
+ if (fails.length) { console.log(`${fails.length} FAILED, ${count - fails.length} passed`); process.exit(1); }
25
+ };
26
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
27
+ const until = async (cond, ms = 8000) => { const end = Date.now() + ms; while (Date.now() < end) { if (cond()) return true; await sleep(25); } return cond(); };
28
+
29
+ const CREATED = '2026-10-01T00:00:00Z', DAY = 86400;
30
+ let now = Date.parse('2026-11-02T12:00:00Z') / 1000;
31
+ const seed = (l) => new Uint8Array(createHash('sha256').update(`sigelo-presence-test/0 ${l}`).digest());
32
+ function agent(label) {
33
+ const k = keygen({ seed: seed(label), recovery: 'sha256:' + '0'.repeat(64), created: CREATED, nonce: seed(`${label} nonce`).slice(0, 16) });
34
+ return { label, did: k.did, secret: k.secret, genesis: k.genesis, bundle: { v: 'sigelo/0', typ: 'bundle', genesis: k.genesis, rotations: [], bindings: [], attestations: [], issuers: [] } };
35
+ }
36
+ const operate = (op, a, days = 90, iat = now - 60) => {
37
+ a.bundle.attestations.push(attest({ secret: op.secret, iss: op.did, sub: a.did, iat, exp: iat + days * DAY, ctx: OPERATOR_CTX, admission: 'invite', admission_by: op.did, claims: { relay: 'relay.test' } }));
38
+ if (!a.bundle.issuers.some((g) => g === op.genesis)) a.bundle.issuers.push(op.genesis);
39
+ };
40
+ const chainOnly = (a) => ({ ...a.bundle, attestations: [], issuers: [] });
41
+
42
+ // ================================================================ the store
43
+ {
44
+ const dir = mkdtempSync(join(tmpdir(), 'sigelo-presence-store-'));
45
+ try {
46
+ const H = agent('store human'), A = agent('store agent'), F = agent('store friend');
47
+ const hs = new Contacts(join(dir, 'h.json'), H.did, { mine: () => ({ chain: [H.did], operators: [] }) });
48
+ const key = (n) => n.toString(16).padStart(64, '0');
49
+ hs.admit(chainOnly(F), verify(chainOnly(F), now), 'friend', { relay: 'relay.test', pair_key: key(1) }, now);
50
+ operate(H, A);
51
+ hs.admit(A.bundle, verify(A.bundle, now), 'agent', { relay: 'relay.test', pair_key: key(2) }, now);
52
+ const c = () => hs.load().s.contacts;
53
+ ok(hs.presenceOf(c()[F.did], now) === 'deny' && hs.presenceOf(c()[A.did], now) === 'own', 'presence: a contact sees nothing by default (deny); an own agent always (own)');
54
+ ok(JSON.stringify(hs.setPresence('friend', true, now)) === JSON.stringify({ did: F.did, name: 'friend', presence: 'allow' }) && c()[F.did].presence === true, 'setPresence allow by name → {did, name, presence: allow}, kept in the record');
55
+ hs.admit(chainOnly(F), verify(chainOnly(F), now), 'friend', { relay: 'relay.test', pair_key: key(3) }, now);
56
+ ok(hs.presenceOf(c()[F.did], now) === 'allow', 'a re-pair keeps the choice');
57
+ ok(hs.setPresence(F.did, false, now).presence === 'deny' && c()[F.did].presence === undefined, 'setPresence deny by DID: off again');
58
+ ok(checkOf(() => hs.setPresence('agent', false, now)) === 'presence_own' && hs.setPresence('agent', true, now).presence === 'own', 'deny on an own agent: presence_own (own agents always see each other)');
59
+ ok(checkOf(() => hs.setPresence('nobody', true, now)) === 'not_contact' && checkOf(() => hs.setPresence('friend', 'yes', now)) === 'presence', 'no such contact: not_contact; allow not a boolean: presence');
60
+ } finally { rmSync(dir, { recursive: true, force: true }); }
61
+ }
62
+
63
+ const RELAY_DIR = process.env.SIGELO_RELAY_DIR ?? join(HERE, '..', '..', 'relay');
64
+ if (!existsSync(join(RELAY_DIR, 'server.mjs'))) {
65
+ report();
66
+ console.log(`ALL PASS (${count}): the store part; SKIP the rest, no relay checkout beside apps/contact/ (the relay is its own AGPL package): set SIGELO_RELAY_DIR`);
67
+ process.exit(0);
68
+ }
69
+
70
+ // ================================================================ on a loopback relay
71
+ const { startRelay } = await import(pathToFileURL(join(RELAY_DIR, 'server.mjs')).href);
72
+ const { relayPolicy } = await import(pathToFileURL(join(RELAY_DIR, 'allowance.mjs')).href);
73
+ const { Carrier, pathsFor, presenceTopic } = await import('./carrier.mjs');
74
+ setTimeout(() => { console.log(`FAIL the run did not finish in 300 s (${count} checks so far)`); process.exit(1); }, 300000).unref();
75
+
76
+ const HOST = 'relay.test';
77
+ const dir = mkdtempSync(join(tmpdir(), 'sigelo-presence-'));
78
+ const relay = await startRelay({ host: HOST, db: join(dir, 'relay.db'), tcpPort: 0, httpPort: 0, loginRate: 100000, verifyBudget: 1e9, clock: () => now, diskUsed: () => 0.1,
79
+ log: () => {}, policy: (ctx) => relayPolicy(ctx, { pow: { bits: 4, loadBits: 8, loadPerHour: 1000, cost: { m: 8, t: 1, p: 1 } } }) });
80
+ const endpoints = { [HOST]: { mqtt: `mqtt://127.0.0.1:${relay.ports.tcp}`, http: `http://127.0.0.1:${relay.ports.http}` } };
81
+ const events = {};
82
+ const make = (a) => {
83
+ events[a.label] = [];
84
+ return new Carrier({ identity: () => ({ secret: a.secret, bundle: a.bundle }), ...pathsFor(join(dir, `${a.label}.local.json`)), relay: HOST, endpoints,
85
+ clock: () => now, onEvent: (e) => events[a.label].push(e), keep: true, backoff: [100, 400], retentionDays: 7 });
86
+ };
87
+ const of = (c, did) => c.contacts().contacts.find((x) => x.did === did);
88
+ async function pair(ci, ca, name, back) {
89
+ const inv = await ci.invite({ name });
90
+ await ca.accept(inv.code, { name: back, wait: 0.3 });
91
+ await ci.inbox(); await ca.inbox(); await ci.inbox();
92
+ }
93
+ const rounds = async (...cs) => { for (let i = 0; i < 4; i++) for (const c of cs) { now += 5; await c.inbox(); } };
94
+ // The relay's session of identity a, by its client id (carrier.mjs clientIdOf).
95
+ const sessionOf = (a) => relay.broker.clients['s' + createHash('sha256').update(a.did).digest('hex').slice(0, 24)];
96
+ try {
97
+ const H = agent('human'), A = agent('atlas'), B = agent('beacon'), F = agent('friend');
98
+ operate(H, A); operate(H, B);
99
+ const ca = make(A), cb = make(B), cf = make(F);
100
+ await pair(ca, cb, 'beacon', 'atlas');
101
+ await rounds(ca, cb);
102
+ await pair(ca, cf, 'friend', 'atlas');
103
+ await rounds(ca, cf);
104
+ ok(of(ca, B.did).tier === 'own' && of(cb, A.did).tier === 'own' && of(ca, F.did).tier === 'friend', 'set-up: atlas and beacon are own to each other (one operator), friend is friend');
105
+ ok(of(ca, B.did).presence === 'own' && of(ca, F.did).presence === 'deny' && of(ca, F.did).online === null, 'contacts(): presence own for an own agent, deny for a friend by default; online null while nothing is read');
106
+
107
+ // A short session (inbox) is never online: no will, no marker; and it reads none (it would forget it
108
+ // at once, and each subscribe draws on the relay's brake).
109
+ const subscribed = [];
110
+ relay.broker.on('subscribe', (subs) => { for (const x of subs) subscribed.push(x.topic); });
111
+ now += 5; await ca.inbox(); await cb.inbox();
112
+ ok(relay.presence.size === 0, 'presence: CLI-style sessions (not started) publish no marker');
113
+ ok(!subscribed.some((t) => t.startsWith('p/')), `presence: CLI-style sessions subscribe to no presence topic (${subscribed.filter((t) => t.startsWith('p/')).length})`);
114
+
115
+ const at0 = now;
116
+ await ca.start(); await cb.start(); await cf.start();
117
+ ok(await until(() => of(ca, B.did).online === true && of(cb, A.did).online === true), 'presence: two own agents, started, see each other online');
118
+ ok(subscribed.filter((t) => t.startsWith('p/')).length >= 3, 'presence: a started carrier subscribes to its contacts\' markers');
119
+ ok(of(ca, B.did).online_since === at0 && of(ca, B.did).last_seen === null, `online_since: when the writer connected (${of(ca, B.did).online_since})`);
120
+ await sleep(300);
121
+ ok(of(ca, F.did).online === null && of(cf, A.did).online === null, 'presence: neither atlas nor friend allowed the other: each reads nothing of the other (null), both started');
122
+ ok(events.atlas.some((e) => e.type === 'presence' && e.did === B.did && e.online === true), 'a presence event says so (onEvent; never kept for inbox)');
123
+ // The denied reader learns nothing: no marker toward it exists at the relay.
124
+ const fK = Buffer.from(JSON.parse((await import('node:fs')).readFileSync(pathsFor(join(dir, 'friend.local.json')).store, 'utf8')).contacts[A.did].pair_key, 'hex');
125
+ ok(!relay.presence.held([presenceTopic(fK, F.did, A.did)]).length, 'presence: no marker from friend toward atlas is held at the relay');
126
+
127
+ // friend allows atlas: atlas sees friend.
128
+ cf.setPresence('atlas', true);
129
+ ok(await until(() => of(ca, F.did).online === true), 'presence: friend allows atlas (setPresence): atlas sees friend online at once (a started carrier applies it)');
130
+ ok(of(cf, A.did).presence === 'allow', 'contacts(): presence allow');
131
+
132
+ // A clean stop: the relay's offline, with its time.
133
+ now += 60;
134
+ const stopAt = now;
135
+ await cb.stop();
136
+ ok(await until(() => of(ca, B.did).online === false) && of(ca, B.did).last_seen === stopAt, `presence: beacon stops: atlas reads offline, last seen at the relay's time (${of(ca, B.did).last_seen})`);
137
+ ok(events.atlas.some((e) => e.type === 'presence' && e.did === B.did && e.online === false && e.last_seen === stopAt), 'the event carries last_seen');
138
+
139
+ // Reconnect: online again.
140
+ now += 60;
141
+ await cb.start();
142
+ ok(await until(() => of(ca, B.did).online === true && of(ca, B.did).online_since === now), 'presence: beacon starts again: online, since the new connection');
143
+
144
+ // A cut (no DISCONNECT): the will. The carrier reconnects by itself (backoff), online again.
145
+ now += 60;
146
+ const cutAt = now;
147
+ sessionOf(B).conn.destroy();
148
+ ok(await until(() => events.atlas.some((e) => e.type === 'presence' && e.did === B.did && e.online === false && e.last_seen === cutAt)), 'presence: beacon\'s connection cut: the relay\'s will says offline at the cut');
149
+ ok(await until(() => of(ca, B.did).online === true), 'presence: beacon reconnects with backoff: online again');
150
+
151
+ // friend denies atlas: the marker is cleared, atlas knows nothing (null), not "offline".
152
+ cf.setPresence('atlas', false);
153
+ ok(await until(() => of(ca, F.did).online === null), 'presence: friend denies atlas: cleared at once, atlas reads nothing (online null, no last seen)');
154
+ ok(of(ca, F.did).last_seen === null, 'and no last seen either');
155
+ // Nor after friend leaves: nothing toward atlas to mark offline.
156
+ await cf.stop();
157
+ await sleep(300);
158
+ ok(of(ca, F.did).online === null && of(ca, F.did).last_seen === null, 'presence: a denied contact\'s stop tells atlas nothing');
159
+
160
+ // The reader's own connection drops: what it read is forgotten (null), not left "online".
161
+ await ca.stop();
162
+ ok(of(ca, B.did).online === null, 'presence: once the reader is offline, it reports nothing it cannot know (null)');
163
+ await cb.stop();
164
+ } finally {
165
+ await relay.close();
166
+ rmSync(dir, { recursive: true, force: true });
167
+ }
168
+ report();
169
+ console.log(`ALL PASS (${count})`);
package/test-push.mjs ADDED
@@ -0,0 +1,136 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // The carrier's push registration (carrier.mjs setPush, sigelo-push/0; design/push.md) against a loopback
3
+ // relay (relay/server.mjs, relay/push.mjs) and a fake UnifiedPush distributor over HTTPS: registered at
4
+ // every login of a started carrier, a wake POSTed when a contact writes while it is stopped (opened here
5
+ // as the phone opens it, RFC 8291), removed with null, refused by name, nothing sent to a relay that does
6
+ // not say it takes it. Prints "ALL PASS (n)".
7
+ // node apps/contact/test-push.mjs
8
+ // The relay is its own AGPL package: SIGELO_RELAY_DIR, else ../../relay; without it: SKIP.
9
+ import { createDecipheriv, createECDH, createHash, hkdfSync } from 'node:crypto';
10
+ import { existsSync, mkdtempSync } from 'node:fs';
11
+ import { createServer } from 'node:https';
12
+ import { tmpdir } from 'node:os';
13
+ import { dirname, join } from 'node:path';
14
+ import { fileURLToPath, pathToFileURL } from 'node:url';
15
+ import { keygen } from 'sigelo';
16
+ import { Carrier, PUSH_TOPIC, PUSH_V, pathsFor } from './carrier.mjs';
17
+
18
+ const HERE = dirname(fileURLToPath(import.meta.url));
19
+ let count = 0;
20
+ const fails = [];
21
+ const ok = (cond, what) => { count++; if (!cond) fails.push(what); };
22
+ const RELAY_DIR = process.env.SIGELO_RELAY_DIR ?? join(HERE, '..', '..', 'relay');
23
+ if (!existsSync(join(RELAY_DIR, 'push.mjs'))) { console.log('ALL PASS (0): SKIP, no relay with push.mjs beside apps/contact/ (set SIGELO_RELAY_DIR)'); process.exit(0); }
24
+ const { startRelay } = await import(pathToFileURL(join(RELAY_DIR, 'server.mjs')).href);
25
+ const { WAKE } = await import(pathToFileURL(join(RELAY_DIR, 'push.mjs')).href);
26
+ const { selfSigned } = await import(pathToFileURL(join(RELAY_DIR, 'test', 'fixtures.mjs')).href);
27
+ setTimeout(() => { console.log(`FAIL the run did not finish in 180 s (${count} checks so far)`); process.exit(1); }, 180000).unref();
28
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
29
+ const until = async (cond, ms = 8000) => { const end = Date.now() + ms; while (Date.now() < end) { if (cond()) return true; await sleep(20); } return cond(); };
30
+
31
+ // The phone's push keys (WebPush.java makes them on the phone): a P-256 pair and a 16-byte auth secret.
32
+ const ua = createECDH('prime256v1');
33
+ ua.generateKeys();
34
+ const AUTH = createHash('sha256').update('sigelo push test auth').digest().subarray(0, 16);
35
+ const KEYS = { p256dh: ua.getPublicKey().toString('base64url'), auth: AUTH.toString('base64url') };
36
+ // RFC 8291 §3.4, as WebPush.java opens a wake.
37
+ function open(body) {
38
+ const salt = body.subarray(0, 16), idlen = body[20], asPublic = body.subarray(21, 21 + idlen), ct = body.subarray(21 + idlen);
39
+ const ikm = Buffer.from(hkdfSync('sha256', ua.computeSecret(asPublic), AUTH, Buffer.concat([Buffer.from('WebPush: info\0'), ua.getPublicKey(), asPublic]), 32));
40
+ const d = createDecipheriv('aes-128-gcm', Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: aes128gcm\0'), 16)), Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: nonce\0'), 12)));
41
+ d.setAuthTag(ct.subarray(ct.length - 16));
42
+ const rec = Buffer.concat([d.update(ct.subarray(0, ct.length - 16)), d.final()]);
43
+ return rec.subarray(0, rec.length - 1);
44
+ }
45
+
46
+ // The fake distributor: every POST kept.
47
+ const cert = selfSigned('localhost'), posts = [];
48
+ const dist = createServer({ cert: cert.cert, key: cert.key }, (req, res) => {
49
+ const parts = [];
50
+ req.on('data', (d) => parts.push(d));
51
+ req.on('end', () => { posts.push({ url: req.url, body: Buffer.concat(parts) }); res.writeHead(201); res.end(); });
52
+ });
53
+ await new Promise((r) => dist.listen(0, '127.0.0.1', r));
54
+ const ENDPOINT = `https://localhost:${dist.address().port}/upPhone?up=1`;
55
+
56
+ const HOST = 'relay.test', dir = mkdtempSync(join(tmpdir(), 'sigelo-push-carrier-'));
57
+ let now = Date.parse('2026-11-24T12:00:00Z') / 1000;
58
+ const cfg = { host: HOST, db: join(dir, 'relay.db'), tcpPort: 0, httpPort: 0, loginRate: 100000, verifyBudget: 1e9, clock: () => now, diskUsed: () => 0.1, log: () => {},
59
+ push: { anyAddress: true, ca: cert.cert } };
60
+ let relay = await startRelay(cfg);
61
+ const endpointsOf = (r) => ({ [HOST]: { mqtt: `mqtt://127.0.0.1:${r.ports.tcp}`, http: `http://127.0.0.1:${r.ports.http}` } });
62
+ const seed = (l) => new Uint8Array(createHash('sha256').update(`sigelo-push-test/0 ${l}`).digest());
63
+ const agent = (label) => {
64
+ const k = keygen({ seed: seed(label), recovery: 'sha256:' + '0'.repeat(64), created: '2026-10-01T00:00:00Z', nonce: seed(`${label} nonce`).slice(0, 16) });
65
+ return { label, secret: k.secret, bundle: { v: 'sigelo/0', typ: 'bundle', genesis: k.genesis, rotations: [], bindings: [], attestations: [], issuers: [] } };
66
+ };
67
+ const events = {};
68
+ const make = (a, r = relay) => { events[a.label] = []; return new Carrier({ identity: () => ({ secret: a.secret, bundle: a.bundle }), ...pathsFor(join(dir, `${a.label}.local.json`)), relay: HOST, endpoints: endpointsOf(r),
69
+ clock: () => now, onEvent: (e) => events[a.label].push(e), keep: true, backoff: [100, 400] }); };
70
+ const rows = () => relay.db.raw.prepare('SELECT count(*) AS n FROM push').get().n;
71
+ const A = agent('alice'), B = agent('bob');
72
+ let alice = make(A), bob = make(B);
73
+ const checkOf = (f) => { try { f(); return 'accepted'; } catch (e) { return e.check ?? e.message; } };
74
+
75
+ try {
76
+ // Pairing, each side in turn (test-carrier.mjs's first scenario).
77
+ const inv = await alice.invite({ name: 'bob' });
78
+ await bob.accept(inv.code, { name: 'alice', wait: 0.3 });
79
+ await alice.inbox(); await bob.inbox(); await alice.inbox();
80
+ ok(alice.contacts().contacts[0]?.prekeys === true, 'alice and bob paired');
81
+
82
+ ok(PUSH_TOPIC === '$sigelo/push' && PUSH_V === 'sigelo-push/0' && bob.pushStatus().state === 'none', 'the wire names; never set: state none, nothing sent');
83
+ const bad = [{ endpoint: 'http://x.example/y', ...KEYS }, { endpoint: ENDPOINT, p256dh: KEYS.p256dh }, { endpoint: ENDPOINT, ...KEYS, more: 1 }, { endpoint: ENDPOINT, p256dh: 'a+b/', auth: KEYS.auth }, 'x'].map((r) => checkOf(() => bob.setPush(r)));
84
+ ok(bad.every((c) => c === 'push'), `setPush: anything but {endpoint (https), p256dh, auth (base64url)} or null refused "push" (${bad})`);
85
+ ok(bob.setPush({ endpoint: ENDPOINT, ...KEYS }).state === 'pending', 'setPush before a login: pending');
86
+ await bob.start();
87
+ ok(await until(() => bob.pushStatus().state === 'registered') && rows() === 1, `a started carrier registers at its login: state registered, one row at the relay (${JSON.stringify(bob.pushStatus())})`);
88
+ ok(events.bob.some((e) => e.type === 'push' && e.state === 'registered' && e.relay === HOST), 'an event push {state: registered, relay}');
89
+ await alice.send('bob', 'while bob is connected');
90
+ await sleep(300);
91
+ ok(posts.length === 0, 'bob connected: no wake');
92
+ await bob.stop();
93
+ await sleep(200);
94
+ await alice.send('bob', 'while bob is away');
95
+ ok(await until(() => posts.length === 1), 'bob stopped, alice writes: one POST to his endpoint');
96
+ ok(posts[0].url === '/upPhone?up=1' && open(posts[0].body).equals(WAKE), 'the wake opens under the phone\'s keys to WAKE (RFC 8291): no sender, no text');
97
+ await alice.send('bob', 'again');
98
+ await sleep(300);
99
+ ok(posts.length === 1, 'a second message before bob is back: no second wake');
100
+
101
+ // The phone's app wakes: bob logs in, takes his mail. The same registration again changes nothing at the relay.
102
+ bob = make(B);
103
+ bob.setPush({ endpoint: ENDPOINT, ...KEYS });
104
+ const box = await bob.inbox();
105
+ ok(box.messages.map((m) => m.content).join('|') === 'while bob is connected|while bob is away|again' && bob.pushStatus().state === 'registered', 'woken, bob reads all three; registered again at that login (an inbox() session too)');
106
+
107
+ // Off: null removes it at the relay.
108
+ bob.setPush(null);
109
+ await bob.inbox();
110
+ ok(bob.pushStatus().state === 'off' && rows() === 0, 'setPush(null): removed at the relay at the next login (state off, no row)');
111
+ await alice.send('bob', 'no wake now');
112
+ await sleep(300);
113
+ ok(posts.length === 1, 'removed: no wake');
114
+
115
+ // A registration the relay refuses (a key off the curve): the notice by name, the session goes on.
116
+ bob.setPush({ endpoint: ENDPOINT, p256dh: Buffer.concat([Buffer.from([4]), Buffer.alloc(64, 1)]).toString('base64url'), auth: KEYS.auth });
117
+ const r2 = await bob.inbox();
118
+ ok(bob.pushStatus().state === 'refused' && bob.pushStatus().code === 'push' && /p256dh/.test(bob.pushStatus().detail) && r2.messages.length === 1, `refused: state refused, code push, why (${bob.pushStatus().detail}); the mail still came`);
119
+
120
+ // A relay without push: nothing is sent (it would close the session), state unsupported.
121
+ await relay.close();
122
+ relay = await startRelay({ ...cfg, db: join(dir, 'off.db'), push: false });
123
+ const carol = make(agent('carol'), relay);
124
+ carol.setPush({ endpoint: ENDPOINT, ...KEYS });
125
+ await carol.inbox();
126
+ ok(carol.pushStatus().state === 'unsupported' && !events.carol.some((e) => e.type === 'notice'), 'a relay that does not say push: nothing sent, state unsupported, no notice');
127
+ } finally {
128
+ try { await bob.stop(); } catch {}
129
+ await relay.close();
130
+ dist.closeAllConnections?.();
131
+ dist.close();
132
+ }
133
+ for (const f of fails) console.log('FAIL ' + f);
134
+ if (fails.length) { console.log(`${fails.length} FAILED, ${count - fails.length} passed`); process.exit(1); }
135
+ console.log(`ALL PASS (${count})`);
136
+ process.exit(0);
@@ -0,0 +1,248 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // The relay lane for transfers (0.1.19; transfer-engine.mjs "The relay lane", apps/agent/TRANSFER.md): the units first
3
+ // (the end `relay`, who may fall back and up to what size, resume on a stuck transfer, a stalled channel, a record stuck
4
+ // for 10 minutes listed as interrupted), then, with the relay checkout beside apps/contact/ (SIGELO_RELAY_DIR, else
5
+ // ../../relay), two agents on a loopback relay with a fake direct path: blocked (ICE never connects) the file lands over
6
+ // sigelo-file/0 and the receiver's record is relayed, then done by the file; a channel that drops and does not come back
7
+ // within the window goes over the relay too; 8 MiB + 1 byte is not fallen back, and the relay lane refuses it.
8
+ // node apps/contact/test-relay-lane.mjs → ALL PASS (n)
9
+ import { createHash } from 'node:crypto';
10
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
11
+ import { tmpdir } from 'node:os';
12
+ import { dirname, join } from 'node:path';
13
+ import { fileURLToPath, pathToFileURL } from 'node:url';
14
+ import { keygen } from 'sigelo';
15
+ import { CHUNK, LOW, REASONS, checkMessage, readFrame, frames } from './transfer.mjs';
16
+ import * as E from './transfer-engine.mjs';
17
+ import { FILE_LABEL, MAX_FILE } from './file.mjs';
18
+
19
+ let count = 0;
20
+ const fails = [];
21
+ const ok = (cond, what, more) => { count++; if (!cond) fails.push(more === undefined ? what : `${what} (${String(more).slice(0, 600)})`); };
22
+ const checkOf = (f) => { try { f(); return 'accepted'; } catch (e) { return e.check ?? `exception ${e.constructor.name}: ${e.message}`; } };
23
+ const failure = async (f) => { try { await f(); return 'accepted'; } catch (e) { return e.check ?? `exception ${e.message}`; } };
24
+ const report = () => {
25
+ for (const f of fails) console.log('FAIL ' + f);
26
+ if (fails.length) { console.log(`${fails.length} FAILED, ${count - fails.length} passed`); process.exit(1); }
27
+ };
28
+ const HERE = dirname(fileURLToPath(import.meta.url));
29
+ const sha = (b) => createHash('sha256').update(b).digest('hex');
30
+ const seeded = (seed, n) => {
31
+ const out = Buffer.alloc(n);
32
+ for (let i = 0, off = 0; off < n; i++, off += 32) createHash('sha256').update(`${seed}\n${i}`).digest().copy(out, off, 0, Math.min(32, n - off));
33
+ return new Uint8Array(out.buffer, out.byteOffset, n);
34
+ };
35
+
36
+ /** The engine's io in memory: the records and bitmaps as strings and bytes, the files sent by name. */
37
+ function memIo(docs = new Map()) {
38
+ let text = null;
39
+ const m = new Map();
40
+ return {
41
+ flushEach: 1, docs,
42
+ lock: (fn) => fn(), read: () => text, write: (t) => { text = t; },
43
+ have: { read: (id) => m.get(`h${id}`) ?? null, write: (id, b) => { if (b === null) m.delete(`h${id}`); else m.set(`h${id}`, Uint8Array.from(b)); } },
44
+ list: { read: (id, side) => m.get(`l${id}${side}`) ?? null, write: (id, side, b) => m.set(`l${id}${side}`, b), drop: (id, side) => m.delete(`l${id}${side}`) },
45
+ part: { open: async () => ({ write: async () => {}, flush: async () => {}, close: async () => {} }), drop: (id) => m.delete(`p${id}`), sha256: async () => '0'.repeat(64), exists: () => false },
46
+ free: () => Infinity, land: async () => 'saved', changed: async () => false,
47
+ prepare: async ({ path }) => { const b = docs.get(path); const n = Math.ceil(b.length / CHUNK), hashes = new Uint8Array(n * 32); for (let i = 0; i < n; i++) hashes.set(createHash('sha256').update(b.subarray(i * CHUNK, (i + 1) * CHUNK)).digest(), i * 32); return { file: path, name: path, size: b.length, mtimeMs: 1, hashes, whole: sha(b) }; },
48
+ source: async (r) => ({ read: async (i) => docs.get(r.file).subarray(i * CHUNK, (i + 1) * CHUNK), close: async () => {} }),
49
+ tor: null,
50
+ };
51
+ }
52
+ const NOW = 1_800_000_000;
53
+ function fakeCarrier(contacts) {
54
+ const sent = [], files = [];
55
+ return { sent, files, clock: () => NOW, contacts: () => ({ contacts }), takeTransfers: () => [], deliver: () => {},
56
+ async send(to, content, o) { sent.push({ to, content, label: o.label }); return { status: 'sent' }; },
57
+ async sendFile(to, f) { files.push({ to, name: f.name, size: f.bytes.length, sha256: sha(f.bytes) }); return { status: 'sent', file: { id: '0'.repeat(32), name: f.name, size: f.bytes.length, sha256: sha(f.bytes) } }; } };
58
+ }
59
+ const OWN = { did: 'did:sigelo:zOwn', name: 'own', tier: 'own' }, PAL = { did: 'did:sigelo:zPal', name: 'pal', tier: 'friend' }, NEW = { did: 'did:sigelo:zNew', name: 'new', tier: 'friend' };
60
+
61
+ // ================================================================ units
62
+ {
63
+ ok(REASONS.at(-1) === 'relay' && checkOf(() => checkMessage({ typ: 'end', id: 'ab'.repeat(16), reason: 'relay' })) === 'accepted' && readFrame(frames.end('relay')).reason === 'relay',
64
+ 'the end reason relay: last in the list (the frames\' indices stay), a well-formed end');
65
+ ok(E.RELAY_MAX === MAX_FILE && MAX_FILE === 8 * 1024 * 1024 && E.FALLBACK_MS === 20_000 && E.STALE_S === 600, 'the relay lane carries send-file\'s 8 MiB; the window 20 s; stuck after 10 minutes');
66
+ const e = new E.Engine({ carrier: fakeCarrier([OWN, PAL, NEW]), io: memIo(), compared: (d) => d === PAL.did, timer: false });
67
+ const rec = (x) => ({ id: 'ab'.repeat(16), size: MAX_FILE, state: 'failed', reason: 'no_path', to: OWN.did, ...x });
68
+ ok(e.relayable(rec({})) && e.relayable(rec({ to: PAL.did })), 'exactly 8 MiB to an own agent, or to a friend whose words were compared: falls back (no dead end at the limit)');
69
+ ok(!e.relayable(rec({ size: MAX_FILE + 1 })), '8 MiB + 1 byte: not fallen back');
70
+ ok(!e.relayable(rec({ to: NEW.did })) && !e.relayable(rec({ relay: 1 })) && !e.relayable(rec({ state: 'done' })), 'words not compared, gone over the relay once already, done: not by itself');
71
+ await e.close();
72
+
73
+ // The sender: a no_path end → over the relay, once; the receiver told first; the bytes checked against the manifest.
74
+ {
75
+ const docs = new Map([['a.apk', seeded('apk', CHUNK + 77)], ['big.bin', seeded('big', MAX_FILE + 1)]]), io = memIo(docs), car = fakeCarrier([OWN]);
76
+ const r = await E.send({ carrier: car, io, to: 'own', path: 'a.apk' }), big = await E.send({ carrier: car, io, to: 'own', path: 'big.bin' });
77
+ const x = new E.Engine({ carrier: car, io, timer: false });
78
+ car.takeTransfers = () => { const l = car.inbound ?? []; car.inbound = []; return l; };
79
+ car.inbound = [{ from: OWN.did, name: 'own', content: { typ: 'end', id: r.id, reason: 'no_path' } }, { from: OWN.did, name: 'own', content: { typ: 'end', id: big.id, reason: 'no_path' } }];
80
+ await x.round();
81
+ for (let i = 0; i < 50 && E.list({ carrier: car, io }).out.find((y) => y.id === r.id)?.state !== 'done'; i++) await new Promise((ok_) => setTimeout(ok_, 20));
82
+ const L = E.list({ carrier: car, io }), a = L.out.find((y) => y.id === r.id), b = L.out.find((y) => y.id === big.id);
83
+ ok(a.state === 'done' && a.path_used === 'relay' && a.relay === 1 && car.files.length === 1 && car.files[0].sha256 === r.sha256 && car.files[0].name === 'a.apk', `no path: over sigelo-file/0, whole, by itself (${JSON.stringify(a)})`);
84
+ ok(car.sent.some((m) => m.content.typ === 'end' && m.content.reason === 'relay' && m.content.id === r.id), 'the receiver told end relay first');
85
+ ok(b.state === 'failed' && b.reason === 'no_path' && !b.relay && car.files.length === 1, '8 MiB + 1 byte: failed no_path as before, nothing over the relay (the page offers Retry)');
86
+ ok(await failure(() => x.relay(big.id, { manual: true })) === 'file_too_large' && await failure(() => x.relay(r.id, { manual: true })) === 'transfer_state', 'Send over the relay: refused past 8 MiB (file_too_large), and on one done');
87
+ const rt = await E.retry({ carrier: car, io, id: big.id, engine: x }), L2 = E.list({ carrier: car, io });
88
+ ok(rt.id !== big.id && rt.state === 'offered' && rt.sha256 === big.sha256 && L2.out.find((y) => y.id === big.id).state === 'cancelled' && car.sent.some((m) => m.content.typ === 'end' && m.content.id === big.id && m.content.reason === 'cancelled'),
89
+ 'Retry: the old one cancelled (the receiver told), the file offered afresh under a new id');
90
+ // An offer that crossed the end relay: answered relay again, never served.
91
+ car.inbound = [{ from: OWN.did, name: 'own', content: { typ: 'offer', id: r.id, attempt: 2, sdp: null, tor: { serve: false, connect: false } } }];
92
+ car.sent.length = 0; await x.round();
93
+ ok(car.sent.length === 1 && car.sent[0].content.reason === 'relay' && E.list({ carrier: car, io }).out.find((y) => y.id === r.id).state === 'done', 'a late offer: told relay again, the record stays done');
94
+ await x.close();
95
+ }
96
+
97
+ // The receiver: resume on a stuck transfer; listed interrupted after 10 minutes; the end relay; a stalled channel.
98
+ {
99
+ const io = memIo(), car = fakeCarrier([OWN]), id = 'cd'.repeat(16), id2 = 'ce'.repeat(16), id3 = 'cf'.repeat(16);
100
+ const base = { from: OWN.did, contact: 'own', name: 'app.apk', size: 1_000_000, sha256: 'ab'.repeat(32), chunks: 1, list: 'ab'.repeat(32), exp: NOW + 86400, attempt: 1, got: 0 };
101
+ E.state(io, NOW, (s) => {
102
+ s.in[id] = { ...base, id, state: 'active', reason: 'drop', detail: 'the channel went: resumed with a new offer', at: NOW - 3600, offerAt: NOW - 3600 };
103
+ s.in[id2] = { ...base, id: id2, state: 'active', at: NOW - 60, offerAt: NOW - 60 };
104
+ s.in[id3] = { ...base, id: id3, state: 'active', at: NOW - 60, offerAt: NOW - 60 };
105
+ });
106
+ ok(checkOf(() => E.accept({ carrier: car, io, id })) === 'transfer_state', 'accept on an active-but-dropped transfer: still refused (it is resume\'s)');
107
+ const L = E.list({ carrier: car, io }), st = L.in.find((r) => r.id === id), fresh = L.in.find((r) => r.id === id2);
108
+ ok(st.state === 'interrupted' && st.reason === 'stalled' && /resume it/.test(st.detail) && fresh.state === 'active', `active with nothing for over 10 minutes: listed interrupted, the resume hint (${st.state}: ${st.detail}); a minute: still active`);
109
+ const rs = E.resume({ carrier: car, io, id });
110
+ ok(rs.state === 'accepted' && rs.restart === true && rs.reason === undefined, `resume on it: accepted again, restart (${JSON.stringify(rs)})`);
111
+ // The engine drops what it holds of it and offers again, attempt 2.
112
+ const rtc = { peer: async () => ({ offer: async () => 'v=0 fake', close() {} }) };
113
+ const x = new E.Engine({ carrier: car, io, rtc: async () => rtc, stun: [], timer: false, stallMs: 1000 });
114
+ x.attempts.set(id, { role: 'in', attempt: 1, got: 0, sent: 0, order: ['direct'] });
115
+ // A channel that moved nothing for longer than stallMs: dropped here, interrupted (resumed by itself).
116
+ x.attempts.set(id2, { role: 'in', attempt: 1, got: 0, sent: 0, channel: { close() {} }, moved: Date.now() - 5000 });
117
+ await x.round();
118
+ const sent = car.sent.find((m) => m.content.typ === 'offer' && m.content.id === id), r2 = E.list({ carrier: car, io }).in.find((r) => r.id === id2);
119
+ ok(sent?.content.attempt === 2 && E.list({ carrier: car, io }).in.find((r) => r.id === id).state === 'offering', `the engine offers it again (attempt ${sent?.content.attempt})`);
120
+ ok(r2.state === 'interrupted' && r2.reason === 'drop' && /nothing came for 1 s/.test(r2.detail) && !x.attempts.has(id2), `a channel stalled past stallMs: dropped, interrupted drop (${r2.state}: ${r2.detail})`);
121
+ // The sender's end relay: the record relayed, no ghost left live.
122
+ car.takeTransfers = () => { const l = car.inbound ?? []; car.inbound = []; return l; };
123
+ car.inbound = [{ from: OWN.did, name: 'own', content: { typ: 'end', id: id3, reason: 'relay' } }];
124
+ await x.round();
125
+ const r3 = E.list({ carrier: car, io }).in.find((r) => r.id === id3);
126
+ ok(r3.state === 'relayed' && /relay lane/.test(r3.detail) && !E.STATES_LIVE_IN.includes(r3.state), `end relay: the receiver's record relayed (${r3.state})`);
127
+ const sup = x.superseded({ type: 'file', from: OWN.did, sha256: base.sha256, path: '/files/own/app.apk', label: FILE_LABEL });
128
+ const r4 = E.list({ carrier: car, io }).in.find((r) => r.id === id3);
129
+ ok(sup.includes(id3) && r4.state === 'done' && r4.path_used === 'relay' && r4.saved === '/files/own/app.apk', `the file over sigelo-file/0 came: the record done, via relay (${JSON.stringify(sup)})`);
130
+ ok(x.superseded({ type: 'file', from: OWN.did, sha256: base.sha256, transfer: id, path: 'x' }).length === 0 && x.superseded({ type: 'file', from: PAL.did, sha256: base.sha256, path: 'x' }).length === 0, 'superseded: never by a transfer\'s own item, nor by another contact\'s file');
131
+ await x.close();
132
+ }
133
+ }
134
+
135
+ // ================================================================ two agents on a loopback relay, a fake direct path
136
+ const RELAY_DIR = process.env.SIGELO_RELAY_DIR ?? join(HERE, '..', '..', 'relay');
137
+ if (!existsSync(join(RELAY_DIR, 'server.mjs'))) {
138
+ report();
139
+ console.log(`ALL PASS (${count}): the unit part; SKIP the flows (no relay checkout)`);
140
+ process.exit(0);
141
+ }
142
+ const { startRelay } = await import(pathToFileURL(join(RELAY_DIR, 'server.mjs')).href);
143
+ const { relayPolicy } = await import(pathToFileURL(join(RELAY_DIR, 'allowance.mjs')).href);
144
+ const { Carrier, pathsFor } = await import('./carrier.mjs');
145
+ const X = await import('./transfer-node.mjs');
146
+ setTimeout(() => { console.log(`FAIL the run did not finish in 600 s (${count} checks so far)`); process.exit(1); }, 600_000).unref();
147
+
148
+ /** A fake direct path: two ends of a channel in this process; blocked: ICE never connects; dropAfter: frames, then it goes. */
149
+ const net = { blocked: false, dropAfter: Infinity, pairs: new Map(), n: 0 };
150
+ function pairOf() {
151
+ const mk = () => ({ handlers: { frame: [], low: [], close: [] }, buffered: 0, closed: false });
152
+ const a = mk(), b = mk();
153
+ let shut = false, sent = 0;
154
+ const close = () => { if (shut) return; shut = true; a.closed = b.closed = true; setImmediate(() => { for (const fn of [...a.handlers.close, ...b.handlers.close]) fn(); }); };
155
+ const end = (me, other) => ({
156
+ send(f) {
157
+ if (me.closed) throw new Error('closed');
158
+ if (++sent > net.dropAfter) { close(); return; }
159
+ me.buffered += f.length;
160
+ setImmediate(() => { me.buffered -= f.length; if (me.buffered < LOW) for (const fn of me.handlers.low) fn(); if (!other.closed) for (const fn of other.handlers.frame) fn(f); });
161
+ },
162
+ buffered: () => me.buffered, close, on(ev, fn) { me.handlers[ev].push(fn); },
163
+ });
164
+ return [end(a, b), end(b, a)];
165
+ }
166
+ const fakeRtc = {
167
+ async peer() {
168
+ let mine = null;
169
+ const open = async () => { if (net.blocked || !mine) throw new Error('ICE failed: no path between these networks (blocked in this test)'); return mine; };
170
+ return {
171
+ async offer() { const k = ++net.n, p = pairOf(); net.pairs.set(k, p); mine = p[0]; return `fake ${k}`; },
172
+ async answer(sdp) { mine = net.pairs.get(Number(sdp.split(' ')[1]))?.[1] ?? null; return 'fake answer'; },
173
+ async accept() {}, open, close() {},
174
+ };
175
+ },
176
+ };
177
+
178
+ const HOST = 'relay.test', now = Date.parse('2026-11-19T12:00:00Z') / 1000;
179
+ const dir = mkdtempSync(join(tmpdir(), 'sigelo-relay-lane-'));
180
+ const relay = await startRelay({ host: HOST, db: join(dir, 'relay.db'), tcpPort: 0, httpPort: 0, loginRate: 100000, verifyBudget: 1e9, clock: () => now, diskUsed: () => 0.1,
181
+ log: () => {}, policy: (ctx) => relayPolicy(ctx, { pow: { bits: 4, loadBits: 8, loadPerHour: 1000, cost: { m: 8, t: 1, p: 1 } } }) });
182
+ const endpoints = { [HOST]: { mqtt: `mqtt://127.0.0.1:${relay.ports.tcp}`, http: `http://127.0.0.1:${relay.ports.http}` } };
183
+ const seed = (l) => new Uint8Array(createHash('sha256').update(`sigelo-relay-lane-test/0 ${l}`).digest());
184
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
185
+ const until = async (f, ms = 60000) => { const t = Date.now() + ms; while (Date.now() < t) { if (await f()) return true; await sleep(100); } return false; };
186
+ function agentOf(label, onEvent) {
187
+ const k = keygen({ seed: seed(label), recovery: 'sha256:' + '0'.repeat(64), created: '2026-10-01T00:00:00Z', nonce: seed(`${label} nonce`).slice(0, 16) });
188
+ const identity = join(dir, `${label}.local.json`);
189
+ const bundle = { v: 'sigelo/0', typ: 'bundle', genesis: k.genesis, rotations: [], bindings: [], attestations: [], issuers: [] };
190
+ return { did: k.did, identity, c: new Carrier({ identity: () => ({ secret: k.secret, bundle }), ...pathsFor(identity), relay: HOST, endpoints, clock: () => now, keep: true, backoff: [100, 400], retentionDays: 7, onEvent }) };
191
+ }
192
+ let A = null, B = null;
193
+ const aEv = [], bEv = [];
194
+ const alice = agentOf('alice', (e) => { if (e.type === 'transfer') A?.kick(); });
195
+ const bob = agentOf('bob', (e) => { if (e.type === 'transfer') B?.kick(); });
196
+ const engineOf = (x, ev, o = {}) => new X.Engine({ carrier: x.c, identity: x.identity, rtc: async () => fakeRtc, stun: [], tor: null, retryMs: 300, fallbackMs: 1000, onEvent: (e) => ev.push(e), ...o });
197
+ try {
198
+ const inv = await alice.c.invite({ name: 'bob' });
199
+ await bob.c.accept(inv.code, { name: 'alice', wait: 0.3 });
200
+ await alice.c.inbox(); await bob.c.inbox(); await alice.c.inbox();
201
+ alice.c.setTier('bob', 'own'); bob.c.setTier('alice', 'own');
202
+ await alice.c.start(); await bob.c.start();
203
+ A = engineOf(alice, aEv); B = engineOf(bob, bEv);
204
+ const aRec = (id) => X.list({ carrier: alice.c, identity: alice.identity }).out.find((r) => r.id === id);
205
+ const bRec = (id) => X.list({ carrier: bob.c, identity: bob.identity }).in.find((r) => r.id === id);
206
+ const bFiles = [];
207
+ const bFile = async (sum) => { bFiles.push(...(await bob.c.inbox({ wait: 0.3 })).messages.filter((m) => m.type === 'file')); return bFiles.find((m) => m.sha256 === sum); };
208
+
209
+ // 1. The direct path blocked (two phones, no path, no Tor): the 1 MB APK lands over the relay lane.
210
+ net.blocked = true;
211
+ const apk = seeded('apk', 1_000_000 + 3); writeFileSync(join(dir, 'sigelo.apk'), apk);
212
+ const r1 = await X.send({ carrier: alice.c, identity: alice.identity, to: 'bob', path: join(dir, 'sigelo.apk') });
213
+ ok(await until(() => aRec(r1.id)?.state === 'done', 60000), 'blocked: the sender\'s record done', JSON.stringify(aRec(r1.id)));
214
+ ok(aRec(r1.id).path_used === 'relay' && aEv.some((e) => e.what === 'done' && e.id === r1.id && e.via === 'relay'), 'the sender\'s record and event name the lane: via relay');
215
+ let item = null;
216
+ ok(await until(async () => (item = await bFile(sha(apk))) !== undefined, 60000), 'the receiver has the file, over sigelo-file/0');
217
+ ok(item?.label === FILE_LABEL && !item.transfer && sha(readFileSync(item.path)) === sha(apk), 'whole, its own inbox item (no transfer id: the relay lane)');
218
+ ok(await until(() => bRec(r1.id)?.state === 'relayed'), 'the receiver\'s transfer record: relayed, not active', JSON.stringify(bRec(r1.id)));
219
+ B.superseded(item);
220
+ ok(bRec(r1.id).state === 'done' && bRec(r1.id).path_used === 'relay' && bRec(r1.id).saved === item.path && !B.live(), 'and done by the file that came (a page does it as the item arrives): no ghost, nothing live');
221
+
222
+ // 2. Direct, then the channel drops midway and nothing comes back within the window: over the relay lane too.
223
+ net.blocked = false; net.dropAfter = 20;
224
+ await B.close(); B = engineOf(bob, bEv, { retryMs: 1e9 }); // the receiver does not come back (a lock, the app gone)
225
+ const film = seeded('film', 3 * CHUNK + 9); writeFileSync(join(dir, 'film.bin'), film);
226
+ const r2 = await X.send({ carrier: alice.c, identity: alice.identity, to: 'bob', path: join(dir, 'film.bin') });
227
+ ok(await until(() => aEv.some((e) => e.what === 'interrupted' && e.id === r2.id), 60000), 'the channel dropped midway (after 20 frames)');
228
+ ok(await until(() => aRec(r2.id)?.state === 'done', 30000) && aRec(r2.id).path_used === 'relay', 'no reconnection within the window: done over the relay lane', JSON.stringify(aRec(r2.id)));
229
+ ok(await until(async () => (await bFile(sha(film))) !== undefined, 60000), 'the receiver has the file whole');
230
+ ok(await until(() => bRec(r2.id)?.state === 'relayed'), 'and its record is relayed, not "active: drop"', JSON.stringify(bRec(r2.id)));
231
+
232
+ // 3. 8 MiB + 1 byte, blocked: no fallback; the relay lane refuses it.
233
+ net.blocked = true; net.dropAfter = Infinity;
234
+ await B.close(); B = engineOf(bob, bEv);
235
+ const big = seeded('big', MAX_FILE + 1); writeFileSync(join(dir, 'big.bin'), big);
236
+ const r3 = await X.send({ carrier: alice.c, identity: alice.identity, to: 'bob', path: join(dir, 'big.bin') });
237
+ ok(await until(() => aRec(r3.id)?.state === 'failed', 60000) && aRec(r3.id).reason === 'no_path', 'blocked, 8 MiB + 1 byte: failed no_path', JSON.stringify(aRec(r3.id)));
238
+ await sleep(1500);
239
+ ok(aRec(r3.id).state === 'failed' && !aRec(r3.id).relay && !aRec(r3.id).path_used, 'not fallen back to the relay lane');
240
+ ok(await failure(() => A.relay(r3.id, { manual: true })) === 'file_too_large', 'Send over the relay is refused past 8 MiB (the bubble offers Retry)');
241
+ } finally {
242
+ await A?.close().catch(() => {}); await B?.close().catch(() => {});
243
+ await alice.c.stop().catch(() => {}); await bob.c.stop().catch(() => {});
244
+ await relay.close();
245
+ rmSync(dir, { recursive: true, force: true });
246
+ }
247
+ report();
248
+ console.log(`ALL PASS (${count})`);