Files
client/app/main/badges.js
T

459 lines
20 KiB
JavaScript

'use strict';
/**
* Public myTeamSpeak badge catalog for displaying other clients' badges (official tree `ts-badges`, client info
* Badge Showcase). Account-free: this only reads TeamSpeak's public catalog; it never redeems, owns, signs or
* sets badges.
*
* Evidence (installed TS6 6.0.0, read-only):
* - TeamSpeak.dll embeds the catalog URL `https://badges-content.teamspeak.com/list` and the protobuf schema
* `global_badge_list.proto` (package com.teamspeak.myteamspeak.proto.cloud):
* message BadgeList { int32 version = 1; int64 updated = 2; repeated Badge badges = 3; }
* message Badge { string uuid = 1; string name = 2; string url = 3; string description = 4;
* int64 created = 5; int32 version = 6; }
* - The native client caches artwork per badge as `<cache>/badges/96/<uuid>` (small SVG, client_ui `url`) and
* `<uuid>_details` (detailed SVG, client_ui `detailed_url`); on Windows the cache is
* %LOCALAPPDATA%/TeamSpeak/Cache/Default/badges/96. Those files are read here read-only when present.
* - Network artwork for a badge missing from both caches is derived from the catalog entry's own `url` as
* `<url>.svg` / `<url>_details.svg` (TeamSpeak.dll string "_details.svg"). Observed live 2026-11-01: GET /list →
* 200 application/octet-stream, 17245 bytes, a plain BadgeList body (no extra header; version 99, 91 badges);
* badge 0005232e-538e-4cb2-93b6-d7d83e873829 has url `https://badges-content.teamspeak.com/<uuid>/PietSmiet`,
* and `<url>.svg` / `<url>_details.svg` → 200 image/svg+xml, 6880 / 7278 bytes, the same sizes as the TS6 cache
* files. The suffix rule is verified for that sample, not for every catalog entry. Only URLs on the fixed
* catalog origin are ever requested.
*
* Network policy (same as phishing-list.js): anonymous GET, no cookies/credentials/referrer, redirect:'error',
* bounded time and bytes, single-flight, no request until the renderer first needs badge data, failed refreshes
* keep the previous list, the last good list and fetched artwork are cached in the profile with a size bound.
*/
const fs = require('node:fs');
const path = require('node:path');
const BADGE_LIST_URL = 'https://badges-content.teamspeak.com/list';
const BADGE_ORIGIN = 'https://badges-content.teamspeak.com';
const REFRESH_MS = 24 * 60 * 60 * 1000;
const RETRY_MS = 10 * 60 * 1000;
const REQUEST_TIMEOUT_MS = 20000;
const MAX_LIST_BYTES = 4 * 1024 * 1024;
const MAX_BADGES = 10000;
const MAX_ART_BYTES = 512 * 1024;
const MAX_CACHED_ART = 400;
const MAX_REQUEST_UUIDS = 64;
const CACHE_VERSION = 1;
const MAX_NAME = 256;
const MAX_DESCRIPTION = 2048;
const MAX_URL = 1024;
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const CONTROL = /[\u0000-\u0008\u000b-\u001f\u007f]/;
const SVG_START = /^\s*(?:<\?xml[^>]*\?>\s*)?(?:<!--[\s\S]*?-->\s*)*(?:<!DOCTYPE[^>]*>\s*)?(?:<!--[\s\S]*?-->\s*)*<svg[\s>]/i;
class BadgeError extends Error {
constructor(code, message) { super(message); this.code = code; }
}
const validUuid = (v) => typeof v === 'string' && UUID.test(v);
// ---------- protobuf (proto3 wire format, only what BadgeList needs) ----------
function readVarint(buf, state) {
let result = 0;
let scale = 1;
for (let i = 0; i < 10; i += 1) {
if (state.pos >= buf.length) throw new BadgeError('format', 'badge list: truncated varint');
const byte = buf[state.pos++];
result += (byte & 0x7f) * scale;
if ((byte & 0x80) === 0) return result;
scale *= 128;
}
throw new BadgeError('format', 'badge list: varint too long');
}
/** Calls onField(fieldNo, wireType, value) for each field of buf; value is a Number (varint) or a subarray. */
function readFields(buf, onField) {
const state = { pos: 0 };
while (state.pos < buf.length) {
const key = readVarint(buf, state);
const field = Math.floor(key / 8);
const wire = key % 8;
if (field < 1) throw new BadgeError('format', 'badge list: invalid field number');
switch (wire) {
case 0: onField(field, wire, readVarint(buf, state)); break;
case 1:
if (state.pos + 8 > buf.length) throw new BadgeError('format', 'badge list: truncated fixed64');
state.pos += 8;
break;
case 2: {
const length = readVarint(buf, state);
if (length > buf.length - state.pos) throw new BadgeError('format', 'badge list: truncated field');
onField(field, wire, buf.subarray(state.pos, state.pos + length));
state.pos += length;
break;
}
case 5:
if (state.pos + 4 > buf.length) throw new BadgeError('format', 'badge list: truncated fixed32');
state.pos += 4;
break;
default: throw new BadgeError('format', `badge list: unsupported wire type ${wire}`);
}
}
}
const utf8 = new TextDecoder('utf-8', { fatal: true });
function text(bytes) {
try { return utf8.decode(bytes); } catch { throw new BadgeError('format', 'badge list: invalid UTF-8'); }
}
/** Only https URLs on the fixed catalog origin, without credentials, query or fragment. */
function catalogUrl(value) {
if (typeof value !== 'string' || value.length === 0 || value.length > MAX_URL) return null;
let url;
try { url = new URL(value); } catch { return null; }
if (url.origin !== BADGE_ORIGIN || url.username || url.password || url.search || url.hash || url.pathname.length < 2) return null;
return url.href;
}
function cleanBadge(raw) {
const uuid = typeof raw.uuid === 'string' ? raw.uuid.toLowerCase() : '';
if (!validUuid(uuid)) return null;
const name = raw.name ?? '';
const description = raw.description ?? '';
if (name.length > MAX_NAME || CONTROL.test(name) || description.length > MAX_DESCRIPTION || CONTROL.test(description)) return null;
return { uuid, name, description, url: catalogUrl(raw.url) };
}
/**
* Bytes → { version, updated, badges }. Structural errors reject the whole body; individual badges with an invalid
* UUID or text are dropped, duplicates keep the first entry. A body without any valid badge is rejected.
*/
function parseBadgeList(bytes) {
const buf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes);
if (buf.length === 0 || buf.length > MAX_LIST_BYTES) throw new BadgeError('format', 'badge list: empty or too large');
let version = 0;
let updated = 0;
const raws = [];
readFields(buf, (field, wire, value) => {
if (field === 1 && wire === 0) version = value;
else if (field === 2 && wire === 0) updated = value;
else if (field === 3 && wire === 2) {
if (raws.length >= MAX_BADGES) throw new BadgeError('format', 'badge list: too many badges');
const badge = {};
readFields(value, (f, w, v) => {
if (w !== 2) return;
if (f === 1) badge.uuid = text(v);
else if (f === 2) badge.name = text(v);
else if (f === 3) badge.url = text(v);
else if (f === 4) badge.description = text(v);
});
raws.push(badge);
}
});
const seen = new Set();
const badges = [];
for (const raw of raws) {
const badge = cleanBadge(raw);
if (!badge || seen.has(badge.uuid)) continue;
seen.add(badge.uuid);
badges.push(badge);
}
if (badges.length === 0) throw new BadgeError('format', 'badge list: no valid badges');
return { version, updated, badges };
}
/** Network artwork URL for a catalog entry; null unless it stays on the fixed origin. */
function artworkUrl(badge, detailed) {
if (!badge?.url) return null;
const base = badge.url.endsWith('.svg') ? badge.url.slice(0, -4) : badge.url;
return catalogUrl(`${base}${detailed ? '_details' : ''}.svg`);
}
function validSvg(value) {
return typeof value === 'string' && value.length > 0 && Buffer.byteLength(value) <= MAX_ART_BYTES && SVG_START.test(value.replace(/^\uFEFF/, ''));
}
async function readBounded(res, max, signal) {
const declared = Number(res.headers?.get?.('content-length'));
if (Number.isFinite(declared) && declared > max) throw new BadgeError('too-large', 'badge response too large');
if (!res.body || typeof res.body.getReader !== 'function') {
const buf = Buffer.from(await res.arrayBuffer());
if (signal.aborted) throw signal.reason;
if (buf.length > max) throw new BadgeError('too-large', 'badge response too large');
return buf;
}
const reader = res.body.getReader();
const chunks = [];
let total = 0;
const onAbort = () => { reader.cancel(signal.reason).catch(() => {}); };
signal.addEventListener('abort', onAbort, { once: true });
try {
for (;;) {
if (signal.aborted) throw signal.reason;
const { done, value } = await reader.read();
if (signal.aborted) throw signal.reason;
if (done) break;
total += value.byteLength;
if (total > max) {
await reader.cancel().catch(() => {});
throw new BadgeError('too-large', 'badge response too large');
}
chunks.push(Buffer.from(value.buffer, value.byteOffset, value.byteLength));
}
} finally {
signal.removeEventListener('abort', onAbort);
}
return Buffer.concat(chunks, total);
}
/** The installed official client's artwork cache directory (observed on Windows only; read-only use). */
function officialBadgeCacheDirs(env = process.env, platform = process.platform) {
if (platform !== 'win32' || typeof env.LOCALAPPDATA !== 'string' || !path.win32.isAbsolute(env.LOCALAPPDATA)) return [];
return [path.win32.join(env.LOCALAPPDATA, 'TeamSpeak', 'Cache', 'Default', 'badges', '96')];
}
class BadgeCatalog {
/**
* @param {object} o
* @param {string} o.cacheDir profile directory for list.json and fetched artwork
* @param {(url: string, init: object) => Promise<Response>} o.fetchImpl Electron net.fetch in the app
* @param {string[]} [o.officialCacheDirs] read-only artwork directories of an installed TS6 client
* @param {boolean} [o.enabled] false: no network (offscreen tests); caches are still read
*/
constructor({ cacheDir, fetchImpl, officialCacheDirs = [], enabled = true, now = Date.now, log = () => {} }) {
Object.assign(this, { cacheDir, fetchImpl, officialCacheDirs, enabled, now, log });
this.badges = new Map();
this.fetchedAt = null;
this.checkedAt = null;
this.fromCache = false;
this.error = null;
this.cacheLoaded = false;
this.pending = null;
this.artPending = new Map();
this.artFailures = new Map();
this.controllers = new Set();
this.generation = 0;
}
status() {
return {
enabled: this.enabled, source: BADGE_LIST_URL, loaded: this.fetchedAt !== null, count: this.badges.size,
fetchedAt: this.fetchedAt, checkedAt: this.checkedAt, fromCache: this.fromCache, error: this.error,
};
}
get listFile() { return path.join(this.cacheDir, 'list.json'); }
get artDir() { return path.join(this.cacheDir, 'art'); }
loadCache() {
if (this.cacheLoaded) return;
this.cacheLoaded = true;
try {
const stat = fs.statSync(this.listFile);
if (!stat.isFile() || stat.size > MAX_LIST_BYTES * 2) return;
const data = JSON.parse(fs.readFileSync(this.listFile, 'utf8'));
if (data?.version !== CACHE_VERSION || data.source !== BADGE_LIST_URL || !Number.isFinite(data.fetchedAt)
|| !Array.isArray(data.badges) || data.badges.length > MAX_BADGES) return;
const badges = new Map();
for (const entry of data.badges) {
const badge = entry && typeof entry === 'object' ? cleanBadge(entry) : null;
if (badge && !badges.has(badge.uuid)) badges.set(badge.uuid, badge);
}
if (badges.size === 0 || (this.fetchedAt !== null && this.fetchedAt >= data.fetchedAt)) return;
this.badges = badges;
this.fetchedAt = data.fetchedAt;
this.fromCache = true;
} catch {
// no cache yet or unreadable
}
}
/** Loads the cache and starts a refresh when the list is missing or older than REFRESH_MS (RETRY_MS after a failure). */
ensureFresh() {
this.loadCache();
if (!this.enabled) return Promise.resolve(this.status());
const now = this.now();
const stale = this.fetchedAt === null || now - this.fetchedAt >= REFRESH_MS;
const recentlyTried = this.checkedAt !== null && now - this.checkedAt < (this.error ? RETRY_MS : REFRESH_MS);
if (stale && !recentlyTried) return this.refresh();
return this.pending ?? Promise.resolve(this.status());
}
refresh() {
if (!this.enabled) return Promise.resolve(this.status());
if (!this.pending) {
const pending = this.fetchList().finally(() => { if (this.pending === pending) this.pending = null; });
this.pending = pending;
}
return this.pending;
}
stop() {
this.generation += 1;
for (const controller of this.controllers) controller.abort(new BadgeError('stopped', 'badge catalog stopped'));
this.controllers.clear();
this.pending = null;
this.artPending.clear();
}
async request(url, accept) {
const generation = this.generation;
const controller = new AbortController();
this.controllers.add(controller);
const timer = setTimeout(() => controller.abort(new BadgeError('timeout', `badges: no answer in ${REQUEST_TIMEOUT_MS / 1000} s`)), REQUEST_TIMEOUT_MS);
timer.unref?.();
try {
const res = await this.fetchImpl(url, {
method: 'GET', signal: controller.signal, redirect: 'error', cache: 'no-store',
credentials: 'omit', referrerPolicy: 'no-referrer', headers: { Accept: accept },
});
if (generation !== this.generation) throw new BadgeError('stopped', 'badge catalog stopped');
if (res.redirected || (res.url && res.url !== url)) throw new BadgeError('redirect', 'badge response did not come from the fixed endpoint');
if (!res.ok) throw new BadgeError('http', `badges: HTTP ${res.status}`);
const body = await readBounded(res, accept === 'image/svg+xml' ? MAX_ART_BYTES : MAX_LIST_BYTES, controller.signal);
if (generation !== this.generation) throw new BadgeError('stopped', 'badge catalog stopped');
return body;
} catch (err) {
const reason = controller.signal.aborted ? controller.signal.reason : null;
throw reason instanceof BadgeError ? reason : err;
} finally {
clearTimeout(timer);
this.controllers.delete(controller);
}
}
async fetchList() {
const generation = this.generation;
this.checkedAt = this.now();
try {
const body = await this.request(BADGE_LIST_URL, 'application/octet-stream');
const { badges } = parseBadgeList(body);
if (generation !== this.generation) return this.status();
this.badges = new Map(badges.map((badge) => [badge.uuid, badge]));
this.fetchedAt = this.now();
this.fromCache = false;
this.error = null;
this.writeList();
this.log('info', `badge catalog: ${badges.length} badges`);
} catch (err) {
if (generation !== this.generation) return this.status();
this.error = { code: err instanceof BadgeError ? err.code : 'network', message: String(err?.message ?? err) };
this.log('warn', `badge catalog: ${this.error.message} (keeping ${this.badges.size} known badges)`);
}
return this.status();
}
writeList() {
try {
fs.mkdirSync(this.cacheDir, { recursive: true });
const tmp = `${this.listFile}.tmp`;
fs.writeFileSync(tmp, JSON.stringify({ version: CACHE_VERSION, source: BADGE_LIST_URL, fetchedAt: this.fetchedAt, badges: [...this.badges.values()] }));
fs.renameSync(tmp, this.listFile);
} catch (err) {
this.log('warn', `badge catalog cache not written: ${err.message}`);
}
}
/** Catalog entries for the requested UUIDs (unknown ones flagged), plus the source status. */
async info(uuids) {
await this.ensureFresh();
return {
status: this.status(),
badges: uuids.map((uuid) => {
const badge = this.badges.get(uuid);
return badge ? { uuid, known: true, name: badge.name, description: badge.description } : { uuid, known: false, name: '', description: '' };
}),
};
}
readArtFile(file) {
try {
const stat = fs.statSync(file);
if (!stat.isFile() || stat.size === 0 || stat.size > MAX_ART_BYTES) return null;
const svg = fs.readFileSync(file, 'utf8');
return validSvg(svg) ? svg : null;
} catch {
return null;
}
}
/** SVG text for a badge: profile cache, then the installed TS6 cache, then the fixed catalog origin. */
async artwork(uuid, detailed) {
if (!validUuid(uuid)) throw new BadgeError('bad_request', 'invalid badge id');
const name = `${uuid}${detailed ? '_details' : ''}`;
const own = this.readArtFile(path.join(this.artDir, `${name}.svg`));
if (own) return { svg: own, source: 'cache' };
for (const dir of this.officialCacheDirs) {
const svg = this.readArtFile(path.join(dir, name));
if (svg) return { svg, source: 'teamspeak-cache' };
}
if (!this.enabled) throw new BadgeError('unavailable', 'badge artwork is not cached and network access is disabled');
const failedAt = this.artFailures.get(name);
if (failedAt !== undefined && this.now() - failedAt < RETRY_MS) throw new BadgeError('unavailable', 'badge artwork recently failed');
let pending = this.artPending.get(name);
if (!pending) {
pending = this.fetchArt(uuid, detailed, name).finally(() => { if (this.artPending.get(name) === pending) this.artPending.delete(name); });
this.artPending.set(name, pending);
}
return pending;
}
async fetchArt(uuid, detailed, name) {
await this.ensureFresh();
const url = artworkUrl(this.badges.get(uuid), detailed);
if (!url) throw new BadgeError('unavailable', 'badge is not in the public catalog');
try {
const svg = (await this.request(url, 'image/svg+xml')).toString('utf8');
if (!validSvg(svg)) throw new BadgeError('format', 'badge artwork is not an SVG image');
this.artFailures.delete(name);
this.writeArt(name, svg);
return { svg, source: 'network' };
} catch (err) {
this.artFailures.set(name, this.now());
throw err instanceof BadgeError ? err : new BadgeError('network', String(err?.message ?? err));
}
}
/** Atomic write; the oldest files beyond MAX_CACHED_ART are evicted. */
writeArt(name, svg) {
try {
fs.mkdirSync(this.artDir, { recursive: true });
const entries = fs.readdirSync(this.artDir).filter((file) => file.endsWith('.svg'));
if (entries.length >= MAX_CACHED_ART) {
const aged = entries.map((file) => {
try { return { file, at: fs.statSync(path.join(this.artDir, file)).mtimeMs }; } catch { return { file, at: 0 }; }
}).sort((a, b) => a.at - b.at);
for (const { file } of aged.slice(0, entries.length - MAX_CACHED_ART + 1)) fs.rmSync(path.join(this.artDir, file), { force: true });
}
const file = path.join(this.artDir, `${name}.svg`);
fs.writeFileSync(`${file}.tmp`, svg);
fs.renameSync(`${file}.tmp`, file);
} catch (err) {
this.log('warn', `badge artwork not cached: ${err.message}`);
}
}
}
const FORBIDDEN = Object.freeze({ ok: false, error: { code: 'forbidden', message: 'forbidden' } });
const failure = (err) => ({ ok: false, error: { code: err instanceof BadgeError ? err.code : 'internal', message: String(err?.message ?? err) } });
/** badges:info(uuids[]) and badges:art(uuid, detailed): the renderer never supplies a URL or a path. */
function registerBadgesIpc({ ipcMain, trustedSender, catalog }) {
ipcMain.handle('badges:info', async (event, uuids) => {
if (!trustedSender(event)) return FORBIDDEN;
if (!Array.isArray(uuids) || uuids.length > MAX_REQUEST_UUIDS || !uuids.every(validUuid)) {
return { ok: false, error: { code: 'bad_request', message: 'Invalid badge ids' } };
}
try { return { ok: true, ...(await catalog.info([...new Set(uuids)])) }; } catch (err) { return failure(err); }
});
ipcMain.handle('badges:art', async (event, uuid, detailed) => {
if (!trustedSender(event)) return FORBIDDEN;
if (!validUuid(uuid) || typeof detailed !== 'boolean') return { ok: false, error: { code: 'bad_request', message: 'Invalid badge request' } };
try { return { ok: true, ...(await catalog.artwork(uuid, detailed)) }; } catch (err) { return failure(err); }
});
}
module.exports = {
BadgeCatalog, registerBadgesIpc, parseBadgeList, artworkUrl, validSvg, officialBadgeCacheDirs,
BADGE_LIST_URL, BADGE_ORIGIN, MAX_LIST_BYTES, MAX_BADGES, MAX_ART_BYTES, MAX_CACHED_ART, MAX_REQUEST_UUIDS, REFRESH_MS,
};