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

298 lines
16 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict';
// Server Icons manager (official client_ui module 33609 with icon provider 66727): the virtual server's
// icon files live in file-transfer channel 0. Listing is `/icons/`; classic storage addresses each file as
// `/icon_<id>` on the wire, which the core derives from the canonical `/icons/icon_<id>` bridge path.
// Channel 0 never reaches the renderer's generic file commands: everything here is main-owned, pinned to
// one connection session, and host paths come only from the native dialog opened by an explicit click.
// HTTPFT/S3 servers are refused by the core (`media_unsupported`); nothing pretends to reach that storage.
const crypto = require('node:crypto');
const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const { crc32 } = require('./server-snapshot-codec');
const ICON_FOLDER = '/icons/';
/** Same bound as snapshot icon transfers; also below the core's 256 KiB `fetch_icon` preview limit. */
const MAX_ICON_BYTES = 128 * 1024;
/** Local decode-safety bound for raster headers (not a TeamSpeak rule; the server stays authoritative). */
const MAX_ICON_SIDE = 1024;
const MAX_SELECTION = 32;
/** `file_delete` accepts at most this many paths per command (core/src/file_transfer.rs MAX_DELETE). */
const DELETE_BATCH = 100;
const MAX_DELETE_IDS = 10_000;
const TRANSFER_DEADLINE_MS = 120_000;
/** Official upload dialog filter: image/jpeg, image/png, image/svg+xml. */
const UPLOAD_EXTENSIONS = ['png', 'jpg', 'jpeg', 'svg'];
/** Listing grants (one per open panel listing) and how long a panel may act on one. */
const MAX_GRANTS = 32;
const GRANT_TTL_MS = 30 * 60 * 1000;
function coded(code, message, extra = {}) { return Object.assign(new Error(message), { code }, extra); }
const fail = error => ({ ok: false, error: { code: error.code || 'server_icons_error', message: String(error.message || error) } });
/** Icon id of a listing entry name `icon_<canonical nonzero u32>`, else null. */
function iconIdOf(name) {
const match = /^icon_([1-9]\d{0,9})$/.exec(typeof name === 'string' ? name : '');
if (!match) return null;
const id = Number(match[1]);
return id <= 0xffffffff ? id : null;
}
function validIconId(id) { return Number.isSafeInteger(id) && id >= 1 && id <= 0xffffffff; }
const iconPath = id => `${ICON_FOLDER}icon_${id}`;
/** PNG IHDR or JPEG SOFn dimensions; null when the header is malformed. */
function rasterSize(bytes, mime) {
if (mime === 'image/png') {
if (bytes.length < 24 || bytes.subarray(12, 16).toString('ascii') !== 'IHDR') return null;
return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
}
let i = 2;
while (i + 4 <= bytes.length) {
if (bytes[i] !== 0xff) return null;
const marker = bytes[i + 1];
if (marker === 0xff) { i += 1; continue; }
if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) { i += 2; continue; }
if (marker === 0xd9 || marker === 0xda) return null;
const length = bytes.readUInt16BE(i + 2);
if (length < 2) return null;
const sof = marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker);
if (sof) return i + 9 <= bytes.length ? { height: bytes.readUInt16BE(i + 5), width: bytes.readUInt16BE(i + 7) } : null;
i += 2 + length;
}
return null;
}
/**
* Type, size and decode checks for one chosen file. Raster headers are bounded before any decode; when
* Electron's nativeImage is supplied the bytes must also decode. SVG stays opaque bytes in main and is only
* ever shown by the renderer as an <img> blob (no script execution).
*/
function checkIconBytes(bytes, nativeImage) {
if (!bytes.length || bytes.length > MAX_ICON_BYTES) throw coded('too_large', 'Icon must be 1 byte to 128 KiB');
let mime = null;
if (bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) mime = 'image/png';
else if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) mime = 'image/jpeg';
else if (/^(?:\uFEFF)?\s*(?:<\?xml[^>]*>\s*)?(?:<!--[\s\S]*?-->\s*)*(?:<!DOCTYPE[^>]*>\s*)?<svg[\s>]/i.test(bytes.toString('utf8'))) mime = 'image/svg+xml';
if (!mime) throw coded('unsupported_type', 'Icons must be PNG, JPEG or SVG');
if (mime !== 'image/svg+xml') {
const size = rasterSize(bytes, mime);
if (!size || size.width < 1 || size.height < 1) throw coded('invalid_image', 'The image header is damaged');
if (size.width > MAX_ICON_SIDE || size.height > MAX_ICON_SIDE) throw coded('too_large', `Icons may be at most ${MAX_ICON_SIDE}×${MAX_ICON_SIDE} pixels`);
if (nativeImage && nativeImage.createFromBuffer(bytes).isEmpty()) throw coded('invalid_image', 'The image could not be decoded');
}
return mime;
}
/** Read a dialog-chosen regular file of bounded size; never follows a size that changed while reading. */
async function readChosenFile(file) {
const handle = await fs.open(file, 'r');
try {
const stat = await handle.stat();
if (!stat.isFile()) throw coded('not_a_file', 'Choose a regular image file');
if (stat.size < 1 || stat.size > MAX_ICON_BYTES) throw coded('too_large', 'Icon must be 1 byte to 128 KiB');
const bytes = Buffer.alloc(stat.size + 1);
let read = 0;
for (;;) {
const { bytesRead } = await handle.read(bytes, read, bytes.length - read, read);
if (bytesRead === 0) break;
read += bytesRead;
if (read > stat.size) throw coded('changed', 'The file changed while it was read');
}
if (read !== stat.size) throw coded('changed', 'The file changed while it was read');
return bytes.subarray(0, read);
} finally { await handle.close(); }
}
function registerServerIconsIpc({ ipcMain, trustedSender, dialog, getWindow, request, validConnectionId, getConnection, subscribeCore, testOffscreen, tr, nativeImage = null }) {
const busy = new Set();
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;
};
/** The exact connection entry, main session counter and core process the operation started on. */
const pin = id => {
if (!validConnectionId(id)) throw coded('bad_request', 'Invalid server connection');
const entry = getConnection(id); if (!entry) throw coded('connection_closed', 'Server connection is closed');
const pinned = { id, entry, session: entry.session, core: entry.core };
pinned.same = () => getConnection(id) === entry && entry.session === pinned.session && entry.core === pinned.core;
pinned.alive = () => { if (!pinned.same()) throw coded('connection_changed', 'Server connection changed; reopen Server Icons'); };
return pinned;
};
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); }
});
/** One icon operation per connection; `guard.check` fails once the connection or window changed. */
async function exclusive(event, id, work) {
const pinned = pin(id);
if (busy.has(id)) throw coded('busy', 'Another server icon operation is running');
busy.add(id);
const check = () => { pinned.alive(); if (!trustedSender(event)) throw coded('forbidden', 'Server Icons window changed'); };
try { return await work({ check, pinned }); } finally { busy.delete(id); }
}
// Opaque list grants: mutations are accepted only for the exact connection entry, session, core and admin
// generation that produced the listing the user saw. A UI from before a reconnect cannot mutate the new one.
const grants = new Map();
function grant(pinned, generation) {
const now = Date.now();
for (const [token, entry] of grants) if (entry.expires < now || !entry.pinned.same()) grants.delete(token);
while (grants.size >= MAX_GRANTS) grants.delete(grants.keys().next().value);
const token = crypto.randomUUID();
grants.set(token, { pinned, generation, expires: now + GRANT_TTL_MS });
return token;
}
/** Before the first mutation: the grant must belong to this pinned session and its generation still be current. */
async function authorize(id, token, { check, pinned }) {
const entry = typeof token === 'string' ? grants.get(token) : undefined;
const stale = () => coded('connection_changed', 'Server connection changed; reload Server Icons');
if (!entry || entry.expires < Date.now() || entry.pinned.id !== id || entry.pinned.entry !== pinned.entry
|| entry.pinned.session !== pinned.session || entry.pinned.core !== pinned.core || !entry.pinned.same()) throw stale();
const context = await invoke(id, 'admin_context'); check();
if (context?.generation !== entry.generation) { grants.delete(token); throw stale(); }
}
async function list(id, check) {
const listing = await invoke(id, 'file_list', { channel_id: 0, path: ICON_FOLDER }); check();
if (!Array.isArray(listing?.entries)) throw coded('server_error', 'Invalid icon list response');
const icons = [];
for (const entry of listing.entries) {
const iconId = entry?.type === 'file' ? iconIdOf(entry.name) : null;
if (iconId !== null) icons.push({ id: iconId, size: Number(entry.size) || 0, datetime: Number(entry.datetime) || 0 });
}
return icons;
}
/**
* Run one queued transfer to its terminal `file_transfer` event. A transfer abandoned while its session is
* unchanged (window changed, timeout) is cancelled; after a reconnect it is not: transfer ids restart per
* session, so the old id could name an unrelated transfer of the new session.
*/
async function transfer(id, command, args, { check, pinned }) {
check();
let transferId, finished = false, resolve, reject;
const early = new Map();
const completion = new Promise((a, b) => { resolve = a; reject = b; });
completion.catch(() => {});
const accept = event => {
if (finished || !['done', 'failed', 'cancelled'].includes(event.state)) return;
finished = true;
if (event.state === 'done') resolve(event);
else reject(coded(event.error?.code || event.state, event.error?.message || `Icon transfer ${event.state}`));
};
// Installed before the request: short transfers can finish before the queued reply arrives.
const unsubscribe = subscribeCore((connectionId, event) => {
if (connectionId !== id || event?.event !== 'file_transfer' || !pinned.same()) return;
if (transferId === undefined) early.set(event.transfer_id, event);
else if (event.transfer_id === transferId) accept(event);
});
let timer = null, deadline = null;
try {
transferId = (await invoke(id, command, args)).transfer_id;
if (!Number.isSafeInteger(transferId)) throw coded('server_error', 'Missing icon transfer ID');
if (early.has(transferId)) accept(early.get(transferId));
timer = setInterval(() => { try { check(); } catch (error) { if (!finished) { finished = true; reject(error); } } }, 250);
deadline = setTimeout(() => { if (!finished) { finished = true; reject(coded('timeout', 'Icon transfer did not finish')); } }, TRANSFER_DEADLINE_MS);
await completion;
check();
} catch (error) {
const terminal = ['done', 'failed', 'cancelled'].includes(error.code);
if (Number.isSafeInteger(transferId) && !terminal && pinned.same()) {
await request(id, 'file_cancel', { transfer_id: transferId }).catch(() => {});
}
throw error;
} finally {
clearInterval(timer); clearTimeout(deadline); unsubscribe();
}
}
const temporary = async fn => {
const folder = await fs.mkdtemp(path.join(os.tmpdir(), 'teamspeach-icons-'));
try { return await fn(folder); } finally { await fs.rm(folder, { recursive: true, force: true }); }
};
/** Content-addressed upload: never overwrites a different file that already holds this CRC32 name. */
async function uploadBytes(id, bytes, guard) {
const iconId = crc32(bytes);
if (!validIconId(iconId)) throw coded('invalid_image', 'This image has a reserved icon checksum');
const name = `icon_${iconId}`;
return temporary(async folder => {
if ((await list(id, guard.check)).some(icon => icon.id === iconId)) {
await transfer(id, 'file_download', { channel_id: 0, path: iconPath(iconId), dest_dir: folder, subdirs: [], overwrite: false }, guard);
const existing = await fs.readFile(path.join(folder, name));
if (!existing.equals(bytes)) throw coded('collision', 'A different icon already uses this checksum; it was not overwritten');
return { id: iconId, existing: true };
}
const source = path.join(folder, name);
await fs.writeFile(source, bytes, { flag: 'wx', mode: 0o600 });
await transfer(id, 'file_upload', { channel_id: 0, path: iconPath(iconId), source, overwrite: false }, guard);
if (!(await list(id, guard.check)).some(icon => icon.id === iconId)) throw coded('server_error', 'The upload finished but the server does not list the icon');
return { id: iconId, existing: false };
});
}
// A failed listing (e.g. HTTPFT/S3 storage) returns no grant, so nothing can be mutated from it.
handle('server-icons:list', (event, id) => exclusive(event, id, async ({ check, pinned }) => {
const context = await invoke(id, 'admin_context'); check();
if (!Number.isSafeInteger(context?.generation) || context.generation < 1) throw coded('connection_changed', 'Server connection is not ready');
const icons = await list(id, check);
return { ok: true, icons, generation: context.generation, authorization: grant(pinned, context.generation) };
}));
handle('server-icons:upload', (event, id, authorization) => exclusive(event, id, async guard => {
const { check } = guard;
if (testOffscreen) throw coded('unavailable', 'Icon file dialogs are disabled in offscreen tests');
await authorize(id, authorization, guard);
const window = getWindow();
const options = {
title: tr ? tr('server.icons.upload.title') : 'Select icon',
filters: [{ name: 'PNG, JPEG, SVG', extensions: UPLOAD_EXTENSIONS }],
properties: ['openFile', 'multiSelections', 'dontAddToRecent'],
};
const picked = await (window ? dialog.showOpenDialog(window, options) : dialog.showOpenDialog(options)); check();
if (picked.canceled || !picked.filePaths?.length) return { ok: true, cancelled: true };
// The dialog can stay open across a reconnect: verify the grant again before the first transfer.
await authorize(id, authorization, guard);
if (picked.filePaths.length > MAX_SELECTION) throw coded('bad_request', `Choose at most ${MAX_SELECTION} icons at once`);
const uploaded = [], errors = [];
for (const file of picked.filePaths) {
const name = path.basename(file);
try {
const bytes = await readChosenFile(file); check();
checkIconBytes(bytes, nativeImage);
uploaded.push({ ...(await uploadBytes(id, bytes, guard)), name });
} catch (error) {
if (['connection_changed', 'connection_closed', 'forbidden'].includes(error.code)) throw error;
errors.push({ name, code: error.code || 'server_icons_error', message: String(error.message || error) });
}
}
return { ok: true, uploaded, errors };
}));
handle('server-icons:delete', (event, id, authorization, ids) => exclusive(event, id, async guard => {
const { check } = guard;
if (!Array.isArray(ids) || ids.length < 1 || ids.length > MAX_DELETE_IDS || !ids.every(validIconId) || new Set(ids).size !== ids.length) {
throw coded('bad_request', 'Invalid icon selection');
}
await authorize(id, authorization, guard);
const deleted = [];
try {
for (let i = 0; i < ids.length; i += DELETE_BATCH) {
const batch = ids.slice(i, i + DELETE_BATCH);
await invoke(id, 'file_delete', { channel_id: 0, paths: batch.map(iconPath) }); check();
deleted.push(...batch);
}
} catch (error) {
return { ...fail(error), deleted };
}
return { ok: true, deleted };
}));
return { dispose() { busy.clear(); grants.clear(); } };
}
module.exports = { registerServerIconsIpc, checkIconBytes, rasterSize, iconIdOf, MAX_ICON_BYTES };