Files
client/test/badges-main.test.js
T

195 lines
11 KiB
JavaScript
Raw Permalink 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';
// 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);
});