init
This commit is contained in:
247 files changed
+35538
No files matched your search
@@ -0,0 +1,92 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomBytes, createHash, createHmac } from 'node:crypto';
|
||||
import { createAccounts, accountKey } from '../src/auth/accounts.mjs';
|
||||
import { createUserContext } from '../src/auth/user-context.mjs';
|
||||
import { createSessions } from '../src/auth/session.mjs';
|
||||
import { createStore } from '../src/auth/store.mjs';
|
||||
import { createVault } from '../src/identity/vault.mjs';
|
||||
import { createPreferences } from '../src/preferences.mjs';
|
||||
import { hashPassword } from '../src/auth/password.mjs';
|
||||
import { readConfig } from '../src/config.mjs';
|
||||
|
||||
const password = 'synthetic-account-password';
|
||||
const ownerHash = await hashPassword(password);
|
||||
const config = () => ({ memory: true, secret: randomBytes(32).toString('hex'), identityKey: randomBytes(32).toString('hex'), passwordHash: ownerHash, sessionSeconds: 900 });
|
||||
const identity = suffix => ({ identity: { key: `synthetic-key-${suffix}` }, metadata: { uid: `synthetic-uid-${suffix}`, level: 8 } });
|
||||
|
||||
test('registration is atomic, canonical, durable, and stores a salted password hash', async () => {
|
||||
const settings = config(); const store = createStore(settings); const accounts = createAccounts(settings, store);
|
||||
const results = await Promise.allSettled(['Alice', 'ALICE'].map(username => accounts.register({ username, password })));
|
||||
assert.equal(results.filter(result => result.status === 'fulfilled').length, 1);
|
||||
const user = results.find(result => result.status === 'fulfilled').value;
|
||||
assert.equal(user.username, 'alice'); assert.match(user.id, /^[a-f0-9]{32}$/);
|
||||
const raw = await store.get(accountKey('alice'));
|
||||
assert.equal(raw.includes(password), false); assert.match(JSON.parse(raw).passwordHash, /^scrypt:/);
|
||||
assert.deepEqual(await createAccounts(settings, store).authenticate({ username: 'ALICE', password }), user);
|
||||
for (const input of [{ username: 'alice', password: 'wrong' }, { username: 'missing', password }, { username: '../alice', password }, { username: 'owner', password: 'wrong' }]) assert.equal(await accounts.authenticate(input), null);
|
||||
assert.deepEqual(await accounts.authenticate({ password }), { id: 'owner', username: 'owner' });
|
||||
for (const username of ['owner', 'OwNeR', 'ab', 'with space', '../owner', 'a'.repeat(33)]) await assert.rejects(accounts.register({ username, password }));
|
||||
await assert.rejects(accounts.register({ username: 'valid', password: 'short' }), error => error.status === 400);
|
||||
});
|
||||
|
||||
test('registration can close without disabling existing accounts; no owner secret is needed for a new deployment', async () => {
|
||||
const settings = { ...config(), passwordHash: undefined }; const store = createStore(settings);
|
||||
const user = await createAccounts(settings, store).register({ username: 'alice', password });
|
||||
const closed = createAccounts({ ...settings, registration: false }, store);
|
||||
await assert.rejects(closed.register({ username: 'bob', password }), error => error.status === 403);
|
||||
assert.deepEqual(await closed.authenticate({ username: 'alice', password }), user);
|
||||
assert.equal(await closed.authenticate({ username: 'owner', password }), null);
|
||||
assert.equal(await closed.principal({}), null);
|
||||
await assert.rejects(createAccounts({ ...settings, identityKey: undefined }, store).register({ username: 'bob', password }), error => error.status === 409);
|
||||
assert.equal(readConfig({ APP_ORIGIN: 'http://localhost:3000', SESSION_SECRET: settings.secret, ALLOW_LOCAL_MEMORY_STORE: '1', ALLOW_REGISTRATION: '0' }).registration, false);
|
||||
});
|
||||
|
||||
test('user identities, settings, leases and rate limits are isolated and ciphertext is bound to its account', async () => {
|
||||
const settings = config(); const store = createStore(settings); const accounts = createAccounts(settings, store);
|
||||
const a = await accounts.register({ username: 'alice', password }); const b = await accounts.register({ username: 'bob', password });
|
||||
const alice = createUserContext(settings, store, a); const bob = createUserContext(settings, store, b);
|
||||
await alice.vault.initialize(identity('alice')); await bob.vault.initialize(identity('bob'));
|
||||
const saved = await alice.preferences.saveConnection({ host: 'voice.example.test', port: 9987, nickname: 'Alice nickname', password: 'synthetic-server-password' });
|
||||
assert.equal((await bob.preferences.read()).connection, null); assert.equal((await bob.preferences.read()).nickname, 'bob');
|
||||
await assert.rejects(bob.preferences.activeConnection(saved.connection.id), error => error.code === 'connection_required');
|
||||
assert.equal((await bob.vault.read()).metadata.uid, 'synthetic-uid-bob');
|
||||
assert.equal(await alice.store.putIfAbsent('lease', 'alice', 35), true); assert.equal(await bob.store.putIfAbsent('lease', 'bob', 35), true);
|
||||
assert.equal(await alice.store.limit('rate', 1, 60), true); assert.equal(await alice.store.limit('rate', 1, 60), false); assert.equal(await bob.store.limit('rate', 1, 60), true);
|
||||
const aIdentity = await alice.store.get('voxharbor:identity:v1:owner'); const bIdentity = await bob.store.get('voxharbor:identity:v1:owner');
|
||||
await bob.store.compareSet('voxharbor:identity:v1:owner', bIdentity, aIdentity);
|
||||
await assert.rejects(bob.vault.read(), /could not be decrypted/);
|
||||
const aPreferences = await alice.store.get('voxharbor:preferences:v1:owner');
|
||||
await bob.store.putIfAbsent('voxharbor:preferences:v1:owner', aPreferences);
|
||||
await assert.rejects(bob.preferences.read(), /could not be decrypted/);
|
||||
assert.equal((await alice.vault.read()).metadata.uid, 'synthetic-uid-alice');
|
||||
assert.throws(() => createUserContext(settings, store, { id: '../owner' }));
|
||||
});
|
||||
|
||||
test('legacy owner ciphertext and pre-account sessions keep their existing scope unchanged', async () => {
|
||||
const settings = config(); const store = createStore(settings);
|
||||
await createVault(settings, store).initialize(identity('owner'));
|
||||
await createPreferences(settings, store).saveConnection({ host: 'owner.example.test', port: 9987, nickname: 'Original owner' });
|
||||
const before = await store.get('voxharbor:identity:v1:owner'); const prefsBefore = await store.get('voxharbor:preferences:v1:owner');
|
||||
const sessions = createSessions(settings, store); const created = await sessions.create();
|
||||
const token = created.cookie.split(';')[0].split('=')[1];
|
||||
const namespace = createHmac('sha256', settings.secret).update('session-namespace-v1').digest('hex');
|
||||
const key = `vh:${namespace}:session:${createHash('sha256').update(token).digest('hex')}`;
|
||||
await store.set(key, JSON.stringify({ csrf: created.session.csrf, expires: created.session.expires }), 900);
|
||||
const legacy = await sessions.read({ headers: { cookie: created.cookie.split(';')[0] } });
|
||||
const principal = await createAccounts(settings, store).principal(legacy);
|
||||
const owner = createUserContext(settings, store, principal);
|
||||
assert.equal((await owner.vault.read()).metadata.uid, 'synthetic-uid-owner');
|
||||
assert.equal((await owner.preferences.read()).connection.nickname, 'Original owner');
|
||||
assert.equal(await store.get('voxharbor:identity:v1:owner'), before); assert.equal(await store.get('voxharbor:preferences:v1:owner'), prefsBefore);
|
||||
});
|
||||
|
||||
test('sessions cannot claim another account ID and deleted account sessions fail closed', async () => {
|
||||
const settings = config(); const store = createStore(settings); const accounts = createAccounts(settings, store);
|
||||
const alice = await accounts.register({ username: 'alice', password }); const bob = await accounts.register({ username: 'bob', password });
|
||||
const session = { userId: alice.id, username: alice.username };
|
||||
assert.deepEqual(await accounts.principal(session), alice);
|
||||
assert.equal(await accounts.principal({ ...session, userId: bob.id }), null);
|
||||
assert.equal(await accounts.principal({ userId: 'owner', username: 'alice' }), null);
|
||||
await store.delete(accountKey('alice')); assert.equal(await accounts.principal(session), null);
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { AudioRecovery } from '../public/audio-recovery.mjs';
|
||||
import { safeDiagnostic } from '../public/connection-diagnostics.mjs';
|
||||
function fixture() {
|
||||
const recovery = new AudioRecovery(); const calls = [];
|
||||
const audio = { outputMuted: false, muted: false, context: { setSinkId: async id => calls.push(['output', id]) },
|
||||
listen: async enabled => calls.push(['listen', enabled]), microphone: async id => calls.push(['mic', id]), mute: () => calls.push(['mute']) };
|
||||
const options = { visible: true, create: () => audio, valid: () => true, output: 'speaker', microphone: 'input', resumeMicrophone: () => true, status: text => calls.push(['status', text]) };
|
||||
return { recovery, audio, options, calls };
|
||||
}
|
||||
test('recovery restores listening and selected devices but requires microphone opt-in', async () => {
|
||||
for (const optIn of [false, true]) {
|
||||
const f = fixture(); f.recovery.interrupted(f.audio, optIn, true);
|
||||
// Repeated disconnect callbacks during authentication must retain intent.
|
||||
f.recovery.interrupted(undefined, optIn, true);
|
||||
await f.recovery.restore(f.options);
|
||||
assert.ok(f.calls.some(([type]) => type === 'listen'));
|
||||
assert.ok(f.calls.some(([type, id]) => type === 'output' && id === 'speaker'));
|
||||
assert.equal(f.calls.some(([type]) => type === 'mic'), optIn);
|
||||
const count = f.calls.length; await f.recovery.restore(f.options); assert.equal(f.calls.length, count);
|
||||
}
|
||||
});
|
||||
test('muted audio, background pages, cancellation and revoked opt-in never resume microphone', async () => {
|
||||
for (const scenario of ['muted', 'hidden', 'clear', 'optout']) {
|
||||
const f = fixture(); if (scenario === 'muted') f.audio.muted = true;
|
||||
f.recovery.interrupted(f.audio, true, scenario !== 'hidden');
|
||||
if (scenario === 'clear') f.recovery.clear();
|
||||
if (scenario === 'optout') f.options.resumeMicrophone = () => false;
|
||||
await f.recovery.restore(f.options); assert.equal(f.calls.some(([type]) => type === 'mic'), false);
|
||||
}
|
||||
const f = fixture(); f.audio.outputMuted = true; f.recovery.interrupted(f.audio, true, true);
|
||||
await f.recovery.restore(f.options); assert.deepEqual(f.calls, []);
|
||||
});
|
||||
test('late listening completion cannot re-enable microphone after logout or a hidden page', async () => {
|
||||
const f = fixture(); let resolve;
|
||||
f.audio.listen = () => new Promise(done => { resolve = done; });
|
||||
f.recovery.interrupted(f.audio, true, true); const restoring = f.recovery.restore(f.options);
|
||||
f.recovery.clear(); resolve(); await restoring;
|
||||
assert.equal(f.calls.some(([type]) => type === 'mic'), false);
|
||||
});
|
||||
test('automatic audio failures leave microphone muted with an actionable status', async () => {
|
||||
const f = fixture(); f.audio.listen = async () => { throw new Error('browser blocked'); };
|
||||
f.recovery.interrupted(f.audio, true, true); await f.recovery.restore(f.options);
|
||||
assert.ok(f.calls.some(([type]) => type === 'mute')); assert.ok(f.calls.some(([type, text]) => type === 'status' && text.includes('could not resume')));
|
||||
});
|
||||
test('connection log excludes secrets and arbitrary payloads', () => {
|
||||
assert.deepEqual(safeDiagnostic({ type: 'transport_closed', closeCode: 1006, durationMs: 240000, receivedState: true,
|
||||
password: 'private', host: 'private.example', reason: 'private message', code: 'invalid secret@example.com', roundTripMs: -1,
|
||||
csrf: 'secret', participants: [{ name: 'private' }] }), { type: 'transport_closed', closeCode: 1006, durationMs: 240000, receivedState: true });
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createEncoder, createDecoder, getPacketInfo, Application } from 'libopus-wasm';
|
||||
import { encodeVoice, decodeVoice } from '../public/voice-frame.mjs';
|
||||
import { JitterBuffer } from '../public/jitter-buffer.mjs';
|
||||
import { Worker } from 'node:worker_threads';
|
||||
|
||||
test('voice frame rejects malformed, oversized, spoofed and reverse-direction input', () => {
|
||||
const bytes = encodeVoice({ direction: 1, sequence: 65535, data: new Uint8Array([1, 2, 3]) });
|
||||
assert.equal(decodeVoice(bytes, 1).sequence, 65535);
|
||||
for (const index of [0, 1, 2, 6, 7]) {
|
||||
const invalid = bytes.slice(); invalid[index] = 255;
|
||||
assert.throws(() => decodeVoice(invalid, 1));
|
||||
}
|
||||
assert.throws(() => decodeVoice(bytes, 2));
|
||||
assert.throws(() => decodeVoice(new Uint8Array(1284), 1));
|
||||
assert.throws(() => decodeVoice(new Uint8Array(7), 1));
|
||||
assert.equal(decodeVoice(encodeVoice({ direction: 2, clientId: 42, data: new Uint8Array() }), 2).end, true);
|
||||
});
|
||||
|
||||
test('jitter buffer orders wrapped sequences, discards duplicates and late packets', () => {
|
||||
const queue = new JitterBuffer({ prebuffer: 0 });
|
||||
for (const sequence of [65534, 0, 65535, 1, 1]) queue.push({ sequence });
|
||||
assert.deepEqual(Array.from({ length: 4 }, () => queue.pull().packet.sequence), [65534, 65535, 0, 1]);
|
||||
assert.equal(queue.stats.duplicate, 1);
|
||||
queue.push({ sequence: 0 });
|
||||
assert.equal(queue.stats.late, 1);
|
||||
});
|
||||
|
||||
test('jitter buffer supplies following packet for FEC, bounds backlog and ends dead speakers', () => {
|
||||
const queue = new JitterBuffer({ prebuffer: 0 });
|
||||
queue.push({ sequence: 8 }); queue.push({ sequence: 10 });
|
||||
assert.equal(queue.pull().type, 'packet');
|
||||
const gap = queue.pull(); assert.equal(gap.type, 'loss'); assert.equal(gap.next.sequence, 10);
|
||||
assert.equal(queue.pull().packet.sequence, 10);
|
||||
queue.push({ sequence: 200 });
|
||||
assert.equal(queue.packets.size, 1); assert.equal(queue.stats.overflow, 1);
|
||||
assert.equal(queue.pull().packet.sequence, 200);
|
||||
assert.deepEqual([queue.pull().type, queue.pull().type, queue.pull().type, queue.pull().type], ['loss', 'loss', 'end', 'idle']);
|
||||
for (let sequence = 300; sequence < 1000; sequence++) queue.push({ sequence });
|
||||
assert.ok(queue.packets.size <= 12);
|
||||
});
|
||||
|
||||
test('real Opus encodes 20 ms PCM, independently decodes speakers and conceals packet loss', async () => {
|
||||
const encoder = await createEncoder({ sampleRate: 48000, channels: 1, application: Application.Voip, frameSize: 960, fec: true, packetLossPercent: 15 });
|
||||
const decoders = await Promise.all(Array.from({ length: 4 }, () => createDecoder({ sampleRate: 48000, channels: 2, maxFrameSize: 960 })));
|
||||
try {
|
||||
let energy = 0;
|
||||
for (let frame = 0; frame < 30; frame++) {
|
||||
const pcm = Float32Array.from({ length: 960 }, (_, i) => Math.sin((frame * 960 + i) * 2 * Math.PI * 440 / 48000) * 0.15);
|
||||
const packet = encoder.encodeFloat(pcm, { maxPacketBytes: 1275 });
|
||||
assert.equal((await getPacketInfo(packet, { sampleRate: 48000 })).samples, 960);
|
||||
for (const decoder of decoders) {
|
||||
const result = frame === 10 ? decoder.decodePacketLossFloat(960) : decoder.decodeFloat(packet, { maxFrameSize: 960 });
|
||||
assert.equal(result.length, 1920);
|
||||
for (const sample of result) { assert.ok(Number.isFinite(sample)); energy += sample * sample; }
|
||||
}
|
||||
}
|
||||
assert.ok(energy > 100, 'Decoded tone must contain actual signal');
|
||||
} finally { encoder.free(); decoders.forEach(decoder => decoder.free()); }
|
||||
});
|
||||
|
||||
test('application worker mixes speakers and enforces PTT, voice activation, mute and permission gates', async t => {
|
||||
const worker = new Worker(new URL('./fixtures/audio-worker-node.mjs', import.meta.url));
|
||||
t.after(() => worker.terminate());
|
||||
let encoded = 0; let energy = 0; let acknowledged = 0; const speakers = new Set(); const errors = [];
|
||||
let ready;
|
||||
const initialized = new Promise(resolve => { ready = resolve; });
|
||||
worker.on('error', error => errors.push(error.message));
|
||||
worker.on('message', event => {
|
||||
if (event.type === 'ready') ready();
|
||||
else if (event.type === 'error') errors.push(event.code);
|
||||
else if (event.type === 'packet_ack') acknowledged++;
|
||||
else if (event.type === 'encoded') {
|
||||
const packet = decodeVoice(event.frame, 1);
|
||||
if (packet.end) return;
|
||||
encoded++;
|
||||
for (const clientId of [40, 41, 42]) {
|
||||
if (clientId === 42 && encoded % 11 === 0) continue;
|
||||
const frame = encodeVoice({ direction: 2, clientId, sequence: (65520 + encoded) & 65535, data: packet.data });
|
||||
worker.postMessage({ type: 'packet', frame: frame.buffer }, [frame.buffer]);
|
||||
}
|
||||
} else if (event.type === 'pcm') {
|
||||
for (const value of event.pcm) { assert.ok(Number.isFinite(value) && Math.abs(value) <= 1); energy += value * value; }
|
||||
} else if (event.type === 'speaking') event.ids.forEach(id => speakers.add(id));
|
||||
});
|
||||
worker.postMessage({ type: 'init' });
|
||||
await Promise.race([initialized, new Promise((_, reject) => { const timer = setTimeout(() => reject(new Error('Worker initialization timed out')), 5000); timer.unref(); })]);
|
||||
worker.postMessage({ type: 'configure', mode: 'ptt', muted: false, outputMuted: false, canSend: true, codec: 4, threshold: 0.025 });
|
||||
worker.postMessage({ type: 'ptt', pressed: true });
|
||||
// A malformed server packet must be dropped, without breaking other speakers.
|
||||
worker.postMessage({ type: 'packet', frame: new Uint8Array([1, 2]).buffer });
|
||||
for (let frame = 0; frame < 45; frame++) {
|
||||
const pcm = Float32Array.from({ length: 960 }, (_, i) => 0.1 * Math.sin((frame * 960 + i) * 2 * Math.PI * 440 / 48000));
|
||||
worker.postMessage({ type: 'capture', pcm, at: Date.now() }, [pcm.buffer]);
|
||||
await new Promise(resolve => setTimeout(resolve, 20));
|
||||
}
|
||||
worker.postMessage({ type: 'ptt', pressed: false });
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
const before = encoded;
|
||||
worker.postMessage({ type: 'capture', pcm: new Float32Array(960).fill(0.1), at: Date.now() });
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
assert.equal(encoded, before, 'PTT release must stop transmission');
|
||||
const configure = overrides => worker.postMessage({ type: 'configure', mode: 'vad', muted: false, outputMuted: false, canSend: true, codec: 4, threshold: 0.025, ...overrides });
|
||||
const capture = async amplitude => {
|
||||
worker.postMessage({ type: 'capture', pcm: new Float32Array(960).fill(amplitude), at: Date.now() });
|
||||
await new Promise(resolve => setTimeout(resolve, 40));
|
||||
};
|
||||
configure({}); await capture(0); assert.equal(encoded, before, 'VAD silence must not transmit');
|
||||
await capture(0.1); assert.equal(encoded, before + 1, 'VAD above threshold must transmit');
|
||||
for (const gate of [{ muted: true }, { outputMuted: true }, { canSend: false }, { codec: 3 }]) {
|
||||
configure(gate); const count = encoded; await capture(0.1);
|
||||
assert.equal(encoded, count, 'Mute, output, permission and codec gates must each stop transmission');
|
||||
}
|
||||
assert.ok(encoded > 30); assert.ok(energy > 50); assert.ok(acknowledged > 70);
|
||||
assert.deepEqual([...speakers].sort(), [40, 41, 42]); assert.deepEqual(errors, []);
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { orderChannels } from '../public/channel-order.mjs';
|
||||
|
||||
test('channel hierarchy follows preceding-sibling links, not numeric IDs or order ranks', () => {
|
||||
const result = orderChannels([
|
||||
{ id: 1, parentId: 2, order: 0 },
|
||||
{ id: 20, parentId: 100, order: 30 },
|
||||
{ id: 30, parentId: 100, order: 2 },
|
||||
{ id: 100, parentId: 0, order: 0 },
|
||||
{ id: 2, parentId: 100, order: 0 },
|
||||
]);
|
||||
assert.deepEqual(result.map(item => [item.channel.id, item.depth]), [[100, 0], [2, 1], [1, 2], [30, 1], [20, 1]]);
|
||||
});
|
||||
test('malformed channel cycles and missing parents remain finite and appear once', () => {
|
||||
const channels = [{ id: 1, parentId: 2, order: 2 }, { id: 2, parentId: 1, order: 1 }, { id: 3, parentId: 900, order: 0 }];
|
||||
const result = orderChannels(channels);
|
||||
assert.equal(result.length, 3);
|
||||
assert.equal(new Set(result.map(item => item.channel.id)).size, 3);
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { createPreferences } from '../src/preferences.mjs';
|
||||
import { createStore } from '../src/auth/store.mjs';
|
||||
import { normalizeCommand } from '../src/protocol/commands.mjs';
|
||||
import { createProtocolControl } from '../src/protocol/session.mjs';
|
||||
import { mkdtemp, writeFile, readFile, rm, symlink } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { setTimeout as sleep } from 'node:timers/promises';
|
||||
|
||||
test('only typed client commands cross the native boundary', () => {
|
||||
assert.equal(normalizeCommand({ type: 'raw', command: 'serverstop' }), null);
|
||||
assert.equal(normalizeCommand({ type: 'text_message', target: 'all', message: 'test' }), null);
|
||||
assert.equal(normalizeCommand({ type: 'text_message', target: 'private', clientId: 65536, message: 'test' }), null);
|
||||
assert.equal(normalizeCommand({ type: 'join_channel', channelId: '411' }), null);
|
||||
assert.equal(normalizeCommand({ type: 'join_channel', channelId: 0 }), null);
|
||||
assert.equal(normalizeCommand({ type: 'join_channel', channelId: 411, password: 'x'.repeat(257) }), null);
|
||||
assert.equal(normalizeCommand({ type: 'nickname', name: 'x'.repeat(65) }), null);
|
||||
assert.equal(normalizeCommand({ type: 'subscribe', channelId: 1, subscribed: 'yes' }), null);
|
||||
assert.equal(normalizeCommand({ type: 'away', away: true, message: '\u0000' }), null);
|
||||
assert.deepEqual(normalizeCommand({ type: 'join_channel', channelId: 411, password: 'fixture-only', extra: 'never forwarded' }), { type: 'join_channel', channel_id: 411, password: 'fixture-only' });
|
||||
assert.deepEqual(normalizeCommand({ type: 'text_message', target: 'channel', channelId: 1, clientId: 25, message: '<img src=x onerror=alert(1)>' }), { type: 'text_message', target: 'channel', channel_id: 1, client_id: null, client_uid: null, message: '<img src=x onerror=alert(1)>' });
|
||||
});
|
||||
|
||||
test('message byte and control limits fit the bounded native input without truncating Unicode', () => {
|
||||
assert.ok(normalizeCommand({ type: 'text_message', target: 'channel', channelId: 1, message: '🙂'.repeat(250) }));
|
||||
assert.equal(normalizeCommand({ type: 'text_message', target: 'channel', channelId: 1, message: '🙂'.repeat(251) }), null);
|
||||
assert.equal(normalizeCommand({ type: 'text_message', target: 'channel', channelId: 1, message: ' ' }), null);
|
||||
assert.equal(normalizeCommand({ type: 'text_message', target: 'channel', channelId: 1, message: 'secret\u0001control' }), null);
|
||||
});
|
||||
|
||||
test('client commands require the live owner CSRF and fail explicitly before connection', async () => {
|
||||
const events = []; const closes = [];
|
||||
const control = createProtocolControl({ readyState: 1, bufferedAmount: 0, send: data => events.push(JSON.parse(data)) }, { config: {}, store: {}, vault: {}, csrf: 'fixture', close: (...args) => closes.push(args) });
|
||||
await control.command(Buffer.from(JSON.stringify({ type: 'command', csrf: 'wrong', requestId: 1, command: { type: 'nickname', name: 'Fixture' } })));
|
||||
assert.equal(closes[0][0], 4403);
|
||||
await control.command(Buffer.from(JSON.stringify({ type: 'command', csrf: 'fixture', requestId: 2, command: { type: 'nickname', name: 'Fixture' } })));
|
||||
assert.deepEqual(events.at(-1), { type: 'ts3_command_result', requestId: 2, ok: false, code: 'not_connected' });
|
||||
await control.command(Buffer.from(JSON.stringify({ type: 'command', csrf: 'fixture', requestId: 3, command: { type: 'raw', value: 'clientkick' } })));
|
||||
assert.equal(closes.at(-1)[0], 1003);
|
||||
});
|
||||
|
||||
test('native command acknowledgements are correlated and message contents stay outside diagnostics', async t => {
|
||||
const directory = await mkdtemp(join(tmpdir(), 'voxharbor-command-fixture-')); const binary = join(directory, 'native');
|
||||
await symlink(process.execPath, join(directory, 'node'));
|
||||
await writeFile(binary, `#!${directory}/node\nconst readline = require('node:readline');\nlet first = true;\n(async () => { for await (const line of readline.createInterface({input:process.stdin})) {\n const request=JSON.parse(line);\n if(first){first=false; require('node:fs').writeFileSync(${JSON.stringify(join(directory, 'request.json'))}, JSON.stringify(request)); console.log(JSON.stringify({type:'status',status:'connected'})); continue;}\n if(request.op==='disconnect') break;\n if(request.op==='command') { console.log(JSON.stringify({type:'client_command_result',requestId:request.request_id,ok:true,privateKey:'never forwarded'})); if(request.command.type==='text_message') console.log(JSON.stringify({type:'message',target:'private',clientId:7,name:'<b>sender</b>',message:request.command.message,privateKey:'never forwarded'})); }\n} })().catch(() => process.exit(1));\n`, { mode: 0o700 });
|
||||
t.after(() => rm(directory, { recursive: true, force: true }));
|
||||
const events = [];
|
||||
const ws = { readyState: 1, bufferedAmount: 0, send: data => events.push(JSON.parse(data)) };
|
||||
const config = { protocolBinary: binary, identityKey: randomBytes(32).toString('hex') };
|
||||
const store = createStore({ memory: true }); const preferences = createPreferences(config, store);
|
||||
const settings = await preferences.saveConnection({ host: '1.1.1.1', port: 9987, nickname: 'Fixture', channelId: 12, password: 'fixture-private-server', channelPassword: 'fixture-private-channel' });
|
||||
const control = createProtocolControl(ws, { config, store, preferences, vault: { read: async () => ({ identity: { simulated: true } }) }, csrf: 'fixture', close: () => { ws.readyState = 3; } });
|
||||
t.after(() => control.stop());
|
||||
await control.command(Buffer.from(JSON.stringify({ type: 'connect', csrf: 'fixture', connectionId: settings.connection.id })));
|
||||
for (let i = 0; i < 100 && !events.some(event => event.status === 'connected'); i++) await sleep(10);
|
||||
assert.ok(events.some(event => event.status === 'connected'));
|
||||
const request = JSON.parse(await readFile(join(directory, 'request.json'), 'utf8'));
|
||||
assert.equal(request.address, '1.1.1.1:9987');
|
||||
assert.equal(request.nickname, 'Fixture'); assert.equal(request.channel_id, 12);
|
||||
assert.equal(request.password, 'fixture-private-server'); assert.equal(request.channel_password, 'fixture-private-channel');
|
||||
assert.equal(JSON.stringify(events).includes('fixture-private'), false);
|
||||
await control.command(Buffer.from(JSON.stringify({ type: 'command', csrf: 'fixture', requestId: 41, command: { type: 'nickname', name: 'Renamed' } })));
|
||||
for (let i = 0; i < 100 && !events.some(event => event.type === 'ts3_connection_saved'); i++) await sleep(10);
|
||||
assert.equal((await preferences.activeConnection(settings.connection.id)).nickname, 'Renamed');
|
||||
assert.equal(events.find(event => event.type === 'ts3_connection_saved').preferences.connection.hasPassword, true);
|
||||
assert.equal(JSON.stringify(events).includes('fixture-private'), false);
|
||||
const content = '<img src=x onerror=alert(1)> [b]literal[/b]';
|
||||
await control.command(Buffer.from(JSON.stringify({ type: 'command', csrf: 'fixture', requestId: 42, command: { type: 'text_message', target: 'private', clientId: 7, message: content } })));
|
||||
for (let i = 0; i < 100 && !events.some(event => event.type === 'ts3_message'); i++) await sleep(10);
|
||||
assert.deepEqual(events.find(event => event.type === 'ts3_command_result' && event.requestId === 42), { type: 'ts3_command_result', requestId: 42, ok: true });
|
||||
assert.equal(events.find(event => event.type === 'ts3_message').message, content);
|
||||
assert.equal(JSON.stringify(events).includes('privateKey'), false);
|
||||
await control.stop();
|
||||
});
|
||||
|
||||
|
||||
test('stale saved connection IDs fail before reading the identity or starting a child', async () => {
|
||||
const config = { identityKey: randomBytes(32).toString('hex') }; const store = createStore({ memory: true });
|
||||
const preferences = createPreferences(config, store);
|
||||
const first = await preferences.saveConnection({ host: 'one.example.test', port: 9987, nickname: 'Fixture' });
|
||||
await preferences.saveConnection({ host: 'two.example.test', port: 9987, nickname: 'Fixture' });
|
||||
const events = []; let identityReads = 0; const closes = [];
|
||||
const control = createProtocolControl({ readyState: 1, bufferedAmount: 0, send: data => events.push(JSON.parse(data)) }, {
|
||||
config, store, preferences, vault: { read: async () => { identityReads++; } }, csrf: 'fixture', close: (...args) => closes.push(args),
|
||||
});
|
||||
await control.command(Buffer.from(JSON.stringify({ type: 'connect', csrf: 'fixture', connectionId: first.connection.id })));
|
||||
assert.equal(events.at(-1).code, 'connection_settings_changed'); assert.equal(identityReads, 0); assert.equal(closes[0][0], 1011);
|
||||
await control.stop();
|
||||
});
|
||||
Vendored
+62
@@ -0,0 +1,62 @@
|
||||
import { encodeVoice, decodeVoice } from '/voice-frame.mjs';
|
||||
const result = document.getElementById('result');
|
||||
document.getElementById('run').onclick = async event => {
|
||||
event.target.disabled = true;
|
||||
let context; let worker; let oscillator;
|
||||
const report = { environment: 'local-browser-synthetic-only', browser: navigator.userAgent, sampleRate: 0, encoded: 0, decoded: 0, decodedEnergy: 0, playbackEnergy: 0, playbackSamples: 0, peak: 0, speaking: [], errors: [], stats: null };
|
||||
try {
|
||||
result.textContent = 'Testing…';
|
||||
context = new AudioContext({ sampleRate: 48000 }); report.sampleRate = context.sampleRate;
|
||||
if (context.sampleRate !== 48000) throw new Error('48 kHz unavailable');
|
||||
await context.audioWorklet.addModule('/voice-worklet.mjs');
|
||||
await context.audioWorklet.addModule('/probe.mjs');
|
||||
const capture = new AudioWorkletNode(context, 'vox-capture');
|
||||
const playback = new AudioWorkletNode(context, 'vox-playback', { numberOfInputs: 0, numberOfOutputs: 1, outputChannelCount: [2] });
|
||||
const probe = new AudioWorkletNode(context, 'playback-probe');
|
||||
playback.connect(probe); probe.connect(context.destination);
|
||||
probe.port.onmessage = ({ data }) => { report.playbackEnergy += data.energy; report.playbackSamples += data.samples; };
|
||||
const silent = context.createGain(); silent.gain.value = 0; capture.connect(silent); silent.connect(context.destination);
|
||||
oscillator = context.createOscillator(); oscillator.frequency.value = 440;
|
||||
const level = context.createGain(); level.gain.value = 0.12; oscillator.connect(level); level.connect(capture);
|
||||
worker = new Worker('/voice-worker.mjs', { type: 'module' });
|
||||
let ready;
|
||||
const initialized = new Promise(resolve => { ready = resolve; });
|
||||
const talking = new Set();
|
||||
worker.onerror = error => report.errors.push(error.message);
|
||||
worker.onmessage = ({ data }) => {
|
||||
if (data.type === 'ready') ready();
|
||||
else if (data.type === 'capture_ack') capture.port.postMessage({ type: 'ack' });
|
||||
else if (data.type === 'encoded') {
|
||||
const packet = decodeVoice(data.frame, 1); if (packet.end) return;
|
||||
report.encoded++;
|
||||
for (const clientId of [41, 42, 43]) {
|
||||
if (clientId === 42 && report.encoded % 13 === 0) continue;
|
||||
const frame = encodeVoice({ direction: 2, clientId, sequence: (65520 + report.encoded) & 65535, codec: 4, data: packet.data });
|
||||
worker.postMessage({ type: 'packet', frame: frame.buffer }, [frame.buffer]);
|
||||
}
|
||||
} else if (data.type === 'pcm') {
|
||||
report.decoded++;
|
||||
for (const value of data.pcm) { report.decodedEnergy += value * value; report.peak = Math.max(report.peak, Math.abs(value)); }
|
||||
playback.port.postMessage({ pcm: data.pcm }, [data.pcm.buffer]);
|
||||
} else if (data.type === 'speaking') { data.ids.forEach(id => talking.add(id)); report.speaking = [...talking]; }
|
||||
else if (data.type === 'stats') report.stats = data;
|
||||
else if (data.type === 'error') report.errors.push(data.code);
|
||||
};
|
||||
worker.postMessage({ type: 'init' });
|
||||
await Promise.race([initialized, new Promise((_, reject) => setTimeout(() => reject(new Error('Codec initialization timeout')), 10000))]);
|
||||
worker.postMessage({ type: 'configure', mode: 'ptt', muted: false, outputMuted: false, canSend: true, codec: 4, threshold: 0.025 });
|
||||
worker.postMessage({ type: 'ptt', pressed: true });
|
||||
capture.port.onmessage = ({ data }) => worker.postMessage({ type: 'capture', pcm: data.pcm, at: Date.now() }, [data.pcm.buffer]);
|
||||
capture.port.postMessage({ type: 'enabled', value: true });
|
||||
await context.resume(); oscillator.start();
|
||||
await new Promise(resolve => setTimeout(resolve, 2400));
|
||||
worker.postMessage({ type: 'ptt', pressed: false });
|
||||
capture.port.postMessage({ type: 'enabled', value: false });
|
||||
const atRelease = report.encoded;
|
||||
await new Promise(resolve => setTimeout(resolve, 200));
|
||||
report.pttReleaseStopped = report.encoded <= atRelease + 1;
|
||||
report.pass = report.encoded > 50 && report.decodedEnergy > 10 && report.playbackEnergy > 10 && report.peak <= 1 && report.speaking.length === 3 && report.pttReleaseStopped && report.errors.length === 0;
|
||||
} catch (error) { report.errors.push(error.message); report.pass = false; }
|
||||
finally { oscillator?.stop(); worker?.terminate(); await context?.close(); }
|
||||
result.textContent = JSON.stringify(report, null, 2); event.target.disabled = false;
|
||||
};
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
// Unit-test adapter for the application worker. It does not open or automate a browser.
|
||||
import { parentPort } from 'node:worker_threads';
|
||||
globalThis.onmessage = null;
|
||||
globalThis.postMessage = (message, transfer = []) => parentPort.postMessage(message, transfer);
|
||||
globalThis.close = () => process.exit(0);
|
||||
await import('../../public/voice-worker.mjs');
|
||||
parentPort.on('message', data => { void globalThis.onmessage({ data }); });
|
||||
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
class PlaybackProbe extends AudioWorkletProcessor {
|
||||
constructor() { super(); this.count = 0; this.energy = 0; }
|
||||
process(inputs) {
|
||||
for (const value of inputs[0]?.[0] || []) { this.energy += value * value; this.count++; }
|
||||
if (this.count >= 4800) { this.port.postMessage({ samples: this.count, energy: this.energy }); this.count = 0; this.energy = 0; }
|
||||
return true; // Output remains silence.
|
||||
}
|
||||
}
|
||||
registerProcessor('playback-probe', PlaybackProbe);
|
||||
@@ -0,0 +1,56 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { createVault, openIdentity, sealIdentity } from '../src/identity/vault.mjs';
|
||||
import { createStore } from '../src/auth/store.mjs';
|
||||
import { resolveTeamSpeak } from '../src/transport/destination.mjs';
|
||||
|
||||
const key = () => randomBytes(32).toString('hex');
|
||||
const material = { identity: { key: 'sensitive-test-key', counter: 4, max_counter: 4 }, metadata: { uid: 'test-uid', level: 16 }, createdAt: '2026-10-30' };
|
||||
test('identity encryption authenticates ciphertext, nonce, key ID and key selection', () => {
|
||||
const config = { identityKey: key() };
|
||||
const ciphertext = sealIdentity(config, material);
|
||||
assert.doesNotMatch(ciphertext, /sensitive-test-key|test-uid/);
|
||||
assert.deepEqual(openIdentity(config, ciphertext), material);
|
||||
assert.notEqual(sealIdentity(config, material), ciphertext);
|
||||
for (const field of ['ciphertext', 'iv', 'tag', 'keyId']) {
|
||||
const tampered = JSON.parse(ciphertext);
|
||||
tampered[field] = `a${tampered[field].slice(1)}`;
|
||||
if (tampered[field] === JSON.parse(ciphertext)[field]) tampered[field] = `b${tampered[field].slice(1)}`;
|
||||
assert.throws(() => openIdentity(config, JSON.stringify(tampered)), /no identity was regenerated/);
|
||||
}
|
||||
assert.throws(() => openIdentity({ identityKey: key() }, ciphertext), /no identity was regenerated/);
|
||||
});
|
||||
test('durable identity is initialized once and survives session secret changes', async () => {
|
||||
const config = { identityKey: key(), memory: true };
|
||||
const store = createStore(config);
|
||||
const first = createVault(config, store);
|
||||
await first.initialize(material);
|
||||
await assert.rejects(first.initialize(material), /already exists/);
|
||||
const replacement = createVault({ ...config, secret: key() }, store);
|
||||
const loaded = await replacement.read();
|
||||
assert.deepEqual(loaded.identity, material.identity);
|
||||
await assert.rejects(replacement.update({ ...material, identity: { ...material.identity, key: 'changed-key' } }), /changed unexpectedly/);
|
||||
assert.deepEqual((await replacement.read()).identity, material.identity);
|
||||
});
|
||||
test('key rotation rewrites ciphertext and retains the same identity', async () => {
|
||||
const oldKey = key();
|
||||
const config = { identityKey: oldKey, memory: true };
|
||||
const store = createStore(config);
|
||||
await createVault(config, store).initialize(material);
|
||||
const nextConfig = { identityKey: key(), previousIdentityKey: oldKey };
|
||||
await createVault(nextConfig, store).rotate();
|
||||
assert.deepEqual((await createVault({ identityKey: nextConfig.identityKey }, store).read()).identity, material.identity);
|
||||
await assert.rejects(createVault(config, store).read(), /no identity was regenerated/);
|
||||
});
|
||||
test('a store read failure is never treated as a missing identity', async () => {
|
||||
const vault = createVault({ identityKey: key() }, { get: async () => { throw new Error('storage unavailable'); } });
|
||||
await assert.rejects(vault.read(), /storage unavailable/);
|
||||
});
|
||||
test('TeamSpeak resolution pins public addresses and rejects mixed/private DNS results', async () => {
|
||||
const config = { ts3Host: 'voice.example.test', ts3Port: 9987 };
|
||||
assert.equal((await resolveTeamSpeak(config, async () => ['1.1.1.1'])).address, '1.1.1.1:9987');
|
||||
for (const addresses of [[], ['127.0.0.1'], ['1.1.1.1', '169.254.169.254'], ['::ffff:127.0.0.1'], ['100.100.100.200']]) {
|
||||
await assert.rejects(resolveTeamSpeak(config, async () => addresses));
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { once } from 'node:events';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { identityOperation } from '../src/platform/native-protocol.mjs';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { mkdtemp, writeFile, symlink, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { WebSocket } from 'ws';
|
||||
import { readConfig } from '../src/config.mjs';
|
||||
import { createApp } from '../src/http-adapter.mjs';
|
||||
import { createStore } from '../src/auth/store.mjs';
|
||||
import { createAccounts } from '../src/auth/accounts.mjs';
|
||||
import { createUserContext } from '../src/auth/user-context.mjs';
|
||||
import { hashPassword } from '../src/auth/password.mjs';
|
||||
|
||||
const password = 'synthetic-multiuser-password';
|
||||
const ownerHash = await hashPassword(password);
|
||||
async function fixture(t) {
|
||||
const config = readConfig({ APP_ORIGIN: 'http://localhost:3000', OWNER_PASSWORD_HASH: ownerHash, SESSION_SECRET: randomBytes(32).toString('hex'), IDENTITY_ENCRYPTION_KEY: randomBytes(32).toString('hex'), ALLOW_LOCAL_MEMORY_STORE: '1' });
|
||||
const store = createStore(config); const app = createApp(config, store);
|
||||
app.server.listen(0, '127.0.0.1'); await once(app.server, 'listening');
|
||||
const origin = `http://127.0.0.1:${app.server.address().port}`; config.origin = origin;
|
||||
t.after(async () => { for (const ws of app.wss.clients) ws.terminate(); app.server.closeAllConnections(); await new Promise(resolve => app.server.close(resolve)); });
|
||||
const request = (path, options = {}) => fetch(origin + path, options);
|
||||
const post = (path, input, auth = {}, requestOrigin = origin) => request(path, { method: 'POST', headers: { 'Content-Type': 'application/json', Origin: requestOrigin, Cookie: auth.cookie || '', 'X-CSRF-Token': auth.csrf || '' }, body: JSON.stringify(input) });
|
||||
async function sign(username, register = true, previous) {
|
||||
const response = await post(register ? '/api/register' : '/api/login', { username, password }, previous);
|
||||
assert.equal(response.status, register ? 201 : 200); const data = await response.json();
|
||||
return { cookie: response.headers.get('set-cookie').split(';')[0], csrf: data.csrf, user: data.user };
|
||||
}
|
||||
const get = async (path, auth) => { const response = await request(path, { headers: { Cookie: auth.cookie } }); assert.equal(response.status, 200); return response.json(); };
|
||||
async function socket(auth) {
|
||||
const ws = new WebSocket(origin.replace('http:', 'ws:') + '/api/ts3', { headers: { Cookie: auth.cookie, Origin: origin } });
|
||||
ws.events = []; ws.on('message', data => ws.events.push(JSON.parse(data)));
|
||||
await once(ws, 'open'); return ws;
|
||||
}
|
||||
return { config, store, app, origin, request, post, sign, get, socket };
|
||||
}
|
||||
function event(ws, predicate) {
|
||||
const existing = ws.events.find(predicate); if (existing) return Promise.resolve(existing);
|
||||
return new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(() => { ws.off('message', handler); reject(new Error('Expected protocol event did not arrive')); }, 3000);
|
||||
function handler(data) { const value = JSON.parse(data); if (predicate(value)) { clearTimeout(timeout); ws.off('message', handler); resolve(value); } }
|
||||
ws.on('message', handler);
|
||||
});
|
||||
}
|
||||
const settings = nickname => ({ host: '1.1.1.1', port: 9987, nickname, password: 'synthetic-connection-password' });
|
||||
|
||||
test('registration has an origin gate and validation, and cannot replace the reserved owner or an existing account', async t => {
|
||||
const f = await fixture(t);
|
||||
assert.equal((await f.request('/api/auth')).status, 200);
|
||||
assert.equal((await f.post('/api/register', { username: 'alice', password }, {}, 'https://other.invalid')).status, 403);
|
||||
assert.equal((await f.post('/api/register', { username: '../alice', password })).status, 400);
|
||||
assert.equal((await f.post('/api/register', { username: 'alice', password: 'short' })).status, 400);
|
||||
const alice = await f.sign('alice'); assert.deepEqual(alice.user, { username: 'alice' });
|
||||
assert.equal((await f.post('/api/register', { username: 'ALICE', password })).status, 409);
|
||||
assert.equal((await f.post('/api/register', { username: 'owner', password })).status, 409);
|
||||
assert.equal((await f.get('/api/session', alice)).user.username, 'alice');
|
||||
f.config.registration = false;
|
||||
assert.equal((await (await f.request('/api/auth')).json()).registrationEnabled, false);
|
||||
assert.equal((await f.post('/api/register', { username: 'bob', password })).status, 403);
|
||||
await f.sign('alice', false); await f.sign('owner', false);
|
||||
});
|
||||
|
||||
test('HTTP settings and bookmarks belong to the session, ignore supplied account selectors, and survive a new sign-in', async t => {
|
||||
const f = await fixture(t); const alice = await f.sign('alice'); const bob = await f.sign('bob'); const owner = await f.sign('owner', false);
|
||||
assert.equal((await f.post('/api/connection', settings('Alice'), { ...alice, csrf: bob.csrf })).status, 403);
|
||||
const response = await f.post('/api/connection', { ...settings('Alice'), userId: 'owner', username: 'bob' }, alice);
|
||||
assert.equal(response.status, 200); const saved = await response.json();
|
||||
assert.equal(saved.connection.nickname, 'Alice'); assert.equal(JSON.stringify(saved).includes('synthetic-connection-password'), false);
|
||||
const pref = await f.get('/api/preferences', alice);
|
||||
const update = await f.post('/api/preferences', { ...pref, bookmarks: [{ id: 'alice-only', name: 'Alice bookmark', host: 'voice.example.test', port: 9987, nickname: 'Alice' }] }, alice);
|
||||
assert.equal(update.status, 200);
|
||||
for (const auth of [bob, owner]) { const result = await f.get('/api/preferences', auth); assert.equal(result.connection, null); assert.equal(result.bookmarks.length, 0); }
|
||||
const again = await f.sign('ALICE', false);
|
||||
const restored = await f.get('/api/preferences', again); assert.equal(restored.connection.id, saved.connection.id); assert.equal(restored.bookmarks[0].id, 'alice-only');
|
||||
assert.equal((await f.post('/api/preferences', { ...restored, userId: 'owner' }, bob)).status, 409);
|
||||
const a = await createAccounts(f.config, f.store).authenticate({ username: 'alice', password });
|
||||
const b = await createAccounts(f.config, f.store).authenticate({ username: 'bob', password });
|
||||
await createUserContext(f.config, f.store, a).vault.initialize({ identity: { key: 'synthetic-alice-key' }, metadata: { uid: 'synthetic-alice-uid', level: 8 } });
|
||||
await createUserContext(f.config, f.store, b).vault.initialize({ identity: { key: 'synthetic-bob-key' }, metadata: { uid: 'synthetic-bob-uid', level: 8 } });
|
||||
assert.equal((await f.get('/api/identity', alice)).identity.uid, 'synthetic-alice-uid'); assert.equal((await f.get('/api/identity', bob)).identity.uid, 'synthetic-bob-uid');
|
||||
assert.equal((await f.get('/api/identity', owner)).identity, null);
|
||||
assert.equal((await f.post('/api/identity/create', {}, bob)).status, 409);
|
||||
});
|
||||
|
||||
test('two users can hold simulated protocol sessions concurrently; cross-user connection IDs fail and logout is isolated', async t => {
|
||||
const f = await fixture(t); const alice = await f.sign('alice'); const bob = await f.sign('bob');
|
||||
const directory = await mkdtemp(join(tmpdir(), 'voxharbor-multiuser-')); await symlink(process.execPath, join(directory, 'node'));
|
||||
const binary = join(directory, 'native');
|
||||
await writeFile(binary, `#!${directory}/node\nconst readline=require('node:readline'); let first=true; (async()=>{for await(const line of readline.createInterface({input:process.stdin})){const input=JSON.parse(line);if(first){first=false;console.log(JSON.stringify({type:'status',status:'connected'}));}else if(input.op==='disconnect')break;}})();\n`, { mode: 0o700 });
|
||||
t.after(() => rm(directory, { recursive: true, force: true })); f.config.protocolBinary = binary;
|
||||
const accounts = createAccounts(f.config, f.store);
|
||||
for (const name of ['alice', 'bob']) {
|
||||
const principal = await accounts.authenticate({ username: name, password });
|
||||
await createUserContext(f.config, f.store, principal).vault.initialize({ identity: { key: `synthetic-${name}` }, metadata: { uid: `synthetic-${name}`, level: 8 } });
|
||||
}
|
||||
const a = await (await f.post('/api/connection', settings('Alice'), alice)).json(); const b = await (await f.post('/api/connection', settings('Bob'), bob)).json();
|
||||
const wrong = await f.socket(bob); const denied = event(wrong, value => value.type === 'ts3_error');
|
||||
wrong.send(JSON.stringify({ type: 'connect', csrf: bob.csrf, connectionId: a.connection.id }));
|
||||
assert.equal((await denied).code, 'connection_settings_changed');
|
||||
const aw = await f.socket(alice); const bw = await f.socket(bob);
|
||||
for (const [ws, auth, saved] of [[aw, alice, a], [bw, bob, b]]) {
|
||||
const connected = event(ws, value => value.type === 'ts3_status' && value.status === 'connected');
|
||||
ws.send(JSON.stringify({ type: 'connect', csrf: auth.csrf, connectionId: saved.connection.id })); await connected;
|
||||
}
|
||||
const duplicate = await f.socket(alice); const capacity = event(duplicate, value => value.type === 'ts3_error');
|
||||
duplicate.send(JSON.stringify({ type: 'connect', csrf: alice.csrf, connectionId: a.connection.id }));
|
||||
assert.equal((await capacity).code, 'another_session_is_active');
|
||||
const closed = once(aw, 'close'); assert.equal((await f.post('/api/logout', {}, alice)).status, 200); assert.equal((await closed)[0], 4401);
|
||||
const pong = event(bw, value => value.type === 'ts3_pong'); bw.send(JSON.stringify({ type: 'ping', csrf: bob.csrf, nonce: 10 })); assert.equal((await pong).nonce, 10);
|
||||
assert.equal((await f.request('/api/preferences', { headers: { Cookie: alice.cookie } })).status, 401);
|
||||
assert.equal((await f.get('/api/preferences', bob)).connection.nickname, 'Bob');
|
||||
});
|
||||
|
||||
test('replacing a browser login revokes the old session and socket without revoking another browser', async t => {
|
||||
const f = await fixture(t); const alice = await f.sign('alice'); const bob = await f.sign('bob');
|
||||
const ws = await f.socket(alice); const closed = once(ws, 'close');
|
||||
const replacement = await f.sign('bob', false, alice); assert.equal((await closed)[0], 4401);
|
||||
assert.equal((await f.request('/api/session', { headers: { Cookie: alice.cookie } })).status, 401);
|
||||
assert.equal((await f.get('/api/session', replacement)).user.username, 'bob'); assert.equal((await f.get('/api/session', bob)).user.username, 'bob');
|
||||
});
|
||||
|
||||
|
||||
const nativePath = fileURLToPath(new URL('../native/bin/voxharbor-protocol', import.meta.url));
|
||||
test('registered users generate different real native identities and export only their own identity', { skip: !existsSync(nativePath) }, async t => {
|
||||
const f = await fixture(t); f.config.protocolBinary = nativePath;
|
||||
const alice = await f.sign('alice'); const bob = await f.sign('bob');
|
||||
const identities = [];
|
||||
for (const auth of [alice, bob]) {
|
||||
const created = await f.post('/api/identity/create', {}, auth); assert.equal(created.status, 201);
|
||||
const result = await created.json(); assert.equal(Object.hasOwn(result.identity, 'key'), false); identities.push(result.identity);
|
||||
}
|
||||
assert.notEqual(identities[0].uid, identities[1].uid);
|
||||
const exports = [];
|
||||
for (const [i, auth] of [alice, bob].entries()) {
|
||||
const response = await f.post('/api/identity/export', { username: i === 0 ? 'bob' : 'alice' }, auth); assert.equal(response.status, 200);
|
||||
const exported = await response.text(); const value = exported.match(/^identity="([^"\r\n]+)"/m)[1];
|
||||
const restored = await identityOperation(f.config, { op: 'import', value }); assert.equal(restored.metadata.uid, identities[i].uid); exports.push(exported);
|
||||
}
|
||||
assert.notEqual(exports[0], exports[1]);
|
||||
await f.post('/api/logout', {}, alice); const again = await f.sign('alice', false);
|
||||
assert.equal((await f.get('/api/identity', again)).identity.uid, identities[0].uid);
|
||||
assert.equal((await f.get('/api/identity', bob)).identity.uid, identities[1].uid);
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtemp, writeFile, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { spawnProtocol } from '../src/platform/native-protocol.mjs';
|
||||
|
||||
for (const event of [{ type: 'status', status: 'disconnected' }, { type: 'error', code: 'connection_failed' }]) {
|
||||
test(`terminal native ${event.type} delivers stdin EOF so the child and lease can finish`, async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), 'voxharbor-shutdown-'));
|
||||
const executable = join(directory, 'protocol');
|
||||
// Reproduce a reader still waiting on stdin after its terminal status.
|
||||
await writeFile(executable, `#!/bin/sh\nread -r request\nprintf '%s\\n' '${JSON.stringify(event)}'\ncat >/dev/null\n`, { mode: 0o700 });
|
||||
let timeout;
|
||||
let native;
|
||||
try {
|
||||
const events = [];
|
||||
native = spawnProtocol({ protocolBinary: executable }, { op: 'connect', seconds: 20 }, event => events.push(event));
|
||||
await Promise.race([native.done, new Promise((_, reject) => { timeout = setTimeout(() => reject(new Error('Terminal child did not exit promptly')), 2000); })]);
|
||||
assert.deepEqual(events, [event]);
|
||||
} finally {
|
||||
clearTimeout(timeout); native?.stop(); await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtemp, readFile, writeFile, stat, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { saveLocalOwner, updateOwnerConfig } from '../scripts/local-owner-config.mjs';
|
||||
|
||||
const hash = `scrypt:${'a'.repeat(32)}:${'b'.repeat(128)}`;
|
||||
test('owner setup replaces duplicate assignments and preserves unrelated settings', () => {
|
||||
const result = updateOwnerConfig('APP_ORIGIN=http://localhost:4000\n# Keep this comment\nOWNER_PASSWORD_HASH=\nexport OWNER_PASSWORD_HASH=old\nSESSION_SECRET=old\nOTHER_PRIVATE_SETTING=45987\n', hash, 'c'.repeat(64));
|
||||
assert.equal(result.match(/^OWNER_PASSWORD_HASH=/gm).length, 1);
|
||||
assert.match(result, /APP_ORIGIN=http:\/\/localhost:4000/);
|
||||
assert.match(result, /# Keep this comment/);
|
||||
assert.match(result, /OTHER_PRIVATE_SETTING=45987/);
|
||||
assert.doesNotMatch(result, /old/);
|
||||
assert.throws(() => updateOwnerConfig('', 'password', 'c'.repeat(64)), /Invalid/);
|
||||
});
|
||||
test('owner setup initializes a private env file and rotates the secret on replacement', async t => {
|
||||
const directory = await mkdtemp(join(tmpdir(), 'voxharbor-owner-'));
|
||||
t.after(() => rm(directory, { recursive: true, force: true }));
|
||||
const root = pathToFileURL(`${directory}/`);
|
||||
await writeFile(new URL('.env.example', root), 'APP_ORIGIN=http://localhost:3000\nOWNER_PASSWORD_HASH=\nSESSION_SECRET=\n');
|
||||
await saveLocalOwner(hash, root);
|
||||
const first = await readFile(new URL('.env.local', root), 'utf8');
|
||||
assert.ok(first.includes(hash));
|
||||
assert.match(first, /^SESSION_SECRET=[a-f0-9]{64}$/m);
|
||||
assert.equal((await stat(new URL('.env.local', root))).mode & 0o777, 0o600);
|
||||
await saveLocalOwner(hash, root);
|
||||
assert.notEqual(await readFile(new URL('.env.local', root), 'utf8'), first);
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { createPreferences, destinationOptions } from '../src/preferences.mjs';
|
||||
import { createStore } from '../src/auth/store.mjs';
|
||||
|
||||
const fixture = () => ({ config: { identityKey: randomBytes(32).toString('hex') }, store: createStore({ memory: true }) });
|
||||
const input = revision => ({ revision, theme: 'dark', nickname: 'Owner', bookmarks: [{ id: 'fixture', name: 'Test server', host: 'ts.example.com', port: 9987, nickname: 'Owner', channelId: 411, password: 'fixture-server-password', channelPassword: 'fixture-channel-password' }] });
|
||||
|
||||
test('saved connections survive a new preferences instance and never expose passwords in metadata', async () => {
|
||||
const { config, store } = fixture(); const vault = createPreferences(config, store);
|
||||
const saved = await vault.save(input((await vault.read()).revision));
|
||||
assert.equal(saved.bookmarks[0].hasPassword, true); assert.equal(saved.bookmarks[0].hasChannelPassword, true);
|
||||
assert.equal(JSON.stringify(saved).includes('fixture-channel-password'), false);
|
||||
assert.equal(JSON.stringify(saved).includes('fixture-server-password'), false);
|
||||
const ciphertext = await store.get('voxharbor:preferences:v1:owner');
|
||||
assert.equal(ciphertext.includes('fixture-channel-password'), false); assert.equal(ciphertext.includes('ts.example.com'), false);
|
||||
const restarted = createPreferences(config, store);
|
||||
assert.deepEqual(await restarted.read(), saved);
|
||||
assert.equal((await restarted.connection('fixture')).channelPassword, 'fixture-channel-password');
|
||||
await assert.rejects(restarted.connection('missing'), error => error.status === 404);
|
||||
});
|
||||
|
||||
test('metadata edits preserve stored secrets, explicit clearing removes them, and stale writes fail', async () => {
|
||||
const { config, store } = fixture(); const vault = createPreferences(config, store);
|
||||
const saved = await vault.save(input('empty')); const edited = await vault.save({ ...saved, nickname: 'Renamed' });
|
||||
assert.equal((await vault.connection('fixture')).password, 'fixture-server-password');
|
||||
await assert.rejects(vault.save(saved), error => error.status === 409);
|
||||
const cleared = await vault.save({ ...edited, bookmarks: edited.bookmarks.map(bookmark => ({ ...bookmark, password: '', channelPassword: '' })) });
|
||||
assert.equal(cleared.bookmarks[0].hasPassword, false); assert.equal((await vault.connection('fixture')).channelPassword, '');
|
||||
});
|
||||
|
||||
test('wrong keys and tampering fail closed without resetting saved connections', async () => {
|
||||
const { config, store } = fixture(); const vault = createPreferences(config, store); await vault.save(input('empty'));
|
||||
const original = await store.get('voxharbor:preferences:v1:owner');
|
||||
const wrong = createPreferences({ identityKey: randomBytes(32).toString('hex') }, store);
|
||||
await assert.rejects(wrong.read(), /could not be decrypted/); await assert.rejects(wrong.save(input('empty')), /could not be decrypted/);
|
||||
assert.equal(await store.get('voxharbor:preferences:v1:owner'), original);
|
||||
const envelope = JSON.parse(original); envelope.tag = Buffer.alloc(16).toString('base64');
|
||||
await store.compareSet('voxharbor:preferences:v1:owner', original, JSON.stringify(envelope));
|
||||
await assert.rejects(vault.read(), /could not be decrypted/);
|
||||
});
|
||||
|
||||
test('preferences can be rewrapped with the previous key without replacing identity data', async () => {
|
||||
const { config, store } = fixture(); const vault = createPreferences(config, store); await vault.save(input('empty'));
|
||||
await store.putIfAbsent('voxharbor:identity:v1:owner', 'untouched-fixture-identity');
|
||||
const newKey = randomBytes(32).toString('hex');
|
||||
await createPreferences({ identityKey: newKey, previousIdentityKey: config.identityKey }, store).rotate();
|
||||
assert.equal((await createPreferences({ identityKey: newKey }, store).connection('fixture')).password, 'fixture-server-password');
|
||||
assert.equal(await store.get('voxharbor:identity:v1:owner'), 'untouched-fixture-identity');
|
||||
});
|
||||
|
||||
test('saved connection inputs are bounded and destinations are normalized without resolving them', async () => {
|
||||
const { config, store } = fixture(); const vault = createPreferences(config, store);
|
||||
for (const options of [{ host: 'http://example.com', port: 9987 }, { host: 'example.com', port: 80 }, { host: 'example.com', port: 65536 }, { host: 'example.com', port: '9987' }]) assert.throws(() => destinationOptions(options));
|
||||
assert.deepEqual(destinationOptions({ host: 'TS.Example.com', port: 9987 }), { host: 'ts.example.com', port: 9987 });
|
||||
await assert.rejects(vault.save({ ...input('empty'), bookmarks: [...input('empty').bookmarks, ...input('empty').bookmarks] }), /Invalid saved connection/);
|
||||
await assert.rejects(vault.save({ ...input('empty'), theme: 'anything' }), /Invalid workspace/);
|
||||
});
|
||||
|
||||
test('current connection credentials stay encrypted and survive reload without metadata disclosure', async () => {
|
||||
const { config, store } = fixture(); const vault = createPreferences(config, store);
|
||||
const saved = await vault.saveConnection({ host: 'voice.example.test', port: 9987, nickname: 'Owner', channelId: 12, password: 'fixture-server-secret', channelPassword: 'fixture-channel-secret' });
|
||||
assert.equal(saved.connection.hasPassword, true); assert.equal(saved.connection.hasChannelPassword, true);
|
||||
assert.equal(JSON.stringify(saved).includes('fixture-server-secret'), false); assert.equal(JSON.stringify(saved).includes('fixture-channel-secret'), false);
|
||||
assert.equal((await store.get('voxharbor:preferences:v1:owner')).includes('fixture-server-secret'), false);
|
||||
const restarted = createPreferences(config, store);
|
||||
assert.equal((await restarted.activeConnection(saved.connection.id)).channelPassword, 'fixture-channel-secret');
|
||||
await assert.rejects(restarted.activeConnection('a'.repeat(32)), error => error.code === 'connection_settings_changed');
|
||||
const edited = await restarted.save({ ...saved, theme: 'light' });
|
||||
assert.equal((await restarted.activeConnection(edited.connection.id)).password, 'fixture-server-secret');
|
||||
});
|
||||
|
||||
test('passwords are preserved only for the same destination and channel and can be cleared explicitly', async () => {
|
||||
const { config, store } = fixture(); const vault = createPreferences(config, store);
|
||||
const base = { host: 'one.example.test', port: 9987, nickname: 'Owner', channelId: 12 };
|
||||
await vault.saveConnection({ ...base, password: 'server-fixture-secret', channelPassword: 'channel-fixture-secret' });
|
||||
let result = await vault.saveConnection(base);
|
||||
assert.equal((await vault.activeConnection(result.connection.id)).password, 'server-fixture-secret');
|
||||
result = await vault.saveConnection({ ...base, channelId: 13 });
|
||||
let connection = await vault.activeConnection(result.connection.id);
|
||||
assert.equal(connection.password, 'server-fixture-secret'); assert.equal(connection.channelPassword, '');
|
||||
result = await vault.saveConnection({ ...base, host: 'two.example.test' });
|
||||
connection = await vault.activeConnection(result.connection.id); assert.equal(connection.password, ''); assert.equal(connection.channelPassword, '');
|
||||
await vault.saveConnection({ ...base, password: 'server-fixture-secret' });
|
||||
result = await vault.saveConnection({ ...base, password: '', channelPassword: '' });
|
||||
assert.equal((await vault.activeConnection(result.connection.id)).password, '');
|
||||
});
|
||||
|
||||
test('bookmark credentials are selected on the backend and cannot follow an edited host', async () => {
|
||||
const { config, store } = fixture(); const vault = createPreferences(config, store); await vault.save(input('empty'));
|
||||
const bookmark = { bookmarkId: 'fixture', host: 'ts.example.com', port: 9987, nickname: 'Owner', channelId: 411 };
|
||||
let result = await vault.saveConnection(bookmark);
|
||||
assert.equal((await vault.activeConnection(result.connection.id)).password, 'fixture-server-password');
|
||||
result = await vault.saveConnection({ ...bookmark, host: 'different.example.test' });
|
||||
const connection = await vault.activeConnection(result.connection.id); assert.equal(connection.password, ''); assert.equal(connection.channelPassword, '');
|
||||
await assert.rejects(vault.saveConnection({ ...bookmark, bookmarkId: 'missing' }), error => error.status === 404);
|
||||
});
|
||||
|
||||
test('acknowledged connection changes preserve bookmarks, IDs and secrets without reviving stale settings', async () => {
|
||||
const { config, store } = fixture(); const vault = createPreferences(config, store); await vault.save(input('empty'));
|
||||
const initial = await vault.saveConnection({ host: 'voice.example.test', port: 9987, nickname: 'Owner', password: 'fixture-secret', channelId: 12 });
|
||||
const id = initial.connection.id;
|
||||
const changed = await vault.updateConnection(id, { channelId: 13, channelPassword: 'fixture-channel-secret' });
|
||||
assert.equal(changed.connection.id, id); assert.equal(changed.bookmarks.length, 1);
|
||||
assert.equal((await vault.activeConnection(id)).password, 'fixture-secret');
|
||||
await vault.saveConnection({ host: 'new.example.test', port: 9987, nickname: 'New' });
|
||||
assert.equal(await vault.updateConnection(id, { nickname: 'Stale' }), false);
|
||||
});
|
||||
|
||||
|
||||
test('editing a bookmark destination never carries credentials to another server or channel', async () => {
|
||||
const { config, store } = fixture(); const vault = createPreferences(config, store);
|
||||
let saved = await vault.save(input('empty'));
|
||||
saved = await vault.save({ ...saved, bookmarks: saved.bookmarks.map(bookmark => ({ ...bookmark, channelId: 12 })) });
|
||||
let bookmark = await vault.connection('fixture');
|
||||
assert.equal(bookmark.password, 'fixture-server-password'); assert.equal(bookmark.channelPassword, '');
|
||||
await vault.save({ ...saved, bookmarks: saved.bookmarks.map(bookmark => ({ ...bookmark, host: 'other.example.test' })) });
|
||||
bookmark = await vault.connection('fixture');
|
||||
assert.equal(bookmark.password, ''); assert.equal(bookmark.channelPassword, '');
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtemp, writeFile, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { setTimeout as sleep } from 'node:timers/promises';
|
||||
import { createProtocolControl } from '../src/protocol/session.mjs';
|
||||
|
||||
test('an unresponsive owner transport stops its native child and releases the lease', async t => {
|
||||
const directory = await mkdtemp(join(tmpdir(), 'voxharbor-owner-liveness-'));
|
||||
const binary = join(directory, 'protocol');
|
||||
await writeFile(binary, `#!/bin/sh\nread -r request\nprintf '%s\\n' '{"type":"status","status":"connected"}'\ncat >/dev/null\n`, { mode: 0o700 });
|
||||
t.after(() => rm(directory, { recursive: true, force: true }));
|
||||
t.mock.timers.enable({ apis: ['setInterval'] });
|
||||
const actualNow = Date.now; let offset = 0; Date.now = () => actualNow() + offset;
|
||||
t.after(() => { Date.now = actualNow; });
|
||||
const events = []; const closes = []; let released = 0;
|
||||
const ws = { readyState: 1, bufferedAmount: 0, send: data => events.push(JSON.parse(data)) };
|
||||
const control = createProtocolControl(ws, {
|
||||
config: { protocolBinary: binary, ts3Host: '1.1.1.1', ts3Port: 9987 },
|
||||
// No real network or Redis: this executable reads stdin and writes status only.
|
||||
store: { limit: async () => true, putIfAbsent: async () => true, compareSet: async () => true, compareDelete: async () => { released++; return true; } },
|
||||
preferences: { activeConnection: async () => ({ id: 'c'.repeat(32), host: '1.1.1.1', port: 9987, nickname: 'Fixture' }) }, vault: { read: async () => ({ identity: {} }) }, csrf: 'fixture-csrf',
|
||||
close: code => { if (ws.readyState === 1) { closes.push(code); ws.readyState = 3; } },
|
||||
});
|
||||
t.after(() => control.stop());
|
||||
await control.command(Buffer.from(JSON.stringify({ type: 'connect', csrf: 'fixture-csrf', connectionId: 'c'.repeat(32), heartbeat: true })));
|
||||
for (let i = 0; i < 100 && !events.some(event => event.status === 'connected'); i++) await sleep(10);
|
||||
assert.ok(events.some(event => event.status === 'connected'));
|
||||
offset = 40000; t.mock.timers.tick(10000);
|
||||
for (let i = 0; i < 100 && !released; i++) await sleep(10);
|
||||
assert.ok(events.some(event => event.code === 'owner_transport_timeout'));
|
||||
assert.deepEqual(closes, [4000]); assert.equal(released, 1);
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { ProtocolConnection } from '../public/protocol-connection.mjs';
|
||||
|
||||
const settle = async () => { for (let i = 0; i < 5; i++) await Promise.resolve(); };
|
||||
function fixture({ session = async () => ({ csrf: 'fixture-csrf' }) } = {}) {
|
||||
let time = 0; let next = 0; let checks = 0; let expired = 0; let muted = 0;
|
||||
const timers = new Map(); const sockets = []; const phases = []; const diagnostics = [];
|
||||
class Socket extends EventTarget {
|
||||
constructor() { super(); this.readyState = 0; this.bufferedAmount = 0; this.sent = []; this.autoClose = true; this.autoPong = true; }
|
||||
open() { this.readyState = 1; this.dispatchEvent(new Event('open')); }
|
||||
message(message) { this.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(message) })); }
|
||||
send(data) {
|
||||
this.sent.push(data);
|
||||
if (typeof data === 'string') { const input = JSON.parse(data); if (input.type === 'ping' && this.autoPong) this.message({ type: 'ts3_pong', nonce: input.nonce }); }
|
||||
}
|
||||
close(code = 1000) { this.readyState = this.autoClose ? 3 : 2; if (this.autoClose) this.dispatchEvent(Object.assign(new Event('close'), { code })); }
|
||||
healthy() { this.open(); this.message({ type: 'ts3_status', status: 'connected' }); this.message({ type: 'ts3_state', channels: [], participants: [] }); }
|
||||
}
|
||||
const connection = new ProtocolConnection({ url: 'wss://fixture.invalid/api/ts3', session: async options => { checks++; return session(options); },
|
||||
socket: () => { const socket = new Socket(); sockets.push(socket); return socket; },
|
||||
diagnostic: event => diagnostics.push(event), phase: phase => phases.push(phase), disconnected: () => { muted++; }, expired: () => { expired++; },
|
||||
now: () => time, random: () => 0,
|
||||
later: (fn, delay) => { const id = ++next; timers.set(id, { fn, at: time + delay }); return id; }, cancel: id => timers.delete(id),
|
||||
});
|
||||
async function tick(ms) {
|
||||
const target = time + ms;
|
||||
while (true) {
|
||||
const entry = [...timers].filter(([, item]) => item.at <= target).sort((a, b) => a[1].at - b[1].at)[0];
|
||||
if (!entry) break;
|
||||
time = entry[1].at; timers.delete(entry[0]); entry[1].fn(); await settle();
|
||||
}
|
||||
time = target; await settle();
|
||||
}
|
||||
async function start() { connection.start({ connectionId: 'c'.repeat(32) }); await settle(); return sockets.at(-1); }
|
||||
return { connection, sockets, phases, diagnostics, tick, start, timers, checks: () => checks, expired: () => expired, muted: () => muted };
|
||||
}
|
||||
|
||||
test('protocol cap reconnects with a fresh session check and a backend settings reference, audio stays gated', async () => {
|
||||
const f = fixture(); const first = await f.start(); first.healthy();
|
||||
assert.equal(f.connection.voice(new Uint8Array([1])), true);
|
||||
await f.tick(240000);
|
||||
first.message({ type: 'ts3_status', status: 'session_limit' }); first.close();
|
||||
assert.equal(f.connection.connected, false); assert.equal(f.connection.voice(new Uint8Array([2])), false);
|
||||
await f.tick(1000); assert.equal(f.sockets.length, 2); assert.equal(f.checks(), 2);
|
||||
const second = f.sockets[1]; second.open();
|
||||
const request = JSON.parse(second.sent[0]); assert.equal(request.connectionId, 'c'.repeat(32)); assert.equal('password' in request, false); assert.equal('destination' in request, false);
|
||||
assert.equal(second.sent.some(data => typeof data !== 'string'), false);
|
||||
second.message({ type: 'ts3_status', status: 'connected' });
|
||||
assert.ok(f.muted() >= 3); assert.equal(f.connection.desired, true);
|
||||
f.connection.stop(); assert.equal(f.connection.options, undefined); assert.equal(f.timers.size, 0);
|
||||
});
|
||||
|
||||
test('unexpected socket loss retries below the connection rate gate and ignores stale events', async () => {
|
||||
const f = fixture(); const first = await f.start(); first.open(); first.close(1006);
|
||||
await f.tick(11999); assert.equal(f.sockets.length, 1);
|
||||
await f.tick(1); assert.equal(f.sockets.length, 2);
|
||||
first.message({ type: 'ts3_status', status: 'connected' }); assert.equal(f.connection.connected, false);
|
||||
f.sockets[1].healthy(); assert.equal(f.connection.connected, true); f.connection.stop();
|
||||
});
|
||||
|
||||
test('missing heartbeat abandons a stuck closing socket and reconnects', async () => {
|
||||
const f = fixture(); const socket = await f.start(); socket.autoPong = false; socket.autoClose = false; socket.healthy();
|
||||
await f.tick(29999); assert.equal(f.connection.connected, true);
|
||||
await f.tick(1); assert.equal(f.connection.connected, false); assert.equal(socket.readyState, 2);
|
||||
await f.tick(2000); assert.equal(f.sockets.length, 2); f.connection.stop();
|
||||
});
|
||||
|
||||
test('healthy heartbeats avoid reconnecting an otherwise quiet server', async () => {
|
||||
const f = fixture(); (await f.start()).healthy(); await f.tick(180000);
|
||||
assert.equal(f.sockets.length, 1); assert.equal(f.connection.connected, true); f.connection.stop();
|
||||
});
|
||||
|
||||
test('protocol handshake watchdog bounds an open but nonresponsive transport', async () => {
|
||||
const f = fixture(); (await f.start()).open(); await f.tick(45000);
|
||||
assert.equal(f.connection.connected, false); assert.ok(f.phases.some(p => p.state === 'retrying')); f.connection.stop();
|
||||
});
|
||||
|
||||
test('expired authentication stops recovery, clears credentials and requests sign-in', async () => {
|
||||
const f = fixture({ session: async () => { throw Object.assign(new Error('expired'), { status: 401 }); } });
|
||||
await f.start(); await f.tick(120000); assert.equal(f.sockets.length, 0); assert.equal(f.checks(), 1);
|
||||
assert.equal(f.expired(), 1); assert.equal(f.connection.options, undefined); assert.equal(f.connection.desired, false);
|
||||
});
|
||||
|
||||
test('revocation on an active socket stops without another connection attempt', async () => {
|
||||
const f = fixture(); const socket = await f.start(); socket.healthy(); socket.close(4401); await f.tick(120000);
|
||||
assert.equal(f.expired(), 1); assert.equal(f.sockets.length, 1); assert.equal(f.connection.options, undefined);
|
||||
});
|
||||
|
||||
test('disconnect during a pending authentication check cannot open a late socket', async () => {
|
||||
let resolve; const f = fixture({ session: () => new Promise(done => { resolve = done; }) });
|
||||
await f.start(); f.connection.stop(); resolve({ csrf: 'late' }); await settle();
|
||||
assert.equal(f.sockets.length, 0); assert.equal(f.connection.desired, false);
|
||||
});
|
||||
|
||||
test('manual stop cancels scheduled recovery and network restoration cannot restart it', async () => {
|
||||
const f = fixture(); const socket = await f.start(); socket.open(); socket.close(1006);
|
||||
f.connection.stop(); f.connection.online(); await f.tick(120000); assert.equal(f.sockets.length, 1);
|
||||
});
|
||||
|
||||
test('offline pauses retries, online resumes, and a new owner request clears offline state', async () => {
|
||||
const f = fixture(); (await f.start()).healthy(); f.connection.offline(); await f.tick(120000);
|
||||
assert.equal(f.sockets.length, 1); assert.equal(f.connection.voice(new Uint8Array()), false);
|
||||
f.connection.online(); await f.tick(1000); assert.equal(f.sockets.length, 2);
|
||||
f.connection.offline(); f.connection.stop(); await f.start(); assert.equal(f.sockets.length, 3); f.connection.stop();
|
||||
});
|
||||
|
||||
test('server rejection and packet authentication failures require owner action', async () => {
|
||||
for (const code of ['server_rejected_connection', 'packet_authentication_failed', 'identity_storage_or_destination_error']) {
|
||||
const f = fixture(); const socket = await f.start(); socket.open(); socket.message({ type: 'ts3_error', code }); await f.tick(120000);
|
||||
assert.equal(f.sockets.length, 1); assert.equal(f.connection.desired, false); assert.equal(f.connection.options, undefined);
|
||||
assert.ok(f.phases.some(p => p.state === 'failed' && p.code === code));
|
||||
}
|
||||
});
|
||||
|
||||
test('repeated failures stop after five handshakes instead of retrying indefinitely', async () => {
|
||||
const f = fixture(); await f.start();
|
||||
for (let i = 0; i < 5; i++) { f.sockets.at(-1).open(); f.sockets.at(-1).close(1006); await f.tick(30000); }
|
||||
await f.tick(120000); assert.equal(f.sockets.length, 5); assert.equal(f.connection.desired, false);
|
||||
});
|
||||
|
||||
test('an abandoned native lease waits its expiry before a new handshake', async () => {
|
||||
const f = fixture(); const socket = await f.start(); socket.open(); socket.message({ type: 'ts3_error', code: 'another_session_is_active' }); socket.close(1011);
|
||||
await f.tick(35999); assert.equal(f.sockets.length, 1); await f.tick(1); assert.equal(f.sockets.length, 2); f.connection.stop();
|
||||
});
|
||||
|
||||
test('a stalled authentication request times out and manual stop aborts the next request', async () => {
|
||||
const signals = []; const f = fixture({ session: ({ signal }) => { signals.push(signal); return new Promise(() => {}); } });
|
||||
await f.start(); await f.tick(15000); assert.equal(signals[0].aborted, true);
|
||||
assert.ok(f.phases.some(p => p.state === 'retrying')); await f.tick(2000);
|
||||
assert.equal(signals.length, 2); f.connection.stop(); assert.equal(signals[1].aborted, true); assert.equal(f.timers.size, 0);
|
||||
});
|
||||
|
||||
test('diagnostics distinguish session cap, socket close, heartbeat timeout and retry timing', async () => {
|
||||
const f = fixture(); const socket = await f.start(); socket.healthy();
|
||||
await f.tick(10000);
|
||||
assert.ok(f.diagnostics.some(e => e.type === 'heartbeat' && e.roundTripMs === 0));
|
||||
socket.message({ type: 'ts3_status', status: 'session_limit' }); socket.close(1000);
|
||||
assert.ok(f.diagnostics.some(e => e.type === 'protocol_status' && e.stage === 'session_limit'));
|
||||
assert.ok(f.diagnostics.some(e => e.type === 'transport_closed' && e.durationMs === 10000 && e.closeCode === 1000));
|
||||
assert.ok(f.diagnostics.some(e => e.type === 'retry' && e.delay >= 1000));
|
||||
f.connection.stop();
|
||||
const g = fixture(); const dead = await g.start(); dead.autoPong = false; dead.healthy(); await g.tick(30000);
|
||||
assert.ok(g.diagnostics.some(e => e.type === 'timeout' && e.stage === 'heartbeat'));
|
||||
g.connection.stop();
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { inspectContent } from '../scripts/publication-audit.mjs';
|
||||
import { privatePath } from '../scripts/source-files.mjs';
|
||||
|
||||
test('publication excludes private data paths while allowing the blank environment template', () => {
|
||||
for (const path of ['.env.local', '.local/identity.enc.json', '.idea/workspace.xml', 'native/bin/client', 'native/target/release/client', 'docs/verification/screenshot.jpg', 'identity.ini', 'backup.pem']) assert.equal(privatePath(path), true, path);
|
||||
for (const path of ['.env.example', 'src/preferences.mjs', 'native/Cargo.lock', 'LICENSE']) assert.equal(privatePath(path), false, path);
|
||||
});
|
||||
|
||||
test('publication scans exact and encoded private values without returning their contents', () => {
|
||||
const secret = 'synthetic-private-test-value-123';
|
||||
for (const content of [secret, Buffer.from(secret).toString('base64'), encodeURIComponent(secret)]) {
|
||||
const findings = inspectContent('src/accidental-copy.mjs', Buffer.from(content), [secret]);
|
||||
assert.ok(findings.some(item => item.rule === 'local-private-value'));
|
||||
assert.equal(JSON.stringify(findings).includes(secret), false);
|
||||
}
|
||||
});
|
||||
|
||||
test('publication detects credential formats and personal paths in ordinary source', () => {
|
||||
const privateKey = ['-----BEGIN', 'PRIVATE KEY-----'].join(' ');
|
||||
for (const [value, rule] of [[privateKey, 'private-key'], ['ghp_' + 'a'.repeat(36), 'credential-format'], ['scrypt:' + 'a'.repeat(32) + ':' + 'b'.repeat(128), 'password-hash'], ['/Users' + '/fixture-person/project/file', 'personal-filesystem-path']]) assert.ok(inspectContent('src/leak.mjs', Buffer.from(value)).some(item => item.rule === rule));
|
||||
// A named vendor path alone is not an exemption for a modified codec artifact.
|
||||
assert.ok(inspectContent('public/vendor/opus/generated/libopus.generated.mjs', Buffer.from('/Users' + '/fixture-person/project/file')).some(item => item.rule === 'personal-filesystem-path'));
|
||||
});
|
||||
@@ -0,0 +1,320 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { once } from 'node:events';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { WebSocket } from 'ws';
|
||||
import { hashPassword } from '../src/auth/password.mjs';
|
||||
import { readConfig } from '../src/config.mjs';
|
||||
import { createStore } from '../src/auth/store.mjs';
|
||||
import { createApp } from '../src/http-adapter.mjs';
|
||||
|
||||
const password = 'test-only-owner-password';
|
||||
const passwordHash = await hashPassword(password);
|
||||
function env() {
|
||||
return { APP_ORIGIN: 'http://localhost:3000', OWNER_PASSWORD_HASH: passwordHash, SESSION_SECRET: randomBytes(32).toString('hex'), ALLOW_LOCAL_MEMORY_STORE: '1' };
|
||||
}
|
||||
test('deployment fails closed without secure configuration and durable storage', () => {
|
||||
assert.throws(() => readConfig({ ...env(), VERCEL: '1' }), /HTTPS/);
|
||||
assert.throws(() => readConfig({ ...env(), APP_ORIGIN: 'https://example.com', VERCEL: '1' }), /Redis/);
|
||||
assert.throws(() => readConfig({ ...env(), SESSION_SECRET: 'weak' }), /SESSION_SECRET/);
|
||||
assert.throws(() => readConfig({ ...env(), APP_ORIGIN: 'http://localhost:3000/' }), /exact origin/);
|
||||
});
|
||||
|
||||
test('browser audio assets load under a CSP allowing WASM without inline scripts', async t => {
|
||||
const f = await fixture(t);
|
||||
const response = await f.request('/voice-worker.mjs');
|
||||
assert.equal(response.status, 200);
|
||||
assert.match(response.headers.get('content-security-policy'), /'wasm-unsafe-eval'/);
|
||||
assert.match(response.headers.get('content-security-policy'), /font-src 'self'; img-src 'self'/);
|
||||
assert.doesNotMatch(response.headers.get('content-security-policy'), /'unsafe-inline'|'unsafe-eval'/);
|
||||
for (const path of ['/workspace-model.mjs', '/fonts/ibm-plex-sans-regular.ttf', '/fonts/ibm-plex-sans-medium.ttf', '/fonts/ibm-plex-sans-semibold.ttf', '/fonts/ibm-plex-mono-regular.ttf', '/fonts/ibm-plex-mono-medium.ttf', '/fonts/OFL.txt', '/icons/microphone.svg', '/icons/headphones.svg', '/audio-recovery.mjs', '/connection-diagnostics.mjs', '/voice-worklet.mjs', '/voice-frame.mjs', '/jitter-buffer.mjs', '/vendor/opus/index.js', '/vendor/opus/generated/libopus.generated.mjs']) assert.equal((await f.request(path)).status, 200);
|
||||
});
|
||||
|
||||
test('app icons and manifest are public, valid images allowed by the content policy', async t => {
|
||||
const f = await fixture(t);
|
||||
const shell = await f.request('/');
|
||||
const html = await shell.text();
|
||||
assert.match(html, /rel="manifest" href="\/site\.webmanifest"/);
|
||||
assert.match(html, /rel="apple-touch-icon"/);
|
||||
assert.match(shell.headers.get('content-security-policy'), /manifest-src 'self'/);
|
||||
const response = await f.request('/site.webmanifest');
|
||||
assert.equal(response.status, 200);
|
||||
assert.match(response.headers.get('content-type'), /application\/manifest\+json/);
|
||||
const manifest = await response.json();
|
||||
assert.equal(manifest.start_url, '/');
|
||||
assert.ok(manifest.icons.some(icon => icon.purpose === 'maskable'));
|
||||
for (const [path, size] of [['/favicon-16x16.png', 16], ['/favicon-32x32.png', 32], ['/apple-touch-icon.png', 180], ...manifest.icons.map(icon => [icon.src, Number(icon.sizes.split('x')[0])])]) {
|
||||
const image = await f.request(path); assert.equal(image.status, 200, path);
|
||||
assert.match(image.headers.get('content-type'), /image\/png/);
|
||||
const bytes = Buffer.from(await image.arrayBuffer());
|
||||
assert.deepEqual([...bytes.subarray(0, 8)], [137,80,78,71,13,10,26,10]);
|
||||
assert.equal(bytes.readUInt32BE(16), size); assert.equal(bytes.readUInt32BE(20), size);
|
||||
}
|
||||
const ico = await f.request('/favicon.ico'); assert.equal(ico.status, 200);
|
||||
const bytes = Buffer.from(await ico.arrayBuffer()); assert.equal(bytes.readUInt16LE(2), 1); assert.equal(bytes.readUInt16LE(4), 3);
|
||||
for (const path of ['/favicon.svg', '/icons/safari-pinned-tab.svg']) {
|
||||
const svg = await f.request(path); assert.equal(svg.status, 200); assert.match(svg.headers.get('content-type'), /image\/svg\+xml/);
|
||||
}
|
||||
});
|
||||
|
||||
test('protocol audio controls reject wrong CSRF and malformed binary frames', async t => {
|
||||
const f = await fixture(t); const auth = await f.login();
|
||||
for (const payload of [JSON.stringify({ type: 'audio_state', inputMuted: false, outputMuted: false, csrf: 'wrong' }), Buffer.from([1, 2])]) {
|
||||
const client = f.ws(auth.cookie, f.origin, '/api/ts3');
|
||||
await once(client, 'open'); client.send(payload);
|
||||
const [code] = await once(client, 'close');
|
||||
assert.equal(code, typeof payload === 'string' ? 4403 : 1003);
|
||||
}
|
||||
});
|
||||
|
||||
test('protocol heartbeat requires owner authentication, origin and CSRF, and validates its nonce', async t => {
|
||||
const f = await fixture(t); const auth = await f.login();
|
||||
assert.equal(await rejectedUpgrade(f.ws('', f.origin, '/api/ts3')), 401);
|
||||
assert.equal(await rejectedUpgrade(f.ws(auth.cookie, 'https://other.invalid', '/api/ts3')), 403);
|
||||
for (const [nonce, csrf, expected] of [[0, auth.csrf, null], [-1, auth.csrf, 1003], ['0', auth.csrf, 1003], [0, 'wrong', 4403]]) {
|
||||
const client = f.ws(auth.cookie, f.origin, '/api/ts3'); await once(client, 'open');
|
||||
if (expected) { const closed = once(client, 'close'); client.send(JSON.stringify({ type: 'ping', nonce, csrf })); assert.equal((await closed)[0], expected); }
|
||||
else {
|
||||
const reply = new Promise(resolve => client.on('message', data => { const event = JSON.parse(data); if (event.type === 'ts3_pong') resolve(event); }));
|
||||
client.send(JSON.stringify({ type: 'ping', nonce, csrf })); assert.deepEqual(await reply, { type: 'ts3_pong', nonce: 0 }); client.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('channel connection options are bounded and local channel creation is not a public command', async t => {
|
||||
const f = await fixture(t); const auth = await f.login();
|
||||
for (const options of [{ channelId: 0 }, { channelId: 1.5 }, { channelId: '411' }, { channelPassword: {} }, { channelPassword: 'x'.repeat(257) }, { heartbeat: 'yes' }]) {
|
||||
const client = f.ws(auth.cookie, f.origin, '/api/ts3'); await once(client, 'open');
|
||||
const error = new Promise(resolve => client.on('message', data => { const event = JSON.parse(data); if (event.type === 'ts3_error') resolve(event); }));
|
||||
client.send(JSON.stringify({ type: 'connect', csrf: auth.csrf, connectionId: 'c'.repeat(32), ...options }));
|
||||
assert.equal((await error).code, 'invalid_connection_options'); client.close();
|
||||
}
|
||||
const client = f.ws(auth.cookie, f.origin, '/api/ts3'); await once(client, 'open');
|
||||
const closed = once(client, 'close'); client.send(JSON.stringify({ type: 'create_test_channel', csrf: auth.csrf }));
|
||||
assert.equal((await closed)[0], 1003);
|
||||
});
|
||||
|
||||
test('Marketplace Redis aliases are supported without mixing incomplete credential pairs', () => {
|
||||
const settings = { ...env(), APP_ORIGIN: 'https://example.com', VERCEL: '1', KV_REST_API_URL: 'https://redis.example.com', KV_REST_API_TOKEN: 'test-only-token' };
|
||||
const config = readConfig(settings);
|
||||
assert.equal(config.redisUrl, settings.KV_REST_API_URL);
|
||||
assert.equal(config.redisToken, settings.KV_REST_API_TOKEN);
|
||||
assert.throws(() => readConfig({ ...settings, UPSTASH_REDIS_REST_URL: 'https://other.example.com' }), /Redis/);
|
||||
});
|
||||
|
||||
async function fixture(t, storeOverride) {
|
||||
const config = readConfig(env());
|
||||
const store = storeOverride || createStore(config);
|
||||
const app = createApp(config, store);
|
||||
app.server.listen(0, '127.0.0.1');
|
||||
await once(app.server, 'listening');
|
||||
const origin = `http://127.0.0.1:${app.server.address().port}`;
|
||||
config.origin = origin;
|
||||
t.after(async () => {
|
||||
for (const client of app.wss.clients) client.terminate();
|
||||
app.server.closeAllConnections();
|
||||
await new Promise(resolve => app.server.close(resolve));
|
||||
});
|
||||
const request = (path, options = {}) => fetch(origin + path, options);
|
||||
const post = (path, body = {}, cookie = '', csrf = '', requestOrigin = origin) => request(path, {
|
||||
method: 'POST', headers: { Origin: requestOrigin, 'Content-Type': 'application/json', Cookie: cookie, 'X-CSRF-Token': csrf }, body: JSON.stringify(body),
|
||||
});
|
||||
async function login() {
|
||||
const response = await post('/api/login', { password });
|
||||
assert.equal(response.status, 200);
|
||||
return { cookie: response.headers.get('set-cookie').split(';')[0], csrf: (await response.json()).csrf, header: response.headers.get('set-cookie') };
|
||||
}
|
||||
function ws(cookie = '', customOrigin = origin, path = '/api/ts3') {
|
||||
return new WebSocket(origin.replace('http:', 'ws:') + path, { headers: { Cookie: cookie, Origin: customOrigin } });
|
||||
}
|
||||
return { ...app, config, store, origin, request, post, login, ws };
|
||||
}
|
||||
function rejectedUpgrade(client) {
|
||||
return new Promise((resolve, reject) => {
|
||||
client.once('unexpected-response', (_req, res) => { res.resume(); client.terminate(); resolve(res.statusCode); });
|
||||
client.on('error', () => {});
|
||||
client.once('open', () => { client.terminate(); reject(new Error('Unauthorized upgrade succeeded')); });
|
||||
});
|
||||
}
|
||||
test('owner HTTP gate, origin checks, CSRF and durable logout revocation', async t => {
|
||||
const f = await fixture(t);
|
||||
assert.equal((await f.request('/api/session')).status, 401);
|
||||
assert.equal((await f.post('/api/connection')).status, 401);
|
||||
assert.equal((await f.post('/api/login', { password }, '', '', 'https://attacker.invalid')).status, 403);
|
||||
assert.equal((await f.post('/api/login', { password: 'wrong' })).status, 401);
|
||||
const auth = await f.login();
|
||||
assert.match(auth.header, /HttpOnly; SameSite=Strict/);
|
||||
assert.equal((await f.request('/api/session', { headers: { Cookie: auth.cookie } })).status, 200);
|
||||
assert.equal((await f.post('/api/connection', {}, auth.cookie)).status, 403);
|
||||
assert.equal((await f.post('/api/connection', {}, auth.cookie, auth.csrf)).status, 400);
|
||||
assert.equal((await f.post('/api/logout', {}, auth.cookie, auth.csrf)).status, 200);
|
||||
assert.equal((await f.request('/api/session', { headers: { Cookie: auth.cookie } })).status, 401);
|
||||
assert.equal((await f.request('/api/session?token=forbidden')).status, 400);
|
||||
});
|
||||
|
||||
test('saving connection settings requires owner origin and CSRF and never returns bookmark passwords', async t => {
|
||||
const f = await fixture(t); f.config.identityKey = randomBytes(32).toString('hex');
|
||||
for (const path of ['/api/preferences', '/api/connection']) assert.equal((await f.request(path)).status, 401);
|
||||
const auth = await f.login();
|
||||
const value = { revision: 'empty', theme: 'system', nickname: 'Fixture', bookmarks: [{ id: 'only-me', name: 'Fixture', host: 'example.com', port: 9987, nickname: 'Fixture', password: 'test-only-bookmark-secret' }] };
|
||||
assert.equal((await f.post('/api/preferences', value, auth.cookie, 'wrong')).status, 403);
|
||||
assert.equal((await f.post('/api/preferences', value, auth.cookie, auth.csrf)).status, 200);
|
||||
const metadata = await (await f.request('/api/preferences', { headers: { Cookie: auth.cookie } })).text();
|
||||
assert.equal(metadata.includes('test-only-bookmark-secret'), false);
|
||||
const connection = { bookmarkId: 'only-me', host: 'example.com', port: 9987, nickname: 'Fixture' };
|
||||
assert.equal((await f.post('/api/connection', connection, auth.cookie, auth.csrf, 'https://other.invalid')).status, 403);
|
||||
assert.equal((await f.post('/api/connection', connection, auth.cookie)).status, 403);
|
||||
const saved = await f.post('/api/connection', connection, auth.cookie, auth.csrf);
|
||||
assert.equal(saved.status, 200);
|
||||
const body = await saved.text();
|
||||
assert.equal(body.includes('test-only-bookmark-secret'), false);
|
||||
const current = JSON.parse(body).connection;
|
||||
assert.match(current.id, /^[a-f0-9]{32}$/);
|
||||
assert.equal(current.hasPassword, true);
|
||||
assert.equal(Object.hasOwn(current, 'password'), false);
|
||||
const reloaded = await (await f.request('/api/preferences', { headers: { Cookie: auth.cookie } })).json();
|
||||
assert.equal(reloaded.connection.id, current.id);
|
||||
assert.equal(reloaded.connection.hasPassword, true);
|
||||
assert.equal((await f.post('/api/bookmarks/connection', { id: 'only-me' }, auth.cookie, auth.csrf)).status, 404);
|
||||
});
|
||||
test('WebSocket upgrades reject missing auth, cross-origin requests and query tokens', async t => {
|
||||
const f = await fixture(t);
|
||||
assert.equal(await rejectedUpgrade(f.ws()), 401);
|
||||
const auth = await f.login();
|
||||
assert.equal(await rejectedUpgrade(f.ws(auth.cookie, 'https://attacker.invalid')), 403);
|
||||
assert.equal(await rejectedUpgrade(f.ws(auth.cookie, f.origin, '/api/ts3?token=x')), 403);
|
||||
});
|
||||
test('authenticated protocol heartbeats work and logout closes active sockets', async t => {
|
||||
const f = await fixture(t);
|
||||
const auth = await f.login();
|
||||
const client = f.ws(auth.cookie);
|
||||
const metadata = once(client, 'message');
|
||||
await once(client, 'open');
|
||||
assert.equal(JSON.parse((await metadata)[0]).type, 'runtime');
|
||||
const response = once(client, 'message');
|
||||
client.send(JSON.stringify({ type: 'ping', nonce: 7, csrf: auth.csrf }));
|
||||
assert.deepEqual(JSON.parse((await response)[0]), { type: 'ts3_pong', nonce: 7 });
|
||||
const closed = once(client, 'close');
|
||||
await f.post('/api/logout', {}, auth.cookie, auth.csrf);
|
||||
assert.equal((await closed)[0], 4401);
|
||||
});
|
||||
test('sessions survive application replacement with the same durable store; secret rotation revokes them', async t => {
|
||||
const first = await fixture(t);
|
||||
const auth = await first.login();
|
||||
const replacement = createApp(first.config, first.store);
|
||||
assert.ok(await replacement.sessions.read({ headers: { cookie: auth.cookie } }));
|
||||
const rotated = createApp({ ...first.config, secret: randomBytes(32).toString('hex') }, first.store);
|
||||
assert.equal(await rotated.sessions.read({ headers: { cookie: auth.cookie } }), null);
|
||||
replacement.wss.close();
|
||||
rotated.wss.close();
|
||||
});
|
||||
test('session expiration and duplicate cookies fail authentication', async t => {
|
||||
const f = await fixture(t);
|
||||
f.config.sessionSeconds = 0;
|
||||
const auth = await f.login();
|
||||
assert.equal((await f.request('/api/session', { headers: { Cookie: auth.cookie } })).status, 401);
|
||||
assert.equal((await f.request('/api/session', { headers: { Cookie: `${auth.cookie}; ${auth.cookie}` } })).status, 401);
|
||||
});
|
||||
test('storage failure cannot open HTTP or WebSocket access', async t => {
|
||||
const failed = async () => { throw new Error('secret backend error'); };
|
||||
const f = await fixture(t, { get: failed, set: failed, delete: failed, limit: failed });
|
||||
const cookie = `voxharbor-local=${'a'.repeat(64)}`;
|
||||
const response = await f.request('/api/session', { headers: { Cookie: cookie } });
|
||||
assert.equal(response.status, 503);
|
||||
assert.doesNotMatch(await response.text(), /secret backend/);
|
||||
assert.equal(await rejectedUpgrade(f.ws(cookie)), 503);
|
||||
});
|
||||
test('login attempts are bounded across clients', async t => {
|
||||
const f = await fixture(t);
|
||||
for (let i = 0; i < 10; i++) assert.equal((await f.post('/api/login', { password: 'wrong' })).status, 401);
|
||||
assert.equal((await f.post('/api/login', { password })).status, 429);
|
||||
});
|
||||
|
||||
test('revocation through another application instance closes the original socket', { timeout: 5000 }, async t => {
|
||||
const f = await fixture(t);
|
||||
const auth = await f.login();
|
||||
const client = f.ws(auth.cookie);
|
||||
await once(client, 'open');
|
||||
const closed = once(client, 'close');
|
||||
const replacement = createApp(f.config, f.store);
|
||||
await replacement.sessions.revoke({ headers: { cookie: auth.cookie } });
|
||||
assert.equal((await closed)[0], 4401);
|
||||
replacement.wss.close();
|
||||
});
|
||||
|
||||
test('oversized WebSocket frames are rejected before processing', async t => {
|
||||
const f = await fixture(t);
|
||||
const auth = await f.login();
|
||||
const client = f.ws(auth.cookie);
|
||||
await once(client, 'open');
|
||||
const closed = once(client, 'close');
|
||||
client.send(randomBytes(4097));
|
||||
assert.equal((await closed)[0], 1009);
|
||||
});
|
||||
|
||||
test('malformed and oversized login bodies cannot bypass authentication', async t => {
|
||||
const f = await fixture(t);
|
||||
const headers = { Origin: f.origin, 'Content-Type': 'application/json' };
|
||||
assert.equal((await f.request('/api/login', { method: 'POST', headers, body: '{broken' })).status, 400);
|
||||
assert.equal((await f.post('/api/login', { password: 'a'.repeat(3000) })).status, 413);
|
||||
const response = await f.request('/');
|
||||
assert.equal(response.status, 200);
|
||||
assert.match(response.headers.get('content-security-policy'), /frame-ancestors 'none'/);
|
||||
assert.match(await response.text(), /<label for="username">Username<\/label>/);
|
||||
assert.equal((await f.request('/app.mjs')).status, 200);
|
||||
assert.equal((await f.request('/style.css')).status, 200);
|
||||
});
|
||||
|
||||
test('protocol and identity operations enforce authentication, origin and CSRF before native execution', async t => {
|
||||
const f = await fixture(t);
|
||||
for (const path of ['/api/identity', '/api/protocol']) assert.equal((await f.request(path)).status, 401);
|
||||
assert.equal((await f.post('/api/identity/create')).status, 401);
|
||||
assert.equal(await rejectedUpgrade(f.ws('', f.origin, '/api/ts3')), 401);
|
||||
const auth = await f.login();
|
||||
assert.equal((await f.post('/api/identity/create', {}, auth.cookie)).status, 403);
|
||||
assert.equal((await f.post('/api/identity/create', {}, auth.cookie, auth.csrf)).status, 409);
|
||||
assert.equal((await f.request('/api/identity/export', { headers: { Cookie: auth.cookie } })).status, 404);
|
||||
assert.equal(await rejectedUpgrade(f.ws(auth.cookie, 'https://attacker.invalid', '/api/ts3')), 403);
|
||||
});
|
||||
|
||||
test('an authenticated protocol socket still rejects a command with the wrong CSRF token', async t => {
|
||||
const f = await fixture(t);
|
||||
const auth = await f.login();
|
||||
const client = f.ws(auth.cookie, f.origin, '/api/ts3');
|
||||
const welcome = once(client, 'message');
|
||||
await once(client, 'open');
|
||||
await welcome;
|
||||
const closed = once(client, 'close');
|
||||
client.send(JSON.stringify({ type: 'connect', csrf: 'wrong', nickname: 'test' }));
|
||||
assert.equal((await closed)[0], 4403);
|
||||
});
|
||||
|
||||
const nativePath = fileURLToPath(new URL('../native/bin/voxharbor-protocol', import.meta.url));
|
||||
test('real native identity creation persists once; ordinary responses never contain private material', { skip: !existsSync(nativePath) }, async t => {
|
||||
const f = await fixture(t);
|
||||
f.config.identityKey = randomBytes(32).toString('hex');
|
||||
f.config.protocolBinary = nativePath;
|
||||
const auth = await f.login();
|
||||
const created = await f.post('/api/identity/create', {}, auth.cookie, auth.csrf);
|
||||
assert.equal(created.status, 201);
|
||||
const metadata = (await created.json()).identity;
|
||||
assert.equal(metadata.level >= 16, true);
|
||||
assert.deepEqual(Object.keys(metadata).sort(), ['createdAt', 'level', 'uid']);
|
||||
const again = await f.post('/api/identity/create', {}, auth.cookie, auth.csrf);
|
||||
assert.equal(again.status, 409);
|
||||
const ordinary = await f.request('/api/identity', { headers: { Cookie: auth.cookie } });
|
||||
assert.deepEqual((await ordinary.json()).identity, metadata);
|
||||
const backup = await f.post('/api/identity/export', {}, auth.cookie, auth.csrf);
|
||||
assert.equal(backup.status, 200);
|
||||
assert.match(backup.headers.get('content-disposition'), /attachment/);
|
||||
const value = await backup.text();
|
||||
const replacement = await fixture(t);
|
||||
replacement.config.identityKey = randomBytes(32).toString('hex');
|
||||
replacement.config.protocolBinary = nativePath;
|
||||
const auth2 = await replacement.login();
|
||||
const imported = await replacement.post('/api/identity/import', { value }, auth2.cookie, auth2.csrf);
|
||||
assert.equal(imported.status, 201);
|
||||
assert.equal((await imported.json()).identity.uid, metadata.uid);
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { VoiceAudio } from '../public/voice.mjs';
|
||||
|
||||
const deferred = () => { let resolve; const promise = new Promise(done => { resolve = done; }); return { promise, resolve }; };
|
||||
const settle = async () => { for (let i = 0; i < 5; i++) await Promise.resolve(); };
|
||||
function globals(t, values) {
|
||||
for (const [key, value] of Object.entries(values)) {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(globalThis, key);
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
t.after(() => { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else delete globalThis[key]; });
|
||||
}
|
||||
}
|
||||
|
||||
test('disconnect during worklet initialization cannot resurrect listening', async t => {
|
||||
const loading = deferred(); let closed = 0; const commands = [];
|
||||
globals(t, { AudioContext: class {
|
||||
sampleRate = 48000; state = 'running'; audioWorklet = { addModule: () => loading.promise };
|
||||
async close() { closed++; }
|
||||
} });
|
||||
const audio = new VoiceAudio(command => commands.push(command), () => {});
|
||||
const pending = audio.listen(true); audio.stop(); loading.resolve();
|
||||
await assert.rejects(pending, { name: 'AbortError' });
|
||||
assert.equal(closed, 1); assert.equal(audio.outputMuted, true); assert.equal(audio.muted, true); assert.equal(commands.length, 0);
|
||||
});
|
||||
|
||||
test('disconnect cancels pending codec initialization and terminates its worker', async t => {
|
||||
let terminated = 0; const commands = [];
|
||||
globals(t, {
|
||||
AudioContext: class { sampleRate = 48000; state = 'running'; audioWorklet = { addModule: async () => {} }; destination = {}; async close() {} },
|
||||
AudioWorkletNode: class { port = { postMessage() {} }; connect() {} disconnect() {} },
|
||||
Worker: class { postMessage() {} terminate() { terminated++; } },
|
||||
});
|
||||
const audio = new VoiceAudio(command => commands.push(command), () => {});
|
||||
const pending = audio.listen(true); await settle(); audio.stop();
|
||||
await assert.rejects(pending, { name: 'AbortError' });
|
||||
assert.equal(terminated, 1); assert.equal(audio.worker, null); assert.equal(audio.context, null); assert.equal(commands.length, 0);
|
||||
});
|
||||
|
||||
test('disconnect during AudioContext resume cannot enable output afterward', async () => {
|
||||
const resume = deferred(); const audio = new VoiceAudio(() => assert.fail('Ended audio must not send control'), () => {});
|
||||
audio.context = { resume: () => resume.promise, close: async () => {} };
|
||||
const pending = audio.listen(true); audio.stop(); resume.resolve();
|
||||
await assert.rejects(pending, { name: 'AbortError' }); assert.equal(audio.outputMuted, true);
|
||||
});
|
||||
|
||||
for (const action of ['mute', 'stop']) test(`pending microphone permission is canceled by ${action}`, async t => {
|
||||
const permission = deferred(); let stopped = 0; const commands = [];
|
||||
globals(t, { navigator: { mediaDevices: { getUserMedia: () => permission.promise } } });
|
||||
const audio = new VoiceAudio(command => commands.push(command), () => {}); audio.outputMuted = false;
|
||||
const pending = audio.microphone(); audio[action]();
|
||||
permission.resolve({ getTracks: () => [{ stop() { stopped++; } }] }); await pending;
|
||||
assert.equal(stopped, 1); assert.equal(audio.muted, true); assert.equal(audio.stream, undefined);
|
||||
assert.equal(commands.some(command => command.inputMuted === false), false);
|
||||
});
|
||||
|
||||
test('a disposed audio instance cannot deliver delayed worker errors to the new connection', () => {
|
||||
const audio = new VoiceAudio(() => {}, () => {}); let events = 0;
|
||||
audio.addEventListener('error', () => events++); audio.stop(); audio.event('error', 'late failure'); assert.equal(events, 0);
|
||||
});
|
||||
|
||||
test('ending active audio deafens and mutes the native connection once', () => {
|
||||
const commands = []; const audio = new VoiceAudio(command => commands.push(command), () => {});
|
||||
audio.outputMuted = false; audio.muted = false; audio.stop(); audio.stop();
|
||||
assert.deepEqual(commands, [{ type: 'audio_state', inputMuted: true, outputMuted: true }]);
|
||||
});
|
||||
|
||||
test('a participant muted before listening stays at zero volume after codec startup', async t => {
|
||||
const messages = [];
|
||||
globals(t, {
|
||||
AudioContext: class { sampleRate = 48000; state = 'running'; audioWorklet = { addModule: async () => {} }; destination = {}; async resume() {} async close() {} },
|
||||
AudioWorkletNode: class { port = { postMessage() {} }; connect() {} disconnect() {} },
|
||||
Worker: class { postMessage(message) { messages.push(message); if (message.type === 'init') queueMicrotask(() => this.onmessage({ data: { type: 'ready' } })); } terminate() {} },
|
||||
});
|
||||
const audio = new VoiceAudio(() => {}, () => {}); audio.volume(42, 0);
|
||||
await audio.listen(true);
|
||||
assert.ok(messages.some(message => message.type === 'volume' && message.clientId === 42 && message.volume === 0));
|
||||
audio.stop();
|
||||
});
|
||||
|
||||
test('concurrent listening requests share initialization and cannot bypass codec readiness', async t => {
|
||||
const loading = deferred(); let workers = 0; let contexts = 0; let complete = false;
|
||||
globals(t, {
|
||||
AudioContext: class { constructor() { contexts++; } sampleRate = 48000; state = 'running'; audioWorklet = { addModule: () => loading.promise }; destination = {}; async resume() {} async close() {} },
|
||||
AudioWorkletNode: class { port = { postMessage() {} }; connect() {} disconnect() {} },
|
||||
Worker: class { constructor() { workers++; } postMessage(message) { if (message.type === 'init') queueMicrotask(() => this.onmessage({ data: { type: 'ready' } })); } terminate() {} },
|
||||
});
|
||||
const audio = new VoiceAudio(() => {}, () => {});
|
||||
const first = audio.listen(true); const second = audio.listen(true).then(() => { complete = true; });
|
||||
await settle(); assert.equal(complete, false); assert.equal(audio.outputMuted, true); assert.equal(workers, 0);
|
||||
loading.resolve(); await Promise.all([first, second]);
|
||||
assert.equal(contexts, 1); assert.equal(workers, 1); assert.equal(audio.outputMuted, false); audio.stop();
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
const processors = new Map();
|
||||
// Processor logic only. This does not simulate browser audio scheduling or permissions.
|
||||
globalThis.AudioWorkletProcessor = class {
|
||||
constructor() { this.port = { sent: [], postMessage(message) { this.sent.push(message); } }; }
|
||||
};
|
||||
globalThis.registerProcessor = (name, processor) => processors.set(name, processor);
|
||||
globalThis.currentTime = 3;
|
||||
await import('../public/voice-worklet.mjs');
|
||||
|
||||
test('capture worklet is muted by default and bounds outstanding frames with capture timestamps', () => {
|
||||
const Capture = processors.get('vox-capture'); const capture = new Capture();
|
||||
const inputs = [[new Float32Array(960).fill(0.1)]];
|
||||
capture.process(inputs); assert.equal(capture.port.sent.length, 0);
|
||||
capture.port.onmessage({ data: { type: 'enabled', value: true } });
|
||||
for (let i = 0; i < 100; i++) capture.process(inputs);
|
||||
assert.equal(capture.port.sent.length, 2); assert.equal(capture.pending, 2);
|
||||
assert.equal(capture.port.sent[0].pcm.length, 960); assert.equal(capture.port.sent[0].at, 3);
|
||||
capture.port.onmessage({ data: { type: 'ack' } }); capture.process(inputs);
|
||||
assert.equal(capture.port.sent.length, 3);
|
||||
capture.port.onmessage({ data: { type: 'enabled', value: false } }); capture.process(inputs);
|
||||
assert.equal(capture.port.sent.length, 3);
|
||||
});
|
||||
|
||||
test('playback worklet drops stale backlog at the queue cap and clears on mute', () => {
|
||||
const Playback = processors.get('vox-playback'); const playback = new Playback();
|
||||
for (let i = 1; i <= 5; i++) playback.port.onmessage({ data: { pcm: new Float32Array(1920).fill(i / 10) } });
|
||||
assert.equal(playback.frames.length, 1);
|
||||
const output = [[new Float32Array(128), new Float32Array(128)]];
|
||||
playback.process([], output); assert.equal(output[0][0][0], 0.5); assert.equal(output[0][1][0], 0.5);
|
||||
playback.port.onmessage({ data: { type: 'clear' } });
|
||||
assert.equal(playback.frames.length, 0); assert.equal(playback.offset, 0);
|
||||
const silent = [[new Float32Array(128), new Float32Array(128)]];
|
||||
playback.process([], silent); assert.ok(silent[0].every(channel => channel.every(sample => sample === 0)));
|
||||
});
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { recentChannels, matchesChannel, channelPath, resolvePage, sameDestination } from '../public/workspace-model.mjs';
|
||||
test('a large channel list never becomes a full row of room tabs', () => {
|
||||
const channels = Array.from({length:150}, (_,i) => ({id:i+1,name:`Room ${i+1}`}));
|
||||
assert.deepEqual(recentChannels(channels, 80, [79, 80, 78, 77, 76, 999]).map(x=>x.id), [80,79,78,77]);
|
||||
});
|
||||
test('channel search finds people and ancestors, and malformed hierarchies terminate', () => {
|
||||
const channels = [{id:1,parentId:0,name:'Community'},{id:2,parentId:1,name:'Studio'},{id:3,parentId:2,name:'Quiet'}];
|
||||
assert.equal(channelPath(channels[2],channels),'Community / Studio');
|
||||
assert.equal(matchesChannel(channels[2],channels,[{channelId:3,name:'Sofia'}],'sof'),true);
|
||||
assert.equal(matchesChannel(channels[2],channels,[],'studio'),true);
|
||||
assert.equal(matchesChannel(channels[2],channels,[{channelId:2,name:'Alex'}],'alex'),false);
|
||||
channels[0].parentId=3;
|
||||
assert.equal(channelPath(channels[2],channels),'Community / Studio');
|
||||
});
|
||||
test('page routes accept only known page names and destination status includes the voice port', () => {
|
||||
assert.equal(resolvePage('#channels'),'channels'); assert.equal(resolvePage('#not-a-page'),'connections'); assert.equal(resolvePage('#connection?password=secret'),'connections');
|
||||
assert.equal(sameDestination({host:'example.com',port:9987},{host:'example.com',port:9988}),false);
|
||||
});
|
||||
Reference in new issue
Block a user