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

193 lines
13 KiB
JavaScript

'use strict';
const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const crypto = require('node:crypto');
const { SnapshotOperation, validate, validVars, crc32 } = require('./server-snapshot-codec');
const MAX_DOCUMENT_BYTES = 32 * 1024 * 1024;
const MAX_ICON_BYTES = 128 * 1024;
const fail = error => ({ ok: false, error: { code: error.code || 'snapshot_error', message: String(error.message || error) } });
function coded(code, message) { return Object.assign(new Error(message), { code }); }
function iconBytes(icon) {
const encoded = icon.data.startsWith('data:') ? icon.data.slice(icon.data.indexOf(',') + 1) : icon.data;
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded)) throw new Error('Invalid icon base64');
const bytes = Buffer.from(encoded, 'base64');
if (!bytes.length || bytes.length > MAX_ICON_BYTES) throw new Error('Icon exceeds 128 KiB');
mimeType(bytes); // Never turn arbitrary imported bytes into server files.
return bytes;
}
function mimeType(bytes) {
if (bytes.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10]))) return 'image/png';
if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return 'image/jpeg';
if (/^GIF8[79]a$/.test(bytes.subarray(0, 6).toString('ascii'))) return 'image/gif';
if (bytes.subarray(0, 4).toString() === 'RIFF' && bytes.subarray(8, 12).toString() === 'WEBP') return 'image/webp';
// SVG stays opaque file bytes in main; it is never parsed or inserted into renderer DOM.
if (/^(?:\uFEFF)?\s*(?:<\?xml[^>]*>\s*)?(?:<!--[\s\S]*?-->\s*)*<svg[\s>]/i.test(bytes.toString('utf8'))) return 'image/svg+xml';
throw new Error('Unsupported server icon image format');
}
function registerServerSnapshotsIpc({ ipcMain, trustedSender, dialog, getWindow, request, validConnectionId, getConnection, subscribeCore, testOffscreen, tr }) {
const jobs = new Map();
const imports = new Map();
const invoke = async (id, command, args = {}) => {
const response = await request(id, command, args);
if (!response?.ok) throw coded(response?.error?.code || 'server_error', response?.error?.message || `${command} failed`);
return response.result;
};
const pin = id => {
if (!validConnectionId(id)) throw new Error('Invalid server connection');
const entry = getConnection(id); if (!entry) throw coded('connection_closed', 'Server connection is closed');
const session = entry.session, core = entry.core;
return () => { if (getConnection(id) !== entry || entry.session !== session || entry.core !== core) throw coded('connection_changed', 'Server connection changed; reopen snapshots'); };
};
const pick = async (method, options) => {
if (testOffscreen) throw coded('unavailable', 'Snapshot file dialogs are disabled in offscreen tests');
const window = getWindow(); return window ? dialog[method](window, options) : dialog[method](options);
};
const nativeTitle = key => tr ? tr(key) : key;
const handle = (channel, callback) => ipcMain.handle(channel, async (event, ...args) => {
if (!trustedSender(event)) return fail(coded('forbidden', 'Forbidden'));
try { return await callback(event, ...args); } catch (error) { return fail(error); }
});
const iconsFor = (id, job, check) => {
const transfer = async (command, args) => {
check();
let transferId, finished = false;
const early = new Map();
let resolve, reject;
const completion = new Promise((a, b) => { resolve = a; reject = b; });
// Install before starting: short transfers can finish before the queued reply arrives.
const accept = event => {
if (finished || !['done', 'failed', 'cancelled'].includes(event.state)) return;
finished = true;
if (event.state === 'done') resolve(event);
else reject(coded(event.state, event.error?.message || event.error || `Icon transfer ${event.state}`));
};
const unsubscribe = subscribeCore((connectionId, event) => {
if (connectionId !== id || event.event !== 'file_transfer') return;
try { job.alive(); } catch (error) { if (!finished) { finished = true; reject(error); } return; }
if (transferId === undefined) early.set(event.transfer_id, event);
else if (event.transfer_id === transferId) accept(event);
});
// Attach immediately so a terminal event racing the request cannot become unhandled.
completion.catch(() => {});
try {
const result = await invoke(id, command, args); transferId = result.transfer_id;
job.alive();
if (!Number.isSafeInteger(transferId) && typeof transferId !== 'string') throw new Error('Missing icon transfer ID');
job.transferId = transferId;
if (early.has(transferId)) accept(early.get(transferId));
if (job.cancelled) { job.alive(); await invoke(id, 'file_cancel', { transfer_id: transferId }); }
const timer = setInterval(() => { try { check(); } catch (error) { if (error.code !== 'cancelled' && !finished) { finished = true; reject(error); } } }, 250);
try { await completion; } finally { clearInterval(timer); }
check();
} finally {
unsubscribe(); job.transferId = null;
}
};
const temporary = async fn => {
const folder = await fs.mkdtemp(path.join(os.tmpdir(), 'teamspeach-snapshot-'));
try { return await fn(folder); } finally { await fs.rm(folder, { recursive: true, force: true }); }
};
return {
collect: async operation => {
const listing = await invoke(id, 'file_list', { channel_id: 0, path: '/icons/' });
if (!Array.isArray(listing.entries)) throw new Error('Invalid icon list response');
const icons = [];
for (const file of listing.entries) {
if (file.type !== 'file' || !/^icon_\d{1,10}$/.test(file.name)) continue;
const icon = await operation.step('icon', file.name, () => temporary(async folder => {
if (Number(file.size) > MAX_ICON_BYTES) throw new Error('Icon exceeds 128 KiB');
await transfer('file_download', { channel_id: 0, path: '/icons/' + file.name, dest_dir: folder, subdirs: [], overwrite: false });
const bytes = await fs.readFile(path.join(folder, file.name)); if (bytes.length > MAX_ICON_BYTES) throw new Error('Icon exceeds 128 KiB');
return { id: file.name.slice(5), data: bytes.toString('base64'), mimeType: mimeType(bytes) };
}));
if (icon) icons.push(icon);
}
return icons;
},
upload: async icon => temporary(async folder => {
const bytes = iconBytes(icon), iconId = crc32(bytes), name = 'icon_' + iconId;
// Identical content-addressed icons need no write. Never overwrite a different file.
const listing = await invoke(id, 'file_list', { channel_id: 0, path: '/icons/' });
if (!Array.isArray(listing.entries)) throw new Error('Invalid icon list response');
if (listing.entries?.some(file => file.name === name)) {
await transfer('file_download', { channel_id: 0, path: '/icons/' + name, dest_dir: folder, subdirs: [], overwrite: false });
const existing = await fs.readFile(path.join(folder, name));
if (!existing.equals(bytes)) throw new Error('Icon CRC32 collision; existing icon was not overwritten');
return iconId;
}
const source = path.join(folder, name); await fs.writeFile(source, bytes, { flag: 'wx', mode: 0o600 });
await transfer('file_upload', { channel_id: 0, path: '/icons/' + name, source, overwrite: false });
const uploaded = await invoke(id, 'file_list', { channel_id: 0, path: '/icons/' });
if (!uploaded.entries?.some(file => file.name === name)) throw new Error('Icon upload completed but its target ID was not listed; references were not changed');
return iconId;
}),
};
};
async function run(event, id, mode, prepare, action) {
if (jobs.has(id)) throw coded('busy', 'A snapshot operation is already running on this connection');
const alive = pin(id), job = { cancelled: false, transferId: null, alive };
jobs.set(id, job);
let operation;
const check = () => { alive(); if (!trustedSender(event)) throw coded('forbidden', 'Snapshot window changed'); if (job.cancelled) throw coded('cancelled', 'Snapshot cancelled; completed changes are retained'); };
try {
const context = await invoke(id, 'admin_context'); check();
const prepared = await prepare(context, check); check();
if (prepared === null) return { ok: true, cancelled: true, success: false };
const progress = value => { if (!event.sender.isDestroyed()) event.sender.send('snapshots:progress', { connectionId: id, mode, ...value }); };
const call = async (command, args) => { check(); const result = await invoke(id, command, args); alive(); return result; };
operation = new SnapshotOperation({ call, context, check, progress, icons: iconsFor(id, job, check) });
const result = await action(operation, prepared, check);
check();
return { ok: true, success: operation.errors.length === 0, partial: operation.errors.length > 0, errors: operation.errors, created: operation.created, ...result };
} catch (error) {
if (!operation) throw error;
operation.errors.push({ type: mode, identifier: 'operation', code: error.code, message: error.message });
return { ok: true, success: false, partial: true, cancelled: error.code === 'cancelled', errors: operation.errors, created: operation.created };
} finally { jobs.delete(id); }
}
handle('snapshots:export', (event, id, options) => run(event, id, 'export', async (_context, check) => {
const picked = await pick('showSaveDialog', { title: nativeTitle('snapshots.export'), defaultPath: 'server-snapshot.json', filters: [{ name: 'JSON', extensions: ['json'] }] }); check();
return picked.canceled || !picked.filePath ? null : picked.filePath;
}, async (operation, file, check) => {
const document = await operation.create(options); check();
const contents = JSON.stringify(document, null, 2); if (Buffer.byteLength(contents) > MAX_DOCUMENT_BYTES) throw new Error('Snapshot exceeds 32 MiB');
await fs.writeFile(file, contents, { mode: 0o600 });
return { saved: true, name: path.basename(file) };
}));
handle('snapshots:open', async (event, id) => {
const alive = pin(id);
const check = () => { alive(); if (!trustedSender(event)) throw coded('forbidden', 'Snapshot window changed'); };
const context = await invoke(id, 'admin_context'); check();
const result = await pick('showOpenDialog', { title: nativeTitle('snapshots.open'), filters: [{ name: 'JSON', extensions: ['json'] }], properties: ['openFile', 'dontAddToRecent'] }); check();
if (result.canceled || !result.filePaths?.length) return { ok: true, cancelled: true };
const file = await fs.open(result.filePaths[0], 'r'); let text;
try { const stat = await file.stat(); if (!stat.isFile() || stat.size > MAX_DOCUMENT_BYTES) throw new Error('Snapshot must be a regular file no larger than 32 MiB'); text = await file.readFile('utf8'); } finally { await file.close(); }
if (text.trimStart().startsWith('version=')) throw new Error('Server-side snapshot files are not supported; choose a client JSON snapshot');
const document = validate(JSON.parse(text)); check();
for (const [token, entry] of imports) if (entry.expires < Date.now() || entry.id === id) imports.delete(token);
if (imports.size >= 16) imports.delete(imports.keys().next().value);
const token = crypto.randomUUID(); imports.set(token, { id, document, check, generation: context.generation, serverUid: context.server_uid, expires: Date.now() + 30 * 60 * 1000 });
return { ok: true, token, name: path.basename(result.filePaths[0]), meta: document.meta, vars: document.vars || {}, confirmation: context.server_uid, catalog: document.catalog.map(item => ({ id: item.id, description: item.description || '', sections: ['server', 'channels', 'serverGroups', 'channelGroups', 'icons'].filter(key => item[key] !== undefined) })) };
});
handle('snapshots:apply', (event, id, options) => run(event, id, 'apply', async (context, check) => {
const entry = imports.get(options?.token);
if (!entry || entry.id !== id || entry.expires < Date.now()) throw new Error('Open the snapshot file again');
entry.check(); check();
if (entry.generation !== context.generation || entry.serverUid !== context.server_uid || options.confirmation !== context.server_uid) throw new Error('Confirm the current server identity before applying');
if (!['skip', 'rename_new', 'rename_existing'].includes(options.conflictMode) || !validVars(options.vars)) throw new Error('Invalid apply options');
const catalog = entry.document.catalog.find(c => c.id === options.catalogId); if (!catalog) throw new Error('Choose a catalog entry');
return { catalog, vars: { ...entry.document.vars, ...options.vars }, conflictMode: options.conflictMode };
}, async (operation, value) => { await operation.apply(value.catalog, value.vars, value.conflictMode); return {}; }));
handle('snapshots:cancel', async (_event, id) => {
const job = jobs.get(id); if (!job) return { ok: true, cancelling: false };
job.cancelled = true;
if (job.transferId !== null) { job.alive(); await invoke(id, 'file_cancel', { transfer_id: job.transferId }); }
return { ok: true, cancelling: true };
});
return { dispose() { for (const job of jobs.values()) job.cancelled = true; imports.clear(); } };
}
module.exports = { registerServerSnapshotsIpc };