'use strict'; 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 themes = require('../app/main/themes'); const { manifest, writeExtension, png, woff2Stub } = require('./fixtures/themes-fixture.cjs'); const ID = 'invalid.example.theme'; const OTHER = 'org.fixture.other'; const ORIGIN = 'app://teamspeach'; function tempRoot() { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'teamspeach-themes-')); return { root: path.join(dir, 'extensions'), cleanup: () => fs.rmSync(dir, { recursive: true, force: true }) }; } function memoryPrefs(initial = null) { let values = { userStyle: initial }; const writes = []; return { writes, get: () => ({ ...values }), set(partial) { if (!themes.USER_STYLE_PREF.check(partial.userStyle)) throw new Error('invalid'); values = { ...values, ...partial }; writes.push(partial.userStyle); return { ...values }; }, }; } function service(root, prefs, extra = {}) { return themes.createThemeService({ root, appOrigin: ORIGIN, prefs, openPath: async () => '', openExternal: async () => {}, allowShell: false, ...extra }); } const get = (svc, url, method = 'GET') => svc.handle(new Request(url, { method })); // ---------- schema ---------- test('the official Extensions.md example validates; schema violations are rejected with a path', () => { const example = { name: 'Example Theme', description: 'This is an example theme, making everything purple', version: '1.0.0', identifier: 'invalid.example.theme', engines: { teamspeak: 1 }, repository: { url: 'https://github.com/bestDudeEver/themes/', directory: 'purple', type: 'git' }, image: 'preview.png', license: 'MIT', author: { name: 'Joe Doe', email: 'joe@example.net', url: 'https://example.net', userTag: 'TeamSpeak@myteamspeak.com' }, content: { themes: [{ name: 'Purple Theme', source: 'purple.css', image: 'purple-preview.png', apiVersion: 1 }] }, }; assert.doesNotThrow(() => themes.validatePackage(example)); assert.doesNotThrow(() => themes.validatePackage({ ...example, author: 'Joe Doe', repository: 'https://github.com/x/y' })); const bad = [ [{ ...example, $schema: 'x' }, /unknown property "\$schema"/], [{ ...example, engines: { teamspeak: 1, other: 2 } }, /engines/], [{ ...example, engines: { teamspeak: 0 } }, /engines.teamspeak/], [{ ...example, engines: { teamspeak: 1.5 } }, /integer/], [{ ...example, identifier: 'Invalid.Example.Theme' }, /identifier/], [{ ...example, identifier: 'ab.cd.ef' }, /identifier/], [{ ...example, name: 'abcd' }, /name/], [{ ...example, description: 'too short' }, /description/], [{ ...example, version: '1.0' }, /version/], [{ ...example, license: 'XY' }, /license/], [{ ...example, homepage: 'http://example.org' }, /homepage/], [{ ...example, repository: { url: 'https://example.org/r', type: 'hg' } }, /repository.type/], [{ ...example, repository: 'https://e.o' }, /repository/], [{ ...example, author: { name: 'Jo' } }, /author.name/], [{ ...example, author: { name: 'Joe', email: 'not an email' } }, /author.email/], [{ ...example, keywords: ['dark', 'dark'] }, /unique/], [{ ...example, keywords: ['ab'] }, /keywords\[0\]/], [{ ...example, community: { server: 'bad host!' } }, /community.server/], [{ ...example, content: {} }, /content/], [{ ...example, content: { themes: [] } }, /content.themes/], [{ ...example, content: { themes: [{ name: 'Purple Theme', source: 'sub/purple.css', image: 'p.png', apiVersion: 1 }] } }, /source/], [{ ...example, content: { themes: [{ name: 'Purple Theme', source: 'purple.css', image: 'p.jpg', apiVersion: 1 }] } }, /image/], [{ ...example, content: { themes: [{ name: 'Purple Theme', source: 'purple.css', image: 'pp.png', apiVersion: 1, extra: 1 }] } }, /unknown property/], [{ ...example, content: { themes: [{ name: 'Pur', source: 'purple.css', image: 'pp.png', apiVersion: 1 }] } }, /name/], ]; const missing = { ...example }; delete missing.license; bad.push([missing, /missing "license"/]); for (const [pkg, message] of bad) assert.throws(() => themes.validatePackage(pkg), message, JSON.stringify(pkg).slice(0, 120)); // Lengths are code points, as in JSON Schema: 5 astral characters are a valid name. assert.doesNotThrow(() => themes.validatePackage({ ...example, name: '\u{1F3A8}'.repeat(5) })); }); test('selection format "//" and the official legacy object form', () => { assert.deepEqual(themes.parseSelection(`${ID}//Purple Theme`), { identifier: ID, name: 'Purple Theme' }); assert.equal(themes.parseSelection(`${ID}//a//bc`)?.name, 'a//bc'); for (const bad of ['', 'nope', `${ID}//abc`, `Bad.Id.Here//Purple`, `//Purple`, `${ID}//${'x'.repeat(31)}`, `${ID}//Pur\nple`, 42, {}]) { assert.equal(themes.parseSelection(bad), null, String(bad)); } assert.equal(themes.normalizeSelection({ extensionIdentifier: ID, name: 'Purple Theme' }), `${ID}//Purple Theme`); assert.equal(themes.normalizeSelection(null), null); assert.equal(themes.normalizeSelection('junk'), undefined); assert.equal(themes.USER_STYLE_PREF.default, null); assert.equal(themes.USER_STYLE_PREF.check(null), true); assert.equal(themes.USER_STYLE_PREF.check(`${ID}//Purple Theme`), true); assert.equal(themes.USER_STYLE_PREF.check({ extensionIdentifier: ID, name: 'Purple Theme' }), false); }); // ---------- CSS policy ---------- test('CSS: local fonts/images, data: and fragments pass; @import and non-local references are rejected even when escaped', () => { const ok = [ ':root { --tsv-bg: #102030; }', '@font-face { font-family: X; src: url(fonts/x.woff2) format("woff2"), local("Arial"); }', 'body { background: url("img/bg.png") no-repeat, url(\'a b.png\'); }', 'div { background-image: image-set("bg.png" 1x, "bg@2x.png" 2x); mask: url(#m); }', 'a { background: url(data:image/png;base64,AAAA); content: "https://example.org is text"; }', 'a::after { content: "/* not a comment"; } b { color: red }', ]; for (const css of ok) assert.doesNotThrow(() => themes.checkCss(css), css); const bad = [ '@import "other.css";', '@IMPORT url(other.css);', '@\\69mport "x.css";', '@\\000069 mport "x.css";'.replace(' mport', 'mport'), 'a { background: url(https://example.org/x.png); }', 'a { background: url("http://example.org/x.png"); }', 'a { background: u\\72l(https://example.org/x.png); }', 'a { background: url(//example.org/x.png); }', 'a { background: url(/etc/x.png); }', 'a { background: url(../outside.png); }', 'a { background: url(img/%2e%2e/%2e%2e/x.png); }', 'a { background: url(file:///C:/x.png); }', 'a { background: url(tsext://org.fixture.other/preview.png); }', 'a { background: image-set("https://example.org/x.png" 1x); }', 'a { background: -webkit-image-set(url("https://example.org/x.png") 1x); }', 'a { color: red } /* unterminated', ]; for (const css of bad) assert.throws(() => themes.checkCss(css), (err) => err.code === 'css', css); }); // ---------- scanning / confinement ---------- test('scan: valid extension listed; mismatched folder, bad JSON, oversize, traversal, missing file and links are skipped with reasons', async () => { const { root, cleanup } = tempRoot(); try { writeExtension(root, ID, { themes: [{ name: 'Purple Theme', source: 'purple.css', css: ':root{--tsv-bg:#800080}' }] }); writeExtension(root, 'org.fixture.mismatch', { folder: 'org.fixture.mismatched', themes: [{ name: 'Some Theme', source: 'a.css', css: '' }] }); writeExtension(root, 'org.fixture.badjson', { pkg: '{ "name": ', themes: [] }); writeExtension(root, 'org.fixture.huge', { pkg: JSON.stringify({ pad: 'x'.repeat(themes.LIMITS.packageBytes) }), themes: [] }); writeExtension(root, 'org.fixture.escape', { themes: [{ name: 'Some Theme', source: 'a.css', css: '' }], extra: { image: '../org.fixture.badjson/preview.png' } }); writeExtension(root, 'org.fixture.nosource', { themes: [{ name: 'Some Theme', source: 'missing.css' }] }); writeExtension(root, 'org.fixture.notcss', { themes: [{ name: 'Some Theme', source: 'theme.txt', css: '' }] }); writeExtension(root, 'org.fixture.dupname', { themes: [{ name: 'Same Name', source: 'a.css', css: '' }, { name: 'Same Name', source: 'b.css', css: '' }] }); fs.mkdirSync(path.join(root, '.hidden')); fs.writeFileSync(path.join(root, 'stray-file.txt'), 'ignored'); // A directory link (junction on Windows, symlink elsewhere) pointing at a valid extension. const linkTarget = writeExtension(path.join(root, '..', 'outside'), 'org.fixture.linked', { themes: [{ name: 'Some Theme', source: 'a.css', css: '' }] }); fs.symlinkSync(linkTarget, path.join(root, 'org.fixture.linked'), process.platform === 'win32' ? 'junction' : 'dir'); // A file link inside an otherwise valid extension. const fileLink = writeExtension(root, 'org.fixture.filelink', { themes: [{ name: 'Some Theme', source: 'a.css', css: '' }] }); fs.rmSync(path.join(fileLink, 'preview.png')); let fileLinkMade = true; try { fs.symlinkSync(path.join(linkTarget, 'preview.png'), path.join(fileLink, 'preview.png'), 'file'); } catch { fileLinkMade = false; // Windows without Developer Mode cannot create file symlinks fs.writeFileSync(path.join(fileLink, 'preview.png'), png()); } const { entries, invalid } = await themes.scanExtensions(root); assert.deepEqual([...entries.keys()].sort(), fileLinkMade ? [ID] : ['org.fixture.filelink', ID].sort()); const reasons = Object.fromEntries(invalid.map((v) => [v.folder, v.reason])); assert.equal(reasons['org.fixture.mismatched'], 'folder'); assert.equal(reasons['org.fixture.badjson'], 'json'); assert.equal(reasons['org.fixture.huge'], 'size'); assert.equal(reasons['org.fixture.escape'], 'file'); assert.equal(reasons['org.fixture.nosource'], 'file'); assert.equal(reasons['org.fixture.notcss'], 'file'); assert.equal(reasons['org.fixture.dupname'], 'schema'); assert.equal(reasons['org.fixture.linked'], 'link'); if (fileLinkMade) assert.equal(reasons['org.fixture.filelink'], 'link'); assert.ok(!('.hidden' in reasons) && !('stray-file.txt' in reasons)); } finally { cleanup(); } }); test('scan: the number of extension folders read is bounded', async () => { const { root, cleanup } = tempRoot(); try { for (let i = 0; i < themes.LIMITS.extensions + 2; i++) fs.mkdirSync(path.join(root, `org.fixture.n${String.fromCharCode(97 + Math.floor(i / 26))}${String.fromCharCode(97 + (i % 26))}x`), { recursive: true }); const { invalid } = await themes.scanExtensions(root); assert.equal(invalid.filter((v) => v.reason === 'package').length, themes.LIMITS.extensions); assert.deepEqual(invalid.at(-1), { folder: '', reason: 'limit', detail: null, max: themes.LIMITS.extensions }); } finally { cleanup(); } }); // ---------- service: selection, fallback, cache, protocol ---------- test('service: select persists, unknown selection falls back to stock, 5-minute cache unless forced', async () => { const { root, cleanup } = tempRoot(); try { writeExtension(root, ID, { themes: [{ name: 'Purple Theme', source: 'purple.css', css: ':root{--tsv-bg:#800080}' }, { name: 'Green Theme', source: 'green.css', css: ':root{--tsv-bg:#008000}' }] }); let clock = 1_000_000; const prefs = memoryPrefs(`${OTHER}//Gone Theme`); const svc = service(root, prefs, { now: () => clock }); let r = await svc.list(false); assert.equal(r.ok, true); assert.equal(r.selection, null, 'missing selection resets to stock'); assert.deepEqual(r.missing, { selection: `${OTHER}//Gone Theme`, name: 'Gone Theme' }); assert.equal(r.active, null); assert.equal(r.extensions.length, 1); const ext = r.extensions[0]; assert.match(ext.image, /^tsext:\/\/invalid\.example\.theme\/preview\.png\?v=/); assert.deepEqual(ext.themes.map((t) => t.name), ['Purple Theme', 'Green Theme']); assert.equal((await svc.list(false)).missing, null, 'reported once'); assert.equal((await svc.select('junk')).error.code, 'bad_request'); assert.equal((await svc.select(`${ID}//Blue Theme`)).error.code, 'not_found'); r = await svc.select(`${ID}//Green Theme`); assert.equal(r.ok, true); assert.equal(r.active.name, 'Green Theme'); assert.match(r.active.source, /^tsext:\/\/invalid\.example\.theme\/green\.css\?v=/); assert.equal(prefs.get().userStyle, `${ID}//Green Theme`); r = await svc.select({ extensionIdentifier: ID, name: 'Purple Theme' }); assert.equal(prefs.get().userStyle, `${ID}//Purple Theme`); // A newly installed extension is invisible inside the cache window, visible on forced refresh or after 5 min. writeExtension(root, OTHER, { themes: [{ name: 'Other Theme', source: 'o.css', css: '' }] }); assert.equal((await svc.list(false)).extensions.length, 1); assert.equal((await svc.list(true)).extensions.length, 2); fs.rmSync(path.join(root, OTHER), { recursive: true }); clock += themes.CACHE_MS - 1; assert.equal((await svc.list(false)).extensions.length, 2); clock += 2; assert.equal((await svc.list(false)).extensions.length, 1); // Selecting a theme installed after the last scan rescans once instead of failing. writeExtension(root, OTHER, { themes: [{ name: 'Other Theme', source: 'o.css', css: '' }] }); assert.equal((await svc.select(`${OTHER}//Other Theme`)).ok, true); // Removing the selected extension: the next list resets to stock (official behaviour). fs.rmSync(path.join(root, OTHER), { recursive: true }); r = await svc.list(true); assert.equal(r.selection, null); assert.equal(r.missing.name, 'Other Theme'); assert.equal((await svc.select(null)).selection, null); } finally { cleanup(); } }); test('protocol: only the selected variant CSS, its fonts/images, and other extensions\' previews are served', async () => { const { root, cleanup } = tempRoot(); try { writeExtension(root, ID, { themes: [ { name: 'Purple Theme', source: 'purple.css', css: '@font-face{font-family:F;src:url(fonts/f.woff2)} body{background:url(img/bg.png)}' }, { name: 'Import Theme', source: 'import.css', css: '@import "purple.css";' }, { name: 'Remote Theme', source: 'remote.css', css: 'body{background:url(https://example.org/x.png)}' }, ], files: { 'fonts/f.woff2': woff2Stub(), 'img/bg.png': png(), 'img/fake.png': 'not a png', 'secret.txt': 'x' }, }); writeExtension(root, OTHER, { themes: [{ name: 'Other Theme', source: 'o.css', css: '' }], files: { 'img/bg.png': png() } }); const prefs = memoryPrefs(null); const svc = service(root, prefs); const base = `tsext://${ID}`; let res = await get(svc, `${base}/purple.css`); assert.equal(res.status, 403, 'no CSS while the stock theme is selected'); assert.equal((await get(svc, `${base}/preview.png`)).status, 200, 'previews are always visible to the picker'); assert.equal((await get(svc, `${base}/variant.svg`)).status, 200); assert.equal((await get(svc, `${base}/img/bg.png`)).status, 403, 'non-preview images only for the active extension'); await svc.select(`${ID}//Purple Theme`); res = await get(svc, `${base}/purple.css?v=abc`); assert.equal(res.status, 200); assert.equal(res.headers.get('content-type'), 'text/css; charset=utf-8'); assert.equal(res.headers.get('x-content-type-options'), 'nosniff'); assert.equal(res.headers.get('access-control-allow-origin'), ORIGIN); assert.equal(res.headers.get('cache-control'), 'no-store'); assert.match(res.headers.get('content-security-policy'), /default-src 'none'/); assert.match(await res.text(), /font-face/); assert.equal((await get(svc, `${base}/fonts/f.woff2`)).headers.get('content-type'), 'font/woff2'); assert.equal((await get(svc, `${base}/img/bg.png`)).status, 200); assert.equal((await get(svc, `${base}/img/fake.png`)).status, 403, 'content must match its type'); assert.equal((await get(svc, `${base}/secret.txt`)).status, 403, 'unknown types are never served'); assert.equal((await get(svc, `${base}/green.css`)).status, 403, 'other CSS files are not served'); assert.equal((await get(svc, `${base}/import.css`)).status, 403, 'not the selected variant'); assert.equal((await get(svc, `${base}/img/missing.png`)).status, 404); assert.equal((await get(svc, `${base}/purple.css`, 'POST')).status, 405); assert.equal((await get(svc, `tsext://${OTHER}/img/bg.png`)).status, 403, 'another extension\'s files stay closed'); assert.equal((await get(svc, `tsext://${OTHER}/preview.png`)).status, 200); assert.equal((await get(svc, 'tsext://org.fixture.unknown/preview.png')).status, 404); for (const p of ['%2e%2e/%2e%2e/outside.png', '..%2fpreview.png', 'img%5c..%5c..%5cpreview.png', 'img/%00.png', 'C:%5cWindows%5cwin.ini', 'img//bg.png']) { const status = (await get(svc, `${base}/${p}`)).status; assert.ok(status === 403 || status === 404, `${p} → ${status}`); } await svc.select(`${ID}//Import Theme`); assert.equal((await get(svc, `${base}/import.css`)).status, 403, '@import rejected at load time'); await svc.select(`${ID}//Remote Theme`); assert.equal((await get(svc, `${base}/remote.css`)).status, 403, 'remote url() rejected at load time'); // A file that grows past the limit after the scan is still refused at read time. await svc.select(`${ID}//Purple Theme`); fs.writeFileSync(path.join(root, ID, 'purple.css'), `/*${'x'.repeat(themes.LIMITS.cssBytes)}*/`); assert.equal((await get(svc, `${base}/purple.css`)).status, 413, 'bounded read'); // The same oversize file at scan time marks the extension invalid with reason "size". assert.equal((await themes.scanExtensions(root)).invalid.find((v) => v.folder === ID)?.reason, 'size'); } finally { cleanup(); } }); test('shell actions: disabled in offscreen test sessions; otherwise only package links and known folders', async () => { const { root, cleanup } = tempRoot(); try { writeExtension(root, ID, { themes: [{ name: 'Purple Theme', source: 'purple.css', css: '' }], extra: { homepage: 'https://example.org/home' } }); const blocked = service(root, memoryPrefs()); assert.equal((await blocked.openDirectory(null)).error.code, 'unavailable'); assert.equal((await blocked.openLink({ identifier: ID, kind: 'homepage' })).error.code, 'unavailable'); const opened = []; const svc = service(root, memoryPrefs(), { allowShell: true, openPath: async (p) => { opened.push(['path', p]); return ''; }, openExternal: async (u) => { opened.push(['url', u]); } }); assert.equal((await svc.openLink({ identifier: ID, kind: 'homepage' })).url, 'https://example.org/home'); assert.equal((await svc.openLink({ identifier: ID, kind: 'repository' })).url, 'https://example.org/fixture/'); assert.equal((await svc.openLink({ identifier: ID, kind: 'email' })).url, 'mailto:fixture@example.org'); assert.equal((await svc.openLink({ identifier: ID, kind: 'docs' })).error.code, 'not_found'); assert.equal((await svc.openLink({ identifier: ID, kind: 'javascript' })).error.code, 'bad_request'); assert.equal((await svc.openLink({ identifier: '../x', kind: 'homepage' })).error.code, 'bad_request'); assert.equal((await svc.openDirectory('org.fixture.absent')).error.code, 'not_found'); assert.equal((await svc.openDirectory(ID)).ok, true); assert.equal((await svc.openDirectory(null)).ok, true); assert.deepEqual(opened.map(([k]) => k), ['url', 'url', 'url', 'path', 'path']); assert.equal(fs.realpathSync(opened[3][1]), fs.realpathSync(path.join(root, ID))); assert.equal(opened[4][1], root); } finally { cleanup(); } }); test('IPC: untrusted senders are refused; handlers are registered under themes:*', async () => { const { root, cleanup } = tempRoot(); try { const handlers = {}; service(root, memoryPrefs()).registerIpc({ handle: (ch, fn) => { handlers[ch] = fn; } }, (event) => event.trusted === true); assert.deepEqual(Object.keys(handlers).sort(), ['themes:list', 'themes:open-dir', 'themes:open-link', 'themes:select']); assert.equal((await handlers['themes:list']({ trusted: false }, true)).error.code, 'forbidden'); assert.equal((await handlers['themes:list']({ trusted: true }, true)).ok, true); } finally { cleanup(); } }); test('manifest helper output is schema-valid (fixtures stay in sync with extensions.json)', () => { assert.doesNotThrow(() => themes.validatePackage(manifest(ID, [{ name: 'Purple Theme', source: 'purple.css' }]))); }); test('root links and cached extension-root replacements are refused', async () => { const { root, cleanup } = tempRoot(); try { writeExtension(root, ID, { themes: [{ name: 'Purple Theme', source: 'purple.css', css: ':root{color:purple}' }] }); const svc = service(root, memoryPrefs()); await svc.select(`${ID}//Purple Theme`); const extension = path.join(root, ID); const moved = path.join(path.dirname(root), 'moved-extension'); fs.renameSync(extension, moved); fs.symlinkSync(moved, extension, process.platform === 'win32' ? 'junction' : 'dir'); assert.equal((await get(svc, `tsext://${ID}/purple.css`)).status, 403); // unlink removes the link itself, never recursively visits its populated target. fs.unlinkSync(extension); assert.ok(fs.existsSync(path.join(moved, 'purple.css')), 'junction target remains intact'); fs.renameSync(moved, extension); const movedRoot = path.join(path.dirname(root), 'moved-root'); fs.renameSync(root, movedRoot); fs.symlinkSync(movedRoot, root, process.platform === 'win32' ? 'junction' : 'dir'); await assert.rejects(themes.scanExtensions(root), /link/); assert.equal((await get(svc, `tsext://${ID}/purple.css`)).status, 403); } finally { cleanup(); } }); test('active SVG assets cannot carry script, external references or entity declarations', async () => { const { root, cleanup } = tempRoot(); try { writeExtension(root, ID, { themes: [{ name: 'Purple Theme', source: 'purple.css', css: '' }] }); const svc = service(root, memoryPrefs()); await svc.select(`${ID}//Purple Theme`); for (const svg of [ '', '', '', ']>&x;', ]) { fs.writeFileSync(path.join(root, ID, 'active.svg'), svg); assert.equal((await get(svc, `tsext://${ID}/active.svg`)).status, 403); } } finally { cleanup(); } });