180 lines
8.2 KiB
JavaScript
180 lines
8.2 KiB
JavaScript
// node ide/ui/js/remote/channel.test.mjs (RELAY_URL=ws://localhost:8090/ws adds the integration test against the relay)
|
|
import { Channel, b64uEncode, relayTransport, streamTransport } from './channel.js';
|
|
import assert from 'node:assert/strict';
|
|
|
|
let failed = 0;
|
|
const tests = [];
|
|
const test = (name, fn) => tests.push([name, fn]);
|
|
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
const until = async (fn, ms = 3000) => { const t = Date.now(); while (!fn()) { if (Date.now() - t > ms) throw new Error('timeout'); await wait(5); } };
|
|
|
|
// in-memory transport pair; `tap(from, bytes)` may alter / duplicate frames
|
|
function memPair(tap = (_who, b) => [b]) {
|
|
const mk = (who) => {
|
|
const h = {};
|
|
const t = { on: (n, f) => { (h[n] ||= []).push(f); return t; }, emit: (n, ...a) => (h[n] || []).forEach((f) => f(...a)), peers: () => [], close() {}, start() { queueMicrotask(() => t.emit('open')); },
|
|
send(bytes) { for (const b of tap(who, bytes)) queueMicrotask(() => other(who).emit('frame', b, 0)); } };
|
|
return t;
|
|
};
|
|
const a = mk('a'), b = mk('b');
|
|
const other = (w) => (w === 'a' ? b : a);
|
|
return [a, b];
|
|
}
|
|
async function pair(tap, keyB) {
|
|
const key = b64uEncode(crypto.getRandomValues(new Uint8Array(32)));
|
|
const [ta, tb] = memPair(tap);
|
|
const host = await Channel.open({ role: 'host', key, transport: ta });
|
|
const remote = await Channel.open({ role: 'remote', key: keyB ?? key, transport: tb });
|
|
const got = { host: [], remote: [], hostErr: [], remoteErr: [] };
|
|
host.on('message', (m) => got.host.push(m)).on('error', (e) => got.hostErr.push(e));
|
|
remote.on('message', (m) => got.remote.push(m)).on('error', (e) => got.remoteErr.push(e));
|
|
return { host, remote, got, tb };
|
|
}
|
|
|
|
test('roundtrip both ways, unicode', async () => {
|
|
const { host, remote, got } = await pair();
|
|
await host.send({ t: 'welcome', s: 'héllo ✓ 日本' });
|
|
await remote.send({ t: 'hello', n: 1 });
|
|
await until(() => got.host.length && got.remote.length);
|
|
assert.deepEqual(got.remote[0], { t: 'welcome', s: 'héllo ✓ 日本' });
|
|
assert.deepEqual(got.host[0], { t: 'hello', n: 1 });
|
|
});
|
|
|
|
test('replay is rejected', async () => {
|
|
const { host, got } = await pair((who, b) => [b, b]); // every frame delivered twice
|
|
await host.send({ n: 1 });
|
|
await host.send({ n: 2 });
|
|
await wait(100);
|
|
assert.deepEqual(got.remote.map((m) => m.n), [1, 2]);
|
|
});
|
|
|
|
test('an old frame replayed later is rejected', async () => {
|
|
const seen = [];
|
|
const { host, got, tb } = await pair((who, b) => { if (who === 'a') seen.push(b); return [b]; });
|
|
await host.send({ n: 1 });
|
|
await host.send({ n: 2 });
|
|
await until(() => got.remote.length === 2);
|
|
tb.emit('frame', seen[0], 0); // an attacker re-injects frame 1
|
|
tb.emit('frame', seen[1], 0);
|
|
await wait(100);
|
|
assert.deepEqual(got.remote.map((m) => m.n), [1, 2]);
|
|
});
|
|
|
|
test('tampered frame is dropped', async () => {
|
|
let n = 0;
|
|
const { host, got } = await pair((who, b) => { if (who === 'a' && n++ === 0) { b = b.slice(); b[b.length - 3] ^= 1; } return [b]; });
|
|
await host.send({ n: 1 });
|
|
await host.send({ n: 2 });
|
|
await wait(100);
|
|
assert.deepEqual(got.remote.map((m) => m.n), [2]);
|
|
assert.equal(got.remoteErr[0].code, 'decrypt');
|
|
});
|
|
|
|
test('tampered header (AAD) is dropped', async () => {
|
|
const { host, got } = await pair((who, b) => { b = b.slice(); b[1] ^= 1; return [b]; });
|
|
await host.send({ n: 1 });
|
|
await wait(100);
|
|
assert.equal(got.remote.length, 0);
|
|
});
|
|
|
|
test('chunking 200 KB', async () => {
|
|
const frames = [];
|
|
const { host, got } = await pair((who, b) => { frames.push(b.length); return [b]; });
|
|
const big = { t: 'snap', data: 'x'.repeat(200 * 1024) + '日本'.repeat(1000) };
|
|
await host.send(big);
|
|
await until(() => got.remote.length);
|
|
assert.deepEqual(got.remote[0], big);
|
|
assert.ok(frames.length >= 5, 'cut in parts: ' + frames.length);
|
|
assert.ok(Math.max(...frames) <= 48 * 1024 + 30);
|
|
});
|
|
|
|
test('wrong key is rejected', async () => {
|
|
const { host, got } = await pair(undefined, b64uEncode(crypto.getRandomValues(new Uint8Array(32))));
|
|
await host.send({ n: 1 });
|
|
await wait(100);
|
|
assert.equal(got.remote.length, 0);
|
|
assert.equal(got.remoteErr[0].code, 'decrypt');
|
|
});
|
|
|
|
test('stream: fragmented bytes are re-assembled', async () => {
|
|
const key = Channel.newPairing().key;
|
|
let toRemote, toHost;
|
|
const wire = [];
|
|
const th = streamTransport({ send: (b) => wire.push(['h', b]), onData: (cb) => { toHost = cb; } });
|
|
const tr = streamTransport({ send: (b) => wire.push(['r', b]), onData: (cb) => { toRemote = cb; } });
|
|
const host = await Channel.open({ role: 'host', key, transport: th });
|
|
const remote = await Channel.open({ role: 'remote', key, transport: tr });
|
|
const got = [];
|
|
remote.on('message', (m) => got.push(m));
|
|
const opened = new Promise((r) => host.on('open', r));
|
|
await opened;
|
|
await host.send({ a: 1 });
|
|
await host.send({ big: 'y'.repeat(100000) });
|
|
await host.send({ a: 3 });
|
|
const bytes = Uint8Array.from(wire.filter(([w]) => w === 'h').flatMap(([, b]) => [...b]));
|
|
// feed in odd fragments (1, 2, 3, 5, 7... bytes then big slices)
|
|
let i = 0, step = 1;
|
|
while (i < bytes.length) { toRemote(bytes.slice(i, i + step)); i += step; step = step < 5000 ? step * 2 + 1 : 70001; }
|
|
await until(() => got.length === 3);
|
|
assert.equal(got[0].a, 1);
|
|
assert.equal(got[1].big.length, 100000);
|
|
assert.equal(got[2].a, 3);
|
|
void toHost;
|
|
});
|
|
|
|
test('pairing helpers', () => {
|
|
const p = Channel.newPairing();
|
|
assert.equal(p.room.length, 32);
|
|
assert.equal(p.key.length, 43);
|
|
const url = Channel.pairingUrl('https://x.test/app/#old', { ...p, direct: ['192.168.1.2:4000', '10.0.0.3:5'] });
|
|
assert.ok(url.startsWith('https://x.test/app/#r='));
|
|
const back = Channel.parsePairing(new URL(url).hash);
|
|
assert.deepEqual(back, { ...p, direct: ['192.168.1.2:4000', '10.0.0.3:5'] });
|
|
assert.equal(Channel.parsePairing('#r=short&k=x'), null);
|
|
assert.equal(Channel.parsePairing(''), null);
|
|
});
|
|
|
|
if (process.env.RELAY_URL) {
|
|
test('relay integration: host + remote, reconnect, missing room', async () => {
|
|
const url = process.env.RELAY_URL;
|
|
const { room, key } = Channel.newPairing();
|
|
const host = await Channel.open({ role: 'host', key, transport: relayTransport({ url, room, role: 'host' }) });
|
|
const remote = await Channel.open({ role: 'remote', key, transport: relayTransport({ url, room, role: 'remote', joinRetry: 200 }) });
|
|
const gh = [], gr = [], peers = [];
|
|
host.on('message', (m, from) => gh.push([m, from])).on('peer', (p) => peers.push(p));
|
|
remote.on('message', (m) => gr.push(m));
|
|
await until(() => host.isOpen && remote.isOpen);
|
|
await until(() => host.peers().length === 1);
|
|
await remote.send({ t: 'hello' });
|
|
await until(() => gh.length);
|
|
assert.equal(gh[0][0].t, 'hello');
|
|
await host.send({ t: 'welcome' }, { to: gh[0][1] });
|
|
await host.send({ big: 'z'.repeat(150000) });
|
|
await until(() => gr.length === 2);
|
|
assert.equal(gr[1].big.length, 150000);
|
|
// a wrong-key stranger who knows the room gets nothing readable
|
|
const bad = await Channel.open({ role: 'remote', key: Channel.newPairing().key, transport: relayTransport({ url, room, role: 'remote' }) });
|
|
const badErr = []; bad.on('error', (e) => badErr.push(e));
|
|
await until(() => bad.isOpen);
|
|
await host.send({ t: 'secret' });
|
|
await until(() => badErr.length);
|
|
assert.equal(badErr[0].code, 'decrypt');
|
|
bad.close();
|
|
// a remote joining an unknown long room keeps retrying, then enters when the host appears
|
|
const room2 = Channel.newPairing().room;
|
|
const lone = await Channel.open({ role: 'remote', key, transport: relayTransport({ url, room: room2, role: 'remote', joinRetry: 200 }) });
|
|
const errs = []; lone.on('error', (e) => errs.push(e));
|
|
await until(() => errs.some((e) => e.code === 'no-room'));
|
|
assert.equal(lone.isOpen, false);
|
|
const host2 = await Channel.open({ role: 'host', key, transport: relayTransport({ url, room: room2, role: 'host' }) });
|
|
await until(() => lone.isOpen);
|
|
lone.close(); host2.close();
|
|
host.close(); remote.close();
|
|
});
|
|
}
|
|
|
|
for (const [name, fn] of tests) {
|
|
try { await fn(); console.log('ok ' + name); } catch (e) { failed++; console.log('FAIL ' + name + '\n ' + (e.stack || e)); }
|
|
}
|
|
console.log(failed ? `${failed} failed` : 'all passed');
|
|
process.exit(failed ? 1 : 0);
|