Files
client/test/server-snapshots-main.test.js
T

127 lines
8.7 KiB
JavaScript

'use strict';
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 { registerServerSnapshotsIpc } = require('../app/main/server-snapshots');
const document = entry => ({ type: 'teamspeak.server.snapshot', schemaVersion: '0.0.1', meta: { createdAt: '2026-11-01T00:00:00.000Z' }, catalog: [{ id: 'default', ...entry }] });
async function fixture(t, { entry = {}, request, offscreen = false } = {}) {
const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'teamspeach-snapshot-test-'));
t.after(() => fs.rm(directory, { recursive: true, force: true }));
const source = path.join(directory, 'source.json'), destination = path.join(directory, 'export.json');
await fs.writeFile(source, JSON.stringify(document(entry)));
const handlers = new Map(), listeners = new Set(), calls = [], events = [];
const connection = { session: 1, core: {} }; let generation = 1, trusted = true;
const context = () => ({ generation, server_uid: 'server-uid', permissions_catalog: [] });
const fakeDialog = { showOpenDialog: async () => ({ canceled: false, filePaths: [source] }), showSaveDialog: async () => ({ canceled: false, filePath: destination }) };
const api = registerServerSnapshotsIpc({
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([id, command, args]); if (command === 'admin_context') return { ok: true, result: context() }; return request ? request(command, args, { listeners, context }) : { ok: true, result: { rows: [] } }; },
});
t.after(() => api.dispose());
const sender = { isDestroyed: () => false, send: (name, data) => events.push([name, data]) };
return { source, destination, calls, events, connection, fakeDialog, listeners, setGeneration: value => { generation = value; }, untrust: () => { trusted = false; }, invoke: (name, ...args) => handlers.get('snapshots:' + name)({ sender }, 'one', ...args) };
}
test('open exposes only token/summary and apply rejects stale generation before mutation', async t => {
const f = await fixture(t, { entry: { server: { name: 'Imported' } } });
const opened = await f.invoke('open');
assert.equal(opened.ok, true); assert.ok(opened.token); assert.equal(opened.confirmation, 'server-uid');
assert.equal(opened.path, undefined); assert.equal(opened.document, undefined); assert.equal(opened.name, 'source.json');
f.setGeneration(2);
const result = await f.invoke('apply', { token: opened.token, catalogId: 'default', conflictMode: 'rename_new', vars: {}, confirmation: 'server-uid' });
assert.equal(result.ok, false); assert.ok(!f.calls.some(([, command]) => command === 'server_edit'));
});
test('native dialog continuation cannot export onto a replaced connection', async t => {
const f = await fixture(t);
f.fakeDialog.showSaveDialog = async () => { f.connection.session++; return { canceled: false, filePath: f.destination }; };
const result = await f.invoke('export', {});
assert.equal(result.ok, false); assert.equal(result.error.code, 'connection_changed');
await assert.rejects(fs.stat(f.destination), { code: 'ENOENT' });
});
test('export writes official JSON and reports individual permission failure as partial', async t => {
const f = await fixture(t, { request: async command => {
if (command === 'server_info') return { ok: true, result: { rows: [{ virtualserver_name: 'Test', virtualserver_version: '6.0', virtualserver_platform: 'Linux' }] } };
if (command === 'server_group_list') return { ok: true, result: { rows: [{ sgid: '5', type: '1', name: 'Admin' }] } };
if (command === 'server_group_perm_list') return { ok: false, error: { code: 'permission_denied', message: 'Denied' } };
throw new Error(command);
} });
const result = await f.invoke('export', { includeServerSettings: true, includeServerGroups: true });
assert.equal(result.ok, true); assert.equal(result.saved, true); assert.equal(result.success, false); assert.equal(result.partial, true);
assert.equal(result.errors[0].code, 'permission_denied');
const saved = JSON.parse(await fs.readFile(f.destination, 'utf8'));
assert.equal(saved.type, 'teamspeak.server.snapshot'); assert.equal(saved.schemaVersion, '0.0.1'); assert.equal(saved.meta.createdBy, 'Unknown');
assert.equal(saved.catalog[0].server.name, 'Test'); assert.deepEqual(saved.catalog[0].serverGroups, []);
});
test('cancellation after a native mutation retains acknowledged IDs and prevents the next mutation', async t => {
let unblock, started;
const waiting = new Promise(resolve => { started = resolve; });
const f = await fixture(t, { entry: { channels: [{ name: 'First' }, { name: 'Second' }] }, request: async command => {
if (command === 'channel_list') return { ok: true, result: { rows: [] } };
if (command === 'channel_create') { started(); await new Promise(resolve => { unblock = resolve; }); return { ok: true, result: { channel_id: 10 } }; }
throw new Error(command);
} });
const opened = await f.invoke('open');
const pending = f.invoke('apply', { token: opened.token, catalogId: 'default', conflictMode: 'rename_new', vars: {}, confirmation: 'server-uid' });
await waiting; assert.equal((await f.invoke('cancel')).cancelling, true); unblock();
const result = await pending;
assert.equal(result.cancelled, true); assert.equal(result.success, false); assert.deepEqual(result.created.channels, [10]);
assert.equal(f.calls.filter(([, command]) => command === 'channel_create').length, 1);
});
test('icon export correlates terminal events which precede queued transfer reply', async t => {
const png = Buffer.from([137,80,78,71,13,10,26,10]);
const f = await fixture(t, { request: async (command, args, { listeners }) => {
if (command === 'server_info') return { ok: true, result: { rows: [{}] } };
if (command === 'file_list') return { ok: true, result: { entries: [{ name: 'icon_5000', type: 'file', size: png.length }] } };
if (command === 'file_download') {
assert.equal(args.channel_id, 0); assert.equal(args.path, '/icons/icon_5000');
await fs.writeFile(path.join(args.dest_dir, 'icon_5000'), png);
for (const callback of listeners) callback('one', { event: 'file_transfer', transfer_id: 8, state: 'done' });
return { ok: true, result: { transfer_id: 8, state: 'queued' } };
}
throw new Error(command);
} });
const result = await f.invoke('export', { includeIcons: true });
assert.equal(result.success, true); assert.equal(f.listeners.size, 0);
const saved = JSON.parse(await fs.readFile(f.destination, 'utf8'));
assert.deepEqual(saved.catalog[0].icons, [{ id: '5000', data: png.toString('base64'), mimeType: 'image/png' }]);
});
test('untrusted sender and offscreen modes cannot open native dialogs', async t => {
const f = await fixture(t, { offscreen: true });
let invoked = false; f.fakeDialog.showOpenDialog = async () => { invoked = true; throw new Error('must not run'); };
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' });
});