173 lines
10 KiB
TypeScript
173 lines
10 KiB
TypeScript
import test, { type TestContext } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { FileSession, QUEUE_LIMIT, type SessionCallbacks, type QueueItem } from '../src/lib/session.ts';
|
|
import type { TransferChannel, TransferResult, TransferState } from '../src/lib/transfer.ts';
|
|
|
|
class Channel extends EventTarget implements TransferChannel {
|
|
binaryType: BinaryType = 'arraybuffer';
|
|
bufferedAmountLowThreshold = 0;
|
|
bufferedAmount = 0;
|
|
readyState: RTCDataChannelState = 'open';
|
|
onopen: TransferChannel['onopen'] = null;
|
|
onmessage: TransferChannel['onmessage'] = null;
|
|
onclose: TransferChannel['onclose'] = null;
|
|
onerror: TransferChannel['onerror'] = null;
|
|
peer: Channel | null = null;
|
|
frames: (string | ArrayBuffer)[] = [];
|
|
send(data: string | ArrayBuffer) { this.frames.push(data); queueMicrotask(() => this.peer?.onmessage?.(new MessageEvent('message', { data }))); }
|
|
close() { this.readyState = 'closed'; this.dispatchEvent(new Event('close')); }
|
|
}
|
|
const tick = () => new Promise<void>(resolve => setImmediate(resolve));
|
|
async function until(check: () => boolean) { for (let n = 0; n < 500; n++) { if (check()) return; await tick(); } assert.fail('Condition did not become true'); }
|
|
const file = (name: string, size = 3) => new File([new Uint8Array(size).fill(42)], name);
|
|
function side(channel: Channel, initiator: boolean) {
|
|
const state = { ready: false, queue: [] as QueueItem[], send: '' as TransferState | '', receive: '' as TransferState | '', results: [] as { direction: string; result: TransferResult }[], declined: [] as string[], errors: [] as string[], closed: false, pairings: [] as Record<string, unknown>[] };
|
|
const callbacks: SessionCallbacks = {
|
|
onReady() { state.ready = true; }, onQueue(items) { state.queue = items; },
|
|
onState(direction, value) { state[direction] = value; }, onProgress() {},
|
|
onComplete(direction, result) { state.results.push({ direction, result }); },
|
|
onDecline(direction, meta) { state.declined.push(meta.name); state[direction] = ''; },
|
|
onError(error) { state.errors.push(error.message); }, onClose() { state.closed = true; },
|
|
onPairing(message) { state.pairings.push(message); },
|
|
};
|
|
return { session: new FileSession(channel, initiator, callbacks), state, channel };
|
|
}
|
|
function pair(t: TestContext) {
|
|
const a = new Channel(), b = new Channel(); a.peer = b; b.peer = a;
|
|
const first = side(a, true), second = side(b, false);
|
|
t.after(() => { first.session.close(); second.session.close(); });
|
|
return { first, second };
|
|
}
|
|
|
|
test('queues remain private until both peers verify, then require per-file acceptance', async t => {
|
|
const { first, second } = pair(t);
|
|
first.session.add([file('one'), file('two', 0)]);
|
|
first.session.verify(); await tick();
|
|
assert.equal(first.channel.frames.length, 1); assert.equal(second.state.receive, '');
|
|
second.session.verify(); await until(() => second.state.receive === 'choose-storage');
|
|
assert.equal(first.state.send, 'waiting-accept');
|
|
second.session.accept(); await until(() => first.state.results.length === 1 && second.state.receive === 'choose-storage');
|
|
assert.equal(first.state.send, 'waiting-accept');
|
|
second.session.accept(); await until(() => first.state.results.length === 2);
|
|
assert.deepEqual(second.state.results.map(item => item.result.meta.name), ['one', 'two']);
|
|
assert.equal(second.state.results[1]!.result.blob!.size, 0);
|
|
assert.deepEqual(first.state.errors, []); assert.deepEqual(second.state.errors, []);
|
|
});
|
|
|
|
test('simultaneous bidirectional queues have isolated bytes, receipts and destinations', async t => {
|
|
const { first, second } = pair(t);
|
|
first.session.add([file('a', 40000), file('b')]); second.session.add([file('c', 20000), file('d', 0)]);
|
|
first.session.verify(); second.session.verify();
|
|
for (let index = 0; index < 2; index++) {
|
|
await until(() => first.state.receive === 'choose-storage' && second.state.receive === 'choose-storage');
|
|
first.session.accept(); second.session.accept();
|
|
await until(() => first.state.results.length >= (index + 1) * 2 && second.state.results.length >= (index + 1) * 2);
|
|
}
|
|
for (const side of [first, second]) {
|
|
for (const { result } of side.state.results.filter(item => item.direction === 'receive')) {
|
|
assert.ok(new Uint8Array(await result.blob!.arrayBuffer()).every(byte => byte === 42));
|
|
}
|
|
assert.deepEqual(side.state.errors, []);
|
|
}
|
|
assert.deepEqual(first.state.results.filter(item => item.direction === 'receive').map(item => item.result.meta.name), ['c', 'd']);
|
|
});
|
|
|
|
test('remove pending and decline offered files without ending the session', async t => {
|
|
const { first, second } = pair(t);
|
|
first.session.add([file('decline'), file('remove'), file('keep')]);
|
|
first.session.remove(first.state.queue[1]!.id);
|
|
first.session.verify(); second.session.verify();
|
|
await until(() => second.state.receive === 'choose-storage'); second.session.decline();
|
|
await until(() => first.state.declined.length === 1 && second.state.receive === 'choose-storage');
|
|
second.session.accept(); await until(() => first.state.results.length === 1);
|
|
assert.equal(first.state.results[0]!.result.meta.name, 'keep');
|
|
assert.deepEqual(first.state.declined, ['decline']); assert.equal(first.state.closed, false);
|
|
});
|
|
|
|
test('queue limit is atomic and cancellation aborts both active disk destinations', async t => {
|
|
const { first, second } = pair(t);
|
|
assert.throws(() => first.session.add(Array.from({ length: QUEUE_LIMIT + 1 }, () => file('too-many'))), /Queue up to/);
|
|
assert.equal(first.state.queue.length, 0);
|
|
first.session.add([file('a')]); second.session.add([file('b')]);
|
|
first.session.verify(); second.session.verify();
|
|
await until(() => first.state.receive === 'choose-storage' && second.state.receive === 'choose-storage');
|
|
let aborted = 0;
|
|
const destination = () => {
|
|
let release: (() => void) | undefined;
|
|
return { write() { return new Promise<void>(resolve => { release = resolve; }); }, async close() { assert.fail('Cancelled destination must not close'); }, async abort() { aborted++; release?.(); } };
|
|
};
|
|
first.session.accept(destination()); second.session.accept(destination()); await tick();
|
|
first.session.close(); second.session.close(); await until(() => aborted === 2);
|
|
assert.equal(first.state.results.length, 0); assert.equal(second.state.results.length, 0);
|
|
});
|
|
|
|
test('reused file IDs and stale receipts fail closed', async t => {
|
|
for (const stale of ['start', 'frame']) {
|
|
const { first, second } = pair(t);
|
|
first.session.add([file('one', 0)]); first.session.verify(); second.session.verify();
|
|
await until(() => second.state.receive === 'choose-storage'); second.session.accept();
|
|
await until(() => first.state.results.length === 1);
|
|
const target = stale === 'start' ? second : first;
|
|
target.channel.onmessage?.(new MessageEvent('message', { data: JSON.stringify({ v: 3, type: stale, id: 1, data: JSON.stringify({ v: 2, type: 'complete', bytes: 0 }) }) }));
|
|
await until(() => target.state.closed);
|
|
assert.equal(target.state.closed, true); assert.equal(target.state.errors.length, 1);
|
|
}
|
|
});
|
|
|
|
test('unsolicited offers before verification and excess binary payload fail closed', async t => {
|
|
const { first, second } = pair(t);
|
|
first.channel.onmessage?.(new MessageEvent('message', { data: JSON.stringify({ v: 3, type: 'start', id: 2 }) }));
|
|
second.channel.onmessage?.(new MessageEvent('message', { data: new ArrayBuffer(100000) }));
|
|
await until(() => first.state.closed && second.state.closed);
|
|
assert.equal(first.state.closed, true); assert.equal(second.state.closed, true);
|
|
});
|
|
|
|
test('identity proofs gate metadata even when a remembered contact requests automatic verification', async t => {
|
|
const { first, second } = pair(t);
|
|
let release!: () => void;
|
|
const pending = new Promise<void>(resolve => { release = resolve; });
|
|
first.session.authenticate({ sign: async () => 'sender-proof', verify: async proof => { assert.equal(proof, 'receiver-proof'); await pending; } });
|
|
second.session.authenticate({ sign: async () => 'receiver-proof', verify: async proof => { assert.equal(proof, 'sender-proof'); await pending; } });
|
|
first.session.add([file('private-name')]); first.session.verify(); second.session.verify();
|
|
await tick();
|
|
assert.equal(first.state.ready, false); assert.equal(second.state.ready, false);
|
|
assert.doesNotMatch(first.channel.frames.join(''), /private-name/);
|
|
release(); await until(() => second.state.receive === 'choose-storage');
|
|
second.session.accept(); await until(() => first.state.results.length === 1);
|
|
assert.deepEqual(first.state.errors, []); assert.deepEqual(second.state.errors, []);
|
|
});
|
|
|
|
test('invalid or missing identity proof closes the session without releasing file metadata', async t => {
|
|
const { first, second } = pair(t);
|
|
first.session.authenticate({ sign: async () => 'proof', verify: async () => { throw new Error('Device proof failed'); } });
|
|
first.session.add([file('private-name')]); first.session.verify(); second.session.verify();
|
|
await until(() => first.state.closed);
|
|
assert.match(first.state.errors.join(''), /Device proof failed/);
|
|
assert.doesNotMatch(first.channel.frames.join(''), /private-name/);
|
|
});
|
|
|
|
test('pairing messages wait for mutual verification and device proofs', async t => {
|
|
const { first, second } = pair(t);
|
|
let release!: () => void;
|
|
const proof = new Promise<void>(resolve => { release = resolve; });
|
|
t.after(() => release());
|
|
for (const side of [first, second]) side.session.authenticate({ sign: async () => 'proof', verify: () => proof });
|
|
first.session.verify(); second.session.verify(); await tick();
|
|
assert.throws(() => first.session.sendPairing({ step: 'propose' }));
|
|
assert.deepEqual(second.state.pairings, []);
|
|
release(); await until(() => first.state.ready && second.state.ready);
|
|
first.session.sendPairing({ step: 'check', value: '' });
|
|
await until(() => second.state.pairings.length === 1);
|
|
assert.deepEqual(second.state.pairings, [{ v: 3, type: 'pairing', step: 'check', value: '' }]);
|
|
first.session.close();
|
|
assert.throws(() => first.session.sendPairing({ step: 'propose' }));
|
|
});
|
|
|
|
test('unsolicited pairing messages before verification never reach the setup handler', async t => {
|
|
const { first } = pair(t);
|
|
first.channel.onmessage?.(new MessageEvent('message', { data: JSON.stringify({ v: 3, type: 'pairing', step: 'propose' }) }));
|
|
await until(() => first.state.closed);
|
|
assert.deepEqual(first.state.pairings, []);
|
|
assert.match(first.state.errors[0]!, /before verification/);
|
|
});
|