sigelo-contact 0.1.14 → 0.1.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -10
- package/call.mjs +831 -0
- package/carrier.mjs +1013 -112
- package/control.mjs +81 -22
- package/device.mjs +1 -1
- package/enrol.mjs +214 -35
- package/gen-carrier.mjs +4 -4
- package/gen-device.mjs +2 -2
- package/gen-envelope.mjs +3 -3
- package/gen-invite.mjs +3 -3
- package/gen-short.mjs +3 -3
- package/group.mjs +28 -9
- package/invite.mjs +63 -13
- package/kdf.mjs +1 -1
- package/link.mjs +1 -1
- package/package.json +34 -7
- package/page.mjs +1018 -81
- package/photo.mjs +37 -0
- package/platform-node.mjs +110 -13
- package/prekeys.mjs +10 -2
- package/public.mjs +93 -0
- package/relays.mjs +1 -1
- package/restore.mjs +3 -3
- package/rtc-web.mjs +109 -0
- package/short.mjs +19 -3
- package/store.mjs +126 -10
- package/test-carrier.mjs +121 -18
- package/test-device.mjs +1 -1
- package/test-enrol.mjs +123 -8
- package/test-envelope.mjs +16 -3
- package/test-file.mjs +5 -5
- package/test-group.mjs +48 -7
- package/test-invite.mjs +15 -2
- package/test-link.mjs +6 -6
- package/test-platform.mjs +5 -5
- package/test-presence.mjs +5 -5
- package/test-push.mjs +136 -0
- package/test-relay-lane.mjs +323 -0
- package/test-short.mjs +35 -12
- package/test-tier.mjs +6 -6
- package/test-transfer-web.mjs +313 -0
- package/test-transfer.mjs +51 -11
- package/test-voice.mjs +161 -0
- package/test-ws.mjs +5 -5
- package/transfer-engine.mjs +858 -0
- package/transfer-node.mjs +254 -641
- package/transfer-web.mjs +80 -0
- package/transfer.mjs +25 -6
- package/voice-web.mjs +113 -0
- package/voice.mjs +70 -0
- package/words-lock.mjs +25 -10
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,323 @@
|
|
|
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, manifest } 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
|
+
// ================================================================ the accept rule, whatever the lane (2026-11-25)
|
|
136
|
+
// On the phone, with direct off, every file waited for a manual accept. The rule (transfer auto <contact> <MB>)
|
|
137
|
+
// says yes under the size; the direct switch only picks the lane: off, no Tor, the receiver ends no_path at once and the
|
|
138
|
+
// sender's relay lane carries it (up to 8 MiB).
|
|
139
|
+
{
|
|
140
|
+
const io = memIo(), car = fakeCarrier([OWN, PAL, NEW]), x = new E.Engine({ carrier: car, io, compared: (d) => d === PAL.did, timer: false });
|
|
141
|
+
car.takeTransfers = () => { const l = car.inbound ?? []; car.inbound = []; return l; };
|
|
142
|
+
const offer = async (from, size) => {
|
|
143
|
+
const n = Math.ceil(size / CHUNK), m = manifest({ name: 'f.bin', size, sha256: 'ab'.repeat(32), hashes: new Uint8Array(n * 32), now: NOW });
|
|
144
|
+
car.inbound = [{ from: from.did, name: from.name, content: m }];
|
|
145
|
+
await x.round();
|
|
146
|
+
return E.list({ carrier: car, io }).in.find((r) => r.id === m.id);
|
|
147
|
+
};
|
|
148
|
+
E.setDirect({ carrier: car, io, contact: 'own', on: false });
|
|
149
|
+
E.setAuto({ carrier: car, io, contact: 'own', mb: 100 });
|
|
150
|
+
const r1 = await offer(OWN, 3_000_000);
|
|
151
|
+
ok(r1.by === 'rule' && r1.state === 'failed' && r1.reason === 'no_path', `direct off, auto 100 MB, 3 MB: accepted by the rule, no question (${r1.state}${r1.reason ? `: ${r1.reason}` : ''})`);
|
|
152
|
+
ok(car.sent.some((m) => m.content.typ === 'end' && m.content.id === r1.id && m.content.reason === 'no_path') && !car.sent.some((m) => m.content.typ === 'offer' && m.content.id === r1.id),
|
|
153
|
+
'no direct and no Tor here: no_path to the sender at once (its relay lane takes it), no offer with addresses');
|
|
154
|
+
const r12 = await offer(OWN, 12_000_000);
|
|
155
|
+
ok(r12.state === 'asked' && !r12.by, `direct off, no Tor, 12 MB (over the relay lane's 8 MiB): asked, not accepted to fail no_path unseen (${r12.state})`);
|
|
156
|
+
io.tor = { caps: async () => ({ serve: false, connect: false }), close() {} };
|
|
157
|
+
const r13 = await offer(OWN, 13_000_000);
|
|
158
|
+
ok(r13.by === 'rule', `direct off, Tor on here, 13 MB: accepted by the rule (Tor may carry it) (${r13.state})`);
|
|
159
|
+
io.tor = null;
|
|
160
|
+
const r2 = await offer(OWN, 101_000_000);
|
|
161
|
+
ok(r2.state === 'asked' && !r2.by, 'the size cap kept: 101 MB over 100 MB is asked');
|
|
162
|
+
E.setAuto({ carrier: car, io, contact: 'own', mb: 0 });
|
|
163
|
+
ok((await offer(OWN, 10)).state === 'asked', 'auto 0 for the contact: always asked, direct off or not');
|
|
164
|
+
E.setAuto({ carrier: car, io, contact: 'own', mb: null });
|
|
165
|
+
const r3 = await offer(PAL, 1000);
|
|
166
|
+
ok(r3.by === 'rule' && E.list({ carrier: car, io }).direct[PAL.did] === undefined, 'a compared friend, direct never asked: accepted by the rule, the switch left unset (no address shown)');
|
|
167
|
+
E.setAuto({ carrier: car, io, contact: 'new', mb: 100 });
|
|
168
|
+
ok((await offer(NEW, 10)).state === 'asked', 'words not compared: asked, whatever its size');
|
|
169
|
+
// Direct on: the rule's yes is followed by an offer (the direct lane), as before.
|
|
170
|
+
E.setDirect({ carrier: car, io, contact: 'own', on: true });
|
|
171
|
+
const rtc = { peer: async () => ({ offer: async () => 'v=0 fake', close() {} }) };
|
|
172
|
+
const y = new E.Engine({ carrier: car, io, rtc: async () => rtc, stun: [], timer: false });
|
|
173
|
+
car.inbound = [{ from: OWN.did, name: 'own', content: manifest({ name: 'g.bin', size: 10, sha256: 'cd'.repeat(32), hashes: new Uint8Array(32), now: NOW }) }];
|
|
174
|
+
await y.round();
|
|
175
|
+
const r4 = E.list({ carrier: car, io }).in.find((r) => r.name === 'g.bin');
|
|
176
|
+
ok(r4.by === 'rule' && r4.state === 'offering' && car.sent.some((m) => m.content.typ === 'offer' && m.content.id === r4.id), `direct on: the rule's yes, then an offer (${r4.state})`);
|
|
177
|
+
// The rule's yeses add up: the disk must hold every file still coming, and at most 8 a contact (WAIT_CONTACT) come
|
|
178
|
+
// unasked at once; past either, asked (a sender sending more than its 8, or many large ones, cannot fill the disk).
|
|
179
|
+
const offerY = async (name, size) => {
|
|
180
|
+
const n = Math.ceil(size / CHUNK), m = manifest({ name, size, sha256: createHash('sha256').update(name).digest('hex'), hashes: new Uint8Array(n * 32), now: NOW });
|
|
181
|
+
car.inbound = [{ from: OWN.did, name: 'own', content: m }];
|
|
182
|
+
await y.round();
|
|
183
|
+
return E.list({ carrier: car, io }).in.find((r) => r.id === m.id);
|
|
184
|
+
};
|
|
185
|
+
const freeWas = io.free;
|
|
186
|
+
io.free = () => E.FREE_MARGIN + 12_000_000;
|
|
187
|
+
const d1 = await offerY('d1.bin', 5_000_000), d2 = await offerY('d2.bin', 5_000_000), d3 = await offerY('d3.bin', 5_000_000);
|
|
188
|
+
ok(d1.by === 'rule' && d2.by === 'rule' && d3.state === 'asked' && !d3.by,
|
|
189
|
+
`12 MB free, three 5 MB files: two by the rule, the third asked (10 MB promised + 5 > 12) (${[d1, d2, d3].map((r) => r.by ?? r.state)})`);
|
|
190
|
+
io.free = freeWas;
|
|
191
|
+
const many = [];
|
|
192
|
+
for (let i = 0; i < 6; i++) many.push(await offerY(`m${i}.bin`, 10));
|
|
193
|
+
const nRule = [r4, d1, d2, ...many].filter((r) => E.list({ carrier: car, io }).in.find((z) => z.id === r.id)?.by === 'rule').length;
|
|
194
|
+
ok(nRule === 8 && many.at(-1).state === 'asked' && many.slice(0, -1).every((r) => r.by === 'rule'),
|
|
195
|
+
`3 files from one contact already coming, 6 more: 5 by the rule (8 at once), the 6th asked (${many.map((r) => r.by ?? r.state)})`);
|
|
196
|
+
for (const r of [r4, d1, d2, ...many]) y.drop(r.id, 'cancelled');
|
|
197
|
+
await x.close(); await y.close();
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// ================================================================ two agents on a loopback relay, a fake direct path
|
|
201
|
+
const RELAY_DIR = process.env.SIGELO_RELAY_DIR ?? join(HERE, '..', '..', 'relay');
|
|
202
|
+
if (!existsSync(join(RELAY_DIR, 'server.mjs'))) {
|
|
203
|
+
report();
|
|
204
|
+
console.log(`ALL PASS (${count}): the unit part; SKIP the flows (no relay checkout)`);
|
|
205
|
+
process.exit(0);
|
|
206
|
+
}
|
|
207
|
+
const { startRelay } = await import(pathToFileURL(join(RELAY_DIR, 'server.mjs')).href);
|
|
208
|
+
const { relayPolicy } = await import(pathToFileURL(join(RELAY_DIR, 'allowance.mjs')).href);
|
|
209
|
+
const { Carrier, pathsFor } = await import('./carrier.mjs');
|
|
210
|
+
const X = await import('./transfer-node.mjs');
|
|
211
|
+
setTimeout(() => { console.log(`FAIL the run did not finish in 600 s (${count} checks so far)`); process.exit(1); }, 600_000).unref();
|
|
212
|
+
|
|
213
|
+
/** A fake direct path: two ends of a channel in this process; blocked: ICE never connects; dropAfter: frames, then it goes. */
|
|
214
|
+
const net = { blocked: false, dropAfter: Infinity, pairs: new Map(), n: 0 };
|
|
215
|
+
function pairOf() {
|
|
216
|
+
const mk = () => ({ handlers: { frame: [], low: [], close: [] }, buffered: 0, closed: false });
|
|
217
|
+
const a = mk(), b = mk();
|
|
218
|
+
let shut = false, sent = 0;
|
|
219
|
+
const close = () => { if (shut) return; shut = true; a.closed = b.closed = true; setImmediate(() => { for (const fn of [...a.handlers.close, ...b.handlers.close]) fn(); }); };
|
|
220
|
+
const end = (me, other) => ({
|
|
221
|
+
send(f) {
|
|
222
|
+
if (me.closed) throw new Error('closed');
|
|
223
|
+
if (++sent > net.dropAfter) { close(); return; }
|
|
224
|
+
me.buffered += f.length;
|
|
225
|
+
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); });
|
|
226
|
+
},
|
|
227
|
+
buffered: () => me.buffered, close, on(ev, fn) { me.handlers[ev].push(fn); },
|
|
228
|
+
});
|
|
229
|
+
return [end(a, b), end(b, a)];
|
|
230
|
+
}
|
|
231
|
+
const fakeRtc = {
|
|
232
|
+
async peer() {
|
|
233
|
+
let mine = null;
|
|
234
|
+
const open = async () => { if (net.blocked || !mine) throw new Error('ICE failed: no path between these networks (blocked in this test)'); return mine; };
|
|
235
|
+
return {
|
|
236
|
+
async offer() { const k = ++net.n, p = pairOf(); net.pairs.set(k, p); mine = p[0]; return `fake ${k}`; },
|
|
237
|
+
async answer(sdp) { mine = net.pairs.get(Number(sdp.split(' ')[1]))?.[1] ?? null; return 'fake answer'; },
|
|
238
|
+
async accept() {}, open, close() {},
|
|
239
|
+
};
|
|
240
|
+
},
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
const HOST = 'relay.test', now = Date.parse('2026-11-19T12:00:00Z') / 1000;
|
|
244
|
+
const dir = mkdtempSync(join(tmpdir(), 'sigelo-relay-lane-'));
|
|
245
|
+
const relay = await startRelay({ host: HOST, db: join(dir, 'relay.db'), tcpPort: 0, httpPort: 0, loginRate: 100000, verifyBudget: 1e9, clock: () => now, diskUsed: () => 0.1,
|
|
246
|
+
log: () => {}, policy: (ctx) => relayPolicy(ctx, { pow: { bits: 4, loadBits: 8, loadPerHour: 1000, cost: { m: 8, t: 1, p: 1 } } }) });
|
|
247
|
+
const endpoints = { [HOST]: { mqtt: `mqtt://127.0.0.1:${relay.ports.tcp}`, http: `http://127.0.0.1:${relay.ports.http}` } };
|
|
248
|
+
const seed = (l) => new Uint8Array(createHash('sha256').update(`sigelo-relay-lane-test/0 ${l}`).digest());
|
|
249
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
250
|
+
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; };
|
|
251
|
+
function agentOf(label, onEvent) {
|
|
252
|
+
const k = keygen({ seed: seed(label), recovery: 'sha256:' + '0'.repeat(64), created: '2026-10-01T00:00:00Z', nonce: seed(`${label} nonce`).slice(0, 16) });
|
|
253
|
+
const identity = join(dir, `${label}.local.json`);
|
|
254
|
+
const bundle = { v: 'sigelo/0', typ: 'bundle', genesis: k.genesis, rotations: [], bindings: [], attestations: [], issuers: [] };
|
|
255
|
+
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 }) };
|
|
256
|
+
}
|
|
257
|
+
let A = null, B = null;
|
|
258
|
+
const aEv = [], bEv = [];
|
|
259
|
+
const alice = agentOf('alice', (e) => { if (e.type === 'transfer') A?.kick(); });
|
|
260
|
+
const bob = agentOf('bob', (e) => { if (e.type === 'transfer') B?.kick(); });
|
|
261
|
+
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 });
|
|
262
|
+
try {
|
|
263
|
+
const inv = await alice.c.invite({ name: 'bob' });
|
|
264
|
+
await bob.c.accept(inv.code, { name: 'alice', wait: 0.3 });
|
|
265
|
+
await alice.c.inbox(); await bob.c.inbox(); await alice.c.inbox();
|
|
266
|
+
alice.c.setTier('bob', 'own'); bob.c.setTier('alice', 'own');
|
|
267
|
+
await alice.c.start(); await bob.c.start();
|
|
268
|
+
A = engineOf(alice, aEv); B = engineOf(bob, bEv);
|
|
269
|
+
const aRec = (id) => X.list({ carrier: alice.c, identity: alice.identity }).out.find((r) => r.id === id);
|
|
270
|
+
const bRec = (id) => X.list({ carrier: bob.c, identity: bob.identity }).in.find((r) => r.id === id);
|
|
271
|
+
const bFiles = [];
|
|
272
|
+
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); };
|
|
273
|
+
|
|
274
|
+
// 1. The direct path blocked (two phones, no path, no Tor): the 1 MB APK lands over the relay lane.
|
|
275
|
+
net.blocked = true;
|
|
276
|
+
const apk = seeded('apk', 1_000_000 + 3); writeFileSync(join(dir, 'sigelo.apk'), apk);
|
|
277
|
+
const r1 = await X.send({ carrier: alice.c, identity: alice.identity, to: 'bob', path: join(dir, 'sigelo.apk') });
|
|
278
|
+
ok(await until(() => aRec(r1.id)?.state === 'done', 60000), 'blocked: the sender\'s record done', JSON.stringify(aRec(r1.id)));
|
|
279
|
+
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');
|
|
280
|
+
let item = null;
|
|
281
|
+
ok(await until(async () => (item = await bFile(sha(apk))) !== undefined, 60000), 'the receiver has the file, over sigelo-file/0');
|
|
282
|
+
ok(item?.label === FILE_LABEL && !item.transfer && sha(readFileSync(item.path)) === sha(apk), 'whole, its own inbox item (no transfer id: the relay lane)');
|
|
283
|
+
ok(await until(() => bRec(r1.id)?.state === 'relayed'), 'the receiver\'s transfer record: relayed, not active', JSON.stringify(bRec(r1.id)));
|
|
284
|
+
B.superseded(item);
|
|
285
|
+
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');
|
|
286
|
+
|
|
287
|
+
// 2. Direct, then the channel drops midway and nothing comes back within the window: over the relay lane too.
|
|
288
|
+
net.blocked = false; net.dropAfter = 20;
|
|
289
|
+
await B.close(); B = engineOf(bob, bEv, { retryMs: 1e9 }); // the receiver does not come back (a lock, the app gone)
|
|
290
|
+
const film = seeded('film', 3 * CHUNK + 9); writeFileSync(join(dir, 'film.bin'), film);
|
|
291
|
+
const r2 = await X.send({ carrier: alice.c, identity: alice.identity, to: 'bob', path: join(dir, 'film.bin') });
|
|
292
|
+
ok(await until(() => aEv.some((e) => e.what === 'interrupted' && e.id === r2.id), 60000), 'the channel dropped midway (after 20 frames)');
|
|
293
|
+
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)));
|
|
294
|
+
ok(await until(async () => (await bFile(sha(film))) !== undefined, 60000), 'the receiver has the file whole');
|
|
295
|
+
ok(await until(() => bRec(r2.id)?.state === 'relayed'), 'and its record is relayed, not "active: drop"', JSON.stringify(bRec(r2.id)));
|
|
296
|
+
|
|
297
|
+
// 3. 8 MiB + 1 byte, blocked: no fallback; the relay lane refuses it.
|
|
298
|
+
net.blocked = true; net.dropAfter = Infinity;
|
|
299
|
+
await B.close(); B = engineOf(bob, bEv);
|
|
300
|
+
const big = seeded('big', MAX_FILE + 1); writeFileSync(join(dir, 'big.bin'), big);
|
|
301
|
+
const r3 = await X.send({ carrier: alice.c, identity: alice.identity, to: 'bob', path: join(dir, 'big.bin') });
|
|
302
|
+
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)));
|
|
303
|
+
await sleep(1500);
|
|
304
|
+
ok(aRec(r3.id).state === 'failed' && !aRec(r3.id).relay && !aRec(r3.id).path_used, 'not fallen back to the relay lane');
|
|
305
|
+
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)');
|
|
306
|
+
|
|
307
|
+
// 4. Direct off at the receiver (2026-11-25), its rule "transfer auto alice 100": no question, over the relay lane.
|
|
308
|
+
net.blocked = false;
|
|
309
|
+
X.setDirect({ carrier: bob.c, identity: bob.identity, contact: 'alice', on: false });
|
|
310
|
+
X.setAuto({ carrier: bob.c, identity: bob.identity, contact: 'alice', mb: 100 });
|
|
311
|
+
const pdf = seeded('pdf', 2 * CHUNK + 5); writeFileSync(join(dir, 'notes.pdf'), pdf);
|
|
312
|
+
const r4 = await X.send({ carrier: alice.c, identity: alice.identity, to: 'bob', path: join(dir, 'notes.pdf') });
|
|
313
|
+
ok(await until(() => aRec(r4.id)?.state === 'done', 60000) && aRec(r4.id).path_used === 'relay', 'direct off, auto 100 MB: done over the relay lane', JSON.stringify(aRec(r4.id)));
|
|
314
|
+
ok(await until(async () => (await bFile(sha(pdf))) !== undefined, 60000), 'the receiver has it whole, no accept given');
|
|
315
|
+
ok(bRec(r4.id)?.by === 'rule' && !bEv.some((e) => e.what === 'asked' && e.id === r4.id), 'accepted by the rule: never asked', JSON.stringify(bRec(r4.id)));
|
|
316
|
+
} finally {
|
|
317
|
+
await A?.close().catch(() => {}); await B?.close().catch(() => {});
|
|
318
|
+
await alice.c.stop().catch(() => {}); await bob.c.stop().catch(() => {});
|
|
319
|
+
await relay.close();
|
|
320
|
+
rmSync(dir, { recursive: true, force: true });
|
|
321
|
+
}
|
|
322
|
+
report();
|
|
323
|
+
console.log(`ALL PASS (${count})`);
|
package/test-short.mjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
// SPDX-License-Identifier: MIT
|
|
2
2
|
// Short invite codes (short.mjs, contract sigelo-park/0): fixtures/short-code-v0.json against
|
|
3
3
|
// short.mjs, gen-short.mjs --check, the word list's hash; then, with the relay checkout beside
|
|
4
|
-
// contact/ (SIGELO_RELAY_DIR, else
|
|
4
|
+
// apps/contact/ (SIGELO_RELAY_DIR, else ../../relay), the whole flow on a loopback relay: invite → short
|
|
5
5
|
// code → accept by the short code → paired → the same four words on both sides; one use; a wrong
|
|
6
6
|
// code; an expired one. Then a company relay (closed: relay/closed.mjs) beside it: invite --relay
|
|
7
7
|
// parks the short code there; an accept at the default relay is told to name it; accept --relay
|
|
8
8
|
// pairs, the contact keeps that relay and a message goes over it with the default relay gone; a
|
|
9
9
|
// stranger's accept and invite there are refused `closed`.
|
|
10
|
-
// node contact/test-short.mjs → ALL PASS (n)
|
|
10
|
+
// node apps/contact/test-short.mjs → ALL PASS (n)
|
|
11
11
|
import { spawnSync } from 'node:child_process';
|
|
12
12
|
import { createHash } from 'node:crypto';
|
|
13
13
|
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
|
@@ -17,7 +17,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
|
17
17
|
import { attest, keygen } from 'sigelo';
|
|
18
18
|
import { BIP39_SHA256, WORDS } from './bip39-english.mjs';
|
|
19
19
|
import { makeInvite } from './invite.mjs';
|
|
20
|
-
import { ALPHABET, GIFT_V, SHORT_TTL, TAG_LABEL, codeHash, codeKind, didWords, fingerprint, formatGift, formatShort, giftHash, isShort, makeShort, normaliseGift, normaliseShort, relayTag, tagOf } from './short.mjs';
|
|
20
|
+
import { ALPHABET, GIFT_V, SHORT_TTL, SHORT_TTL_MAX, SHORT_TTL_MIN, TAG_LABEL, codeHash, codeKind, didWords, fingerprint, formatGift, formatShort, giftHash, isShort, makeShort, normaliseGift, normaliseShort, relayTag, tagOf } from './short.mjs';
|
|
21
21
|
import { RELEASE_DID, REGISTRY_CTX, REGISTRY_URL, checkRegistry, loadRegistry, readTable, remember, resolveTag } from './relays.mjs';
|
|
22
22
|
import { createServer } from 'node:http';
|
|
23
23
|
import { did as didOf, parse as parseJson } from 'sigelo';
|
|
@@ -64,7 +64,7 @@ const report = () => {
|
|
|
64
64
|
for (let i = 0; i < 1000; i++) seen.add(makeShort());
|
|
65
65
|
ok(seen.size === 1000 && [...seen].every((s) => /^[0-9A-HJKMNP-TV-Z]{8}$/.test(s)), 'makeShort: 1,000 codes from the CSPRNG, all 8 Crockford digits, no repeat');
|
|
66
66
|
ok(SHORT_TTL === 600, 'a short code lives 10 minutes');
|
|
67
|
-
// Relay tags
|
|
67
|
+
// Relay tags: the first 20 bits of SHA-256("sigelo-relay-tag/0" ‖ relay), 4 characters.
|
|
68
68
|
ok(TAG_LABEL === 'sigelo-relay-tag/0' && relayTag('corp.example.com') === 'FNK5'
|
|
69
69
|
&& createHash('sha256').update('sigelo-relay-tag/0corp.example.com').digest('hex').slice(0, 5) === '7d665', 'relay tag vector: corp.example.com → SHA-256 prefix 7d665 → FNK5');
|
|
70
70
|
for (const t of F.relay_tags) ok(relayTag(t.relay) === t.tag, `relay tag ${t.relay}: ${relayTag(t.relay)}, expected ${t.tag}`);
|
|
@@ -76,7 +76,7 @@ const report = () => {
|
|
|
76
76
|
ok(tagOf('K7F3Q9ZP') === null && checkOf(() => makeShort(undefined, 'ABC')) === 'short_code' && checkOf(() => makeShort(undefined, 'ABCU')) === 'short_code', 'an 8-character code has no tag; a tag is 4 characters of the alphabet');
|
|
77
77
|
ok([...Array(200)].every(() => /^[0-9A-HJKMNP-TV-Z]{12}$/.test(makeShort(undefined, relayTag('corp.test')))), 'makeShort with a tag: 12 Crockford digits');
|
|
78
78
|
ok(checkOf(() => normaliseGift('PRO-K7F3-Q9ZP-4WXN')) === 'gift_code', 'a gift code is 8 characters: a tagged shape is no gift code');
|
|
79
|
-
const pin = join(HERE, '..', 'release', 'release-identity.json');
|
|
79
|
+
const pin = join(HERE, '..', '..', 'release', 'release-identity.json');
|
|
80
80
|
if (existsSync(pin)) ok(didOf(parseJson(readFileSync(pin, 'utf8'))) === RELEASE_DID, `relays.mjs RELEASE_DID is release/release-identity.json's DID (${RELEASE_DID})`);
|
|
81
81
|
ok(REGISTRY_URL === 'https://sigelo.ai/relays.json' && REGISTRY_CTX === 'sigelo.ai/relays', 'the registry: https://sigelo.ai/relays.json, ctx sigelo.ai/relays');
|
|
82
82
|
}
|
|
@@ -196,10 +196,10 @@ const collide = (() => { const seen = new Map(); for (let i = 0; ; i++) { const
|
|
|
196
196
|
ok(normaliseGift(formatGift(g)) === g, 'a code from makeShort, shown as a gift code, reads back');
|
|
197
197
|
}
|
|
198
198
|
|
|
199
|
-
const RELAY_DIR = process.env.SIGELO_RELAY_DIR ?? join(HERE, '..', 'relay');
|
|
199
|
+
const RELAY_DIR = process.env.SIGELO_RELAY_DIR ?? join(HERE, '..', '..', 'relay');
|
|
200
200
|
if (!existsSync(join(RELAY_DIR, 'server.mjs'))) {
|
|
201
201
|
report();
|
|
202
|
-
console.log(`ALL PASS (${count}): the fixture part; SKIP the flow, no relay checkout beside contact/: set SIGELO_RELAY_DIR`);
|
|
202
|
+
console.log(`ALL PASS (${count}): the fixture part; SKIP the flow, no relay checkout beside apps/contact/: set SIGELO_RELAY_DIR`);
|
|
203
203
|
process.exit(0);
|
|
204
204
|
}
|
|
205
205
|
|
|
@@ -214,7 +214,7 @@ const dir = mkdtempSync(join(tmpdir(), 'sigelo-short-'));
|
|
|
214
214
|
let now = Date.parse('2026-10-14T12:00:00Z') / 1000;
|
|
215
215
|
const lines = [];
|
|
216
216
|
const relay = await startRelay({ host: HOST, db: join(dir, 'relay.db'), tcpPort: 0, httpPort: 0, loginRate: 100000, verifyBudget: 1e9, clock: () => now, diskUsed: () => 0.1,
|
|
217
|
-
log: (l) => lines.push(l), policy: (ctx) => relayPolicy(ctx, { pow: { bits:
|
|
217
|
+
log: (l) => lines.push(l), policy: (ctx) => relayPolicy(ctx, { pow: { bits: 4, loadBits: 8, loadPerHour: 1000, cost: { m: 8, t: 1, p: 1 } } }) });
|
|
218
218
|
const endpoints = { [HOST]: { mqtt: `mqtt://127.0.0.1:${relay.ports.tcp}`, http: `http://127.0.0.1:${relay.ports.http}` } };
|
|
219
219
|
const seed = (l) => new Uint8Array(createHash('sha256').update(`sigelo-short-test/0 ${l}`).digest());
|
|
220
220
|
function agent(label) {
|
|
@@ -270,7 +270,7 @@ try {
|
|
|
270
270
|
const nobody = formatShort(makeShort());
|
|
271
271
|
ok(await refused(() => cc.accept(nobody, { wait: 1 })) === 'park_unknown', 'a code nobody parked: park_unknown');
|
|
272
272
|
const pu = await failure(() => cc.accept(nobody.toLowerCase(), { wait: 1 }));
|
|
273
|
-
ok(pu.check === 'park_unknown' && pu.message.includes(`short code ${nobody}: no invite waits under it at ${HOST}`) && pu.message.includes('expired (a short code lives 10 minutes), was used already (once only), or is mistyped; ask the inviter for a new one')
|
|
273
|
+
ok(pu.check === 'park_unknown' && pu.message.includes(`short code ${nobody}: no invite waits under it at ${HOST}`) && pu.message.includes('expired (a short code lives 10 minutes unless its inviter chose up to an hour), was used already (once only), or is mistyped; ask the inviter for a new one')
|
|
274
274
|
&& pu.message.includes('another relay') && pu.http?.status === 404, `park_unknown: the code, the relay, the three reasons, the next step, another relay; the answer kept for SIGELO_DEBUG (${pu.message})`);
|
|
275
275
|
// A mistyped short code is refused before anything connects, as a short code.
|
|
276
276
|
const mt = await failure(() => cc.accept('K7F3-Q9Z', { wait: 1 }));
|
|
@@ -279,13 +279,36 @@ try {
|
|
|
279
279
|
const late = await ca.invite({ name: 'carol', short: true });
|
|
280
280
|
now += SHORT_TTL;
|
|
281
281
|
ok(await refused(() => cc.accept(late.short, { wait: 1 })) === 'park_unknown', 'a short code after its 10 minutes: park_unknown');
|
|
282
|
+
// invite --ttl (a slow agent fetches late): 60 s to an hour for a short code; the long code lives as long.
|
|
283
|
+
const lowTtl = await failure(() => ca.invite({ name: 'slow', short: true, ttl: SHORT_TTL_MIN - 1 })), highTtl = await failure(() => ca.invite({ name: 'slow', short: true, ttl: SHORT_TTL_MAX + 1 }));
|
|
284
|
+
ok(SHORT_TTL_MIN === 60 && SHORT_TTL_MAX === 3600 && lowTtl.check === 'ttl' && highTtl.check === 'ttl' && highTtl.message.includes('a short code lives 60 to 3600 seconds (default 600)'),
|
|
285
|
+
`invite --ttl 59 and 3601 with a short code: refused ttl, before anything is parked (${highTtl.message})`);
|
|
286
|
+
const hour = await ca.invite({ name: 'slow', short: true, ttl: 3600 });
|
|
287
|
+
ok(hour.short_exp === now + 3600 && hour.exp === now + 3600, `invite --ttl 3600: the short code and the long one for an hour (${JSON.stringify({ short_exp: hour.short_exp - now, exp: hour.exp - now })})`);
|
|
288
|
+
now += 3000;
|
|
289
|
+
ok(await cc.unpark(hour.short) === hour.code, 'the hour code, fetched 50 minutes later: the long code it stands for');
|
|
290
|
+
// An older relay keeps short codes 10 minutes at most: a longer --ttl is refused there, and said so.
|
|
291
|
+
{
|
|
292
|
+
const OLD = 'old.test', old = await startRelay({ host: OLD, db: join(dir, 'old.db'), tcpPort: 0, httpPort: 0, loginRate: 100000, verifyBudget: 1e9, clock: () => now, diskUsed: () => 0.1,
|
|
293
|
+
log: () => {}, park: { ttl: 600 }, policy: (ctx) => relayPolicy(ctx, { pow: { bits: 4, loadBits: 8, loadPerHour: 1000, cost: { m: 8, t: 1, p: 1 } } }) });
|
|
294
|
+
const eps = { ...endpoints, [OLD]: { mqtt: `mqtt://127.0.0.1:${old.ports.tcp}`, http: `http://127.0.0.1:${old.ports.http}` } };
|
|
295
|
+
const co = new Carrier({ identity: () => ({ secret: alice.secret, bundle: alice.bundle }), ...pathsFor(join(dir, 'alice-old.local.json')), relay: OLD, shortRelay: OLD, registry: false, endpoints: eps,
|
|
296
|
+
clock: () => now, keep: true, backoff: [100, 400], retentionDays: 7 });
|
|
297
|
+
const oldRefusal = await failure(() => co.invite({ name: 'slow', short: true, ttl: 1800 }));
|
|
298
|
+
const oldDefault = await co.invite({ name: 'slow', short: true });
|
|
299
|
+
ok(oldRefusal.check === 'park' && oldRefusal.message.includes('this relay may keep short codes 10 minutes at most (an older relay): --ttl 600 or less, or the long code (invite --long --ttl 1800)') && oldDefault.short_exp === now + 600,
|
|
300
|
+
`an older relay (PARK_TTL 600): --ttl 1800 refused, saying so; the default 10 minutes parks (${oldRefusal.message})`);
|
|
301
|
+
await co.stop();
|
|
302
|
+
await old.close();
|
|
303
|
+
}
|
|
282
304
|
// An inviter whose clock runs a minute ahead of the relay's still parks (relay/park.mjs PARK_SKEW).
|
|
283
305
|
const ahead = new Carrier({ identity: () => ({ secret: alice.secret, bundle: alice.bundle }), ...pathsFor(join(dir, 'alice.local.json')), relay: HOST, shortRelay: HOST, registry: false, endpoints,
|
|
284
306
|
clock: () => now + 60, keep: true, backoff: [100, 400], retentionDays: 7 });
|
|
285
307
|
let fastInv = {}, fast = 'accepted';
|
|
286
|
-
|
|
308
|
+
// With --ttl at its most (an hour), the relay keeps it its PARK_TTL by its own clock.
|
|
309
|
+
try { fastInv = await ahead.invite({ name: 'carol', short: true, ttl: SHORT_TTL_MAX }); } catch (e) { fast = e.check ?? `exception ${e.message}`; }
|
|
287
310
|
ok(fast === 'accepted', `an inviter's clock a minute ahead of the relay's: the short code parks (${fast})`);
|
|
288
|
-
ok(fastInv.short_exp === now +
|
|
311
|
+
ok(fastInv.short_exp === now + SHORT_TTL_MAX, `short_exp is the relay's exp (${now + SHORT_TTL_MAX}), not the fast clock's (${now + 60 + SHORT_TTL_MAX}): ${fastInv.short_exp}`);
|
|
289
312
|
await ahead.stop();
|
|
290
313
|
// An inviter's clock an hour ahead: the relay refuses the parking, and the refusal says the clock.
|
|
291
314
|
const far = new Carrier({ identity: () => ({ secret: alice.secret, bundle: alice.bundle }), ...pathsFor(join(dir, 'alice.local.json')), relay: HOST, shortRelay: HOST, registry: false, endpoints,
|
|
@@ -382,7 +405,7 @@ try {
|
|
|
382
405
|
now += 600;
|
|
383
406
|
const CORP = 'corp.test', boss = agent('boss');
|
|
384
407
|
const corp = await startRelay({ host: CORP, db: join(dir, 'corp.db'), tcpPort: 0, httpPort: 0, loginRate: 100000, verifyBudget: 1e9, clock: () => now, diskUsed: () => 0.1,
|
|
385
|
-
log: () => {}, closed: [boss.did], policy: (ctx) => relayPolicy(ctx, { pow: { bits:
|
|
408
|
+
log: () => {}, closed: [boss.did], policy: (ctx) => relayPolicy(ctx, { pow: { bits: 4, loadBits: 8, loadPerHour: 1000, cost: { m: 8, t: 1, p: 1 } } }) });
|
|
386
409
|
try {
|
|
387
410
|
endpoints[CORP] = { mqtt: `mqtt://127.0.0.1:${corp.ports.tcp}`, http: `http://127.0.0.1:${corp.ports.http}` };
|
|
388
411
|
const staff = (label) => {
|