feat: add account-free settings and server management panels

This commit is contained in:
omar committed 2026-11-01 22:14:32 +03:00
1 parent 672540499c
commit cf42de67e2
179 files changed
+18817 -810

No files matched your search

+364
View File
@@ -0,0 +1,364 @@
// Noise reduction: the real bundled denoise.wasm inside the real capture worklet (synthetic VM, no devices),
// the AudioEngine capture lifecycle around it with stubbed Web Audio / getUserMedia, and the preference
// schema/migration of the official denoiserLevel.
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import vm from 'node:vm';
import { AudioEngine, DENOISE_DELAY } from '../app/renderer/js/audio/engine.js';
import { captureDenoiseLevel } from '../app/renderer/js/audio/profiles.js';
const require = createRequire(import.meta.url);
const { VOICE_SCHEMA, migrateVoicePrefs } = require('../app/main/voice-prefs.js');
const WASM_URL = new URL('../app/renderer/assets/audio/denoise.wasm', import.meta.url);
const module = new WebAssembly.Module(readFileSync(WASM_URL));
const workletSource = readFileSync(new URL('../app/renderer/js/audio/capture-worklet.js', import.meta.url), 'utf8');
function capture(options, rate = 48000) {
let Processor;
const messages = [];
const context = vm.createContext({
sampleRate: rate,
currentFrame: 0,
ArrayBuffer,
Int16Array,
Float32Array,
WebAssembly,
AudioWorkletProcessor: class {
constructor() { this.port = { postMessage(message) { messages.push(message); }, close() { this.closed = true; } }; }
},
registerProcessor(_id, implementation) { Processor = implementation; },
});
vm.runInContext(workletSource, context, { filename: 'capture-worklet.js' });
const processor = options === undefined ? new Processor() : new Processor(options);
return {
processor,
messages,
frames: () => messages.filter((m) => m.type === 'frame'),
send(data) { processor.port.onmessage({ data }); },
/** Feeds `input` in render quanta of `quantum` samples; returns whether the processor stays alive. */
render(input, quantum = 128) {
for (let offset = 0; offset < input.length; offset += quantum) {
const chunk = input.subarray(offset, Math.min(input.length, offset + quantum));
const output = new Float32Array(chunk.length);
if (!processor.process([[chunk]], [[output]])) return false;
assert.ok(output.every((v) => v === 0), 'the capture node output stays silent');
context.currentFrame += chunk.length;
}
return true;
},
};
}
const denoised = (level) => capture({ processorOptions: { denoise: { module, level } } });
/** Deterministic uniform noise in [-amplitude, amplitude). */
function noise(length, amplitude = 0.1, seed = 1) {
const out = new Float32Array(length);
let state = seed >>> 0;
for (let i = 0; i < length; i += 1) {
state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
out[i] = (state / 2 ** 32 * 2 - 1) * amplitude;
}
return out;
}
const pcmOf = (frames) => {
const all = new Int16Array(frames.length * 960);
frames.forEach((frame, i) => all.set(new Int16Array(frame.pcm), i * 960));
return all;
};
const rms = (samples) => Math.sqrt(samples.reduce((sum, v) => sum + v * v, 0) / samples.length);
const near = (actual, expected, epsilon = 1e-9) => assert.ok(Math.abs(actual - expected) <= epsilon, `${actual} != ${expected}`);
test('the bundled module has the renderer ABI and no imports', () => {
assert.deepEqual(WebAssembly.Module.imports(module), []);
const exports = new Map(WebAssembly.Module.exports(module).map(({ name, kind }) => [name, kind]));
for (const name of ['dsp_new', 'dsp_input', 'dsp_process', 'dsp_reset', 'dsp_free']) assert.equal(exports.get(name), 'function', name);
assert.equal(exports.get('memory'), 'memory');
});
test('noise reduction off is the bit-preserving bypass and never reports a handshake', () => {
const input = noise(48000, 1.6, 7); // includes clipping
const plain = capture();
const off = capture({ processorOptions: {} });
plain.render(input);
off.render(input);
assert.deepEqual(pcmOf(off.frames()), pcmOf(plain.frames()));
assert.equal(off.messages.some((m) => m.type === 'ready' || m.type === 'error'), false);
});
test('every level starts, keeps 20 ms framing and capture timestamps, and is independent of the quantum size', () => {
const input = noise(48000 * 2 + 300, 0.1, 3);
for (const level of [0, 1, 2, 3]) {
const runs = [128, 960, 37].map((quantum) => {
const run = denoised(level);
assert.deepEqual(run.messages.map((m) => m.type), ['ready']); // VM-realm objects: compare fields
assert.equal(run.render(input, quantum), true);
return run.frames();
});
const frames = runs[0];
assert.equal(frames.length, Math.floor(input.length / 960));
frames.forEach((frame, k) => {
assert.equal(frame.pcm.byteLength, 1920);
near(frame.capturedAt, (k + 1) * 0.02);
});
for (const other of runs.slice(1)) {
assert.deepEqual(pcmOf(other), pcmOf(frames), `level ${level}: no sample dropped, duplicated or reordered`);
assert.deepEqual(other.map((f) => f.capturedAt), frames.map((f) => f.capturedAt));
}
}
});
test('stationary noise is reduced, more at Very High than at Low', () => {
const input = noise(48000 * 3, 0.1, 11);
const tail = (frames) => Array.from(pcmOf(frames).subarray(-48000), (v) => v / 32768);
const inputRms = rms(input.subarray(-48000));
const levels = [0, 1, 2, 3].map((level) => {
const run = denoised(level);
run.render(input);
assert.equal(run.messages.some((m) => m.type === 'error'), false);
return rms(tail(run.frames()));
});
for (const level of levels) assert.ok(level < inputRms * 0.9, `${level} vs input ${inputRms}`);
assert.ok(levels[3] < levels[0] * 0.8, `Very High ${levels[3]} vs Low ${levels[0]}`);
});
test('a level change resets the suppressor to a fresh state at that level without losing samples', () => {
const before = noise(9600, 0.1, 5);
const after = noise(9600 * 2, 0.1, 6);
const changed = denoised(1);
changed.render(before);
changed.send({ type: 'denoise-level', level: 3 });
changed.render(after);
const fresh = denoised(3);
fresh.render(after);
assert.deepEqual(pcmOf(changed.frames().slice(10)), pcmOf(fresh.frames()));
assert.equal(changed.processor.denoise.level, 3);
const midBlock = denoised(2);
midBlock.render(noise(1000, 0.1, 8), 1000);
midBlock.send({ type: 'denoise-level', level: 0 });
midBlock.render(noise(8600, 0.1, 9));
const frames = midBlock.frames();
assert.equal(frames.length, 10);
frames.forEach((frame, k) => near(frame.capturedAt, (k + 1) * 0.02));
assert.equal(midBlock.messages.some((m) => m.type === 'error'), false);
});
test('NaN input is quantized as silence, not reported as a denoiser failure', () => {
const run = denoised(1);
const input = noise(1920, 0.1, 4);
input[5] = NaN;
run.render(input);
assert.equal(run.frames().length, 2);
assert.equal(run.messages.some((m) => m.type === 'error'), false);
});
test('denoiser failures are fatal: no frames follow, and the stop handshake still completes', () => {
for (const [options, rate] of [[{ module, level: 4 }, 48000], [{ module, level: 1 }, 44100], [{ module: {}, level: 1 }, 48000]]) {
const run = capture({ processorOptions: { denoise: options } }, rate);
assert.equal(run.messages.length, 1);
assert.equal(run.messages[0].type, 'error');
assert.equal(run.messages[0].fatal, true);
run.render(noise(4800));
assert.equal(run.frames().length, 0);
run.send({ type: 'stop' });
assert.equal(run.render(new Float32Array(128)), false);
assert.equal(run.messages.at(-1).type, 'stopped');
}
const run = denoised(1);
run.render(noise(960));
run.send({ type: 'denoise-level', level: 9 });
assert.equal(run.messages.at(-1).fatal, true);
run.render(noise(4800));
assert.equal(run.frames().length, 1);
assert.equal(run.processor.denoise, null);
});
test('stop releases the denoiser handle', () => {
const run = denoised(2);
run.render(noise(960));
const { exports, handle } = run.processor.denoise;
run.send({ type: 'stop' });
assert.equal(run.render(new Float32Array(128)), false);
assert.equal(run.processor.denoise, null);
assert.equal(exports.dsp_input(handle), 0, 'the freed handle is invalid');
});
// ---------- AudioEngine capture lifecycle ----------
function fakeStream(name) {
const track = {
label: name,
muted: false,
stopped: false,
stop() { this.stopped = true; },
addEventListener() {},
removeEventListener() {},
getSettings: () => ({}),
};
return { track, getTracks: () => [track], getAudioTracks: () => [track] };
}
const mockNode = () => ({
handlers: new Map(),
addEventListener(type, handler) { this.handlers.set(type, handler); },
removeEventListener(type, handler) { if (this.handlers.get(type) === handler) this.handlers.delete(type); },
connect(next) { return next ?? this; },
disconnect() {},
port: { messages: [], postMessage(data) { this.messages.push(data); if (data.type === 'stop') this.onmessage?.({ data: { type: 'stopped' } }); }, close() { this.closed = true; } },
gain: { value: 1 },
});
let wasmAvailable = true;
globalThis.fetch = async (url) => (wasmAvailable && String(url) === WASM_URL.href ? new Response(readFileSync(WASM_URL)) : new Response(null, { status: 404 }));
const answerReady = (node) => { if (node.options.processorOptions.denoise) queueMicrotask(() => node.port.onmessage?.({ data: { type: 'ready' } })); };
function engineSetup(worklet = answerReady) {
const pending = [];
const nodes = [];
Object.defineProperty(globalThis, 'navigator', {
configurable: true,
value: { mediaDevices: { getUserMedia: (constraints) => new Promise((resolve, reject) => pending.push({ constraints, resolve, reject })) } },
});
globalThis.AudioWorkletNode = class {
constructor(_ctx, _name, options) { Object.assign(this, mockNode(), { options }); nodes.push(this); worklet(this); }
};
globalThis.AudioContext = class {
constructor() { this.state = 'running'; this.currentTime = 0; this.audioWorklet = { addModule: async () => {} }; }
createMediaStreamSource() { return mockNode(); }
createGain() { return mockNode(); }
async close() { this.state = 'closed'; }
};
const errors = [];
const engine = new AudioEngine({ onFrame() {}, onError: (e) => errors.push(e), log() {} });
engine.init = async () => {};
return { engine, pending, nodes, errors };
}
async function until(condition) {
for (let i = 0; i < 2000 && !condition(); i += 1) await new Promise((resolve) => setTimeout(resolve, 1));
assert.ok(condition());
}
// First: the module cache must not have loaded the asset yet.
test('a missing noise-reduction module fails the capture before any microphone is requested', async () => {
wasmAvailable = false;
const { engine, pending } = engineSetup();
await assert.rejects(engine.startCapture({ denoiseLevel: 1 }), { code: 'denoise_unavailable' });
assert.equal(pending.length, 0);
assert.equal(engine.capturing, false);
wasmAvailable = true;
});
test('noise reduction capture: browser suppression off, module and level to the processor, live level reset', async () => {
const { engine, pending, nodes } = engineSetup();
const started = engine.startCapture({ denoiseLevel: 1, echoCancellation: true, autoGainControl: true });
await until(() => pending.length === 1);
assert.equal(pending[0].constraints.audio.noiseSuppression, false);
const stream = fakeStream('mic');
pending[0].resolve(stream);
assert.equal(await started, 'mic');
const { denoise } = nodes[0].options.processorOptions;
assert.ok(denoise.module instanceof WebAssembly.Module);
assert.equal(denoise.level, 1);
assert.equal(engine.captureDenoising, true);
engine.setDenoiseLevel(3);
engine.setDenoiseLevel(3);
assert.deepEqual(nodes[0].port.messages.filter((m) => m.type === 'denoise-level'), [{ type: 'denoise-level', level: 3 }]);
engine.capture.ctx.currentTime = 5;
engine.discardCapturedFrames();
near(engine.captureBoundary, 5 + 0.02 + DENOISE_DELAY);
engine.stopCapture();
await engine.captureClosing;
assert.equal(stream.track.stopped, true);
});
test('capture without noise reduction also disables browser suppression and builds the bypass processor', async () => {
const { engine, pending, nodes } = engineSetup();
const started = engine.startCapture({ denoiseLevel: null });
await until(() => pending.length === 1);
assert.equal(pending[0].constraints.audio.noiseSuppression, false);
pending[0].resolve(fakeStream('mic'));
await started;
assert.equal(nodes[0].options.processorOptions.denoise, undefined);
assert.equal(engine.captureDenoising, false);
engine.setDenoiseLevel(2);
assert.equal(nodes[0].port.messages.some((m) => m.type === 'denoise-level'), false);
engine.capture.ctx.currentTime = 5;
engine.discardCapturedFrames();
near(engine.captureBoundary, 5.02);
engine.stopCapture();
await engine.captureClosing;
});
test('a processor that cannot start noise reduction fails the capture and releases the microphone', async () => {
const { engine, pending } = engineSetup((node) => queueMicrotask(() => node.port.onmessage?.({ data: { type: 'error', fatal: true, message: 'Noise reduction could not start: x' } })));
const started = engine.startCapture({ denoiseLevel: 2 });
await until(() => pending.length === 1);
const stream = fakeStream('mic');
pending[0].resolve(stream);
await assert.rejects(started, /Noise reduction could not start: x/);
assert.equal(stream.track.stopped, true);
assert.equal(engine.capturing, false);
});
test('a running noise reduction failure stops capture and reports it', async () => {
const { engine, pending, nodes, errors } = engineSetup();
const started = engine.startCapture({ denoiseLevel: 0 });
await until(() => pending.length === 1);
const stream = fakeStream('mic');
pending[0].resolve(stream);
await started;
nodes[0].port.onmessage({ data: { type: 'error', fatal: true, message: 'Noise reduction failed: boom' } });
assert.equal(engine.capturing, false);
assert.equal(stream.track.stopped, true);
assert.deepEqual(errors, [{ code: 'capture', message: 'Noise reduction failed: boom' }]);
await engine.captureClosing;
});
test('a stop while the processor starts noise reduction supersedes the start at once', async () => {
const { engine, pending, nodes } = engineSetup(() => {});
const started = engine.startCapture({ denoiseLevel: 1 });
await until(() => pending.length === 1);
const stream = fakeStream('mic');
pending[0].resolve(stream);
await until(() => nodes.length === 1);
engine.stopCapture();
assert.equal(await started, null);
assert.equal(stream.track.stopped, true);
assert.equal(nodes[0].port.closed, true);
assert.equal(engine.capturing, false);
await engine.captureClosing;
});
// ---------- preferences ----------
function load(raw) {
const values = {};
for (const [key, spec] of Object.entries(VOICE_SCHEMA)) {
values[key] = Object.hasOwn(raw, key) && spec.check(raw[key]) ? raw[key] : structuredClone(spec.default);
}
return migrateVoicePrefs(raw, values);
}
test('denoiserLevel defaults to Moderate, validates 0..3, and is added to profiles stored before it existed', () => {
assert.equal(VOICE_SCHEMA.inputDsp.default.template.denoiseLevel, 1);
const old = { agc: true, denoise: false, typing: true, vad: true, vadMode: 'hybrid', vadLevel: -12, vadSensitivity: 'low' };
const migrated = load({ inputDsp: { template: { ...old, denoise: true }, devices: { mic: old } } });
assert.deepEqual(migrated.inputDsp, { template: { ...old, denoise: true, denoiseLevel: 1 }, devices: { mic: { ...old, denoiseLevel: 1 } } });
const stored = { template: { ...old, denoiseLevel: 3 }, devices: {} };
assert.deepEqual(load({ inputDsp: stored }).inputDsp, stored);
for (const bad of [4, -1, 1.5, '2']) assert.equal(VOICE_SCHEMA.inputDsp.check({ template: { ...old, denoiseLevel: bad }, devices: {} }), false);
assert.equal(load({ inputDsp: { template: { ...old, denoiseLevel: 9 }, devices: {} } }).inputDsp.template.denoiseLevel, 1);
const legacy = load({ noiseSuppression: false });
assert.equal(legacy.inputDsp.template.denoise, false);
assert.equal(legacy.inputDsp.template.denoiseLevel, 1);
});
test('the capture level is the device profile level only while noise reduction is on', () => {
const prefs = { inputDeviceId: 'a', inputDsp: { template: { denoise: true, denoiseLevel: 1 }, devices: { a: { denoise: true, denoiseLevel: 3 }, b: { denoise: false, denoiseLevel: 2 } } } };
assert.equal(captureDenoiseLevel(prefs), 3);
prefs.inputDeviceId = 'b';
assert.equal(captureDenoiseLevel(prefs), null);
prefs.inputDeviceId = 'other';
assert.equal(captureDenoiseLevel(prefs), 1);
});
+194
View File
@@ -0,0 +1,194 @@
'use strict';
// Badge catalog: protobuf parsing boundaries, fixed-origin network policy and the read-only TS6 artwork cache.
// Injected fetch only; no external network, Electron or real profile.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const {
BadgeCatalog, registerBadgesIpc, parseBadgeList, artworkUrl, validSvg, officialBadgeCacheDirs,
BADGE_LIST_URL, MAX_LIST_BYTES, MAX_REQUEST_UUIDS,
} = require('../app/main/badges.js');
const U1 = 'c2368518-3728-4260-bcd1-8b85e9f8984c';
const U2 = '0005232e-538e-4cb2-93b6-d7d83e873829';
const SVG = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg"><rect width="32" height="32"/></svg>';
// ---- minimal proto3 encoder for fixtures ----
function varint(n) {
const out = [];
let v = n;
while (v >= 128) { out.push((v % 128) | 128); v = Math.floor(v / 128); }
out.push(v);
return Buffer.from(out);
}
const tag = (field, wire) => varint(field * 8 + wire);
const str = (field, s) => { const b = Buffer.isBuffer(s) ? s : Buffer.from(s, 'utf8'); return Buffer.concat([tag(field, 2), varint(b.length), b]); };
const num = (field, n) => Buffer.concat([tag(field, 0), varint(n)]);
const badge = ({ uuid, name = 'Name', url, description = 'Desc', created = 1700000000 }) => Buffer.concat([
str(1, uuid), str(2, name), ...(url === undefined ? [] : [str(3, url)]), str(4, description), num(5, created), num(6, 1),
]);
const list = (badges, extra = []) => Buffer.concat([num(1, 2), num(2, 1730000000000), ...badges.map((b) => str(3, badge(b))), ...extra]);
const tempDir = () => fs.mkdtempSync(path.join(os.tmpdir(), 'tp-badges-'));
const answer = (body, init = {}) => new Response(body, { status: 200, ...init });
test('BadgeList: fields 1–3 and Badge fields 1–6 decode; unknown fields are skipped', () => {
const body = list([{ uuid: U1, name: 'Beta', url: `https://badges-content.teamspeak.com/${U1}/beta`, description: 'Beta tester' }],
[num(15, 7), Buffer.concat([tag(16, 1), Buffer.alloc(8)]), Buffer.concat([tag(17, 5), Buffer.alloc(4)]), str(18, 'future')]);
const parsed = parseBadgeList(body);
assert.equal(parsed.version, 2);
assert.equal(parsed.updated, 1730000000000);
assert.deepEqual(parsed.badges, [{ uuid: U1, name: 'Beta', description: 'Beta tester', url: `https://badges-content.teamspeak.com/${U1}/beta` }]);
});
test('invalid badges are dropped individually; first duplicate wins; uppercase UUIDs are normalised', () => {
const parsed = parseBadgeList(list([
{ uuid: U1.toUpperCase(), name: 'First' },
{ uuid: U1, name: 'Duplicate' },
{ uuid: 'not-a-uuid' },
{ uuid: U2, name: 'bad\u0001name' },
{ uuid: U2, name: 'x'.repeat(257) },
{ uuid: U2, name: 'Second', url: 'https://evil.example/badge' },
]));
assert.deepEqual(parsed.badges.map((b) => [b.uuid, b.name, b.url]), [[U1, 'First', null], [U2, 'Second', null]]);
});
test('structural errors reject the whole body', () => {
const good = list([{ uuid: U1 }]);
const cases = {
empty: Buffer.alloc(0),
'truncated varint': Buffer.from([0x08, 0x80]),
'truncated field': Buffer.concat([tag(3, 2), varint(50), Buffer.alloc(3)]),
'group wire type': Buffer.concat([good, tag(9, 3)]),
'invalid UTF-8': str(3, Buffer.concat([tag(1, 2), varint(2), Buffer.from([0xc3, 0x28])])),
'varint too long': Buffer.concat([tag(1, 0), Buffer.alloc(11, 0xff)]),
'field zero': Buffer.concat([varint(0), varint(1)]),
'no valid badge': list([{ uuid: 'nope' }]),
'too large': Buffer.alloc(MAX_LIST_BYTES + 1),
'html error page': Buffer.from('<html>502</html>'),
};
for (const [name, body] of Object.entries(cases)) assert.throws(() => parseBadgeList(body), /badge list/, name);
});
test('artwork URLs derive from the catalog url and never leave the fixed origin', () => {
const base = { url: `https://badges-content.teamspeak.com/${U1}/beta` };
assert.equal(artworkUrl(base, false), `https://badges-content.teamspeak.com/${U1}/beta.svg`);
assert.equal(artworkUrl(base, true), `https://badges-content.teamspeak.com/${U1}/beta_details.svg`);
assert.equal(artworkUrl({ url: `${base.url}.svg` }, true), `https://badges-content.teamspeak.com/${U1}/beta_details.svg`);
assert.equal(artworkUrl({ url: null }, false), null);
assert.equal(artworkUrl(undefined, false), null);
// URLs that would leave the origin were already dropped by the parser.
for (const url of ['http://badges-content.teamspeak.com/x', 'https://badges-content.teamspeak.com.evil.example/x', 'https://u:p@badges-content.teamspeak.com/x', 'https://badges-content.teamspeak.com/x?q=1', 'https://badges-content.teamspeak.com:8443/x', 'https://badges-content.teamspeak.com/']) {
assert.deepEqual(parseBadgeList(list([{ uuid: U1, url }])).badges[0].url, null, url);
}
});
test('SVG check accepts the observed TS6 cache format and rejects other content', () => {
assert.equal(validSvg(SVG), true);
assert.equal(validSvg('\uFEFF<svg xmlns="http://www.w3.org/2000/svg"/>'), true);
assert.equal(validSvg('<html><svg></svg></html>'), false);
assert.equal(validSvg(''), false);
assert.equal(validSvg(`<svg>${'x'.repeat(600 * 1024)}</svg>`), false);
});
test('catalog fetch: fixed URL, anonymous, no redirects; cached and reused; failures keep the last list', async () => {
const dir = tempDir();
const calls = [];
let now = 1000;
let body = list([{ uuid: U1, name: 'Beta', description: 'Beta tester' }]);
const catalog = new BadgeCatalog({ cacheDir: dir, now: () => now, fetchImpl: async (url, init) => { calls.push({ url, init }); return typeof body === 'function' ? body() : answer(body); } });
const r = await catalog.info([U1, U2]);
assert.equal(calls.length, 1);
assert.equal(calls[0].url, BADGE_LIST_URL);
assert.equal(calls[0].init.redirect, 'error');
assert.equal(calls[0].init.credentials, 'omit');
assert.equal(calls[0].init.referrerPolicy, 'no-referrer');
assert.deepEqual(r.badges, [{ uuid: U1, known: true, name: 'Beta', description: 'Beta tester' }, { uuid: U2, known: false, name: '', description: '' }]);
// Fresh list: no second request.
await catalog.info([U1]);
assert.equal(calls.length, 1);
// A fresh process reads the cache and does not refetch within a day.
const cached = new BadgeCatalog({ cacheDir: dir, now: () => now, fetchImpl: async () => { throw new Error('must not fetch'); } });
assert.equal((await cached.info([U1])).badges[0].name, 'Beta');
// After a day a failed refresh (here: a redirect) keeps the known badges.
now += 25 * 60 * 60 * 1000;
body = () => ({ ok: true, status: 200, redirected: true, url: 'https://elsewhere.example/list', headers: new Headers() });
const after = await catalog.info([U1]);
assert.equal(after.badges[0].known, true);
assert.equal(after.status.error.code, 'redirect');
assert.equal(calls.length, 2);
// Retries are spaced after a failure.
await catalog.info([U1]);
assert.equal(calls.length, 2);
});
test('disabled catalog makes no request', async () => {
const catalog = new BadgeCatalog({ cacheDir: tempDir(), enabled: false, fetchImpl: async () => { throw new Error('no network'); } });
const r = await catalog.info([U1]);
assert.equal(r.badges[0].known, false);
assert.equal(r.status.loaded, false);
await assert.rejects(catalog.artwork(U1, false), /network access is disabled/);
});
test('artwork: profile cache, then the read-only TS6 cache, then the catalog origin; results are cached', async () => {
const dir = tempDir();
const ts6 = tempDir();
fs.writeFileSync(path.join(ts6, U2), SVG);
fs.writeFileSync(path.join(ts6, `${U2}_details`), 'not svg');
const urls = [];
const catalog = new BadgeCatalog({
cacheDir: dir, officialCacheDirs: [ts6],
fetchImpl: async (url) => {
urls.push(url);
if (url === BADGE_LIST_URL) return answer(list([{ uuid: U1, url: `https://badges-content.teamspeak.com/${U1}/beta` }, { uuid: U2, url: `https://badges-content.teamspeak.com/${U2}/two` }]));
return answer(SVG);
},
});
assert.deepEqual(await catalog.artwork(U2, false), { svg: SVG, source: 'teamspeak-cache' });
assert.deepEqual(urls, [], 'TS6 cache hit needs no network');
// An invalid TS6 file is ignored and the detailed artwork comes from the fixed origin.
assert.equal((await catalog.artwork(U2, true)).source, 'network');
assert.deepEqual(urls, [BADGE_LIST_URL, `https://badges-content.teamspeak.com/${U2}/two_details.svg`]);
assert.equal((await catalog.artwork(U2, true)).source, 'cache');
assert.equal(fs.readFileSync(path.join(dir, 'art', `${U2}_details.svg`), 'utf8'), SVG);
await assert.rejects(catalog.artwork('../../etc/passwd', false), /invalid badge id/);
await assert.rejects(catalog.artwork('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', false), /not in the public catalog/);
});
test('non-SVG network artwork is rejected and not retried immediately', async () => {
let artCalls = 0;
const catalog = new BadgeCatalog({
cacheDir: tempDir(),
fetchImpl: async (url) => (url === BADGE_LIST_URL ? answer(list([{ uuid: U1, url: `https://badges-content.teamspeak.com/${U1}/beta` }])) : (artCalls++, answer('<html>oops</html>'))),
});
await assert.rejects(catalog.artwork(U1, false), /not an SVG/);
await assert.rejects(catalog.artwork(U1, false), /recently failed/);
assert.equal(artCalls, 1);
});
test('official cache directory is only the observed Windows path', () => {
assert.deepEqual(officialBadgeCacheDirs({ LOCALAPPDATA: 'C:\\Users\\x\\AppData\\Local' }, 'win32'), ['C:\\Users\\x\\AppData\\Local\\TeamSpeak\\Cache\\Default\\badges\\96']);
assert.deepEqual(officialBadgeCacheDirs({}, 'win32'), []);
assert.deepEqual(officialBadgeCacheDirs({ LOCALAPPDATA: '/home/x' }, 'linux'), []);
});
test('IPC accepts only trusted senders, UUID lists and boolean detail flags', async () => {
const handlers = new Map();
const seen = [];
registerBadgesIpc({
ipcMain: { handle: (channel, fn) => handlers.set(channel, fn) },
trustedSender: (event) => event.trusted,
catalog: { info: async (uuids) => { seen.push(uuids); return { status: {}, badges: [] }; }, artwork: async () => ({ svg: SVG, source: 'cache' }) },
});
const ok = { trusted: true };
assert.equal((await handlers.get('badges:info')({ trusted: false }, [U1])).error.code, 'forbidden');
assert.equal((await handlers.get('badges:info')(ok, [U1, 'https://x'])).error.code, 'bad_request');
assert.equal((await handlers.get('badges:info')(ok, Array(MAX_REQUEST_UUIDS + 1).fill(U1))).error.code, 'bad_request');
assert.equal((await handlers.get('badges:info')(ok, [U1, U1])).ok, true);
assert.deepEqual(seen, [[U1]]);
assert.equal((await handlers.get('badges:art')(ok, U1, 'yes')).error.code, 'bad_request');
assert.equal((await handlers.get('badges:art')(ok, U1.toUpperCase(), false)).error.code, 'bad_request');
assert.equal((await handlers.get('badges:art')(ok, U1, false)).svg, SVG);
});
+132
View File
@@ -0,0 +1,132 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const B = require('../app/renderer/shared/bookmarks.js');
const empty = () => ({ savedServers: [], bookmarkFolders: [], bookmarkOrder: [] });
const ids = (state, folder = null) => B.contents(state, folder).map((entry) => entry.item.id);
function sample() {
let s = empty();
s = B.addBookmark(s, { id: 'bmk001', name: 'One', address: 'one.example' });
s = B.createFolder(s, { id: 'fold01', name: 'Games' });
s = B.addBookmark(s, { id: 'bmk002', name: 'Two', address: 'two.example' }, 'fold01');
s = B.createFolder(s, { id: 'fold02', name: 'Nested' }, 'fold01');
s = B.addBookmark(s, { id: 'bmk003', name: '', address: 'three.example' }, 'fold02');
return s;
}
test('creation appends to the target container and keeps every invariant', () => {
const s = sample();
assert.ok(B.consistent(s));
assert.deepEqual(ids(s), ['bmk001', 'fold01']);
assert.deepEqual(ids(s, 'fold01'), ['bmk002', 'fold02']);
assert.deepEqual(ids(s, 'fold02'), ['bmk003']);
// An empty bookmark name falls back to the address, like the official display name.
assert.equal(s.savedServers.find((entry) => entry.id === 'bmk003').name, 'three.example');
assert.deepEqual(B.allBookmarks(s).map((entry) => entry.id), ['bmk001', 'bmk002', 'bmk003']);
assert.throws(() => B.createFolder(s, { id: 'fold03', name: 'x' }, 'nope00'), { code: 'missing' });
assert.throws(() => B.createFolder(s, { id: 'bmk001', name: 'dup' }), { code: 'id' });
assert.throws(() => B.addBookmark(s, { id: 'bmk009', name: 'bad', address: ' ' }), { code: 'address' });
});
test('moves reorder within a container, enter and leave folders, and update the reference', () => {
let s = sample();
s = B.move(s, 'fold01', null, 'bmk001');
assert.deepEqual(ids(s), ['fold01', 'bmk001']);
s = B.move(s, 'bmk001', 'fold02', 'bmk003');
assert.deepEqual(ids(s), ['fold01']);
assert.deepEqual(ids(s, 'fold02'), ['bmk001', 'bmk003']);
assert.equal(s.savedServers.find((entry) => entry.id === 'bmk001').folder, 'fold02');
s = B.move(s, 'bmk001', null, null);
assert.equal('folder' in s.savedServers.find((entry) => entry.id === 'bmk001'), false);
s = B.move(s, 'fold02', null, 'fold01');
assert.equal('parent' in s.bookmarkFolders.find((entry) => entry.id === 'fold02'), false);
assert.deepEqual(ids(s), ['fold02', 'fold01', 'bmk001']);
assert.ok(B.consistent(s));
// The anchor must be a sibling in the destination container.
assert.throws(() => B.move(s, 'bmk002', null, 'bmk003'), { code: 'missing' });
});
test('a folder can never be moved into itself or its own subtree', () => {
const s = sample();
assert.throws(() => B.move(s, 'fold01', 'fold01', null), { code: 'cycle' });
assert.throws(() => B.move(s, 'fold01', 'fold02', null), { code: 'cycle' });
assert.equal(B.consistent(s), true);
});
test('folder depth and count stay bounded', () => {
let s = empty();
let parent = null;
for (let level = 1; level <= B.MAX_FOLDER_DEPTH; level++) {
const id = `lvl${String(level).padStart(3, '0')}`;
s = B.createFolder(s, { id, name: `L${level}` }, parent);
parent = id;
}
assert.throws(() => B.createFolder(s, { id: 'toodeep', name: 'x' }, parent), { code: 'depth' });
s = B.createFolder(s, { id: 'side01', name: 'Side' });
// Moving the full eight-level chain under a root folder would make it nine levels deep.
assert.throws(() => B.move(s, 'lvl001', 'side01', null), { code: 'depth' });
assert.ok(B.consistent(B.move(s, 'lvl002', 'side01', null)));
let many = empty();
for (let i = 0; i < B.MAX_FOLDERS; i++) many = B.createFolder(many, { id: `f${String(i).padStart(5, '0')}`, name: '' });
assert.throws(() => B.createFolder(many, { id: 'fextra', name: 'x' }), { code: 'folder-limit' });
});
test('deleting a folder removes its whole subtree and nothing else', () => {
const s = B.remove(sample(), 'fold01');
assert.deepEqual(s.savedServers.map((entry) => entry.id), ['bmk001']);
assert.deepEqual(s.bookmarkFolders, []);
assert.deepEqual(s.bookmarkOrder, ['bmk001']);
assert.ok(B.consistent(s));
const single = B.remove(sample(), 'bmk002');
assert.deepEqual(ids(single, 'fold01'), ['fold02']);
assert.throws(() => B.remove(single, 'bmk002'), { code: 'missing' });
});
test('rename keeps identity; empty folder names are allowed, empty bookmark names show the address', () => {
let s = B.rename(sample(), 'fold01', ' ');
assert.equal(s.bookmarkFolders.find((entry) => entry.id === 'fold01').name, '');
s = B.rename(s, 'bmk001', '');
assert.equal(s.savedServers.find((entry) => entry.id === 'bmk001').name, 'one.example');
assert.throws(() => B.rename(s, 'bmk001', 'x'.repeat(B.NAME_MAX + 1)), { code: 'name' });
assert.throws(() => B.rename(s, 'bmk001', 'a\u0007b'), { code: 'name' });
});
test('duplicate places a copy right after the original in the same folder', () => {
const s = B.duplicate(sample(), 'bmk002', 'copy01');
assert.deepEqual(ids(s, 'fold01'), ['bmk002', 'copy01', 'fold02']);
const copy = s.savedServers.find((entry) => entry.id === 'copy01');
assert.deepEqual({ ...copy, id: 'bmk002' }, { ...s.savedServers.find((entry) => entry.id === 'bmk002'), name: 'Two Copy' });
assert.equal(B.duplicate(sample(), 'bmk002', 'copy02', '').savedServers.find((entry) => entry.id === 'copy02').name, 'Two');
assert.throws(() => B.duplicate(sample(), 'fold01', 'copy03'), { code: 'missing' });
});
test('the bookmark limit stays 50 regardless of folders', () => {
let s = empty();
for (let i = 0; i < B.MAX_BOOKMARKS; i++) s = B.addBookmark(s, { id: `b${String(i).padStart(5, '0')}`, name: 'x', address: `h${i}` });
assert.throws(() => B.addBookmark(s, { id: 'bextra', name: 'x', address: 'h' }), { code: 'bookmark-limit' });
assert.throws(() => B.duplicate(s, 'b00000', 'bcopy1'), { code: 'bookmark-limit' });
});
test('normalize keeps legacy bookmark order and moves orphans to the root without losing bookmarks', () => {
const legacy = { savedServers: [{ id: 'aaa111', name: 'A', address: 'a' }, { id: 'bbb222', name: 'B', address: 'b' }], bookmarkFolders: [], bookmarkOrder: [] };
assert.deepEqual(B.normalize(legacy).bookmarkOrder, ['aaa111', 'bbb222']);
const broken = {
savedServers: [{ id: 'aaa111', name: 'A', address: 'a', folder: 'gone00' }, { id: 'bbb222', name: 'B', address: 'b', folder: 'okay01' }],
bookmarkFolders: [
{ id: 'cyc001', name: 'x', parent: 'cyc002' }, { id: 'cyc002', name: 'y', parent: 'cyc001' },
{ id: 'okay01', name: 'ok' }, { id: 'kid001', name: 'kid', parent: 'okay01' },
{ id: 'aaa111', name: 'clash' }, { id: 'kid002', name: 'orphan', parent: 'aaa111' },
],
bookmarkOrder: ['cyc001', 'zzz999', 'bbb222'],
};
const repaired = B.normalize(broken);
assert.deepEqual(repaired, {
savedServers: [{ id: 'aaa111', name: 'A', address: 'a' }, { id: 'bbb222', name: 'B', address: 'b', folder: 'okay01' }],
bookmarkFolders: [{ id: 'cyc001', name: 'x' }, { id: 'cyc002', name: 'y' }, { id: 'okay01', name: 'ok' }, { id: 'kid001', name: 'kid', parent: 'okay01' }, { id: 'kid002', name: 'orphan' }],
bookmarkOrder: ['cyc001', 'bbb222', 'cyc002', 'okay01', 'kid001', 'kid002', 'aaa111'],
});
assert.ok(B.consistent(repaired));
});
+118
View File
@@ -0,0 +1,118 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
MARKDOWN_HELP_IDS, showsMessage, formatClock, opensIncoming, isIgnoredUid, isIgnoredText, withIgnored, withoutIgnored,
} from '../app/renderer/js/chat-options.js';
import { parseMarkdown, toPlainText } from '../app/renderer/js/markdown/parse.js';
import { t, setLanguage, hasTranslation } from '../app/renderer/js/i18n.js';
const BAD = 'QkJCQkJCQkJCQkJCQkJCQkJCQkI=';
const SELF = 'QUFBQUFBQUFBQUFBQUFBQUFBQUE=';
const conn = { snap: { own_client_id: 1, clients: [{ id: 1, uid: SELF }, { id: 2, uid: BAD }, { id: 3, uid: 'other=' }] } };
const ignoring = { chatIgnoredUsers: [{ uid: BAD, name: 'Spammer' }] };
test('moderation events are hidden only when the option is off; messages, pokes and notices always show', () => {
const moderation = { system: true, moderation: true };
const notice = { system: true };
const text = { author: 'A', text: 'hi' };
for (const prefs of [undefined, {}, { chatShowModerationEvents: true }]) assert.equal(showsMessage(moderation, prefs), true);
assert.equal(showsMessage(moderation, { chatShowModerationEvents: false }), false);
assert.equal(showsMessage(notice, { chatShowModerationEvents: false }), true);
assert.equal(showsMessage(text, { chatShowModerationEvents: false }), true);
});
test('timestamps default to 24-hour and switch to the locale 12-hour clock', () => {
const date = new Date(2026, 10, 1, 15, 5);
for (const prefs of [undefined, {}, { chatUse24hTime: true }]) assert.equal(formatClock(date, 'en', prefs), '15:05');
assert.match(formatClock(date, 'en', { chatUse24hTime: false }), /^3:05\sPM$/u);
assert.equal(formatClock(new Date(2026, 10, 1, 9, 7), 'ru', {}), '09:07');
const ru12 = formatClock(date, 'ru', { chatUse24hTime: false });
assert.match(ru12, /^3:05\s/u);
assert.notEqual(ru12, formatClock(date, 'ru', {}));
});
test('incoming chats open in the sidebar by default', () => {
assert.equal(opensIncoming(undefined), true);
assert.equal(opensIncoming({ chatOpenIncoming: true }), true);
assert.equal(opensIncoming({ chatOpenIncoming: false }), false);
});
test('ignored users: only inbound texts and pokes carrying an ignored invoker UID are suppressed', () => {
for (const target of ['channel', 'server', 'client', 'poke']) {
const evt = Object.freeze({ event: 'text', target, from_client_id: 2, from_uid: BAD, from_nickname: 'Spammer', message: 'x', to_client_id: 1 });
assert.equal(isIgnoredText(evt, conn, ignoring), true, target);
assert.equal(isIgnoredText(evt, conn, {}), false, target);
}
// Other senders, our own echoes and events without a reported UID are never dropped.
assert.equal(isIgnoredText({ target: 'channel', from_client_id: 3, from_uid: 'other=' }, conn, ignoring), false);
assert.equal(isIgnoredText({ target: 'client', from_client_id: 1, from_uid: SELF, to_client_id: 2 }, conn, { chatIgnoredUsers: [{ uid: SELF, name: '' }] }), false);
assert.equal(isIgnoredText({ target: 'channel', from_client_id: 2 }, conn, ignoring), false);
assert.equal(isIgnoredText({ target: 'server', from_client_id: 0, from_uid: null }, conn, ignoring), false);
assert.equal(isIgnoredUid(ignoring, BAD), true);
assert.equal(isIgnoredUid(ignoring, ''), false);
assert.equal(isIgnoredUid(ignoring, undefined), false);
});
test('ignore list edits are explicit, deduplicated and never mutate the current prefs', () => {
const prefs = Object.freeze({ chatIgnoredUsers: Object.freeze([Object.freeze({ uid: BAD, name: 'Spammer' })]) });
const added = withIgnored(prefs, 'other=', 'Ot\u0007her'.padEnd(200, 'x'));
assert.deepEqual(added.map((entry) => entry.uid), [BAD, 'other=']);
assert.equal(added[1].name.length, 128);
assert.equal(added[1].name.startsWith('Other'), true);
const renamed = withIgnored({ chatIgnoredUsers: added }, BAD, 'Renamed');
assert.deepEqual(renamed.map((entry) => [entry.uid, entry.name.slice(0, 7)]), [[BAD, 'Renamed'], ['other=', 'Otherxx']]);
assert.deepEqual(withoutIgnored({ chatIgnoredUsers: renamed }, BAD).map((entry) => entry.uid), ['other=']);
assert.deepEqual(withoutIgnored(prefs, 'missing='), prefs.chatIgnoredUsers);
assert.deepEqual(withIgnored(undefined, BAD, 'A'), [{ uid: BAD, name: 'A' }]);
});
function types(value, found = new Set()) {
if (!value || typeof value !== 'object') return found;
if (typeof value.type === 'string') found.add(value.type);
for (const child of Object.values(value)) if (child && typeof child === 'object') types(child, found);
return found;
}
// What the TeamsPeach renderer must produce for each official Markdown Help example.
const EXPECTED = {
heading: ['heading'], setext_heading: ['heading'], emphasis_italic: ['em'], strong_bold: ['strong'],
strikethrough: ['del'], underline: ['u'], highlight: ['mark'], superscript: ['sup'], subscript: ['sub'],
inline_code: ['code'], inline_math: ['math'], link: ['link'], reference_link: ['link'],
link_reference_definition: ['em', 'link'], sized_image_pipe: ['image'], sized_image_equals: ['image'],
autolink: ['link'], plain_url: ['link'], blockquote: ['blockquote'], callout: ['blockquote'],
unordered_list: ['list'], ordered_list: ['list'], task_list_item: ['list'], fenced_code_block: ['code'],
indented_code_block: ['paragraph'], fenced_math_block: ['math_block'], mermaid_diagram: ['mermaid'], table: ['table'],
thematic_break: ['hr'], details_summary: ['details'], align: ['align'], footnote_reference: ['fnref'],
footnote_definition: [], spoiler: ['spoiler'], escape_sequence: ['paragraph'], html_entity: ['paragraph'], emoji: ['emoji'],
};
for (const language of ['en', 'ru']) test(`every Markdown Help example is translated and rendered as its syntax (${language})`, () => {
setLanguage(language);
assert.deepEqual(Object.keys(EXPECTED), MARKDOWN_HELP_IDS);
for (const key of ['title', 'intro.title', 'intro.body', 'syntax.title', 'card.syntax', 'card.example']) {
assert.notEqual(t(`settings.chat.markdown_help.${key}`), `settings.chat.markdown_help.${key}`, key);
}
for (const id of MARKDOWN_HELP_IDS) {
for (const part of ['name', 'syntax', 'example']) {
const key = `settings.chat.markdown_help.syntax.${id}.${part}`;
assert.equal(hasTranslation(key), true, key);
assert.notEqual(t(key), key, key);
}
const doc = parseMarkdown(t(`settings.chat.markdown_help.syntax.${id}.example`));
assert.equal(doc.tooComplex, undefined, id);
const found = types(doc.children);
for (const type of EXPECTED[id]) assert.equal(found.has(type), true, `${id}: ${type} in ${[...found]}`);
if (id === 'callout') assert.ok(doc.children[0].callout, id);
if (id === 'task_list_item') assert.equal(doc.children[0].items[0].task, true, id);
if (id === 'indented_code_block') assert.equal(found.has('code'), false, 'the chat dialect has no indented code blocks');
if (id === 'footnote_reference' || id === 'footnote_definition') assert.equal(doc.footnotes.length, 1, id);
if (id === 'escape_sequence') { assert.equal(found.has('em'), false); assert.match(toPlainText(doc).trim(), /^\*.+\*$/u); }
if (id === 'html_entity') assert.match(toPlainText(doc), /&/u);
}
setLanguage('en');
});
test('a document without footnote references still renders its definitions; references keep first-use order', () => {
assert.deepEqual(parseMarkdown('[^a]: first\n[^b]: second').footnotes.map((note) => note.label), ['a', 'b']);
assert.deepEqual(parseMarkdown('x[^b]\n\n[^a]: first\n[^b]: second').footnotes.map((note) => [note.label, note.number]), [['b', 1]]);
});
+73
View File
@@ -0,0 +1,73 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { Prefs } = require('../app/main/prefs');
const { MAX_IGNORED_USERS } = require('../app/main/chat-prefs');
function tempFile() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'teamspeach-chat-prefs-'));
return { file: path.join(dir, 'prefs.json'), cleanup: () => fs.rmSync(dir, { recursive: true, force: true }) };
}
const UID = 'QkJCQkJCQkJCQkJCQkJCQkJCQkI=';
test('new profiles get the official Settings > Chats defaults', () => {
const { file, cleanup } = tempFile();
try {
const values = new Prefs(file).get();
assert.equal(values.chatToolbarVisibility, 'always-visible');
assert.equal(values.chatMermaidAutoload, 'only-simple');
assert.equal(values.chatOpenIncoming, true);
assert.equal(values.chatShowModerationEvents, true);
assert.equal(values.chatUse24hTime, true);
assert.equal(values.autoDownloadImages, false);
assert.deepEqual(values.chatIgnoredUsers, []);
} finally { cleanup(); }
});
test('chat options and the ignore list persist across restarts', () => {
const { file, cleanup } = tempFile();
try {
new Prefs(file).set({ chatOpenIncoming: false, chatShowModerationEvents: false, chatUse24hTime: false, chatIgnoredUsers: [{ uid: UID, name: 'Spammer' }, { uid: 'serveradmin', name: '' }] });
const values = new Prefs(file).get();
assert.equal(values.chatOpenIncoming, false);
assert.equal(values.chatShowModerationEvents, false);
assert.equal(values.chatUse24hTime, false);
assert.deepEqual(values.chatIgnoredUsers, [{ uid: UID, name: 'Spammer' }, { uid: 'serveradmin', name: '' }]);
} finally { cleanup(); }
});
test('malformed chat values are rejected without changing stored prefs', () => {
const { file, cleanup } = tempFile();
try {
const prefs = new Prefs(file);
prefs.set({ chatIgnoredUsers: [{ uid: UID, name: 'Kept' }] });
const invalid = [
{ chatOpenIncoming: 'yes' }, { chatShowModerationEvents: 1 }, { chatUse24hTime: null },
{ chatIgnoredUsers: [{ uid: UID, name: 'A' }, { uid: UID, name: 'B' }] },
{ chatIgnoredUsers: [{ uid: 'not a uid', name: '' }] },
{ chatIgnoredUsers: [{ uid: UID, name: 'line\nbreak' }] },
{ chatIgnoredUsers: [{ uid: UID, name: 'x'.repeat(129) }] },
{ chatIgnoredUsers: [{ uid: UID, name: '', extra: true }] },
{ chatIgnoredUsers: [{ uid: UID }] },
{ chatIgnoredUsers: Array.from({ length: MAX_IGNORED_USERS + 1 }, (_, i) => ({ uid: `u${i}`, name: '' })) },
];
for (const patch of invalid) assert.throws(() => prefs.set(patch), /prefs: invalid value/, JSON.stringify(patch).slice(0, 80));
assert.deepEqual(new Prefs(file).get().chatIgnoredUsers, [{ uid: UID, name: 'Kept' }]);
} finally { cleanup(); }
});
test('a hand-edited file with invalid chat values falls back to the defaults per key', () => {
const { file, cleanup } = tempFile();
try {
fs.writeFileSync(file, JSON.stringify({ chatUse24hTime: 'no', chatIgnoredUsers: [{ uid: '', name: 'x' }], chatShowModerationEvents: false }));
const values = new Prefs(file).get();
assert.equal(values.chatUse24hTime, true);
assert.deepEqual(values.chatIgnoredUsers, []);
assert.equal(values.chatShowModerationEvents, false);
} finally { cleanup(); }
});
+129
View File
@@ -0,0 +1,129 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
PRESENCE, MAX_CONTACTS, withContact, withoutContact, withAlias, findContact, highlightsContact, sessionsFor, presenceOf,
displayName, buildEntries, sortEntries, arrangeEntries, chooseSession, cleanText,
} from '../app/renderer/js/contacts-model.js';
import { parseClientBadges, MAX_SHOWN_BADGES, MAX_BADGE_STRING } from '../app/renderer/js/badges-model.js';
const A = 'QUFBQUFBQUFBQUFBQUFBQUFBQUE=';
const B = 'QkJCQkJCQkJCQkJCQkJCQkJCQkI=';
const C = 'Q0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0M=';
const SELF = 'U0VMRlNFTEZTRUxGU0VMRlNFTEY=';
const client = (id, uid, nickname, extra = {}) => ({ id, uid, nickname, away: false, is_self: false, ...extra });
const conn = (id, clients, { connected = true, name = id } = {}) => ({
id, connected, snap: { own_client_id: 1, server: { name }, clients: [client(1, SELF, 'me', { is_self: true }), ...clients] },
});
test('adding the same UID again reuses the contact: alias and position kept, remembered nickname refreshed', () => {
let prefs = { contacts: withContact({}, A, 'Alice') };
prefs = { contacts: withContact(prefs, B, 'Bob') };
prefs = { contacts: withAlias(prefs, A, ' Ally ') };
const again = withContact(prefs, A, 'Alice2');
assert.deepEqual(again, [{ uid: A, alias: 'Ally', name: 'Alice2' }, { uid: B, alias: '', name: 'Bob' }]);
// An empty nickname never erases the remembered one.
assert.equal(withContact(prefs, B, '')[1].name, 'Bob');
assert.equal(findContact({ contacts: again }, A).alias, 'Ally');
assert.deepEqual(withoutContact({ contacts: again }, A).map((c) => c.uid), [B]);
assert.deepEqual(withAlias({ contacts: again }, A, '').find((c) => c.uid === A).alias, '');
assert.throws(() => withContact({}, 'not a uid', 'x'), /invalid UID/);
const full = { contacts: Array.from({ length: MAX_CONTACTS }, (_, i) => ({ uid: `u${i}`, alias: '', name: '' })) };
assert.throws(() => withContact(full, A, 'x'), /at most/);
assert.equal(withContact(full, 'u5', 'kept').length, MAX_CONTACTS);
});
test('text written to prefs is stripped of control characters and capped like the main schema', () => {
assert.equal(cleanText('a\u0000b\nc\u007f'), 'abc');
assert.equal(cleanText('x'.repeat(300)).length, 128);
assert.equal(cleanText(42), '');
assert.equal(withContact({}, A, 'Bad\u0007Name')[0].name, 'BadName');
});
test('presence comes only from connected snapshots; the same UID on two servers is one contact with two sessions', () => {
const connections = [
conn('c1', [client(5, A, 'Alice', { away: true }), client(6, B, 'Bob')], { name: 'One' }),
conn('c2', [client(9, A, 'Alice@Two')], { name: 'Two' }),
conn('c3', [client(7, C, 'Carol')], { connected: false }),
];
const sessions = sessionsFor(A, connections);
assert.deepEqual(sessions.map((s) => [s.connectionId, s.clientId, s.serverName, s.away]), [['c1', 5, 'One', true], ['c2', 9, 'Two', false]]);
assert.equal(presenceOf(sessions), PRESENCE.AVAILABLE, 'available on any server wins over away');
assert.equal(presenceOf(sessionsFor(A, [connections[0]])), PRESENCE.AWAY);
// A disconnected connection's last snapshot never counts as presence.
assert.deepEqual(sessionsFor(C, connections), []);
assert.equal(presenceOf([]), PRESENCE.OFFLINE);
// The own client (same identity on this connection) is never a contact session.
assert.deepEqual(sessionsFor(SELF, connections), []);
assert.deepEqual(sessionsFor('bad uid', connections), []);
assert.deepEqual(sessionsFor(A, null), []);
});
test('display name: alias, else current nickname, else remembered nickname', () => {
assert.equal(displayName({ alias: 'Ally', name: 'Alice' }, [{ nickname: 'Now' }]), 'Ally');
assert.equal(displayName({ alias: '', name: 'Alice' }, [{ nickname: 'Now' }]), 'Now');
assert.equal(displayName({ alias: '', name: 'Alice' }, []), 'Alice');
assert.equal(displayName({ alias: '', name: '' }, []), '');
});
test('highlight follows Highlight Contacts and never marks the own client', () => {
const prefs = { contacts: [{ uid: A, alias: '', name: '' }] };
assert.equal(highlightsContact(prefs, { uid: A }), true);
assert.equal(highlightsContact({ ...prefs, highlightContacts: false }, { uid: A }), false);
assert.equal(highlightsContact(prefs, { uid: A, is_self: true }), false);
assert.equal(highlightsContact(prefs, { uid: B }), false);
assert.equal(highlightsContact(prefs, null), false);
});
const entry = (uid, name, presence, unread = 0) => ({ uid, name, presence, unread, sessions: [], contact: { uid, alias: '', name } });
test('sorting: alphabetical (case-insensitive, UID tiebreak) or by presence then name', () => {
const list = [entry(C, 'carol', PRESENCE.OFFLINE), entry(B, 'Bob', PRESENCE.AWAY), entry(A, 'alice', PRESENCE.AVAILABLE), entry('zz', 'Bob', PRESENCE.AVAILABLE)];
assert.deepEqual(sortEntries(list, true).map((e) => e.uid), [A, B, 'zz', C]);
assert.deepEqual(sortEntries(list, false).map((e) => e.uid), [A, 'zz', B, C]);
// Input order is never mutated.
assert.deepEqual(list.map((e) => e.uid), [C, B, A, 'zz']);
});
test('offline arrangement matches the official show/group rules', () => {
const list = [entry(A, 'a', PRESENCE.AVAILABLE), entry(B, 'b', PRESENCE.OFFLINE, 2), entry(C, 'c', PRESENCE.OFFLINE)];
const ids = (xs) => xs?.map((e) => e.uid) ?? null;
// Show + group: online list, separate offline group.
let r = arrangeEntries(list, { showOffline: true, groupOffline: true });
assert.deepEqual([ids(r.main), ids(r.offline), r.grouped], [[A], [B, C], true]);
// Show without grouping: one list with everyone.
r = arrangeEntries(list, { showOffline: true, groupOffline: false });
assert.deepEqual([ids(r.main), ids(r.offline), r.grouped], [[A, B, C], null, false]);
// Hidden: only offline contacts with unread messages stay, grouping is ignored.
r = arrangeEntries(list, { showOffline: false, groupOffline: true });
assert.deepEqual([ids(r.main), ids(r.offline), r.grouped], [[A, B], null, false]);
// Filter by display name.
r = arrangeEntries(list, { filter: ' B ' });
assert.deepEqual([ids(r.main), ids(r.offline)], [[], [B]]);
});
test('entries combine prefs, presence and unread counts', () => {
const prefs = { contacts: [{ uid: A, alias: '', name: 'old' }, { uid: C, alias: 'Cee', name: 'Carol' }] };
const entries = buildEntries(prefs, [conn('c1', [client(5, A, 'Alice')])], (uid) => (uid === C ? 3 : 0));
assert.deepEqual(entries.map((e) => [e.uid, e.name, e.presence, e.unread]), [[A, 'Alice', PRESENCE.AVAILABLE, 0], [C, 'Cee', PRESENCE.OFFLINE, 3]]);
});
test('opening a contact present on several connections picks the viewed one, else creation order', () => {
const sessions = [{ connectionId: 'c1', clientId: 5 }, { connectionId: 'c2', clientId: 9 }];
assert.equal(chooseSession(sessions, 'c2').clientId, 9);
assert.equal(chooseSession(sessions, 'c3').clientId, 5);
assert.equal(chooseSession([], 'c1'), null);
});
test('client badge strings: only the badges key, valid UUIDs, deduplicated, at most three', () => {
const u = (n) => `${String(n).repeat(8)}-1111-2222-3333-444444444444`;
assert.deepEqual(parseClientBadges(`Overwolf=0:badges=${u(1)},${u(2)}`), [u(1), u(2)]);
assert.deepEqual(parseClientBadges(`badges=${u(1).toUpperCase()}, ${u(1)} ,not-a-uuid,${u(2)},${u(3)},${u(4)}`), [u(1), u(2), u(3)]);
assert.equal(parseClientBadges(`BADGES=${u(1)},${u(2)},${u(3)},${u(4)}`).length, MAX_SHOWN_BADGES);
assert.deepEqual(parseClientBadges(`overwolf=1:other=${u(1)}`), []);
assert.deepEqual(parseClientBadges(u(1)), [], 'a bare UUID without the badges key is not trusted');
assert.deepEqual(parseClientBadges('badges='), []);
assert.deepEqual(parseClientBadges(null), []);
assert.deepEqual(parseClientBadges(42), []);
assert.deepEqual(parseClientBadges(`badges=${u(1)}${','.repeat(MAX_BADGE_STRING)}`), [], 'oversized strings are ignored');
});
+75
View File
@@ -0,0 +1,75 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { Prefs } = require('../app/main/prefs');
const { CONTACT_SCHEMA, MAX_CONTACTS } = require('../app/main/contacts-prefs');
const UID = 'QkJCQkJCQkJCQkJCQkJCQkJCQkI=';
const OTHER = 'QUFBQUFBQUFBQUFBQUFBQUFBQUE=';
function tempFile() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'teamspeach-contacts-prefs-'));
return { file: path.join(dir, 'prefs.json'), cleanup: () => fs.rmSync(dir, { recursive: true, force: true }) };
}
test('new profiles get the official contact and tree defaults', () => {
const { file, cleanup } = tempFile();
try {
const values = new Prefs(file).get();
assert.deepEqual(values.contacts, []);
assert.equal(values.contactsSortAlphabetically, true);
assert.equal(values.contactsShowOffline, true);
assert.equal(values.contactsGroupOffline, true);
assert.equal(values.contactsOnlineExpanded, true);
assert.equal(values.contactsOfflineExpanded, false);
assert.equal(values.showBadges, true);
assert.equal(values.highlightContacts, true);
} finally { cleanup(); }
});
test('contacts round-trip; invalid lists are rejected without touching the stored value', () => {
const { file, cleanup } = tempFile();
try {
const prefs = new Prefs(file);
const kept = [{ uid: UID, alias: 'Bee', name: 'Bob' }, { uid: 'serveradmin', alias: '', name: '' }];
prefs.set({ contacts: kept, showBadges: false, highlightContacts: false, contactsGroupOffline: false });
const reread = new Prefs(file).get();
assert.deepEqual(reread.contacts, kept);
assert.equal(reread.showBadges, false);
assert.equal(reread.highlightContacts, false);
assert.equal(reread.contactsGroupOffline, false);
const invalid = [
{ contacts: [{ uid: UID, alias: '', name: '' }, { uid: UID, alias: 'x', name: '' }] },
{ contacts: [{ uid: 'not a uid', alias: '', name: '' }] },
{ contacts: [{ uid: UID, alias: 'line\nbreak', name: '' }] },
{ contacts: [{ uid: UID, alias: '', name: 'x'.repeat(129) }] },
{ contacts: [{ uid: UID, alias: '', name: '', extra: 1 }] },
{ contacts: [{ uid: UID, name: '' }] },
{ contacts: Array.from({ length: MAX_CONTACTS + 1 }, (_, i) => ({ uid: `u${i}`, alias: '', name: '' })) },
{ showBadges: 'yes' }, { highlightContacts: null }, { contactsSortAlphabetically: 1 },
];
for (const patch of invalid) assert.throws(() => prefs.set(patch), /prefs: invalid value/, JSON.stringify(patch).slice(0, 80));
assert.deepEqual(new Prefs(file).get().contacts, kept);
} finally { cleanup(); }
});
test('a corrupt stored list falls back to the default instead of failing the profile', () => {
const { file, cleanup } = tempFile();
try {
fs.writeFileSync(file, JSON.stringify({ contacts: [{ uid: OTHER }], showBadges: false }));
const values = new Prefs(file).get();
assert.deepEqual(values.contacts, []);
assert.equal(values.showBadges, false);
} finally { cleanup(); }
});
test('schema module is self-contained (every key validated)', () => {
for (const [key, spec] of Object.entries(CONTACT_SCHEMA)) {
assert.equal(spec.check(spec.default), true, key);
assert.equal(spec.check(undefined), false, key);
}
});
+18 -2
View File
@@ -1,5 +1,18 @@
// Minimal browser environment for renderer modules under node:test: a fake DOM, Web Audio, getUserMedia and
// the preload bridge. Import this module before any renderer module. No real devices, no network.
// the preload bridge. Import this module before any renderer module. No real devices, no network: fetch of
// a file: URL serves the bundled asset from disk, as the app protocol serves the renderer's own files.
import { readFile } from 'node:fs/promises';
const networkFetch = globalThis.fetch;
globalThis.fetch = async (input, init) => {
const url = URL.canParse(String(input)) ? new URL(String(input)) : null;
if (url?.protocol !== 'file:') return networkFetch(input, init);
try {
return new Response(await readFile(url));
} catch {
return new Response(null, { status: 404 });
}
};
const timeout = globalThis.setTimeout;
globalThis.setTimeout = (fn, ms, ...args) => {
@@ -144,11 +157,14 @@ globalThis.AudioContext = class {
async close() { this.state = 'closed'; }
};
globalThis.AudioWorkletNode = class extends EventTarget {
constructor(context, name) {
constructor(context, name, options = {}) {
super();
this.context = context;
this.name = name;
this.options = options;
Object.assign(this, node(), { port: { postMessage(data) { if (data.type === 'stop') this.onmessage?.({ data: { type: 'stopped' } }); }, close() {}, onmessage: null } });
// A capture processor given a noise-reduction module answers like the real one once it has started it.
if (options.processorOptions?.denoise) queueMicrotask(() => this.port.onmessage?.({ data: { type: 'ready' } }));
env.worklets.push(this);
}
};
+1 -1
View File
@@ -1,7 +1,7 @@
import { S, newConnection } from '../../app/renderer/js/state.js';
export function voicePrefs() {
return { inputDeviceId: '', outputDeviceId: '', pttEnabled: false, pttReleaseDelay: { active: false, ms: 300 },
inputDsp: { template: { agc: true, denoise: true, typing: false, vad: false, vadMode: 'automatic', vadLevel: -30, vadSensitivity: 'normal' }, devices: {} },
inputDsp: { template: { agc: true, denoise: true, denoiseLevel: 1, typing: false, vad: false, vadMode: 'automatic', vadLevel: -30, vadSensitivity: 'normal' }, devices: {} },
outputDsp: { template: { aec: false, agc: true, comfortNoise: false, comfortNoiseLevel: -60, echoReduction: 0 }, devices: {} },
pttCode: 'F8', outputLevelDb: 0, notificationDeviceId: 'none', notificationLevelDb: -200 };
}
+22
View File
@@ -0,0 +1,22 @@
// About renderer helpers (information-panels.js) with the fake bridge; no Electron, file access or network.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import './fixtures/renderer-env.mjs';
const info = await import('../app/renderer/js/information-panels.js');
test('changelog lines keep text verbatim and mark only `code` spans', () => {
assert.deepEqual(info.changelogParts('Use `Добавьте` and `a` b'), [
{ type: 'text', text: 'Use ' }, { type: 'code', text: 'Добавьте' }, { type: 'text', text: ' and ' }, { type: 'code', text: 'a' }, { type: 'text', text: ' b' },
]);
assert.deepEqual(info.changelogParts('no markup <b>'), [{ type: 'text', text: 'no markup <b>' }]);
assert.deepEqual(info.changelogParts('unclosed `tick'), [{ type: 'text', text: 'unclosed `tick' }]);
});
test('changelog dates use the local calendar day; today uses the official "Today" key', () => {
assert.equal(info.formatChangelogDate(null), '');
assert.equal(info.formatChangelogDate('2026-10-24', new Date(2026, 10, 1), 'en'), new Date(2026, 9, 24).toLocaleDateString('en'));
assert.equal(info.formatChangelogDate('2026-11-01', new Date(2026, 10, 1, 23, 59), 'en'), 'Today');
assert.equal(info.changelogTitle({ unreleased: true }), 'Unreleased');
assert.equal(info.changelogTitle({ version: '0.1.0', qualifier: '(pre-release)' }), 'Update 0.1.0 (pre-release)');
});
+167
View File
@@ -0,0 +1,167 @@
'use strict';
// Settings > About data service: CHANGELOG.md, core/renderer/Chromium notices and the production npm tree.
// Synthetic fixtures in a temporary directory plus the repository's own files; no Electron, network or profile.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const {
parseChangelog, parseCoreNotices, parseVendorNotices, parseChromiumCredits, collectProductionPackages,
npmRepository, informationPaths, createInformationService, registerInformationIpc,
} = require('../app/main/information-panels.js');
const ROOT = path.resolve(__dirname, '..');
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'tp-info-'));
const write = (file, text) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, text); };
test('changelog headings, paragraphs and continued bullet items become official entries', () => {
const entries = parseChangelog([
'# Changelog', '', '## Unreleased', '', '- First change with `code`', ' continued here.', '- Second', '',
'## 0.1.4 — 2026-10-24', '', 'Intro paragraph', 'on two lines.', '', '- Fix', '',
'## 0.1.0 — 2026-10-24 (pre-release, superseded by 0.1.1)', '', '- Initial',
].join('\n'));
assert.deepEqual(entries, [
{ version: 'Unreleased', date: null, qualifier: null, unreleased: true, notes: [], changes: ['First change with `code` continued here.', 'Second'] },
{ version: '0.1.4', date: '2026-10-24', qualifier: null, unreleased: false, notes: ['Intro paragraph on two lines.'], changes: ['Fix'] },
{ version: '0.1.0', date: '2026-10-24', qualifier: '(pre-release, superseded by 0.1.1)', unreleased: false, notes: [], changes: ['Initial'] },
]);
});
test('the repository CHANGELOG.md parses into dated releases', () => {
const entries = parseChangelog(fs.readFileSync(path.join(ROOT, 'CHANGELOG.md'), 'utf8'));
assert.ok(entries.length >= 2);
for (const entry of entries) assert.ok(entry.changes.length > 0 || entry.notes.length > 0, entry.version);
assert.ok(entries.some((e) => e.date && /^\d+\.\d+\.\d+$/.test(e.version)));
});
test('core notices: table rows, shared license sections and the bundled libopus section', () => {
const md = [
'# Third-party notices for teamspeach-core', '', 'Generated by a tool.', '',
'| Crate | Version | License | Source |', '|---|---|---|---|',
'| aead | 0.5.2 | MIT OR Apache-2.0 | registry+https://github.com/rust-lang/crates.io-index |',
'| tsproto | 0.2.0 | MIT | git+https://github.com/ReSpeak/tsclientlib?rev=ee#ee |',
'| tsclientlib | 0.2.0 | MIT | vendored (core/vendor) |', '',
'## libopus (bundled in audiopus_sys, statically linked)', '', '```', 'Opus text', '```', '',
'## License texts', '', '### aead 0.5.2 (LICENSE-APACHE); tsproto 0.2.0 (LICENSE-APACHE)', '', '```', 'Apache', '```', '',
'### aead 0.5.2 (LICENSE-MIT)', '', '```', 'MIT text', '```',
].join('\n');
const { intro, entries } = parseCoreNotices(md);
assert.equal(intro, 'Generated by a tool.');
assert.deepEqual(entries.map((e) => [e.name, e.repository]), [
['libopus (bundled in audiopus_sys, statically linked)', null],
['aead', 'https://crates.io/crates/aead/0.5.2'],
['tsproto', 'https://github.com/ReSpeak/tsclientlib'],
['tsclientlib', null],
]);
assert.deepEqual(entries[1].texts, [{ label: 'LICENSE-APACHE', text: 'Apache' }, { label: 'LICENSE-MIT', text: 'MIT text' }]);
assert.equal(entries[0].texts[0].text, 'Opus text');
assert.equal(entries[3].texts.length, 0);
});
test('vendor notices split per package, keep the scope statement and unwrap parenthesised expressions', () => {
const { intro, entries } = parseVendorNotices([
'Chat renderer dependency notices', 'Includes build-only deps.', '',
'===== @scope/pkg@1.2.3 (MIT) =====', '', '--- LICENSE ---', 'MIT body', '',
'===== dompurify@3.4.17 ((MPL-2.0 OR Apache-2.0)) =====', '--- LICENSE ---', 'Dual',
].join('\n'));
assert.equal(intro, 'Includes build-only deps.');
assert.deepEqual(entries, [
{ name: '@scope/pkg', version: '1.2.3', license: 'MIT', text: '--- LICENSE ---\nMIT body' },
{ name: 'dompurify', version: '3.4.17', license: 'MPL-2.0 OR Apache-2.0', text: '--- LICENSE ---\nDual' },
]);
});
test('Chromium credits: one product per block, entities decoded, only http(s) homepages linked', () => {
const html = '<div class="product">\n<span class="title">A &amp; B</span>\n<span class="homepage"><a href="https://a.example/">homepage</a></span>\n'
+ '<div class="license">\n<pre>&quot;x&quot; &lt;y&gt; &#169;</pre>\n</div>\n</div>\n'
+ '<div class="product">\n<span class="title">C</span>\n<span class="homepage"><a href="javascript:x">homepage</a></span>\n<div class="license"><pre>c</pre></div></div>';
assert.deepEqual(parseChromiumCredits(html), [
{ name: 'A & B', repository: 'https://a.example/', text: '"x" <y> ©' },
{ name: 'C', repository: null, text: 'c' },
]);
});
test('npm repository fields normalise to https URLs only', () => {
assert.equal(npmRepository('nodeca/js-yaml'), 'https://github.com/nodeca/js-yaml');
assert.equal(npmRepository({ url: 'git+https://github.com/npm/node-semver.git' }), 'https://github.com/npm/node-semver');
assert.equal(npmRepository({ url: 'git@github.com:jprichardson/node-jsonfile.git' }), 'https://github.com/jprichardson/node-jsonfile');
assert.equal(npmRepository({ url: 'git://github.com/debug-js/debug.git' }), 'https://github.com/debug-js/debug');
assert.equal(npmRepository({ url: 'git+ssh://git@github.com/isaacs/sax-js.git' }), 'https://github.com/isaacs/sax-js');
assert.equal(npmRepository({ url: 'file:../x' }), null);
assert.equal(npmRepository(undefined), null);
});
test('production npm tree follows dependencies only, resolves nested copies and lists license files', () => {
const dir = tmp();
write(path.join(dir, 'package.json'), JSON.stringify({ dependencies: { a: '1' }, devDependencies: { dev: '1' } }));
write(path.join(dir, 'node_modules/a/package.json'), JSON.stringify({ name: 'a', version: '1.0.0', license: 'MIT', dependencies: { b: '2' } }));
write(path.join(dir, 'node_modules/a/LICENSE'), 'A');
write(path.join(dir, 'node_modules/a/node_modules/b/package.json'), JSON.stringify({ name: 'b', version: '2.0.0', license: 'ISC' }));
write(path.join(dir, 'node_modules/b/package.json'), JSON.stringify({ name: 'b', version: '1.0.0', license: 'ISC' }));
write(path.join(dir, 'node_modules/dev/package.json'), JSON.stringify({ name: 'dev', version: '1.0.0' }));
const { packages, missing } = collectProductionPackages(dir);
assert.deepEqual(packages.map((p) => [p.name, p.version, p.files]), [['a', '1.0.0', ['LICENSE']], ['b', '2.0.0', []]]);
assert.deepEqual(missing, []);
});
test('service serves a fixture installation and only ids from its own index', async () => {
const dir = tmp();
const exe = path.join(dir, 'electron', 'electron.exe');
write(path.join(dir, 'CHANGELOG.md'), '# Changelog\n\n## 1.0.0 — 2026-01-02\n\n- Hello\n');
write(path.join(dir, 'LICENSES/NOTICE.md'), 'Our notice');
write(path.join(dir, 'core-bin/win-x64/THIRD_PARTY_NOTICES.md'), '| Crate | Version | License | Source |\n|---|---|---|---|\n| x | 1.0.0 | MIT | registry+https://github.com/rust-lang/crates.io-index |\n\n## License texts\n\n### x 1.0.0 (LICENSE)\n\n```\nX\n```\n');
write(path.join(dir, 'package.json'), JSON.stringify({ dependencies: {} }));
write(path.join(dir, 'app/renderer/vendor/THIRD_PARTY_NOTICES.txt'), 'Title\n\n===== v@1.0.0 (MIT) =====\nV\n');
write(path.join(path.dirname(exe), 'LICENSE'), 'Electron MIT');
const service = createInformationService({ isPackaged: false, appRoot: dir, appPath: dir, resourcesPath: path.join(dir, 'electron', 'resources'), execPath: exe, rendererDir: path.join(dir, 'app/renderer'), platform: 'win32', arch: 'x64', electronVersion: '44.9.3' });
assert.deepEqual((await service.getChangelog()).entries[0].changes, ['Hello']);
const list = await service.getLicenses();
assert.equal(list.ok, true);
const byGroup = Object.fromEntries(list.groups.map((g) => [g.id, g]));
assert.deepEqual(list.groups.map((g) => g.id), ['teamspeach', 'electron', 'chromium', 'npm', 'core', 'renderer']);
assert.equal(byGroup.chromium.error.code, 'missing');
assert.equal(byGroup.electron.entries[0].version, '44.9.3');
const crate = byGroup.core.entries[0];
assert.equal((await service.getLicenseText(crate.id)).text, '--- LICENSE ---\nX');
assert.equal((await service.getLicenseText(byGroup.teamspeach.entries[0].id)).text, 'Our notice');
assert.equal((await service.getLicenseText(byGroup.renderer.entries[0].id)).text, 'V');
assert.equal((await service.getLicenseText('core:99')).error.code, 'not_found');
assert.equal((await service.getLicenseText('../../etc/passwd')).error.code, 'bad_request');
assert.equal((await service.getLicenseText({ id: 1 })).error.code, 'bad_request');
});
test('missing CHANGELOG.md is reported, not replaced', async () => {
const dir = tmp();
write(path.join(dir, 'package.json'), '{}');
const service = createInformationService({ isPackaged: true, appRoot: dir, appPath: dir, resourcesPath: path.join(dir, 'resources'), execPath: path.join(dir, 'app.exe'), rendererDir: path.join(dir, 'renderer'), platform: 'linux', arch: 'x64' });
assert.deepEqual(await service.getChangelog(), { ok: false, error: { code: 'missing', file: 'CHANGELOG.md' } });
});
test('packaged paths are fixed below resources and the executable directory', () => {
const p = informationPaths({ isPackaged: true, appRoot: '/x', appPath: '/opt/tp/resources/app.asar', resourcesPath: '/opt/tp/resources', execPath: '/opt/tp/teamspeach', rendererDir: '/opt/tp/resources/app.asar/app/renderer', platform: 'linux', arch: 'x64' });
assert.deepEqual(p.changelog, [path.join('/opt/tp/resources', 'CHANGELOG.md')]);
assert.equal(p.licensesDir, path.join('/opt/tp/resources', 'licenses'));
assert.deepEqual(p.electronLicenses, [path.join('/opt/tp', 'LICENSE.electron.txt'), path.join('/opt/tp/resources', 'LICENSE.electron.txt')]);
assert.deepEqual(p.chromiumCredits, [path.join('/opt/tp', 'LICENSES.chromium.html')]);
});
test('IPC handlers refuse untrusted senders', async () => {
const handlers = new Map();
const service = { getChangelog: async () => ({ ok: true }), getLicenses: async () => ({ ok: true }), getLicenseText: async (id) => ({ ok: true, id }) };
registerInformationIpc({ ipcMain: { handle: (name, fn) => handlers.set(name, fn) }, trustedSender: (event) => event.trusted, service });
assert.deepEqual([...handlers.keys()], ['about:changelog', 'about:licenses', 'about:license-text']);
assert.equal((await handlers.get('about:licenses')({ trusted: false })).error.code, 'forbidden');
assert.deepEqual(await handlers.get('about:license-text')({ trusted: true }, 'npm:0'), { ok: true, id: 'npm:0' });
});
test('repository sources parse: core notices, renderer vendor notices and the Electron credits page', { skip: !fs.existsSync(path.join(ROOT, 'node_modules/electron/dist/LICENSES.chromium.html')) && 'electron dist not installed' }, () => {
const core = parseCoreNotices(fs.readFileSync(path.join(ROOT, 'core/THIRD_PARTY_NOTICES.md'), 'utf8'));
assert.ok(core.entries.length > 100);
assert.ok(core.entries.filter((e) => !e.name.startsWith('libopus')).every((e) => e.texts.length > 0), 'every crate has a license text');
const vendor = parseVendorNotices(fs.readFileSync(path.join(ROOT, 'app/renderer/vendor/THIRD_PARTY_NOTICES.txt'), 'utf8'));
assert.ok(vendor.entries.some((e) => e.name === 'katex'));
const chromium = parseChromiumCredits(fs.readFileSync(path.join(ROOT, 'node_modules/electron/dist/LICENSES.chromium.html'), 'utf8'));
assert.ok(chromium.length > 100);
assert.ok(chromium.every((p) => p.name && p.text));
});
+74
View File
@@ -0,0 +1,74 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { KeyTracker, KeyChordRecorder, RemoteChordRecorder, matchKeydown, keyupReleases, matchRemote } from '../app/renderer/js/keybind-match.js';
const require = createRequire(import.meta.url);
const schema = require('../app/main/keybind-schema.js');
const key = (code, mods = {}) => ({ code, ctrlKey: false, altKey: false, shiftKey: false, metaKey: false, repeat: false, ...mods });
const bind = (id, code, mods = {}) => ({ id, code, ctrl: false, alt: false, shift: false, meta: false, ...mods });
test('exact match: modifiers must be equal and no other key held', () => {
const tracker = new KeyTracker();
const bindings = [bind('f9', 'F9'), bind('cf9', 'F9', { ctrl: true })];
tracker.down('KeyW'); tracker.down('F9');
assert.deepEqual(matchKeydown(bindings, key('F9'), { exact: true, pressed: tracker.pressed }), [], 'W is also held');
tracker.up('KeyW');
assert.deepEqual(matchKeydown(bindings, key('F9'), { exact: true, pressed: tracker.pressed }).map((b) => b.id), ['f9']);
assert.deepEqual(matchKeydown(bindings, key('F9', { ctrlKey: true, shiftKey: true }), { exact: true, pressed: tracker.pressed }), []);
});
test('non-exact match fires despite other keys, and only the most specific binding', () => {
const pressed = new Set(['KeyW', 'F9']);
const bindings = [bind('f9', 'F9'), bind('cf9', 'F9', { ctrl: true })];
assert.deepEqual(matchKeydown(bindings, key('F9', { shiftKey: true }), { exact: false, pressed }).map((b) => b.id), ['f9']);
assert.deepEqual(matchKeydown(bindings, key('F9', { ctrlKey: true, shiftKey: true }), { exact: false, pressed }).map((b) => b.id), ['cf9']);
assert.deepEqual(matchKeydown([{ ...bind('r', 'F9'), code: undefined, remote: { remoteApp: 'a', remoteButton: 'F9' } }], key('F9'), { exact: false, pressed }), []);
});
test('held physical bindings release on their key or any of their modifiers going up', () => {
const b = bind('x', 'F9', { ctrl: true });
assert.equal(keyupReleases(b, key('KeyW', { ctrlKey: true })), false);
assert.equal(keyupReleases(b, key('ControlLeft')), true);
assert.equal(keyupReleases(b, key('F9', { ctrlKey: true })), true);
});
test('keyboard recorder completes on a full down/up chord and cancels on Escape', () => {
const r = new KeyChordRecorder();
assert.equal(r.keydown(key('ControlLeft', { ctrlKey: true })).kind, 'update');
assert.equal(r.keydown(key('KeyK', { ctrlKey: true })).chord.code, 'KeyK');
assert.equal(r.keyup(key('KeyK', { ctrlKey: true })).kind, 'none', 'Ctrl still held');
assert.deepEqual(r.keyup(key('ControlLeft')), { kind: 'complete', chord: { code: 'KeyK', ctrl: true, alt: false, shift: false, meta: false } });
assert.equal(new KeyChordRecorder().keydown(key('Escape')).kind, 'cancel');
const modifiersOnly = new KeyChordRecorder();
modifiersOnly.keydown(key('ShiftLeft', { shiftKey: true }));
assert.equal(modifiersOnly.keyup(key('ShiftLeft')).kind, 'update', 'a modifier alone is not a binding');
});
test('remote recorder needs one complete button press and ignores releases from before capture', () => {
const r = new RemoteChordRecorder();
assert.equal(r.feed({ identifier: 'app', button: 'old', state: false }).kind, 'none');
r.feed({ identifier: 'app', button: 'b1', state: true });
assert.deepEqual(r.feed({ identifier: 'app', button: 'b1', state: false }), { kind: 'complete', remote: { remoteApp: 'app', remoteButton: 'b1' } });
r.feed({ identifier: 'app', button: 'b1', state: true });
r.feed({ identifier: 'app', button: 'b2', state: true });
r.feed({ identifier: 'app', button: 'b1', state: false });
assert.deepEqual(r.feed({ identifier: 'app', button: 'b2', state: false }), { kind: 'reject', reason: 'single_button' });
const bindings = [{ id: 'm', remote: { remoteApp: 'app', remoteButton: 'b1' } }, { id: 'n', remote: { remoteApp: 'other', remoteButton: 'b1' } }];
assert.deepEqual(matchRemote(bindings, { identifier: 'app', button: 'b1' }).map((b) => b.id), ['m']);
});
test('variant expansion never takes another binding\'s exact chord and respects the helper limit', () => {
const a = { id: 'a', code: 'F9', ctrl: false, alt: false, shift: false, meta: false };
const b = { id: 'b', code: 'F9', ctrl: true, alt: false, shift: false, meta: false };
const { registrations, variantOf } = schema.expandRegistrations([a, b], { exact: false });
const chords = registrations.map(schema.chordKey);
assert.equal(new Set(chords).size, chords.length);
assert.equal(variantOf.get(registrations.find((r) => schema.chordKey(r) === 'C+F9').id), 'b');
assert.equal(variantOf.get(registrations.find((r) => schema.chordKey(r) === 'CS+F9').id), 'b', 'Ctrl+Shift+F9 is closer to Ctrl+F9');
const many = Array.from({ length: 10 }, (_, i) => ({ ...a, id: `k${i}`, code: `F${i + 1}` }));
const limited = schema.expandRegistrations(many, { exact: false });
assert.equal(limited.registrations.length, 64);
assert.ok(limited.variants.wanted > limited.variants.registered);
});
+20 -1
View File
@@ -21,7 +21,11 @@ function fixture(testOffscreen) {
constructor() { super(); calls.push(['tray']); }
setToolTip() {} setContextMenu() {} destroy() { calls.push(['destroyTray']); }
}
class Notification { static isSupported() { return true; } }
class Notification extends EventEmitter {
static isSupported() { return true; }
constructor(options) { super(); this.options = options; }
show() { calls.push(['notify', this.options.title, this.options.body]); }
}
const electron = { app: { isPackaged: true, getLoginItemSettings: () => ({ openAtLogin: false }), setLoginItemSettings: () => calls.push(['login']) },
Menu: { buildFromTemplate: (value) => value }, Notification, Tray, powerMonitor };
const context = { module: { exports: {} }, __dirname: path.resolve(__dirname, '../app/main'), process: { platform: 'win32' },
@@ -58,3 +62,18 @@ test('Both hides on minimize and close only with a recovery tray; Never restores
f.handlers.get('os:apply')({});
assert.deepEqual(f.calls.slice(-2), [['skip', false], ['destroyTray']]);
});
test('channel desktop notifications have independent opt-in and respect focus', async () => {
const f = fixture(false);
const notify = (kind) => f.handlers.get('os:notify')({}, 'Message', 'Body', kind);
assert.equal(await notify('channel'), false);
assert.equal(await notify('private'), true);
f.prefs.systemNotifyChannelChat = true;
f.prefs.systemNotifyServerPrivate = false;
assert.equal(await notify('channel'), true);
assert.equal(await notify('private'), false);
assert.equal(await notify('server'), false);
f.win.isFocused = () => true;
assert.equal(await notify('channel'), false);
assert.equal(f.calls.filter(([kind]) => kind === 'notify').length, 2);
});
+8
View File
@@ -58,3 +58,11 @@ test('permission requests: HTML full screen for the stream player, from an app p
assert.equal(permissionRequestAllowed('fullscreen', undefined, APP), false);
assert.equal(permissionRequestAllowed('pointerLock', { requestingUrl: 'app://teamspeach/index.html' }, APP), false);
});
test('nested app renderers cannot acquire devices or presentation permissions', () => {
const nested = { requestingUrl: 'app://teamspeach/mermaid-frame.html', isMainFrame: false, mediaType: 'audio', mediaTypes: ['audio'] };
for (const permission of ['media', 'speaker-selection', 'fullscreen', 'display-capture']) {
assert.equal(permissionCheckAllowed(permission, APP, nested, APP), false);
assert.equal(permissionRequestAllowed(permission, nested, APP), false);
}
});
+219
View File
@@ -0,0 +1,219 @@
'use strict';
// Tests with an injected fetch; the redirect/abort tests use Node's real fetch against a loopback server that
// stands in for the fixed endpoint. No external network, Electron or real profile.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const http = require('node:http');
const { PhishingList, registerPhishingIpc, parseList, PHISHING_LIST_URL, FETCH_INTERVAL_MS, MAX_BYTES } = require('../app/main/phishing-list.js');
const tempFile = () => path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'tp-phishing-')), 'phishing-domains.json');
const answer = (body, init = {}) => async () => new Response(body, { status: 200, ...init });
function list(fetchImpl, extra = {}) {
const calls = [];
const timers = [];
const l = new PhishingList({
cacheFile: extra.cacheFile ?? tempFile(),
fetchImpl: async (url, init) => { calls.push({ url, init }); return fetchImpl(url, init); },
setIntervalImpl: (fn, ms) => { timers.push({ fn, ms }); return timers.length; },
clearIntervalImpl: () => {},
now: () => 1000,
...extra,
});
return { l, calls, timers };
}
test('parser keeps exact lowercase domains, skips comments/blank lines and rejects any other line as a whole', () => {
const { domains } = parseList('# header\r\nEvil.Example\n\n phish.test. \nxn--80ak6aa92e.com\n');
assert.deepEqual([...domains].sort(), ['evil.example', 'phish.test', 'xn--80ak6aa92e.com']);
assert.equal(parseList('').domains.size, 0);
assert.throws(() => parseList('<!doctype html>\n<html><body>Error</body></html>'), /not a domain/);
assert.throws(() => parseList('evil.example\nnot a domain\n'), /not a domain/);
});
test('refresh GETs only the official list anonymously and classifies by exact hostname', async () => {
const { l, calls } = list(answer('evil.example\nphish.test\n'));
await l.refresh();
assert.equal(calls.length, 1);
assert.equal(calls[0].url, PHISHING_LIST_URL);
assert.equal(PHISHING_LIST_URL, 'https://files.teamspeak-services.com/client/phishing-domains/active.txt');
assert.equal(calls[0].init.credentials, 'omit');
assert.equal(calls[0].init.referrerPolicy, 'no-referrer');
assert.equal(calls[0].init.method, 'GET');
assert.equal(calls[0].init.redirect, 'error');
assert.equal(l.has('evil.example'), true);
assert.equal(l.has('EVIL.example.'), true);
assert.equal(l.has('sub.evil.example'), false, 'official guard matches the exact hostname only');
assert.equal(l.has('example'), false);
assert.deepEqual({ loaded: l.status().loaded, count: l.status().count, error: l.status().error }, { loaded: true, count: 2, error: null });
});
test('failures keep the previous list and report why; oversized and redirected bodies are never partially used', async () => {
let next = answer('evil.example\n');
const { l } = list((...args) => next(...args));
await l.refresh();
next = async () => new Response('nope', { status: 503 });
await l.refresh();
assert.equal(l.status().error.code, 'http');
assert.equal(l.has('evil.example'), true);
next = async () => new Response('a.example\n', { headers: { 'content-length': String(MAX_BYTES + 1) } });
await l.refresh();
assert.equal(l.status().error.code, 'too-large');
const chunk = new Uint8Array(1024 * 1024).fill(0x61);
next = async () => new Response(new ReadableStream({ start(c) { for (let i = 0; i < 17; i += 1) c.enqueue(chunk); c.close(); } }));
await l.refresh();
assert.equal(l.status().error.code, 'too-large');
next = async () => new Response('evil.example\n<html><body>maintenance</body></html>\nother.example\n');
await l.refresh();
assert.equal(l.status().error.code, 'bad-response');
assert.equal(l.has('other.example'), false, 'a mixed error body never replaces the known list');
next = async () => ({ ok: true, status: 200, redirected: true, url: 'https://elsewhere.invalid/list.txt', headers: new Headers(), body: null, text: async () => 'b.example' });
await l.refresh();
assert.equal(l.status().error.code, 'redirect');
next = async () => { throw new TypeError('fetch failed'); };
await l.refresh();
assert.equal(l.status().error.code, 'network');
assert.deepEqual([...l.domains], ['evil.example']);
});
test('concurrent refreshes share one request', async () => {
let release;
const { l, calls } = list(() => new Promise((resolve) => { release = () => resolve(new Response('x.example')); }));
const a = l.refresh(); const b = l.refresh();
await new Promise((r) => setImmediate(r));
release();
await Promise.all([a, b]);
assert.equal(calls.length, 1);
});
test('the last good list is cached and restored on start; start schedules the hourly refresh', async () => {
const cacheFile = tempFile();
const first = list(answer('cached.example\n'), { cacheFile });
await first.l.refresh();
const second = list(() => new Promise(() => {}), { cacheFile });
second.l.start();
assert.equal(second.l.has('cached.example'), true);
assert.equal(second.l.status().fromCache, true);
assert.equal(second.calls.length, 1);
assert.deepEqual(second.timers.map((t) => t.ms), [FETCH_INTERVAL_MS]);
second.l.start();
assert.equal(second.timers.length, 1, 'start is idempotent');
});
test('a cache from another source or with invalid entries is ignored', () => {
const cacheFile = tempFile();
fs.writeFileSync(cacheFile, JSON.stringify({ version: 1, source: 'https://elsewhere.invalid/list.txt', fetchedAt: 1, domains: ['a.example'] }));
const { l } = list(answer(''), { cacheFile });
l.loadCache();
assert.equal(l.status().loaded, false);
fs.writeFileSync(cacheFile, JSON.stringify({ version: 1, source: PHISHING_LIST_URL, fetchedAt: 1, domains: ['ok.example', '<bad>'] }));
l.loadCache();
assert.equal(l.status().loaded, false);
});
test('disabled lists make no request and read no cache', async () => {
const { l, calls, timers } = list(answer('x.example'), { enabled: false });
l.start();
await l.refresh();
assert.equal(calls.length, 0);
assert.equal(timers.length, 0);
assert.equal(l.has('x.example'), false);
});
test('IPC answers only the trusted sender and validates the host', async () => {
const handlers = new Map();
const { l } = list(answer('evil.example'));
await l.refresh();
let trusted = true;
registerPhishingIpc({ ipcMain: { handle: (channel, fn) => handlers.set(channel, fn) }, trustedSender: () => trusted, list: l });
const threat = handlers.get('privacy:link-threat');
assert.deepEqual(threat({}, 'evil.example'), { ok: true, malicious: true, loaded: true });
assert.deepEqual(threat({}, 'good.example'), { ok: true, malicious: false, loaded: true });
assert.equal(threat({}, 42).ok, false);
assert.equal(threat({}, 'a'.repeat(254)).ok, false);
assert.equal(handlers.get('privacy:threat-status')({}).status.count, 1);
trusted = false;
assert.equal(threat({}, 'evil.example').error.code, 'forbidden');
});
/** Loopback stand-in for the fixed endpoint: fetchImpl maps PHISHING_LIST_URL to `${base}/list` with the same init. */
async function loopback(handler) {
const hits = new Map();
const server = http.createServer((req, res) => { hits.set(req.url, (hits.get(req.url) ?? 0) + 1); handler(req, res); });
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const base = `http://127.0.0.1:${server.address().port}`;
const fetchImpl = async (url, init) => {
assert.equal(url, PHISHING_LIST_URL);
const { cache, ...rest } = init; // undici's cache modes are irrelevant here; redirect/signal semantics are what is tested
const res = await fetch(`${base}/list`, rest);
// Only the address is substituted; redirected/status/headers/body are the real response's.
return { ok: res.ok, status: res.status, redirected: res.redirected, url: PHISHING_LIST_URL, headers: res.headers, body: res.body };
};
const close = () => { server.closeAllConnections(); return new Promise((resolve) => server.close(resolve)); };
return { hits, fetchImpl, close };
}
test('a redirect is refused before the redirect target is requested; the known list stays in use', async () => {
let mode = 'list';
const server = await loopback((req, res) => {
if (req.url === '/list' && mode === 'list') { res.end('evil.example\n'); return; }
if (req.url === '/list') { res.writeHead(302, { location: '/elsewhere' }); res.end(); return; }
res.end('other.example\n');
});
try {
const { l } = list(server.fetchImpl);
await l.refresh();
assert.equal(l.has('evil.example'), true);
mode = 'redirect';
await l.refresh();
assert.equal(server.hits.get('/elsewhere') ?? 0, 0, 'redirect:error never follows');
assert.equal(l.status().error.code, 'network');
assert.equal(l.has('evil.example'), true);
assert.equal(l.has('other.example'), false);
} finally { await server.close(); }
});
test('stop aborts the in-flight request and nothing from it reaches the list or cache', async () => {
let requested; const gotRequest = new Promise((resolve) => { requested = resolve; });
let closed; const connectionClosed = new Promise((resolve) => { closed = resolve; });
const server = await loopback((req, res) => {
res.on('close', closed);
res.writeHead(200, { 'content-type': 'text/plain' });
res.write('partial.example\n'); // body never completes
requested();
});
try {
const cacheFile = tempFile();
const { l } = list(server.fetchImpl, { cacheFile });
const pending = l.refresh();
await gotRequest;
await new Promise((r) => setTimeout(r, 50));
l.stop();
await pending;
await connectionClosed;
assert.equal(l.has('partial.example'), false);
assert.equal(l.status().loaded, false);
assert.equal(l.status().error, null, 'a deliberate stop is not reported as a source failure');
assert.equal(fs.existsSync(cacheFile), false);
} finally { await server.close(); }
});
test('a response that arrives after stop is discarded, and refresh works again afterwards', async () => {
let deliver;
let next = () => new Promise((resolve) => { deliver = resolve; }); // ignores the abort signal
const cacheFile = tempFile();
const { l } = list((...args) => next(...args), { cacheFile });
const pending = l.refresh();
await new Promise((r) => setImmediate(r));
l.stop();
deliver(new Response('late.example\n'));
await pending;
assert.equal(l.has('late.example'), false);
assert.equal(fs.existsSync(cacheFile), false);
next = answer('fresh.example\n');
await l.refresh();
assert.equal(l.has('fresh.example'), true);
assert.equal(fs.existsSync(cacheFile), true);
});
+84
View File
@@ -74,6 +74,90 @@ test('a corrupted saved list on disk falls back to the default', () => {
}
});
test('bookmark folders: hierarchy and order persist atomically across instances', () => {
const { file, cleanup } = tempFile();
try {
const p = new Prefs(file);
const state = {
savedServers: [{ id: 'bmk001', name: 'Root', address: 'root.example' }, { id: 'bmk002', name: 'Inside', address: 'in.example', folder: 'fold01' }],
bookmarkFolders: [{ id: 'fold01', name: 'Games' }, { id: 'fold02', name: '', parent: 'fold01' }],
bookmarkOrder: ['fold01', 'bmk001', 'fold02', 'bmk002'],
};
p.set(state);
const loaded = new Prefs(file).get();
assert.deepEqual({ savedServers: loaded.savedServers, bookmarkFolders: loaded.bookmarkFolders, bookmarkOrder: loaded.bookmarkOrder }, state);
} finally { cleanup(); }
});
test('bookmark folders: dangling references, cycles, depth and bad orders are rejected without writing', () => {
const { file, cleanup } = tempFile();
try {
const p = new Prefs(file);
p.set({ savedServers: [{ id: 'bmk001', name: 'A', address: 'a' }], bookmarkFolders: [{ id: 'fold01', name: 'F' }], bookmarkOrder: ['bmk001', 'fold01'] });
const before = fs.readFileSync(file, 'utf8');
const chain = Array.from({ length: 9 }, (_, i) => ({ id: `lvl00${i}`, name: 'x', ...(i ? { parent: `lvl00${i - 1}` } : {}) }));
const bad = [
// a bookmark in a folder that does not exist (removing a non-empty folder alone never orphans bookmarks)
{ savedServers: [{ id: 'bmk001', name: 'A', address: 'a', folder: 'gone00' }] },
{ savedServers: [{ id: 'bmk001', name: 'A', address: 'a', folder: 'fold01' }], bookmarkFolders: [] },
// a cycle and a self-parent
{ bookmarkFolders: [{ id: 'fold01', name: 'F', parent: 'fold02' }, { id: 'fold02', name: 'G', parent: 'fold01' }] },
{ bookmarkFolders: [{ id: 'fold01', name: 'F', parent: 'fold01' }] },
// nine levels exceed the bound
{ bookmarkFolders: chain },
// ids shared between a bookmark and a folder
{ bookmarkFolders: [{ id: 'bmk001', name: 'F' }] },
// explicit orders must list every item exactly once
{ bookmarkOrder: ['bmk001'] },
{ bookmarkOrder: ['bmk001', 'fold01', 'zzz999'] },
{ bookmarkOrder: ['bmk001', 'bmk001'] },
// malformed folder entries
{ bookmarkFolders: [{ id: 'fold01', name: 'F', extra: 1 }] },
{ bookmarkFolders: [{ id: 'fold01', name: 'a\nb' }] },
{ bookmarkFolders: Array.from({ length: 51 }, (_, i) => ({ id: `f${String(i).padStart(5, '0')}`, name: '' })) },
];
for (const partial of bad) assert.throws(() => p.set(partial), undefined, JSON.stringify(partial));
assert.equal(fs.readFileSync(file, 'utf8'), before);
assert.deepEqual(p.get().bookmarkOrder, ['bmk001', 'fold01']);
} finally { cleanup(); }
});
test('bookmark folders: writes without an order keep the stored sequence', () => {
const { file, cleanup } = tempFile();
try {
const p = new Prefs(file);
p.set({ savedServers: [{ id: 'bmk001', name: 'A', address: 'a' }], bookmarkFolders: [{ id: 'fold01', name: 'F' }], bookmarkOrder: ['fold01', 'bmk001'] });
p.set({ savedServers: [{ id: 'bmk001', name: 'A', address: 'a' }, { id: 'bmk002', name: 'B', address: 'b', folder: 'fold01' }] });
assert.deepEqual(p.get().bookmarkOrder, ['fold01', 'bmk001', 'bmk002']);
p.set({ savedServers: [{ id: 'bmk002', name: 'B', address: 'b', folder: 'fold01' }] });
assert.deepEqual(new Prefs(file).get().bookmarkOrder, ['fold01', 'bmk002']);
} finally { cleanup(); }
});
test('bookmark folders: legacy files keep their bookmarks; broken hierarchies move orphans to the root', () => {
const { file, cleanup } = tempFile();
try {
const legacy = [{ id: 'aaa111', name: 'A', address: 'a' }, { id: 'bbb222', name: 'B', address: 'b', identity_id: `${'A'.repeat(27)}=` }];
fs.writeFileSync(file, JSON.stringify({ savedServers: legacy }));
let p = new Prefs(file);
assert.deepEqual(p.get().savedServers, legacy);
assert.deepEqual(p.get().bookmarkFolders, []);
assert.deepEqual(p.get().bookmarkOrder, ['aaa111', 'bbb222']);
// Loading never rewrites the file.
assert.deepEqual(JSON.parse(fs.readFileSync(file, 'utf8')), { savedServers: legacy });
fs.writeFileSync(file, JSON.stringify({
savedServers: [{ id: 'aaa111', name: 'A', address: 'a', folder: 'cyc001' }, { id: 'bbb222', name: 'B', address: 'b', folder: 'gone00' }],
bookmarkFolders: [{ id: 'cyc001', name: 'x', parent: 'cyc002' }, { id: 'cyc002', name: 'y', parent: 'cyc001' }],
bookmarkOrder: ['cyc001', 'cyc002', 'aaa111', 'bbb222'],
}));
p = new Prefs(file);
// Official HandleBookmarks: items whose parent cannot be resolved continue at the root.
assert.deepEqual(p.get().savedServers, [{ id: 'aaa111', name: 'A', address: 'a', folder: 'cyc001' }, { id: 'bbb222', name: 'B', address: 'b' }]);
assert.deepEqual(p.get().bookmarkFolders, [{ id: 'cyc001', name: 'x' }, { id: 'cyc002', name: 'y' }]);
assert.deepEqual(p.get().bookmarkOrder, ['cyc001', 'cyc002', 'aaa111', 'bbb222']);
} finally { cleanup(); }
});
test('theme: a new profile or a prefs file without the key starts dark', () => {
const { file, cleanup } = tempFile();
try {
+56
View File
@@ -0,0 +1,56 @@
'use strict';
// Pure schema tests: no Electron, files or network.
const test = require('node:test');
const assert = require('node:assert/strict');
const { PRIVACY_SCHEMA, CONFIRMATION_KEYS, CONFIRMATION_DEFAULTS, migratePrivacyPrefs, trustedHostsUpdateError } = require('../app/main/privacy-prefs.js');
test('defaults follow the official workflowSettings: no trusted hosts, malicious trust off, every confirmation shown', () => {
assert.deepEqual(PRIVACY_SCHEMA.trustedExternalHosts.default, []);
assert.equal(PRIVACY_SCHEMA.allowWhitelistMalicious.default, false);
assert.deepEqual(PRIVACY_SCHEMA.confirmationSettings.default, { delete_ban: true, delete_temp_pw: true, delete_privilege_key: true, clear_file_transfer_history: true });
assert.deepEqual(Object.keys(CONFIRMATION_DEFAULTS), [...CONFIRMATION_KEYS]);
});
test('confirmationSettings accepts only the complete boolean key set', () => {
const check = PRIVACY_SCHEMA.confirmationSettings.check;
assert.equal(check({ ...CONFIRMATION_DEFAULTS, delete_ban: false }), true);
assert.equal(check({ delete_ban: false }), false);
assert.equal(check({ ...CONFIRMATION_DEFAULTS, extra: true }), false);
assert.equal(check({ ...CONFIRMATION_DEFAULTS, delete_ban: 0 }), false);
assert.equal(check([true, true, true, true]), false);
assert.equal(check(null), false);
});
test('trusted hosts and malicious toggle validation', () => {
const hosts = PRIVACY_SCHEMA.trustedExternalHosts.check;
assert.equal(hosts(['example.com', 'www.example.org']), true);
assert.equal(hosts(['Example.com']), false);
assert.equal(hosts(['exa mple.com']), false);
assert.equal(hosts(Array.from({ length: 501 }, (_, i) => `h${i}.com`)), false);
assert.equal(PRIVACY_SCHEMA.allowWhitelistMalicious.check(true), true);
assert.equal(PRIVACY_SCHEMA.allowWhitelistMalicious.check('true'), false);
});
test('a stored confirmation object from another version keeps remembered choices and defaults the rest', () => {
const values = { confirmationSettings: { ...CONFIRMATION_DEFAULTS } };
migratePrivacyPrefs({ confirmationSettings: { delete_ban: false, obsolete_key: false, delete_temp_pw: 'no' } }, values);
assert.deepEqual(values.confirmationSettings, { delete_ban: false, delete_temp_pw: true, delete_privilege_key: true, clear_file_transfer_history: true });
const untouched = { confirmationSettings: { ...CONFIRMATION_DEFAULTS, delete_ban: false } };
migratePrivacyPrefs({ confirmationSettings: untouched.confirmationSettings }, untouched);
assert.equal(untouched.confirmationSettings.delete_ban, false);
const absent = { confirmationSettings: { ...CONFIRMATION_DEFAULTS } };
migratePrivacyPrefs({}, absent);
assert.deepEqual(absent.confirmationSettings, CONFIRMATION_DEFAULTS);
});
test('a flagged host can become trusted only while trusting malicious sites is allowed', () => {
const flagged = (host) => host === 'evil.example';
const current = { trustedExternalHosts: ['good.example'], allowWhitelistMalicious: false };
assert.match(trustedHostsUpdateError(current, { trustedExternalHosts: ['good.example', 'evil.example'] }, flagged), /evil\.example/);
assert.equal(trustedHostsUpdateError(current, { trustedExternalHosts: ['good.example', 'fine.example'] }, flagged), null);
assert.equal(trustedHostsUpdateError({ ...current, allowWhitelistMalicious: true }, { trustedExternalHosts: ['evil.example'] }, flagged), null);
assert.equal(trustedHostsUpdateError(current, { allowWhitelistMalicious: true, trustedExternalHosts: ['evil.example'] }, flagged), null);
// Already trusted before it was flagged: removing others or keeping it is not a new trust decision.
assert.equal(trustedHostsUpdateError({ trustedExternalHosts: ['evil.example', 'x.example'], allowWhitelistMalicious: false }, { trustedExternalHosts: ['evil.example'] }, flagged), null);
assert.equal(trustedHostsUpdateError(current, { theme: 'dark' }, flagged), null);
});
+106
View File
@@ -0,0 +1,106 @@
// Renderer privacy rules with the fake bridge: link classification, trust guard, remembered confirmations.
// No Electron, dialog, network or server.
import { test, beforeEach } from 'node:test';
import assert from 'node:assert/strict';
import './fixtures/renderer-env.mjs';
const { S } = await import('../app/renderer/js/state.js');
const links = await import('../app/renderer/js/external-links.js');
const confirmations = await import('../app/renderer/js/confirmations.js');
const writes = [];
const flagged = new Set(['evil.example']);
beforeEach(() => {
writes.length = 0;
S.prefs = { trustedExternalHosts: [], allowWhitelistMalicious: false, confirmationSettings: { delete_ban: true, delete_temp_pw: true, delete_privilege_key: true, clear_file_transfer_history: true } };
globalThis.teamspeach.setPrefs = async (patch) => { writes.push(patch); return { ok: true, prefs: { ...S.prefs, ...patch } }; };
globalThis.teamspeach.privacyLinkThreat = async (host) => ({ ok: true, malicious: flagged.has(host), loaded: true });
});
test('classification follows the official guard order; the phishing list only applies to untrusted hosts', () => {
const isMalicious = (host) => flagged.has(host);
assert.equal(links.checkLink('https://www.teamspeak.com/x', [], isMalicious), 'pass');
assert.equal(links.checkLink('https://twitch.tv/teamspeak_tv', [], isMalicious), 'pass');
assert.equal(links.checkLink('https://twitch.tv/teamspeak_tv.evil', [], isMalicious), 'warn');
assert.equal(links.checkLink('mailto:a@b.example', [], isMalicious), 'pass');
assert.equal(links.checkLink('https://evil.example/login', [], isMalicious), 'warn-malicious');
assert.equal(links.checkLink('https://sub.evil.example/', [], isMalicious), 'warn');
assert.equal(links.checkLink('https://evil.example/', ['evil.example'], isMalicious), 'pass');
assert.equal(links.checkLink('https://www.site.example/', ['site.example'], isMalicious), 'pass');
assert.equal(links.checkLink('https://site.example/', ['www.site.example'], isMalicious), 'pass');
assert.equal(links.checkLink('https://user:pw@site.example/', ['site.example'], isMalicious), 'warn');
assert.equal(links.checkLink('javascript:alert(1)', [], isMalicious), 'warn');
});
test('main lookup failures never mark a host malicious', async () => {
assert.equal(await links.isFlaggedHost('evil.example'), true);
assert.equal(await links.isFlaggedHost('good.example'), false);
globalThis.teamspeach.privacyLinkThreat = async () => { throw new Error('ipc gone'); };
assert.equal(await links.isFlaggedHost('evil.example'), false);
});
test('a flagged host is trusted only while "Allow trusting sites flagged as malicious" is on', async () => {
await assert.rejects(links.addTrustedHost('evil.example', { malicious: true }));
assert.equal(writes.length, 0);
S.prefs = { ...S.prefs, allowWhitelistMalicious: true };
await links.addTrustedHost('Evil.Example', { malicious: true });
assert.deepEqual(writes.at(-1), { trustedExternalHosts: ['evil.example'] });
await links.addTrustedHost('evil.example');
assert.equal(writes.length, 1, 'already trusted hosts are not written again');
});
test('trusted sites management removes one host or clears all through prefs', async () => {
S.prefs = { ...S.prefs, trustedExternalHosts: ['a.example', 'b.example'] };
await links.removeTrustedHost('A.example');
assert.deepEqual(S.prefs.trustedExternalHosts, ['b.example']);
await links.clearTrustedHosts();
assert.deepEqual(S.prefs.trustedExternalHosts, []);
globalThis.teamspeach.setPrefs = async () => ({ ok: false, message: 'disk full' });
await assert.rejects(links.removeTrustedHost('b.example'), /disk full/);
});
test('confirmations: defaults ask, skip choices persist the complete object, reset restores every key', async () => {
assert.deepEqual(confirmations.confirmationSettings({}), { delete_ban: true, delete_temp_pw: true, delete_privilege_key: true, clear_file_transfer_history: true });
await confirmations.applyConfirmationSettings({ delete_ban: false });
assert.deepEqual(writes.at(-1), { confirmationSettings: { delete_ban: false, delete_temp_pw: true, delete_privilege_key: true, clear_file_transfer_history: true } });
assert.equal(confirmations.shouldConfirm('delete_ban'), false);
await confirmations.applyConfirmationSettings({ clear_file_transfer_history: false });
await confirmations.resetConfirmations();
assert.deepEqual(writes.at(-1).confirmationSettings, { delete_ban: true, delete_temp_pw: true, delete_privilege_key: true, clear_file_transfer_history: true });
assert.equal(confirmations.shouldConfirm('clear_file_transfer_history'), true);
assert.throws(() => confirmations.applyConfirmationSettings({ bogus: false }), /Invalid confirmation/);
assert.throws(() => confirmations.shouldConfirm('bogus'), /Unknown confirmation/);
});
test('a skipped confirmation runs the action at once without a popup', async () => {
S.prefs = { ...S.prefs, confirmationSettings: { ...S.prefs.confirmationSettings, delete_temp_pw: false } };
let ran = 0;
assert.equal(await confirmations.confirmAction(null, 'delete_temp_pw', 'sure?', async () => { ran += 1; }), true);
assert.equal(ran, 1);
assert.equal(writes.length, 0);
});
test('a failed reset reports the error instead of claiming success', async () => {
globalThis.teamspeach.setPrefs = async () => ({ ok: false, error: { message: 'prefs: invalid value for confirmationSettings' } });
await assert.rejects(confirmations.resetConfirmations(), /invalid value/);
});
test('concurrent skip changes merge in order and a later reset cannot be overwritten', async () => {
let release;
const gate = new Promise(resolve => { release = resolve; });
let first = true;
globalThis.teamspeach.setPrefs = async patch => {
if (first) { first = false; await gate; }
return { ok: true, prefs: { ...S.prefs, ...patch } };
};
const ban = confirmations.applyConfirmationSettings({ delete_ban: false });
const password = confirmations.applyConfirmationSettings({ delete_temp_pw: false });
release();
await Promise.all([ban, password]);
assert.equal(confirmations.shouldConfirm('delete_ban'), false);
assert.equal(confirmations.shouldConfirm('delete_temp_pw'), false);
const skip = confirmations.applyConfirmationSettings({ delete_privilege_key: false });
const reset = confirmations.resetConfirmations();
await Promise.all([skip, reset]);
for (const key of confirmations.CONFIRMATION_KEYS) assert.equal(confirmations.shouldConfirm(key), true);
});
+118 -14
View File
@@ -1,7 +1,8 @@
// Local recording UI state, notification policy and lock-mute scoping. Fake DOM/bridge only: no sound is played
// (notification output is replaced by a recorder), no dialog, no OS API.
// (the fake environment has no audio decoder or output), no dialog, no OS API.
import { test, beforeEach } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync, readdirSync } from 'node:fs';
import { env } from './fixtures/renderer-env.mjs';
const requests = [];
@@ -18,7 +19,7 @@ const notifications = await import('../app/renderer/js/notifications.js');
const recording = await import('../app/renderer/js/recording.js');
const os = await import('../app/renderer/js/os-settings.js');
const { STATE, soundAllowed, synthesize, settingState, eventLog, GROUPS } = notifications;
const { STATE, soundAllowed, settingState, eventLog, GROUPS, EVENTS, SOUNDS, EVENT_SOUNDS } = notifications;
function connection(id, { away = false, outputMuted = false, channel = 1 } = {}) {
const conn = newConnection(id);
@@ -49,8 +50,8 @@ test('sound policy matches the official isNotificationSoundAllowed expression',
for (const state of [0, 1, 2]) {
for (const away of [false, true]) {
for (const outputMuted of [false, true]) {
for (const cue of ['join', 'away', 'sound_off']) {
assert.equal(soundAllowed('x', state, { away, outputMuted }, cue), official(state, away, outputMuted, cue === 'away', cue === 'sound_off'), `${state}/${away}/${outputMuted}/${cue}`);
for (const sound of ['ClientMove.SomeoneJoinedYourChannel', 'ClientUpdate.YouAway', 'ClientUpdate.YouPlaybackMuted']) {
assert.equal(soundAllowed('x', state, { away, outputMuted }, sound), official(state, away, outputMuted, sound === 'ClientUpdate.YouAway', sound === 'ClientUpdate.YouPlaybackMuted'), `${state}/${away}/${outputMuted}/${sound}`);
}
}
}
@@ -65,19 +66,43 @@ test('defaults follow the official table: everything on except "talking while mu
assert.ok(!GROUPS.some(([g]) => g === 'call'), 'calls need a myTeamSpeak account and are not offered');
});
test('cues are synthesized locally, bounded and deterministic', () => {
for (const cue of Object.keys(notifications._test.CUES)) {
const a = synthesize(cue);
const b = synthesize(cue);
assert.equal(a.sampleRate, 48000);
assert.ok(a.pcm.length > 0 && a.pcm.length < 48000, cue);
assert.deepEqual(a.pcm, b.pcm);
const peak = a.pcm.reduce((m, v) => Math.max(m, Math.abs(v)), 0);
assert.ok(peak > 0.2 && peak <= 0.25, `${cue} peak ${peak}`);
assert.ok(Math.abs(a.pcm[0]) < 1e-3 && Math.abs(a.pcm.at(-1)) < 1e-2, `${cue} has soft edges`);
test('every mapped sound is a local, decodable-size PCM wave and every bundled sound is mapped', () => {
const dir = new URL('../app/renderer/assets/sounds/', import.meta.url);
const files = new Set(Object.values(SOUNDS).map((s) => s.file));
assert.deepEqual(readdirSync(dir).sort(), [...files].map((f) => `${f}.wav`).sort());
for (const file of files) {
const bytes = readFileSync(new URL(`${file}.wav`, dir));
assert.ok(bytes.length <= 1024 * 1024, file);
assert.equal(bytes.toString('latin1', 0, 4), 'RIFF', file);
assert.equal(bytes.toString('latin1', 8, 12), 'WAVE', file);
let fmt = null;
let data = 0;
for (let at = 12; at + 8 <= bytes.length;) {
const id = bytes.toString('latin1', at, at + 4);
const size = bytes.readUInt32LE(at + 4);
if (id === 'fmt ') fmt = { format: bytes.readUInt16LE(at + 8), channels: bytes.readUInt16LE(at + 10), rate: bytes.readUInt32LE(at + 12), bits: bytes.readUInt16LE(at + 22) };
if (id === 'data') data = size;
at += 8 + size + (size & 1);
}
assert.equal(fmt?.format, 1, `${file} is PCM`);
assert.ok(fmt.channels >= 1 && fmt.channels <= 2 && fmt.bits === 16 && [44100, 48000].includes(fmt.rate), file);
const seconds = data / (fmt.channels * 2) / fmt.rate;
assert.ok(seconds > 0 && seconds <= 10, `${file} ${seconds} s`);
}
});
test('Listen and advanced events name official sounds; only others\' non-current-channel edits are silent', () => {
const { PREVIEW_SOUND } = notifications._test;
for (const [, items] of GROUPS) for (const { id } of items) assert.ok(SOUNDS[PREVIEW_SOUND[id]], id);
for (const [id, events] of Object.entries(EVENTS)) {
for (const event of events) {
const silent = id === 'edited_other' && event !== 'channel_edited';
assert.equal(Boolean(SOUNDS[EVENT_SOUNDS[id]?.[event]]), !silent, `${id}/${event}`);
}
}
for (const events of Object.values(EVENT_SOUNDS)) for (const key of Object.values(events)) assert.ok(SOUNDS[key], key);
});
test('server events become the right settings and event-log entries (log is independent of sound)', () => {
const conn = connection('c1');
S.prefs.notificationStates = { someone_moved_in: 0 };
@@ -262,4 +287,83 @@ test('preference saves unwrap the bridge envelope and retain prior state on fail
}
});
test('events request the official sound file of their sub type, with the official per-file throttle', () => {
const conn = connection('s1');
S.prefs.notificationDeviceId = 'voice';
S.prefs.notificationStates = { talking_while_muted: STATE.ENABLED };
notifications.applyNotificationOutputPreferences();
const { lastPlayed, onServerEvent, onState, onText, onAudioState, onSnapshot } = notifications._test;
// Every requested file passes through lastPlayed.set; throttle state is kept between cases.
const requested = [];
lastPlayed.clear();
lastPlayed.set = function set(file, time) { requested.push(file); return Map.prototype.set.call(this, file, time); };
const files = (fn) => { requested.length = 0; fn(); return [...requested]; };
const other = (kind, reason, from, to, extra = {}) => onServerEvent({ kind, client_id: 5, nickname: 'Bob', from_channel_id: from, to_channel_id: to, reason, invoker: null, is_self: false, ...extra }, conn);
const self = (kind, reason) => onServerEvent({ kind, client_id: 1, nickname: 'Me', from_channel_id: 1, to_channel_id: 2, reason, invoker: { id: 9, name: 'Admin' }, is_self: true }, conn);
const cases = [
[() => other('client_move', 'none', 2, 1), 'neutral_switched_tocurrentchannel'],
[() => other('client_move', 'moved', 2, 1), 'neutral_moved_tocurrentchannel'],
[() => other('client_move', 'kick_channel', 2, 1), 'neutral_kicked_channel_tocurrentchannel'],
[() => other('client_move', 'subscription', 2, 1), null],
[() => other('client_move', 'none', 1, 2), 'neutral_switched_awayfromcurrentchannel'],
[() => other('client_move', 'moved', 1, 2), 'neutral_moved_awayfromcurrentchannel'],
[() => other('client_move', 'kick_channel', 1, 2), 'neutral_kicked_channel_awayfromcurrentchannel'],
[() => other('client_enter', 'none', 0, 1), 'neutral_connection_connected_currentchannel'],
[() => other('client_leave', 'disconnect', 1, 0), 'neutral_connection_disconnected_currentchannel'],
[() => other('client_leave', 'lost_connection', 1, 0), 'neutral_connection_connectionlost_currentchannel'],
[() => other('client_leave', 'kick_server', 1, 0), 'neutral_kicked_server_currentchannel'],
[() => other('client_leave', 'ban', 1, 0), 'neutral_banned_server_currentchannel'],
[() => self('client_move', 'none'), 'channel_switched'],
[() => self('client_move', 'moved'), 'you_were_moved'],
[() => self('client_move', 'kick_channel'), 'you_kicked_channel'],
[() => self('client_leave', 'kick_server'), 'you_kicked_server'],
[() => self('client_leave', 'ban'), 'you_were_banned'],
[() => onServerEvent({ kind: 'channel_edited', channel_id: 1, name: 'Lobby', invoker: { id: 9, name: 'Admin' } }, conn), 'your_channel_was_edited'],
[() => onServerEvent({ kind: 'channel_edited', channel_id: 2, name: 'Other', invoker: { id: 9, name: 'Admin' } }, conn), null],
[() => onServerEvent({ kind: 'channel_created', channel_id: 3, name: 'New', invoker: { id: 1, name: 'Me' } }, conn), 'channel_created'],
[() => onServerEvent({ kind: 'server_edited', invoker: { id: 1, name: 'Me' } }, conn), 'you_edited_server'],
[() => onServerEvent({ kind: 'server_edited', invoker: { id: 9, name: 'Admin' } }, conn), null],
[() => onServerEvent({ kind: 'talk_request', client_id: 5, requested: true, invoker: null }, conn), 'talkpower_requested'],
[() => onServerEvent({ kind: 'talker_changed', client_id: 1, is_talker: true, invoker: null }, conn), 'talkpower_granted'],
[() => onText({ target: 'poke', from_client_id: 5, from_nickname: 'Alice', message: 'hi' }, conn), 'you_were_poked'],
[() => onText({ target: 'channel', from_client_id: 5, from_nickname: 'Alice', message: 'hi' }, conn), 'chat_message_inbound'],
[() => notifications.notify('message_sent', conn), 'chat_message_outbound'],
[() => onState({ state: 'connected', address: 'fixture.invalid' }, conn), 'connected'],
[() => onState({ state: 'disconnected', reason: { code: 'x', detail: { reason: 'timeout' } } }, conn), 'connection_lost'],
[() => onState({ state: 'disconnected', reason: { code: 'connect_failed' } }, conn), 'error'],
[() => onAudioState({ input_muted: false, output_muted: false }, conn), null],
[() => onAudioState({ input_muted: true, output_muted: false }, conn), 'mic_muted'],
[() => onAudioState({ input_muted: false, output_muted: false }, conn), 'mic_activated'],
[() => notifications.notify('whisper_while_muted', conn), 'stop_talking'],
[() => notifications.notify('whisper_while_muted', conn), null],
[() => notifications.notify('talking_while_muted', conn), 'stop_talking'],
[() => notifications.notify('whisper_error', conn), 'no_whisper_target_found'],
[() => notifications.notify('whisper_received', conn), 'whisper_received'],
[() => notifications.notify('stream_started', conn), 'stream_started'],
[() => notifications.playEventSound('recording_paused', conn), 'recording_paused'],
[() => notifications.playEventSound('recording_paused', conn), null],
];
try {
for (const [fn, file] of cases) assert.deepEqual(files(fn), file ? [file] : [], `${fn}`);
onSnapshot(conn.snap, conn);
const assigned = structuredClone(conn.snap);
assigned.clients[0].server_groups = [8, 9];
conn.snap = assigned;
assert.deepEqual(files(() => onSnapshot(assigned, conn)), ['servergroup_assigned']);
const channelGroup = structuredClone(assigned);
channelGroup.clients[0].channel_group_id = 5;
conn.snap = channelGroup;
assert.deepEqual(files(() => onSnapshot(channelGroup, conn)), ['channelgroup_changed']);
const away = structuredClone(channelGroup);
away.clients[0].away = true;
conn.snap = away;
assert.deepEqual(files(() => onSnapshot(away, conn)), ['away_activated']);
S.prefs.notificationDeviceId = 'none';
notifications.applyNotificationOutputPreferences();
assert.deepEqual(files(() => notifications.notify('message_sent', conn)), [], 'device "none" never requests a file');
} finally {
delete lastPlayed.set;
}
});
void env;
+521
View File
@@ -0,0 +1,521 @@
'use strict';
// Remote Apps: a real loopback WebSocket server (ws) driven by real ws clients against a temporary profile file.
// Nothing here talks to the official client or a TeamSpeak server.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const net = require('node:net');
const path = require('node:path');
const { WebSocket } = require('ws');
const { RemoteAppsService, registerRemoteAppsIpc } = require('../app/main/remote-apps');
const { RemoteAppStore, hashKey } = require('../app/main/remote-app-state');
const snapshot = require('../app/main/remote-app-snapshot');
const APP = Object.freeze({ identifier: 'net.example.myapp', version: '1.0.0', name: 'Example Application', description: 'An example application that does things' });
const SNAP = Object.freeze({
event: 'snapshot', rev: 1, own_client_id: 7, own_channel_id: 1,
server: { name: 'Fixture' },
channels: [
{ id: 1, parent_id: 0, order: 0, name: 'Lobby', topic: '', has_password: false, is_default: true, max_clients: null, needed_talk_power: 0, codec: 'opus_voice', codec_quality: 6, icon_id: null, banner_url: null, banner_mode: null, depth: 0 },
{ id: 2, parent_id: 1, order: 0, name: 'Sub', topic: 'T', has_password: true, is_default: false, max_clients: 5, needed_talk_power: 10, codec: 'opus_music', codec_quality: 10, icon_id: 100, banner_url: null, banner_mode: null, depth: 1 },
],
clients: [
{ id: 7, uid: 'U7=', nickname: 'Alice', channel_id: 1, is_self: true, client_type: 'normal', input_muted: false, output_muted: false, input_hardware: true, output_hardware: true, away: false, away_message: null, talk_power: 0, is_talker: false, is_channel_commander: false, is_priority_speaker: false, is_recording: false, description: null, country: 'RU', server_groups: [7, 10], channel_group_id: 8, channel_group_inherited_from: 1, icon_id: null, badges: null },
{ id: 9, uid: 'U9=', nickname: 'Bob', channel_id: 2, is_self: false, client_type: 'normal', input_muted: true, output_muted: false, input_hardware: true, output_hardware: true, away: true, away_message: 'brb', talk_power: 5, is_talker: false, is_channel_commander: true, is_priority_speaker: false, is_recording: false, description: 'desc', country: null, server_groups: [8], channel_group_id: 9, channel_group_inherited_from: 2, icon_id: 3, badges: null },
],
});
function freePort() {
return new Promise((resolve, reject) => {
const server = net.createServer();
server.once('error', reject);
server.listen(0, '127.0.0.1', () => {
const { port } = server.address();
server.close(() => resolve(port));
});
});
}
async function waitFor(condition, label = 'condition', timeout = 3000) {
const start = Date.now();
while (!condition()) {
if (Date.now() - start > timeout) throw new Error(`timed out waiting for ${label}`);
await new Promise((resolve) => setTimeout(resolve, 10));
}
}
const settle = () => new Promise((resolve) => setTimeout(resolve, 100));
function tempDir(t) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'teamspeach-remote-apps-'));
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
return dir;
}
async function startService(t, { file, port, limits, listen = true } = {}) {
if (!file) file = path.join(tempDir(t), 'remote-apps.json');
if (!fs.existsSync(file)) {
port ??= await freePort();
fs.writeFileSync(file, JSON.stringify({ version: 1, enabled: true, port, apps: {} }));
}
const keys = [];
const logs = [];
const store = new RemoteAppStore(file);
const service = new RemoteAppsService({ store, listen, limits, onKey: (key) => keys.push(key), log: (level, message) => logs.push(`${level}: ${message}`) });
t.after(() => service.dispose());
await service.start();
return { service, store, keys, logs, file, port: store.port };
}
/** `origin` set = a browser page (Origin header); omitted = a native client (no Origin header). */
function connect(port, origin) {
const ws = new WebSocket(`ws://127.0.0.1:${port}`, origin === undefined ? {} : { origin });
const messages = [];
ws.on('message', (data) => messages.push(JSON.parse(data.toString('utf8'))));
ws.on('error', () => {});
const closed = new Promise((resolve) => ws.on('close', (code, reason) => resolve({ code, reason: reason.toString('utf8') })));
const opened = new Promise((resolve, reject) => {
ws.once('open', resolve);
ws.once('unexpected-response', () => reject(new Error('upgrade refused')));
ws.once('error', reject);
});
const client = {
ws, messages, closed, opened,
send: (value) => ws.send(typeof value === 'string' ? value : JSON.stringify(value)),
auth: (apiKey = '', meta = APP) => client.send({ type: 'auth', payload: { ...meta, content: { apiKey } } }),
key: (button, state) => client.send({ type: 'keyPress', payload: { button, state } }),
async next(type) {
await waitFor(() => messages.some((m) => m.type === type), `message ${type}`);
return messages.find((m) => m.type === type);
},
};
return client;
}
async function request(f, meta = APP, apiKey = '', origin) {
const c = connect(f.port, origin);
await c.opened;
c.auth(apiKey, meta);
await waitFor(() => f.service.status().requests.some((r) => r.identifier === meta.identifier), 'permission request');
return { c, req: f.service.status().requests.find((r) => r.identifier === meta.identifier) };
}
async function approved(f, meta = APP, origin) {
const { c, req } = await request(f, meta, '', origin);
assert.deepEqual(f.service.respond(req.id, true), { ok: true });
const reply = await c.next('auth');
return { c, reply, apiKey: reply.payload.apiKey };
}
/** Authenticates with `apiKey` from `origin`; resolves to the auth reply or the close frame. */
async function tryKey(f, apiKey, origin, meta = APP) {
const c = connect(f.port, origin);
await c.opened;
let closed = null;
c.closed.then((frame) => { closed = frame; });
c.auth(apiKey, meta);
await waitFor(() => closed !== null || c.messages.some((m) => m.type === 'auth'), 'auth outcome');
const reply = c.messages.find((m) => m.type === 'auth');
return reply ? { c, reply } : { c, closed };
}
test('nothing is published before the user approves; the approval reply carries the key and the live server view', async (t) => {
const f = await startService(t);
f.service.handleCoreEvent('c1', { event: 'state', state: 'connected' });
f.service.handleCoreEvent('c1', SNAP);
const { c, req } = await request(f);
assert.deepEqual({ ...req, id: undefined }, { ...APP, id: undefined, origin: null, reauth: false });
// Events while pending (talking, snapshot changes, keys) never reach the waiting socket.
f.service.handleCoreEvent('c1', { event: 'talking', client_id: 9, talking: true });
f.service.handleCoreEvent('c1', { ...SNAP, rev: 2, clients: SNAP.clients.slice(0, 1) });
c.key('pending.button', true);
await settle();
assert.deepEqual(c.messages, []);
assert.deepEqual(f.keys, []);
f.service.handleCoreEvent('c1', SNAP);
assert.deepEqual(f.service.respond(req.id, true), { ok: true });
const reply = await c.next('auth');
assert.deepEqual(reply.status, { code: 0, message: 'ok' });
assert.match(reply.payload.apiKey, /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/);
assert.equal(reply.payload.connections.length, 1);
const [conn] = reply.payload.connections;
assert.equal(conn.id, 1);
assert.equal(conn.clientId, 7);
assert.deepEqual(conn.channelInfos.rootChannels.map((ch) => ch.id), [1]);
assert.deepEqual(conn.channelInfos.subChannels['1'].map((ch) => [ch.id, ch.parentId, ch.properties.name, ch.properties.maxclients, ch.properties.flagPassword, ch.properties.codec]), [[2, '1', 'Sub', 5, true, 5]]);
assert.deepEqual(conn.clientInfos.map((ci) => [ci.id, ci.channelId, ci.properties.nickname, ci.properties.uniqueIdentifier]), [[7, 1, 'Alice', 'U7='], [9, 2, 'Bob', 'U9=']]);
assert.equal(Object.hasOwn(conn, 'properties'), false, 'server properties are not invented');
// The key is never in status (renderer) or at rest in plaintext.
assert.equal(JSON.stringify(f.service.status()).includes(reply.payload.apiKey), false);
assert.equal(fs.readFileSync(f.file, 'utf8').includes(reply.payload.apiKey), false);
assert.deepEqual(f.service.status().apps, [{ ...APP, allowed: true, origin: null, connected: true }]);
});
test('a stored key re-authenticates after a restart; wrong keys are rejected without a permission request', async (t) => {
const first = await startService(t);
const { c, apiKey } = await approved(first);
await first.service.dispose();
assert.equal((await c.closed).code, 1001);
const second = await startService(t, { file: first.file });
const again = connect(second.port);
await again.opened;
again.auth(apiKey);
const reply = await again.next('auth');
assert.equal(reply.payload.apiKey, apiKey);
assert.deepEqual(reply.payload.connections, []);
const forged = connect(second.port);
await forged.opened;
forged.auth('aef57c76-123a-acdc-5325-e33fe5c4fa27');
assert.deepEqual(await forged.closed, { code: 1008, reason: 'invalid_api_key' });
assert.deepEqual(forged.messages, []);
assert.deepEqual(second.service.status().requests, []);
});
test('an empty key for a registered app asks again; approval rotates the key and drops the old sockets', async (t) => {
const f = await startService(t);
const old = await approved(f);
const { c, req } = await request(f);
assert.equal(req.reauth, true);
f.service.respond(req.id, true);
const reply = await c.next('auth');
assert.notEqual(reply.payload.apiKey, old.apiKey);
assert.deepEqual(await old.c.closed, { code: 1008, reason: 'key_revoked' });
const stale = connect(f.port);
await stale.opened;
stale.auth(old.apiKey);
assert.deepEqual(await stale.closed, { code: 1008, reason: 'invalid_api_key' });
});
test('a pending request cannot be replaced by another socket; closing the requester withdraws it', async (t) => {
const f = await startService(t);
const { c, req } = await request(f);
const imposter = connect(f.port);
await imposter.opened;
imposter.auth('', { ...APP, name: 'Trusted Name', description: 'replaced' });
assert.deepEqual(await imposter.closed, { code: 1013, reason: 'auth_pending' });
assert.deepEqual(f.service.status().requests.map(({ id, name, description }) => ({ id, name, description })), [{ id: req.id, name: APP.name, description: APP.description }]);
c.ws.close();
await waitFor(() => f.service.status().requests.length === 0, 'request withdrawn');
assert.equal(f.service.respond(req.id, true).ok, false);
assert.deepEqual(f.service.status().apps, []);
});
test('deny registers the app as not allowed and later attempts are refused without asking', async (t) => {
const f = await startService(t);
const { c, req } = await request(f);
f.service.respond(req.id, false);
assert.deepEqual(await c.closed, { code: 1008, reason: 'denied' });
assert.deepEqual(c.messages, []);
assert.deepEqual(f.service.status().apps, [{ ...APP, allowed: false, origin: null, connected: false }]);
const retry = connect(f.port);
await retry.opened;
retry.auth('');
assert.deepEqual(await retry.closed, { code: 1008, reason: 'denied' });
assert.deepEqual(f.service.status().requests, []);
});
test('key presses report only approved transitions and every held button is released on close', async (t) => {
const f = await startService(t);
const early = connect(f.port);
await early.opened;
early.key('early', true);
assert.deepEqual(await early.closed, { code: 1008, reason: 'auth_required' });
const { c } = await approved(f);
c.key('a', true);
c.key('a', true);
c.key('a', false);
c.key('a', false);
c.send({ type: 'keyPress', payload: { button: 'b', state: 'yes' } });
c.key('b', true);
await waitFor(() => f.keys.length >= 3, 'key b');
assert.deepEqual(f.keys, [
{ identifier: APP.identifier, button: 'a', state: true },
{ identifier: APP.identifier, button: 'a', state: false },
{ identifier: APP.identifier, button: 'b', state: true },
]);
c.ws.close();
await waitFor(() => f.keys.length === 4, 'release on close');
assert.deepEqual(f.keys[3], { identifier: APP.identifier, button: 'b', state: false, synthetic: true });
});
test('two sockets of one app share a button: one down, released only when both are up', async (t) => {
const f = await startService(t);
const { c: one, apiKey } = await approved(f);
const two = connect(f.port);
await two.opened;
two.auth(apiKey);
await two.next('auth');
one.key('x', true);
await waitFor(() => f.keys.length === 1, 'down');
two.key('x', true);
one.key('x', false);
await settle();
assert.equal(f.keys.length, 1);
two.key('x', false);
await waitFor(() => f.keys.length === 2, 'release');
assert.deepEqual(f.keys, [{ identifier: APP.identifier, button: 'x', state: true }, { identifier: APP.identifier, button: 'x', state: false }]);
});
for (const [name, revoke, reason, code] of [
['toggling the app off', (f) => f.service.setAllowed(APP.identifier, false), 'denied', 1008],
['removing the app', (f) => f.service.removeApp(APP.identifier), 'removed', 1008],
['disabling remote apps', (f) => f.service.setEnabled(false), 'disabled', 1001],
['changing the port', async (f) => f.service.setPort(await freePort()), 'port_changed', 1001],
]) {
test(`${name} closes the app's sockets and releases held buttons`, async (t) => {
const f = await startService(t);
const { c } = await approved(f);
c.key('held', true);
await waitFor(() => f.keys.length === 1, 'down');
await revoke(f);
assert.deepEqual(await c.closed, { code, reason });
assert.deepEqual(f.keys, [{ identifier: APP.identifier, button: 'held', state: true }, { identifier: APP.identifier, button: 'held', state: false, synthetic: true }]);
});
}
test('removal forgets the key: the old key no longer authenticates', async (t) => {
const f = await startService(t);
const { apiKey } = await approved(f);
assert.deepEqual(f.service.removeApp(APP.identifier), { ok: true });
const c = connect(f.port);
await c.opened;
c.auth(apiKey);
assert.deepEqual(await c.closed, { code: 1008, reason: 'invalid_api_key' });
assert.deepEqual(f.service.status().apps, []);
});
test('authenticated apps receive connect, channel, move, property and talk events derived from snapshots', async (t) => {
const f = await startService(t);
const { c } = await approved(f);
f.service.handleCoreEvent('c3', { event: 'state', state: 'connected' });
f.service.handleCoreEvent('c3', SNAP);
const moved = { ...SNAP, rev: 2, clients: [SNAP.clients[0], { ...SNAP.clients[1], channel_id: 1, nickname: 'Bobby' }] };
f.service.handleCoreEvent('c3', moved);
f.service.handleCoreEvent('c3', { event: 'talking', client_id: 9, talking: true });
f.service.handleCoreEvent('c3', { event: 'audio_state', input_muted: false, output_muted: false, transmitting: true });
f.service.handleCoreEvent('c3', { event: 'audio_state', input_muted: false, output_muted: false, transmitting: true });
f.service.handleCoreEvent('c3', { event: 'state', state: 'disconnected' });
await waitFor(() => c.messages.filter((m) => m.type === 'connectStatusChanged').length === 2, 'disconnect event');
const events = c.messages.slice(1).map((m) => [m.type, m.payload.clientId ?? null]);
assert.deepEqual(events, [
['connectStatusChanged', null],
['channels', null],
['clientMoved', 7],
['clientMoved', 9],
['clientMoved', 9],
['clientPropertiesUpdated', 9],
['talkStatusChanged', 9],
['talkStatusChanged', 7],
['connectStatusChanged', null],
]);
const byType = (type) => c.messages.filter((m) => m.type === type).map((m) => m.payload);
assert.deepEqual(byType('connectStatusChanged'), [{ connectionId: 3, status: 4, info: { clientId: 7 } }, { connectionId: 3, status: 0, info: { clientId: 7 } }]);
const moves = byType('clientMoved');
assert.deepEqual(moves.map(({ clientId, oldChannelId, newChannelId }) => [clientId, oldChannelId, newChannelId]), [[7, 0, 1], [9, 0, 2], [9, 2, 1]]);
assert.deepEqual(byType('talkStatusChanged'), [{ connectionId: 3, clientId: 9, status: 1 }, { connectionId: 3, clientId: 7, status: 1 }]);
assert.equal(byType('clientPropertiesUpdated')[0].properties.nickname, 'Bobby');
});
test('core restarts and closed tabs end the cached view', async (t) => {
const f = await startService(t);
f.service.handleCoreEvent('c1', SNAP);
f.service.handleCoreEvent('c2', SNAP);
f.service.handleCoreStatus('c1', { status: 'exited' });
f.service.updateConnectionList([{ id: 'c1', state: 'disconnected' }]);
const { reply } = await approved(f);
assert.deepEqual(reply.payload.connections, []);
});
test('limits: oversized frames, floods, idle unauthenticated sockets and malformed auth are closed', async (t) => {
const f = await startService(t, { limits: { maxPayload: 1024, authTimeoutMs: 200, messageBurst: 3, messagesPerSecond: 1 } });
const big = connect(f.port);
await big.opened;
big.send({ type: 'auth', payload: { ...APP, description: 'x'.repeat(2048), content: { apiKey: '' } } });
assert.equal((await big.closed).code, 1009);
const idle = connect(f.port);
await idle.opened;
assert.deepEqual(await idle.closed, { code: 1008, reason: 'auth_timeout' });
const bad = connect(f.port);
await bad.opened;
bad.auth('', { ...APP, identifier: 'Net.Example-App' });
assert.deepEqual(await bad.closed, { code: 1008, reason: 'invalid_auth' });
const { c } = await approved(f);
for (let i = 0; i < 6; i++) c.key(`k${i}`, true);
assert.deepEqual(await c.closed, { code: 1008, reason: 'rate_limited' });
await waitFor(() => f.keys.filter((k) => !k.state).length === f.keys.filter((k) => k.state).length, 'all released');
assert.equal(f.service.status().requests.length, 0);
});
test('without the explicit listen permission no port is bound', async (t) => {
const port = await freePort();
const f = await startService(t, { port, listen: false });
assert.deepEqual({ available: f.service.status().available, listening: f.service.status().listening, failure: f.service.status().failure }, { available: false, listening: false, failure: 'test_safety' });
const c = connect(port);
await assert.rejects(c.opened);
});
test('a port already in use is reported as a start failure', async (t) => {
const blocker = net.createServer();
await new Promise((resolve) => blocker.listen(0, '127.0.0.1', resolve));
t.after(() => blocker.close());
const f = await startService(t, { port: blocker.address().port });
assert.equal(f.service.status().listening, false);
assert.equal(f.service.status().failure, 'address_in_use');
});
test('IPC accepts only the trusted window and validated values, and never returns keys', async (t) => {
const dir = tempDir(t);
const handlers = new Map();
const sent = [];
const service = registerRemoteAppsIpc({
ipcMain: { handle: (name, fn) => handlers.set(name, fn) },
trustedSender: (event) => event.trusted === true,
file: path.join(dir, 'remote-apps.json'),
listen: false,
sendToRenderer: (channel, payload) => sent.push([channel, payload]),
});
t.after(() => service.dispose());
const trusted = { trusted: true };
assert.equal(await handlers.get('remote-apps:get')({}), null);
assert.equal((await handlers.get('remote-apps:set-port')({}, 6000)).error.code, 'forbidden');
assert.equal((await handlers.get('remote-apps:set-port')(trusted, 80)).error.code, 'bad_request');
assert.equal((await handlers.get('remote-apps:set-enabled')(trusted, 'yes')).error.code, 'bad_request');
assert.equal((await handlers.get('remote-apps:set-allowed')(trusted, 'Bad Id', true)).error.code, 'bad_request');
assert.equal((await handlers.get('remote-apps:respond')(trusted, 'missing', true)).error.code, 'not_found');
const result = await handlers.get('remote-apps:set-port')(trusted, 6000);
assert.equal(result.ok, true);
assert.equal(result.status.port, 6000);
assert.equal(JSON.parse(fs.readFileSync(path.join(dir, 'remote-apps.json'), 'utf8')).port, 6000);
const status = await handlers.get('remote-apps:get')(trusted);
assert.deepEqual(Object.keys(status).sort(), ['allowLanAccess', 'apps', 'available', 'enabled', 'failure', 'listening', 'port', 'requests']);
assert.ok(sent.every(([channel]) => channel === 'remote-apps:status'));
});
test('a corrupt configuration fails closed and is kept aside', (t) => {
const file = path.join(tempDir(t), 'remote-apps.json');
fs.writeFileSync(file, '{not json');
const store = new RemoteAppStore(file);
assert.equal(store.loadError, 'corrupt');
assert.equal(store.enabled, true);
assert.equal(store.port, 5899);
assert.deepEqual(store.list(), []);
assert.equal(fs.existsSync(`${file}.corrupt`), true);
});
test('snapshot mapping omits fields the core does not know', () => {
const view = snapshot.indexSnapshot(SNAP);
const bob = view.clients.get(9).properties;
assert.deepEqual(bob, {
nickname: 'Bob', uniqueIdentifier: 'U9=', type: 0, inputMuted: true, outputMuted: false, inputHardware: true, outputHardware: true,
away: true, isTalker: false, isChannelCommander: true, isPrioritySpeaker: false, isRecording: false,
awayMessage: 'brb', description: 'desc', country: '', badges: '', talkPower: 5,
serverGroups: '8', channelGroupId: '9', channelGroupInheritedChannelId: '2', iconId: 3,
});
const selfFlag = snapshot.diffEvents(1, view, snapshot.indexSnapshot({ ...SNAP, clients: [{ ...SNAP.clients[0], input_hardware: false }, SNAP.clients[1]] }));
assert.deepEqual(selfFlag.find((e) => e.type === 'clientSelfPropertyUpdated').payload, { connectionId: 1, flag: 'inputHardware', oldValue: true, newValue: false });
const created = snapshot.diffEvents(1, view, snapshot.indexSnapshot({ ...SNAP, channels: [...SNAP.channels, { ...SNAP.channels[0], id: 3, parent_id: 2, order: 0, name: 'New' }] }));
assert.deepEqual(created.map((e) => [e.type, e.payload.channelId, e.payload.parentId]), [['channelCreated', 3, '2']]);
assert.equal(snapshot.connectionNumber('c12'), 12);
assert.equal(snapshot.connectionNumber('x1'), null);
});
test('a key is bound to the origin it was approved for; re-authorization from another origin rebinds it', async (t) => {
const f = await startService(t);
const web = 'http://localhost:3000';
const first = await approved(f, APP, web);
assert.equal(f.service.status().apps[0].origin, web);
const sameOrigin = await tryKey(f, first.apiKey, web);
assert.ok(sameOrigin.reply, 'same origin authenticates');
for (const origin of [undefined, 'http://evil.example', 'null']) {
const attempt = await tryKey(f, first.apiKey, origin);
assert.deepEqual(attempt.closed, { code: 1008, reason: 'invalid_api_key' }, `origin ${origin ?? 'native'}`);
assert.deepEqual(attempt.c.messages, []);
}
assert.deepEqual(f.service.status().requests, [], 'a wrong-origin key never becomes a request');
// Empty key from a native client: explicit user approval is required, then the key moves to the new origin.
const { c, req } = await request(f);
assert.deepEqual({ origin: req.origin, reauth: req.reauth }, { origin: null, reauth: true });
f.service.respond(req.id, true);
const reply = await c.next('auth');
assert.notEqual(reply.payload.apiKey, first.apiKey);
assert.deepEqual(await first.c.closed, { code: 1008, reason: 'key_revoked' });
assert.deepEqual(await sameOrigin.c.closed, { code: 1008, reason: 'key_revoked' });
assert.equal(f.service.status().apps[0].origin, null);
assert.deepEqual((await tryKey(f, reply.payload.apiKey, web)).closed, { code: 1008, reason: 'invalid_api_key' });
assert.ok((await tryKey(f, reply.payload.apiKey)).reply);
});
test('records saved before origin binding are native-only', async (t) => {
const dir = tempDir(t);
const file = path.join(dir, 'remote-apps.json');
const port = await freePort();
const key = '0b5e7a1c-4d2f-4b8e-9c3a-6f1d2e3c4b5a';
fs.writeFileSync(file, JSON.stringify({ version: 1, enabled: true, port, apps: { [APP.identifier]: { ...APP, allowed: true, keyHash: hashKey(key) } } }));
const f = await startService(t, { file });
assert.equal(f.service.status().apps[0].origin, null);
assert.deepEqual((await tryKey(f, key, 'http://localhost:8080')).closed, { code: 1008, reason: 'invalid_api_key' });
assert.ok((await tryKey(f, key)).reply);
});
test('a metadata write failure neither crashes nor blocks a valid key', async (t) => {
const f = await startService(t);
const { apiKey } = await approved(f);
// The atomic write goes through `<file>.tmp`; a directory there makes every write fail.
fs.mkdirSync(`${f.file}.tmp`);
const { c, reply } = await tryKey(f, apiKey, undefined, { ...APP, name: 'Renamed Application' });
assert.equal(reply.status.code, 0);
assert.equal(f.service.status().apps[0].name, APP.name);
assert.ok(f.logs.some((line) => line.includes('application details not saved')));
assert.ok(f.logs.every((line) => !line.includes(apiKey)));
c.key('still.works', true);
await waitFor(() => f.keys.length === 1, 'key after failed write');
// A decision that cannot be saved is reported and leaves the request pending.
const { req } = await request(f, { ...APP, identifier: 'net.example.other' });
assert.throws(() => f.service.respond(req.id, true));
assert.equal(f.service.status().requests.length, 1);
});
test('unanswered permission requests expire', async (t) => {
const f = await startService(t, { limits: { pendingTimeoutMs: 200 } });
const { c } = await request(f);
assert.deepEqual(await c.closed, { code: 1008, reason: 'auth_expired' });
assert.deepEqual(f.service.status().requests, []);
assert.deepEqual(f.service.status().apps, []);
});
test('web origins have socket and request quotas; native clients keep their slots', async (t) => {
const f = await startService(t);
const a = 'http://a.localhost';
const sockets = [];
for (let i = 0; i < 4; i++) {
const c = connect(f.port, a);
await c.opened;
sockets.push(c);
}
await assert.rejects(connect(f.port, a).opened, /upgrade refused/);
await assert.rejects(connect(f.port, 'x'.repeat(300)).opened, /upgrade refused/);
for (const c of sockets) c.ws.close();
await waitFor(() => f.service.clients.size === 0, 'sockets closed');
await request(f, { ...APP, identifier: 'a.one' }, '', a);
await request(f, { ...APP, identifier: 'a.two' }, '', a);
const third = connect(f.port, a);
await third.opened;
third.auth('', { ...APP, identifier: 'a.three' });
assert.deepEqual(await third.closed, { code: 1013, reason: 'too_many_requests' });
const other = await request(f, { ...APP, identifier: 'b.one' }, '', 'http://b.localhost');
const native = await request(f, { ...APP, identifier: 'native.one' });
assert.deepEqual([other.req.origin, native.req.origin], ['http://b.localhost', null]);
assert.equal(f.service.status().requests.length, 4);
});
+217
View File
@@ -0,0 +1,217 @@
'use strict';
// Main-owned Server Icons IPC: channel-0 bridge paths, native-dialog-only uploads, bounded type/size/header
// checks, content-addressed CRC32 names, list grants bound to session/core/generation, reconnect-safe
// cancellation and destructive delete batching. Controlled core replies and temporary files only; no Electron
// window, dialog or server.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const { registerServerIconsIpc, checkIconBytes, iconIdOf } = require('../app/main/server-icons');
const { crc32 } = require('../app/main/server-snapshot-codec');
function png(width = 16, height = 16, extra = 0) {
const ihdr = Buffer.alloc(25);
ihdr.writeUInt32BE(13, 0); ihdr.write('IHDR', 4, 'ascii'); ihdr.writeUInt32BE(width, 8); ihdr.writeUInt32BE(height, 12);
return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), ihdr, Buffer.alloc(extra, 7)]);
}
async function fixture(t, { listing = [], request, offscreen = false } = {}) {
const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'teamspeach-icons-test-'));
t.after(() => fs.rm(directory, { recursive: true, force: true }));
const handlers = new Map(), listeners = new Set(), calls = [];
const connection = { session: 1, core: {} }; let trusted = true;
const state = { listing: [...listing], picked: [], generation: 4 };
const emit = event => { for (const listener of [...listeners]) listener('one', { event: 'file_transfer', ...event }); };
const fakeDialog = { showOpenDialog: async () => ({ canceled: state.picked.length === 0, filePaths: state.picked }) };
const api = registerServerIconsIpc({
ipcMain: { handle: (name, fn) => handlers.set(name, fn) }, trustedSender: () => trusted,
dialog: fakeDialog, getWindow: () => null, validConnectionId: id => id === 'one', getConnection: id => id === 'one' ? connection : null,
subscribeCore: callback => { listeners.add(callback); return () => listeners.delete(callback); }, testOffscreen: offscreen, tr: key => key,
request: async (id, command, args) => {
calls.push([command, args]);
if (request) { const answer = await request(command, args, { state, emit, connection }); if (answer) return answer; }
if (command === 'admin_context') return { ok: true, result: { generation: state.generation, server_uid: 'srv=' } };
if (command === 'file_list') return { ok: true, result: { channel_id: 0, path: '/icons/', entries: state.listing } };
return { ok: true, result: {} };
},
});
t.after(() => api.dispose());
const write = async (name, bytes) => { const file = path.join(directory, name); await fs.writeFile(file, bytes); return file; };
const invoke = (name, ...args) => handlers.get('server-icons:' + name)({ sender: {} }, 'one', ...args);
const grant = async () => { const listed = await invoke('list'); assert.equal(listed.ok, true); return listed.authorization; };
const mutations = () => calls.filter(([command]) => ['file_upload', 'file_delete', 'file_download', 'file_cancel'].includes(command));
return { calls, state, connection, fakeDialog, write, directory, invoke, grant, mutations, untrust: () => { trusted = false; } };
}
/** Core stand-in for transfers: uploads become listed files, downloads write `bytes`. */
const transfers = (bytes = null) => async (command, args, { state, emit }) => {
if (command === 'file_upload') {
const uploaded = await fs.readFile(args.source);
state.listing.push({ name: path.basename(args.path), type: 'file', size: uploaded.length, datetime: 1 });
state.uploaded = uploaded;
emit({ transfer_id: 41, state: 'done' }); // terminal event before the queued reply: must still be matched
return { ok: true, result: { transfer_id: 41, state: 'queued' } };
}
if (command === 'file_download') {
await fs.writeFile(path.join(args.dest_dir, path.basename(args.path)), bytes);
setImmediate(() => emit({ transfer_id: 42, state: 'done' }));
return { ok: true, result: { transfer_id: 42, state: 'queued' } };
}
return null;
};
test('list asks the channel-0 /icons/ folder, keeps canonical icon files and returns a session grant', async t => {
const f = await fixture(t, { listing: [
{ name: 'icon_3558086607', type: 'file', size: 812, datetime: 5 }, { name: 'icon_7', type: 'file', size: 9, datetime: 6 },
{ name: 'icon_0', type: 'file', size: 1 }, { name: 'icon_007', type: 'file', size: 1 }, { name: 'icon_4294967296', type: 'file', size: 1 },
{ name: 'icon_9', type: 'folder', size: 0 }, { name: 'avatar_x', type: 'file', size: 1 },
] });
const result = await f.invoke('list');
assert.equal(result.ok, true); assert.equal(result.generation, 4);
assert.match(result.authorization, /^[0-9a-f-]{36}$/);
assert.deepEqual(result.icons, [{ id: 3558086607, size: 812, datetime: 5 }, { id: 7, size: 9, datetime: 6 }]);
assert.deepEqual(f.calls, [['admin_context', {}], ['file_list', { channel_id: 0, path: '/icons/' }]]);
assert.equal(iconIdOf('icon_4294967295'), 4294967295);
});
test('a failed listing (HTTPFT/S3 storage) returns no grant', async t => {
const f = await fixture(t, { request: async command => command === 'file_list' ? { ok: false, error: { code: 'media_unsupported', message: 'HTTPFT' } } : null });
const result = await f.invoke('list');
assert.equal(result.ok, false); assert.equal(result.error.code, 'media_unsupported'); assert.equal(result.authorization, undefined);
});
test('untrusted senders never reach the core', async t => {
const f = await fixture(t);
f.untrust();
assert.equal((await f.invoke('list')).error.code, 'forbidden');
assert.equal(f.calls.length, 0);
});
test('mutations need a grant from this session and the current generation', async t => {
const f = await fixture(t);
for (const forged of [undefined, 'x', '00000000-0000-0000-0000-000000000000']) {
assert.equal((await f.invoke('delete', forged, [7])).error.code, 'connection_changed');
}
const old = await f.grant();
f.connection.session += 1; // reconnect after the panel listed icons
assert.equal((await f.invoke('delete', old, [7])).error.code, 'connection_changed');
f.state.picked = [await f.write('a.png', png())];
assert.equal((await f.invoke('upload', old)).error.code, 'connection_changed');
const fresh = await f.grant();
f.state.generation = 5; // the core generation moved on without a main session change
assert.equal((await f.invoke('delete', fresh, [7])).error.code, 'connection_changed');
assert.deepEqual(f.mutations(), []);
});
test('upload names the file by content CRC32, uploads a private copy and confirms the listing', async t => {
const f = await fixture(t, { request: transfers() });
const bytes = png(16, 16, 40);
f.state.picked = [await f.write('Мой значок.png', bytes)];
const result = await f.invoke('upload', await f.grant());
const id = crc32(bytes);
assert.equal(result.ok, true);
assert.deepEqual(result.uploaded, [{ id, existing: false, name: 'Мой значок.png' }]);
assert.deepEqual(result.errors, []);
const upload = f.calls.find(([command]) => command === 'file_upload')[1];
assert.equal(upload.channel_id, 0); assert.equal(upload.path, `/icons/icon_${id}`); assert.equal(upload.overwrite, false);
assert.notEqual(upload.source, f.state.picked[0]); // never the user's file itself
assert.ok(f.state.uploaded.equals(bytes));
await assert.rejects(fs.stat(upload.source), { code: 'ENOENT' }); // temporary copy removed
assert.equal(JSON.stringify(result).includes(f.directory), false); // no host path reaches the renderer
});
test('a reconnect while the native dialog is open uploads nothing', async t => {
const f = await fixture(t, { request: transfers() });
const token = await f.grant();
const picked = [await f.write('a.png', png())];
f.fakeDialog.showOpenDialog = async () => { f.connection.session += 1; return { canceled: false, filePaths: picked }; };
assert.equal((await f.invoke('upload', token)).error.code, 'connection_changed');
assert.deepEqual(f.mutations(), []);
});
test('an identical existing icon is reused; a different file with that CRC32 is never overwritten', async t => {
const bytes = png(); const id = crc32(bytes);
const same = await fixture(t, { listing: [{ name: `icon_${id}`, type: 'file', size: bytes.length }], request: transfers(bytes) });
same.state.picked = [await same.write('a.png', bytes)];
assert.deepEqual((await same.invoke('upload', await same.grant())).uploaded, [{ id, existing: true, name: 'a.png' }]);
assert.ok(!same.calls.some(([command]) => command === 'file_upload'));
const download = same.calls.find(([command]) => command === 'file_download')[1];
assert.equal(download.path, `/icons/icon_${id}`); assert.equal(download.channel_id, 0);
const other = await fixture(t, { listing: [{ name: `icon_${id}`, type: 'file', size: 3 }], request: transfers(Buffer.from('xyz')) });
other.state.picked = [await other.write('b.png', bytes)];
const result = await other.invoke('upload', await other.grant());
assert.deepEqual(result.uploaded, []); assert.equal(result.errors[0].code, 'collision');
assert.ok(!other.calls.some(([command]) => command === 'file_upload'));
});
test('type, size and header bounds are enforced per file before any transfer', async t => {
const f = await fixture(t, { request: transfers() });
f.state.picked = [
await f.write('script.png', Buffer.from('#!/bin/sh\necho no')),
await f.write('huge.png', png(16, 16, 128 * 1024)),
await f.write('bomb.png', png(20000, 20000)),
await f.write('ok.svg', Buffer.from('<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"/>')),
];
const result = await f.invoke('upload', await f.grant());
assert.deepEqual(result.errors.map(e => [e.name, e.code]), [['script.png', 'unsupported_type'], ['huge.png', 'too_large'], ['bomb.png', 'too_large']]);
assert.equal(result.uploaded.length, 1); assert.equal(result.uploaded[0].name, 'ok.svg');
assert.equal(f.calls.filter(([command]) => command === 'file_upload').length, 1);
assert.throws(() => checkIconBytes(Buffer.from([0xff, 0xd8, 0xff, 0xd9])), { code: 'invalid_image' });
assert.throws(() => checkIconBytes(png(), { createFromBuffer: () => ({ isEmpty: () => true }) }), { code: 'invalid_image' });
});
test('cancelled or offscreen dialogs upload nothing', async t => {
const f = await fixture(t);
assert.deepEqual(await f.invoke('upload', await f.grant()), { ok: true, cancelled: true });
const off = await fixture(t, { offscreen: true });
assert.equal((await off.invoke('upload', await off.grant())).error.code, 'unavailable');
assert.deepEqual(f.mutations(), []); assert.deepEqual(off.mutations(), []);
});
test('a reconnect during an upload never cancels by the recycled transfer id', async t => {
// Transfer ids restart per session: id 9 of the new session is an unrelated user transfer.
const f = await fixture(t, { request: async (command, _args, { connection }) => {
if (command === 'file_upload') { connection.session += 1; return { ok: true, result: { transfer_id: 9, state: 'queued' } }; }
return null;
} });
f.state.picked = [await f.write('a.png', png()), await f.write('b.png', png(17, 17))];
const result = await f.invoke('upload', await f.grant());
assert.equal(result.ok, false); assert.equal(result.error.code, 'connection_changed');
assert.ok(!f.calls.some(([command]) => command === 'file_cancel'), 'no file_cancel reaches the new session');
assert.equal(f.calls.filter(([command]) => command === 'file_upload').length, 1);
});
test('a window change during an upload in the same session cancels that transfer', async t => {
const f = await fixture(t, { request: async command => {
if (command === 'file_upload') { f.untrust(); return { ok: true, result: { transfer_id: 9, state: 'queued' } }; }
return null;
} });
f.state.picked = [await f.write('a.png', png())];
const result = await f.invoke('upload', await f.grant());
assert.equal(result.error.code, 'forbidden');
assert.deepEqual(f.calls.find(([command]) => command === 'file_cancel'), ['file_cancel', { transfer_id: 9 }]);
});
test('delete validates ids and batches canonical channel-0 paths by 100', async t => {
const f = await fixture(t);
const token = await f.grant();
for (const bad of [[], [0], [1, 1], [4294967296], ['5'], 'icon_5']) assert.equal((await f.invoke('delete', token, bad)).error.code, 'bad_request');
assert.deepEqual(f.mutations(), []);
const ids = Array.from({ length: 150 }, (_, i) => i + 1);
assert.deepEqual(await f.invoke('delete', token, ids), { ok: true, deleted: ids });
const batches = f.calls.filter(([command]) => command === 'file_delete').map(([, args]) => args);
assert.equal(batches.length, 2);
assert.equal(batches[0].channel_id, 0); assert.equal(batches[0].paths.length, 100); assert.equal(batches[0].paths[0], '/icons/icon_1');
assert.deepEqual(batches[1].paths.at(-1), '/icons/icon_150');
});
test('a failed delete batch reports the icons already removed', async t => {
let n = 0;
const f = await fixture(t, { request: async command => command === 'file_delete' && n++ === 1 ? { ok: false, error: { code: 'server_error', message: 'denied' } } : null });
const ids = Array.from({ length: 101 }, (_, i) => i + 1);
const result = await f.invoke('delete', await f.grant(), ids);
assert.equal(result.ok, false); assert.equal(result.error.code, 'server_error'); assert.deepEqual(result.deleted, ids.slice(0, 100));
});
+329
View File
@@ -0,0 +1,329 @@
// Server Icons panel: list/preview, view sizes, confirmed remove/remove-all, assignment commands for every
// official target, picker/direct-edit modes and stale-session refusal. Deterministic fake DOM and bridge;
// no Electron, dialog, server or network.
import { test, beforeEach } from 'node:test';
import assert from 'node:assert/strict';
import { env } from './fixtures/renderer-env.mjs';
class Element extends globalThis.Node {
constructor(tag = 'div') {
super(); this.tagName = tag.toUpperCase(); this.parentNode = null; this.listeners = new Map();
this.attributes = new Map(); this.disabled = false; this.id = ''; this._text = ''; this.open = false; this.returnValue = '';
const props = new Map();
this.style = { props, setProperty(key, value) { props.set(key, value); }, removeProperty(key) { props.delete(key); } };
}
get textContent() { return this._text + this.children.map((c) => c.textContent).join(''); }
set textContent(value) { this._text = String(value ?? ''); this.children = []; }
get isConnected() { return this === document.body || Boolean(this.parentNode?.isConnected); }
appendChild(child) { child.parentNode = this; this.children.push(child); return child; }
append(...children) { for (const child of children.flat()) this.appendChild(child); }
replaceChildren(...children) { for (const child of this.children) child.parentNode = null; this.children = []; this._text = ''; this.append(...children); }
remove() { if (this.parentNode) this.parentNode.children = this.parentNode.children.filter((c) => c !== this); this.parentNode = null; }
// The app's CSP (style-src 'self') rejects inline style attributes; only CSSOM writes are allowed.
setAttribute(key, value) { if (key === 'style') throw new Error('CSP: inline style attribute'); this.attributes.set(key, String(value)); if (key === 'id') this.id = String(value); if (key === 'class') this.className = String(value); }
getAttribute(key) { return this.attributes.get(key) ?? null; }
removeAttribute(key) { this.attributes.delete(key); }
addEventListener(type, fn) { if (!this.listeners.has(type)) this.listeners.set(type, new Set()); this.listeners.get(type).add(fn); }
removeEventListener(type, fn) { this.listeners.get(type)?.delete(fn); }
dispatch(type, extra = {}) { const event = { type, target: this, currentTarget: this, clientX: 0, clientY: 0, preventDefault() {}, stopPropagation() {}, ...extra }; for (const fn of [...(this.listeners.get(type) ?? [])]) fn(event); }
click() { if (!this.disabled) this.dispatch('click'); }
focus() { document.activeElement = this; }
showModal() { this.open = true; }
close(value) { if (!this.open) return; this.open = false; if (value !== undefined) this.returnValue = value; this.dispatch('close'); }
getBoundingClientRect() { return { left: 10, right: 30, top: 10, bottom: 30, width: 20, height: 20 }; }
matches(selector) {
if (selector.startsWith('.')) return String(this.className).split(' ').includes(selector.slice(1));
if (selector.startsWith('#')) return this.id === selector.slice(1);
return this.tagName === selector.toUpperCase();
}
querySelectorAll(selector) { return this.children.flatMap((c) => [...(c.matches?.(selector) ? [c] : []), ...(c.querySelectorAll?.(selector) ?? [])]); }
querySelector(selector) { return this.querySelectorAll(selector)[0] ?? null; }
}
const body = new Element('body');
Object.assign(globalThis.document, {
body, activeElement: null, createElement: (tag) => new Element(tag), createElementNS: (_, tag) => new Element(tag),
createTextNode: (text) => { const node = new Element('#text'); node.textContent = text; return node; },
querySelector: (selector) => body.querySelector(selector), querySelectorAll: (selector) => body.querySelectorAll(selector),
// dom.icon() (warning dialog, toasts) resolves sprite symbols; artwork itself is checked offscreen.
getElementById: (id) => (id.startsWith('i-') ? { id, localName: 'symbol', attributes: [], childNodes: [], childElementCount: 0 } : body.querySelector(`#${id}`)),
});
Object.assign(globalThis, { innerWidth: 1000, innerHeight: 800 });
const { S, newConnection } = await import('../app/renderer/js/state.js');
const { t } = await import('../app/renderer/js/i18n.js');
const { openServerIcons, syncServerIcons, assignIcon, permissionValue, VIEW_MODES } = await import('../app/renderer/js/server-icons.js');
const settle = async () => { for (let i = 0; i < 6; i++) await new Promise((resolve) => setImmediate(resolve)); };
const PNG = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).toString('base64');
const BIG = 3558086607; // > i32::MAX: i_icon_id must travel as the signed value
let conn, ipc;
const sent = (cmd) => env.requests.filter((r) => r.cmd === cmd);
const items = () => body.querySelectorAll('.server-icon-item');
const menuItem = (label) => { const item = body.querySelectorAll('.client-menu-item').find((b) => b.textContent === label); assert.ok(item, `menu item ${label}`); return item; };
const confirmWarning = () => { const button = body.querySelector('.tsv-user-input-dialog-confirm'); assert.ok(button, 'warning dialog'); button.click(); };
beforeEach(() => {
S.connections.clear(); body.replaceChildren(); env.requests.length = 0;
const toasts = new Element('div'); toasts.id = 'toasts'; body.append(toasts);
conn = newConnection('one'); conn.conn = { state: 'connected', address: 'fixture.invalid' }; conn.session = 3;
conn.snap = {
generation: 17,
server: { name: 'Fixture', icon_id: 0 },
server_groups: [{ id: 6, name: 'Admins', icon_id: 0, type: 'regular' }, { id: 1, name: 'Template', icon_id: 0, type: 'template' }],
channel_groups: [{ id: 5, name: 'Channel Admin', icon_id: 100, type: 'regular' }],
channels: [{ id: 1, name: 'Lobby', depth: 0, icon_id: 0 }, { id: 2, name: 'Sub', depth: 1, icon_id: 0 }],
clients: [{ id: 9, uid: 'alice=', nickname: 'Alice', icon_id: 0 }, { id: 4, uid: 'bob=', nickname: 'Bob', icon_id: 0 }],
};
S.connections.set(conn.id, conn); S.viewId = conn.id;
ipc = { list: [], deleted: [], uploads: [], grants: 0,
listResult: () => ({ ok: true, generation: 17, authorization: `grant-${++ipc.grants}`, icons: [{ id: 7, size: 8 }, { id: BIG, size: 8 }, { id: 11, size: 8 }] }),
deleteResult: (ids) => ({ ok: true, deleted: ids }) };
Object.assign(globalThis.teamspeach, {
serverIconsList: async (id) => { ipc.list.push(id); return ipc.listResult(); },
serverIconsDelete: async (id, authorization, ids) => { ipc.deleted.push([id, ids, authorization]); return ipc.deleteResult(ids); },
serverIconsUpload: async (id, authorization) => { ipc.uploads.push([id, authorization]); return { ok: true, uploaded: [{ id: 12, existing: false, name: 'a.png' }], errors: [] }; },
});
env.respond = async (cmd, args) => {
if (cmd === 'fetch_icon') return args.icon_id === 11 ? { ok: false, error: { code: 'not_found', message: 'gone' } } : { ok: true, result: { mime: 'image/png', data: PNG } };
if (cmd === 'admin_context') return { ok: true, result: { generation: 17, server_uid: 'srv=', permissions: {} } };
if (cmd === 'client_context') return { ok: true, result: { generation: 17, permissions: [{ id: 3, name: 'i_client_x' }, { id: 145, name: 'i_icon_id' }] } };
return { ok: true, result: {} };
};
});
test('lists through main, previews via fetch_icon and omits icons that cannot be fetched', async () => {
const ui = openServerIcons('one'); await settle();
assert.deepEqual(ipc.list, ['one']);
assert.deepEqual(items().map((b) => Number(b.dataset.iconId)), [7, BIG]);
assert.deepEqual(sent('fetch_icon').map((r) => r.args.icon_id).sort(), [7, 11, BIG].sort());
assert.ok(!env.requests.some((r) => r.cmd.startsWith('file_')), 'channel 0 never uses generic file commands');
assert.deepEqual(ui.icons, [7, BIG]);
assert.match(items()[0].children[0].className, /tsv-icon tsv-icon-large/);
ui.close();
});
test('view menu switches the four official sizes', async () => {
const ui = openServerIcons('one'); await settle();
for (const [mode, label] of [['small', 'view.s'], ['medium', 'view.m'], ['xlarge', 'view.xl'], ['large', 'view.l']]) {
body.querySelector('.tsv-navigation-bar').querySelectorAll('button').at(-1).click();
menuItem(t(`server.icons.${label}`)).click();
assert.equal(ui.viewMode, mode);
assert.equal(items()[0].children[0].className, VIEW_MODES[mode] ? `tsv-icon ${VIEW_MODES[mode]}` : 'tsv-icon');
}
ui.close();
});
test('remove all asks first; cancelling deletes nothing, confirming deletes every listed icon and reloads', async () => {
const ui = openServerIcons('one'); await settle();
const openRemoveAll = () => { body.querySelector('.tsv-navigation-bar').querySelectorAll('button').at(-1).click(); menuItem(t('universal.remove_all')).click(); };
openRemoveAll(); await settle();
body.querySelector('.tsv-user-input-dialog-cancel').click(); await settle();
assert.deepEqual(ipc.deleted, []);
openRemoveAll(); await settle(); confirmWarning(); await settle();
assert.deepEqual(ipc.deleted, [['one', [7, BIG], 'grant-1']]); // the grant of the listing the user confirmed
assert.equal(ipc.list.length, 2);
ui.close();
});
test('single delete from the icon context menu is confirmed', async () => {
const ui = openServerIcons('one'); await settle();
items()[1].click();
menuItem(t('universal.delete')).click(); await settle();
assert.deepEqual(ipc.deleted, []);
confirmWarning(); await settle();
assert.deepEqual(ipc.deleted, [['one', [BIG], 'grant-1']]);
ui.close();
});
test('manage menu assigns server, group, channel and client icons with typed commands', async () => {
const ui = openServerIcons('one'); await settle();
const use = async (action, target, absent = null) => {
items()[1].click();
menuItem(t(`server.icons.action.${action}`)).click();
if (absent) assert.ok(!body.querySelectorAll('.client-menu-item').some((b) => b.textContent === absent), `${absent} is not offered`);
if (target) menuItem(target).click();
await settle();
};
await use('use.server'); // single click, bound to the session's server identity
assert.deepEqual(sent('server_edit').at(-1).args, { generation: 17, confirm: 'srv=', properties: { virtualserver_icon_id: BIG } });
await use('use.server.icon', 'Admins', 'Template');
assert.deepEqual(sent('group_set_permissions').at(-1).args, { generation: 17, kind: 'server', group_id: 6, permissions: [{ id: 'i_icon_id', value: BIG | 0, negate: false, skip: false }] });
await use('use.channel.group', 'Channel Admin');
assert.equal(sent('group_set_permissions').at(-1).args.kind, 'channel');
await use('use.channel', 'Sub');
assert.deepEqual(sent('channel_set_permissions').at(-1).args, { generation: 17, channel_id: 2, permissions: [{ id: 'i_icon_id', value: -736880689 }] });
await use('use.client', 'Bob');
assert.deepEqual(sent('client_context').at(-1).args, { client_id: 4, uid: 'bob=' });
assert.deepEqual(sent('client_action').at(-1).args, { client_id: 4, uid: 'bob=', generation: 17, action: 'set_client_permission', permission_id: 145, value: -736880689, skip: false });
assert.equal(permissionValue(BIG), -736880689);
ui.close();
});
test('picker mode returns the clicked id or 0 without touching the server', async () => {
const picks = [];
let ui = openServerIcons('one', { select: (id) => picks.push(id) }); await settle();
items()[0].click();
ui = openServerIcons('one', { select: (id) => picks.push(id) }); await settle();
body.querySelector('.tsv-is-destructive').click();
assert.deepEqual(picks, [7, 0]);
assert.ok(!env.requests.some((r) => ['server_edit', 'group_set_permissions', 'channel_set_permissions', 'client_action'].includes(r.cmd)));
ui.close();
});
test('direct edit assigns to its target and Remove clears it', async () => {
openServerIcons('one', { target: { kind: 'server_group', id: 6 } }); await settle();
items()[0].click(); await settle();
assert.deepEqual(sent('group_set_permissions').at(-1).args.permissions, [{ id: 'i_icon_id', value: 7, negate: false, skip: false }]);
openServerIcons('one', { target: { kind: 'client', id: 9, uid: 'alice=' } }); await settle();
body.querySelector('.tsv-is-destructive').click(); await settle();
assert.equal(sent('client_action').at(-1).args.value, null); // clientdelperm
await assert.rejects(assignIcon('one', { kind: 'bogus', id: 1 }, 7, 17));
});
test('a reconnect closes the panel and refuses further assignment', async () => {
const ui = openServerIcons('one'); await settle();
conn.session += 1;
items()[0].click(); await settle();
assert.ok(!sent('server_edit').length && !body.querySelector('.client-menu-item'));
syncServerIcons();
assert.ok(!body.querySelector('.tsv-server-icons'));
ui.close();
});
test('upload runs only through the main dialog and reloads', async () => {
const ui = openServerIcons('one'); await settle();
body.querySelector('.tsv-navigation-bar').querySelectorAll('button').find((b) => b.getAttribute('aria-label') === t('server.icons.upload.title')).click();
await settle();
assert.deepEqual(ipc.uploads, [['one', 'grant-1']]); assert.equal(ipc.list.length, 2);
assert.ok(!env.requests.some((r) => r.cmd === 'file_upload'));
ui.close();
});
test('HTTPFT/S3 servers report unsupported storage instead of an empty list', async () => {
ipc.listResult = () => ({ ok: false, error: { code: 'media_unsupported', message: 'HTTPFT' } });
const ui = openServerIcons('one'); await settle();
assert.ok(body.querySelectorAll('.client-dialog-status').some((s) => s.textContent === t('server.icons.storage_unsupported')));
ui.close();
});
// ---------- detail-pane manage view (official view:server.ServerIcons) ----------
function paneHost() {
const pane = new Element('section'); pane.id = 'channel-info-view';
const toolbar = new Element('div'); toolbar.className = 'adm-navbar-tools';
const host = new Element('div'); host.className = 'adm-readable';
pane.append(toolbar, host); body.append(pane);
return { pane, toolbar, host };
}
test('manage mode renders into the admin pane: toolbar controls, no modal dialog', async () => {
const { toolbar, host } = paneHost();
const backs = [];
const ui = openServerIcons('one', { host, toolbar, onBack: () => backs.push('back') }); await settle();
assert.equal(ui.hosted, true);
assert.equal(body.querySelector('dialog'), null);
assert.deepEqual(toolbar.children.map((b) => b.getAttribute('aria-label') ?? 'remove'), ['remove', t('server.icons.upload.title'), t('admin.refresh'), t('universal.manage')]);
assert.deepEqual(host.querySelectorAll('.server-icon-item').map((b) => Number(b.dataset.iconId)), [7, BIG]);
host.querySelectorAll('.server-icon-item')[0].click();
assert.ok(menuItem(t('server.icons.action.use.server')));
menuItem(t('server.icons.action.use.server')).click(); await settle();
assert.equal(sent('server_edit').at(-1).args.properties.virtualserver_icon_id, 7);
ui.close();
assert.equal(host.children.length, 0); assert.equal(toolbar.children.length, 0);
assert.deepEqual(backs, [], 'an owner-initiated close does not navigate');
});
test('a hosted view leaves through onBack when its session changes', async () => {
const { toolbar, host } = paneHost();
const backs = [];
openServerIcons('one', { host, toolbar, onBack: () => backs.push('back') }); await settle();
conn.session += 1;
host.querySelectorAll('.server-icon-item')[0].click(); await settle();
assert.deepEqual(backs, ['back']);
assert.equal(host.children.length, 0);
assert.ok(!body.querySelector('.client-menu-item') && !sent('server_edit').length);
});
test('a hosted view whose pane page was replaced ends silently', async () => {
const { toolbar, host } = paneHost();
const backs = [];
const ui = openServerIcons('one', { host, toolbar, onBack: () => backs.push('back') }); await settle();
host.replaceChildren(new Element('p')); // admin navigated to another page
await ui.reload(true);
assert.equal(ipc.list.length, 1); assert.deepEqual(backs, []);
assert.equal(host.children.length, 1);
});
test('without a toolbar the hosted view draws its own navigation bar; picker modes stay dialogs', async () => {
const { host } = paneHost();
const ui = openServerIcons('one', { host }); await settle();
assert.ok(host.querySelector('.adm-navbar'));
assert.equal(host.querySelector('.adm-navbar').querySelectorAll('button').length, 4);
assert.throws(() => openServerIcons('one', { host, select: () => {} }), /dialog/);
// A picker opened from an edit form does not close the hosted manager.
const picker = openServerIcons('one', { select: () => {} }); await settle();
assert.ok(body.querySelector('dialog') && host.querySelector('.server-icons-content'));
picker.close(); ui.close();
});
test('assignment refuses a context that arrives after the session changed', async () => {
const respond = env.respond;
env.respond = async (cmd, args) => { if (cmd === 'admin_context' || cmd === 'client_context') conn.session += 1; return respond(cmd, args); };
await assert.rejects(assignIcon('one', { kind: 'server_group', id: 6 }, 7, 17), { code: 'connection_closed' });
await assert.rejects(assignIcon('one', { kind: 'client', id: 4, uid: 'bob=' }, 7, 17), { code: 'connection_closed' });
assert.ok(!['group_set_permissions', 'client_action', 'server_edit', 'channel_set_permissions'].some((cmd) => sent(cmd).length));
});
test('a context from another generation (main reconnected first) cannot mutate', async () => {
const ui = openServerIcons('one'); await settle();
const respond = env.respond;
// The renderer session counter has not caught up yet; main's core already serves the new connection.
env.respond = async (cmd, args) => (cmd === 'admin_context' || cmd === 'client_context'
? { ok: true, result: { generation: 18, server_uid: 'srv=', permissions: [{ id: 145, name: 'i_icon_id' }] } }
: respond(cmd, args));
items()[1].click(); menuItem(t('server.icons.action.use.server')).click(); await settle();
items()[1].click(); menuItem(t('server.icons.action.use.client')).click(); menuItem('Bob').click(); await settle();
assert.ok(!['server_edit', 'client_action'].some((cmd) => sent(cmd).length));
await assert.rejects(assignIcon('one', { kind: 'channel', id: 2 }, 7, 16), { code: 'connection_changed' }); // stale captured generation
assert.ok(!sent('channel_set_permissions').length);
ui.close();
});
test('a listing from another generation yields no grant and the view leaves', async () => {
const { toolbar, host } = paneHost();
const backs = [];
ipc.listResult = () => ({ ok: true, generation: 18, authorization: 'grant-new', icons: [{ id: 7, size: 8 }] });
openServerIcons('one', { host, toolbar, onBack: () => backs.push('back') }); await settle();
assert.deepEqual(backs, ['back']);
assert.equal(host.children.length, 0);
assert.deepEqual(ipc.deleted, []); assert.deepEqual(ipc.uploads, []);
});
test('a failed listing grants nothing: upload stays disabled and remove-all sends nothing', async () => {
ipc.listResult = () => ({ ok: false, error: { code: 'media_unsupported', message: 'HTTPFT' } });
const ui = openServerIcons('one'); await settle();
const upload = body.querySelector('.tsv-navigation-bar').querySelectorAll('button').find((b) => b.getAttribute('aria-label') === t('server.icons.upload.title'));
assert.equal(upload.disabled, true);
ui.close();
assert.deepEqual(ipc.uploads, []); assert.deepEqual(ipc.deleted, []);
});
test('main answering connection_changed to a delete ends the hosted view', async () => {
const { toolbar, host } = paneHost();
const backs = [];
ipc.deleteResult = () => ({ ok: false, error: { code: 'connection_changed', message: 'reload' } });
openServerIcons('one', { host, toolbar, onBack: () => backs.push('back') }); await settle();
host.querySelectorAll('.server-icon-item')[0].click();
menuItem(t('universal.delete')).click(); await settle(); confirmWarning(); await settle();
assert.equal(ipc.deleted.length, 1); assert.deepEqual(backs, ['back']);
assert.equal(ipc.list.length, 1, 'no reload against the new session');
});
test('channel depth in the "Use for channel" menu uses CSSOM, never an inline style attribute', async () => {
const ui = openServerIcons('one'); await settle();
items()[0].click();
menuItem(t('server.icons.action.use.channel')).click();
const sub = menuItem('Sub'), lobby = menuItem('Lobby');
assert.equal(sub.dataset.depth, ''); assert.equal(sub.style.props.get('--depth'), '1');
assert.equal(lobby.dataset.depth, undefined); assert.equal(sub.getAttribute('style'), null);
ui.close();
});
+23
View File
@@ -101,3 +101,26 @@ test('untrusted sender and offscreen modes cannot open native dialogs', async t
assert.equal((await f.invoke('open')).error.code, 'unavailable'); assert.equal(invoked, false);
f.untrust(); assert.equal((await f.invoke('open')).error.code, 'forbidden');
});
test('cancelling an old-session icon transfer cannot cancel a reused transfer id after reconnect', async t => {
let started;
const queued = new Promise(resolve => { started = resolve; });
const f = await fixture(t, { request: async command => {
if (command === 'server_info') return { ok: true, result: { rows: [{}] } };
if (command === 'file_list') return { ok: true, result: { entries: [{ name: 'icon_5000', type: 'file', size: 8 }] } };
if (command === 'file_download') { setImmediate(started); return { ok: true, result: { transfer_id: 8, state: 'queued' } }; }
if (command === 'file_cancel') throw new Error('must not cancel the new session transfer');
throw new Error(command);
} });
const exporting = f.invoke('export', { includeIcons: true });
await queued;
f.connection.session += 1;
const cancelled = await f.invoke('cancel');
assert.equal(cancelled.ok, false);
assert.equal(cancelled.error.code, 'connection_changed');
for (const listener of f.listeners) listener('one', { event: 'file_transfer', transfer_id: 8, state: 'done' });
const result = await exporting;
assert.equal(result.success, false);
assert.equal(f.calls.some(([, command]) => command === 'file_cancel'), false);
await assert.rejects(fs.stat(f.destination), { code: 'ENOENT' });
});
+124 -8
View File
@@ -3,33 +3,149 @@ import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { EventEmitter } from 'node:events';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const { WhisperStore, KeybindStore, HotkeyHelper, conflicts } = require('../app/main/whisper-main.js');
const { WhisperStore, KeybindStore, HotkeyHelper } = require('../app/main/whisper-main.js');
const { conflicts } = require('../app/main/keybind-schema.js');
test('local lists and bindings persist without starting any voice route; deleting target drops binding', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tp-whisper-'));
const tempDir = () => fs.mkdtempSync(path.join(os.tmpdir(), 'tp-whisper-'));
test('local lists and profile bindings persist without starting any voice route; deleting target drops binding', () => {
const dir = tempDir();
try {
const store = new WhisperStore(dir);
const list = store.saveList({ name: 'Team', type: 1, whisper_entry_list: [{ type: 1, uuid: 'uid', name: 'Name' }] });
const keys = new KeybindStore(dir); keys.attach(store.listIds());
keys.set([{ action: 'whisper_list', target: list.list_uuid, code: 'F9', global: false }], store.listIds());
const keys = new KeybindStore(dir);
const profile = keys.addProfile('Main');
keys.setBindings(profile, [{ action: 'whisper_list', target: list.list_uuid, code: 'F9', global: false }]);
assert.equal(new WhisperStore(dir).get().lists[0].whisper_entry_list[0].uuid, 'uid');
assert.equal(keys.get().length, 1); store.deleteList(list.list_uuid); keys.dropTarget(list.list_uuid); assert.equal(keys.get().length, 0);
assert.equal(new KeybindStore(dir).activeBindings().length, 1);
store.deleteList(list.list_uuid); keys.dropTarget(list.list_uuid);
assert.equal(keys.activeBindings().length, 0);
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
});
test('version 1 whisper bindings migrate losslessly into one active profile and the v1 bytes are kept', () => {
const dir = tempDir();
try {
const v1 = { version: 1, bindings: [
{ id: '11111111-1111-4111-8111-111111111111', action: 'whisper_list', target: '22222222-2222-4222-8222-222222222222', code: 'F9', ctrl: true, alt: false, shift: false, meta: false, global: false },
{ id: '33333333-3333-4333-8333-333333333333', action: 'reply_whisper', target: '', code: 'KeyR', ctrl: false, alt: true, shift: false, meta: false, global: true },
] };
const raw = JSON.stringify(v1);
fs.writeFileSync(path.join(dir, 'keybinds.json'), raw);
const keys = new KeybindStore(dir, { now: () => 42, defaultProfileName: 'Standard' });
const state = keys.get();
assert.equal(state.profiles.length, 1);
assert.equal(state.profiles[0].name, 'Standard');
assert.equal(state.activeProfile, state.profiles[0].id);
assert.equal(state.requireExactMatch, true, 'version 1 always matched exactly');
assert.deepEqual(state.profiles[0].bindings, v1.bindings);
assert.equal(fs.readFileSync(path.join(dir, 'keybinds.v1-42.json'), 'utf8'), raw);
const saved = JSON.parse(fs.readFileSync(path.join(dir, 'keybinds.json'), 'utf8'));
assert.equal(saved.version, 2);
assert.deepEqual(new KeybindStore(dir).get(), state, 'v2 reload is stable');
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
});
test('fresh store is "No Profile" with exact match off; profiles add/rename/activate/delete persist', () => {
const dir = tempDir();
try {
const keys = new KeybindStore(dir);
assert.deepEqual([keys.get().activeProfile, keys.get().profiles.length, keys.get().requireExactMatch], [null, 0, false]);
const a = keys.addProfile(' Gaming ');
const b = keys.addProfile('Work');
assert.equal(keys.get().activeProfile, a, 'the first profile becomes active');
keys.renameProfile(b, 'Office');
assert.throws(() => keys.deleteProfile(a), /activate another profile/);
keys.activateProfile(b);
keys.deleteProfile(a);
keys.setExact(true);
const reloaded = new KeybindStore(dir).get();
assert.deepEqual(reloaded.profiles.map((p) => p.name), ['Office']);
assert.equal(reloaded.activeProfile, b);
assert.equal(reloaded.requireExactMatch, true);
assert.throws(() => keys.addProfile(' '), /name/);
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
});
test('remote bindings carry no physical fields; at most six bindings per action group', () => {
const dir = tempDir();
try {
const keys = new KeybindStore(dir);
const p = keys.addProfile('P');
keys.setBindings(p, [{ action: 'push_to_talk', remote: { remoteApp: 'com.example.deck', remoteButton: 'b1' } }]);
assert.deepEqual(keys.activeBindings()[0].remote, { remoteApp: 'com.example.deck', remoteButton: 'b1' });
assert.equal(keys.activeBindings()[0].code, undefined);
assert.throws(() => keys.setBindings(p, [{ action: 'push_to_talk', code: 'F1', remote: { remoteApp: 'a', remoteButton: 'b' } }]), /no physical/);
const seven = ['F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7'].map((code) => ({ action: code === 'F1' ? 'microphone_mute' : 'microphone_toggle', code }));
assert.throws(() => keys.setBindings(p, seven), /at most 6/);
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
});
test('global bindings default empty; offscreen helper cannot launch or register any key', () => {
let spawned = 0;
const helper = new HotkeyHelper({ enabled: false, resolveBinary: () => 'unused', spawnProcess: () => { spawned++; }, onEvent() {}, onStatus() {} });
helper.bind([{ id: 'key', code: 'F9', global: true }]);
assert.equal(spawned, 0); assert.equal(helper.status.global, false); assert.equal(helper.status.detail, 'test_offscreen');
});
test('local binding conflicts include duplicate chords and legacy F8 push-to-talk', () => {
const base = { code: 'F8', ctrl: false, alt: false, shift: false, meta: false };
test('binding conflicts include duplicate chords, duplicate remote buttons, the Audio PTT key and missing lists', () => {
const base = { code: 'F8', ctrl: false, alt: false, shift: false, meta: false, action: 'quick_whisper' };
const result = conflicts([{ ...base, id: 'a' }, { ...base, id: 'b' }], 'F8');
assert.deepEqual(new Set(result.map(value => value.id)), new Set(['a', 'b']));
for (const id of ['a', 'b']) {
assert.ok(result.some(value => value.id === id && value.reason === 'duplicate'), `${id} cannot activate a duplicate chord`);
assert.ok(result.some(value => value.id === id && value.reason === 'ptt'), `${id} cannot steal the push-to-talk chord`);
}
assert.deepEqual(conflicts([{ ...base, id: 'p', action: 'push_to_talk' }], 'F8'), [], 'a PTT binding on the PTT key is not a conflict');
const remote = { action: 'push_to_mute', remote: { remoteApp: 'x', remoteButton: 'y' } };
assert.equal(conflicts([{ ...remote, id: 'r1' }, { ...remote, id: 'r2' }], null).filter((c) => c.reason === 'duplicate').length, 2);
assert.deepEqual(conflicts([{ ...base, id: 'w', action: 'whisper_list', target: '' }], null, new Set()), [{ id: 'w', reason: 'select_list' }]);
});
/** Fake `teamspeach-core hotkeys` child: records stdin lines, lets the test emit stdout lines. */
function fakeHelper() {
const child = new EventEmitter();
child.lines = [];
child.stdin = { write: (s) => { child.lines.push(JSON.parse(s)); }, end() {}, on() {} };
child.stdout = new EventEmitter(); child.stdout.setEncoding = () => {};
child.stderr = { resume() {} };
child.kill = () => {};
child.say = (msg) => child.stdout.emit('data', `${JSON.stringify(msg)}\n`);
return child;
}
test('exact match off registers extra-modifier variants on RegisterHotKey and reports them as the binding', () => {
const child = fakeHelper();
const events = [];
const helper = new HotkeyHelper({ enabled: true, resolveBinary: () => 'core', spawnProcess: () => child, onEvent: (e) => events.push(e), onStatus() {} });
const id = '44444444-4444-4444-8444-444444444444';
helper.bind([{ id, action: 'push_to_talk', code: 'F9', ctrl: false, alt: false, shift: false, meta: false, global: true }], { exact: false });
child.say({ event: 'ready', backend: 'windows_registerhotkey', global: true, release: true });
const bind = child.lines.at(-1);
assert.equal(bind.cmd, 'bind');
assert.equal(bind.bindings.length, 16, 'own chord plus 15 modifier supersets');
assert.equal(new Set(bind.bindings.map((b) => `${b.ctrl}${b.alt}${b.shift}${b.meta}`)).size, 16);
child.say({ event: 'bound', seq: bind.seq, results: bind.bindings.map((b) => ({ id: b.id, ok: true, trigger: '' })) });
assert.deepEqual(helper.status.results.map((r) => r.id), [id]);
assert.equal(helper.status.variants.registered, 15);
const variant = bind.bindings.find((b) => b.ctrl && !b.alt && !b.shift && !b.meta).id;
child.say({ event: 'press', id: variant });
child.say({ event: 'release', id: variant });
assert.deepEqual(events, [{ id, state: 'press', source: 'global' }, { id, state: 'release', source: 'global' }]);
child.say({ event: 'press', id });
helper.bind([], { exact: false });
assert.deepEqual(events.at(-1), { id, state: 'release', source: 'global', synthetic: true }, 'rebind releases held keys synthetically');
});
test('exact match on (and the portal backend) register only the bindings themselves', () => {
for (const [backend, exact] of [['windows_registerhotkey', true], ['xdg_portal_global_shortcuts', false]]) {
const child = fakeHelper();
const helper = new HotkeyHelper({ enabled: true, resolveBinary: () => 'core', spawnProcess: () => child, onEvent() {}, onStatus() {} });
helper.bind([{ id: '55555555-5555-4555-8555-555555555555', action: 'quick_whisper', code: 'F10', ctrl: true, global: true }], { exact });
child.say({ event: 'ready', backend, global: true, release: true });
assert.equal(child.lines.at(-1).bindings.length, 1, backend);
}
});
+80
View File
@@ -0,0 +1,80 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { previewTargets, findChannelByPath } from '../app/renderer/js/whisper-preview.js';
import { WhisperHistory, historyTime } from '../app/renderer/js/whisper-history.js';
const channel = (id, parent_id, name) => ({ id, parent_id, name });
const client = (id, uid, channel_id, extra = {}) => ({ id, uid, nickname: `n${id}`, channel_id, client_type: 'normal', server_groups: [], channel_group_id: 8, ...extra });
const snapshot = (clients, extra = {}) => ({
server: { uid: 'srv', name: 'Server' }, own_client_id: 1, own_channel_id: 11,
channels: [channel(10, 0, 'Lobby'), channel(11, 10, 'Talk'), channel(12, 11, 'Deep'), channel(20, 0, 'Other')],
clients, ...extra,
});
const list = (entries) => ({ type: 1, whisper_entry_list: entries });
test('preview resolves list entries by UID and this server\'s channel path, never the own client', () => {
const snap = snapshot([client(1, 'me', 11), client(2, 'alice', 20), client(3, 'bob', 12), client(4, 'q', 12, { client_type: 'query' })]);
const r = previewTargets(list([{ type: 1, uuid: 'alice', name: 'x' }, { type: 2, uuid: 'srv', name: 'Lobby/Talk/Deep' }, { type: 2, uuid: 'other-server', name: 'Other' }, { type: 1, uuid: 'me', name: '' }]), snap);
assert.deepEqual([...r.clients].sort(), [2, 3]);
assert.deepEqual([...r.channels], [12]);
assert.equal(findChannelByPath(snap.channels, 'Missing/Talk'), null);
assert.equal(findChannelByPath(snap.channels, 'Lobby/Gone/Talk'), 11);
});
test('a recycled client id with another UID is not previewed; a new snapshot never reuses old ids', () => {
const entries = list([{ type: 1, uuid: 'alice', name: 'alice' }]);
assert.deepEqual([...previewTargets(entries, snapshot([client(1, 'me', 11), client(5, 'alice', 10)])).clients], [5]);
const recycled = snapshot([client(1, 'me', 11), client(5, 'mallory', 10)]);
assert.equal(previewTargets(entries, recycled).clients.size, 0);
assert.equal(previewTargets(entries, null).clients.size, 0);
});
test('group preview needs this server for server/channel groups and only channels with matching clients', () => {
const snap = snapshot([client(1, 'me', 11, { server_groups: [7] }), client(2, 'a', 12, { server_groups: [7] }), client(3, 'b', 11), client(4, 'c', 20, { server_groups: [7] })]);
const group = { type: 2, group_type: 0, group_target_mode: 4, target_server_uuid: 'srv', target_group_id: '7' };
const r = previewTargets(group, snap);
assert.deepEqual([...r.channels].sort(), [11, 12]); // own family; channel 11 matches via the own client
assert.deepEqual([...r.clients], [2]);
assert.equal(previewTargets({ ...group, target_server_uuid: 'elsewhere' }, snap).channels.size, 0);
assert.deepEqual([...previewTargets({ ...group, group_type: 3, group_target_mode: 6 }, snap).channels], [12]);
});
test('a whisper received before its speaker is in a snapshot resolves on the next snapshot of the same session only', () => {
let now = 1000;
const h = new WhisperHistory({ now: () => now });
const conn = { session: 1, closed: false, snap: snapshot([client(1, 'me', 11)]) };
assert.equal(h.received(conn, 9), null);
conn.snap = snapshot([client(1, 'me', 11), client(9, 'late', 10)]);
now = 5000;
const [entry] = h.snapshot(conn);
assert.equal(entry.uid, 'late'); assert.equal(entry.timestamp, 1000);
assert.equal(h.received(conn, 7), null);
conn.session = 2;
conn.snap = snapshot([client(1, 'me', 11), client(7, 'someone-else', 10)]);
assert.deepEqual(h.snapshot(conn), []);
assert.deepEqual(h.entries(conn).map((e) => e.uid), ['late']);
});
test('reply/presence ignore other sessions and recycled ids; same UID or id replaces the older entry; clear empties', () => {
const h = new WhisperHistory({ now: () => 1 });
const conn = { session: 1, closed: false, snap: snapshot([client(1, 'me', 11), client(2, 'a', 10), client(3, 'b', 10)]) };
h.received(conn, 2); h.received(conn, 3); h.received(conn, 2);
assert.deepEqual(h.entries(conn).map((e) => e.id), [2, 3]);
assert.deepEqual(h.lastWhisperer(conn), { id: 2, uid: 'a' });
conn.snap = snapshot([client(1, 'me', 11), client(2, 'mallory', 10), client(3, 'b', 10)]);
assert.equal(h.present(conn, h.entries(conn)[0]), null);
assert.deepEqual(h.lastWhisperer(conn), { id: 3, uid: 'b' });
conn.session = 2;
assert.equal(h.lastWhisperer(conn), null);
assert.equal(h.has(conn), true);
h.clear(conn);
assert.equal(h.has(conn), false); assert.deepEqual(h.entries(conn), []);
});
test('history time follows the official calendar buckets', () => {
const now = new Date(2026, 10, 10, 12, 0).getTime();
const clock = (d) => `${d.getHours()}:${String(d.getMinutes()).padStart(2, '0')}`;
assert.equal(historyTime(new Date(2026, 10, 10, 9, 5).getTime(), { now, locale: 'en', clock }), '9:05');
assert.match(historyTime(new Date(2026, 10, 9, 9, 5).getTime(), { now, locale: 'en', clock }), /^9:05 - \S+/);
assert.doesNotMatch(historyTime(new Date(2026, 9, 1).getTime(), { now, locale: 'en', clock }), /:/);
});