Files
client/app/main/information-panels.js
T

516 lines
22 KiB
JavaScript

'use strict';
// Settings > About data (installed client_ui/main.js: ChangelogEntry render@1810599, changelog view
// render@1814959, Open Source Licenses list render@1822582, license detail render@1821111).
//
// The official client reads a changelog feed and fetches tsui://default/licenses/licenses.json
// ({ name: { icon, repository, licenseText } }). TeamsPeach serves the same three views from files that are
// actually part of this installation, chosen here in main only; the renderer passes nothing but an opaque
// license id that must exist in the index built below:
// - CHANGELOG.md (repository root; packaged as resources/CHANGELOG.md),
// - the licenses folder (repository LICENSES/; packaged as resources/licenses/) with the TeamsPeach notice,
// bundled font/noise-reduction notices and the native core's generated THIRD_PARTY_NOTICES.md,
// - Electron's own LICENSE and Chromium's LICENSES.chromium.html next to the executable,
// - license files of the production npm dependency tree inside the application directory,
// - the chat renderer vendor notices (app/renderer/vendor/THIRD_PARTY_NOTICES.txt).
// Nothing is fetched from the network. A source that is missing in this installation is reported as missing.
const fs = require('node:fs');
const fsp = require('node:fs/promises');
const path = require('node:path');
const MAX_CHANGELOG_BYTES = 2 * 1024 * 1024;
const MAX_NOTICE_BYTES = 64 * 1024 * 1024;
const LICENSE_FILE = /^(licen[cs]e|copying|notice|unlicense)([-._].*)?$/i;
const GROUP_ORDER = ['teamspeach', 'electron', 'chromium', 'npm', 'core', 'renderer'];
// ---------- CHANGELOG.md ----------
const RELEASE_HEADING = /^##\s+(.+?)\s*$/;
const DATED = /^(.+?)\s+[—–-]\s+(\d{4}-\d{2}-\d{2})(?:\s+(.*))?$/;
/**
* Keep-a-changelog style CHANGELOG.md → official changelog entries (old format: notes + changes).
* `## <version> — <YYYY-MM-DD> [qualifier]` or `## Unreleased`; paragraphs become notes, `- ` items changes
* (indented continuation lines are joined with a space).
*/
function parseChangelog(markdown) {
const entries = [];
let entry = null;
let block = null; // { kind: 'note' | 'change', lines: [] }
const flush = () => {
if (!entry || !block) { block = null; return; }
const text = block.lines.join(' ').replace(/\s+/g, ' ').trim();
if (text) (block.kind === 'change' ? entry.changes : entry.notes).push(text);
block = null;
};
for (const raw of String(markdown).split(/\r?\n/)) {
const heading = RELEASE_HEADING.exec(raw);
if (heading && !raw.startsWith('###')) {
flush();
const title = heading[1];
const dated = DATED.exec(title);
entry = {
version: dated ? dated[1].trim() : title,
date: dated ? dated[2] : null,
qualifier: dated && dated[3] ? dated[3].trim() : null,
unreleased: !dated && /^unreleased$/i.test(title),
notes: [],
changes: [],
};
entries.push(entry);
continue;
}
if (!entry) continue;
if (/^#/.test(raw)) { flush(); continue; }
if (!raw.trim()) { flush(); continue; }
const item = /^[-*]\s+(.*)$/.exec(raw);
if (item) {
flush();
block = { kind: 'change', lines: [item[1]] };
} else if (block) {
block.lines.push(raw.trim());
} else {
block = { kind: 'note', lines: [raw.trim()] };
}
}
flush();
return entries;
}
// ---------- core THIRD_PARTY_NOTICES.md (core/tools/third_party_notices.py) ----------
const CRATES_IO_INDEX = 'registry+https://github.com/rust-lang/crates.io-index';
function crateRepository(name, version, source) {
if (source === CRATES_IO_INDEX) return `https://crates.io/crates/${encodeURIComponent(name)}/${encodeURIComponent(version)}`;
const git = /^git\+(https:\/\/[^?#\s]+)/.exec(source);
return git ? git[1].replace(/\.git$/, '') : null;
}
/** Fenced text blocks following a `### a 1.0 (FILE); b 2.0 (FILE)` header, keyed by "name version". */
function parseCoreNotices(markdown) {
const lines = String(markdown).split(/\r?\n/);
const crates = [];
let intro = '';
let i = 0;
for (; i < lines.length && !lines[i].startsWith('| '); i++) {
if (!lines[i].startsWith('#') && lines[i].trim()) intro += `${intro ? ' ' : ''}${lines[i].trim()}`;
}
for (; i < lines.length && lines[i].startsWith('|'); i++) {
const cells = lines[i].split('|').slice(1, -1).map((cell) => cell.trim());
if (cells.length !== 4 || cells[0] === 'Crate' || /^-+$/.test(cells[0])) continue;
const [name, version, license, source] = cells;
crates.push({ name, version, license, repository: crateRepository(name, version, source), texts: [] });
}
const byKey = new Map(crates.map((crate) => [`${crate.name} ${crate.version}`, crate]));
const extra = [];
let header = null;
let fence = null;
for (; i < lines.length; i++) {
const line = lines[i];
if (fence) {
if (line.startsWith('```')) {
const text = fence.join('\n');
if (header.kind === 'section') extra.push({ name: header.title, version: null, license: null, repository: null, texts: [{ label: null, text }] });
else {
for (const { key, label } of header.owners) byKey.get(key)?.texts.push({ label, text });
}
fence = null;
header = null;
} else fence.push(line);
continue;
}
if (line.startsWith('### ')) {
const owners = [];
// "a 1.0 (LICENSE-MIT); b 2.0 (LICENSE)"; a label may itself contain "; " (crates without a license file).
for (const m of line.slice(4).matchAll(/(?:^|; )([^\s;()]+) ([^\s;()]+) \(([^)]*)\)/g)) {
owners.push({ key: `${m[1]} ${m[2]}`, label: m[3] });
}
header = { kind: 'texts', owners };
} else if (line.startsWith('## ') && line.trim() !== '## License texts') {
// e.g. "## libopus (bundled in audiopus_sys, statically linked)"
header = { kind: 'section', title: line.slice(3).trim() };
} else if (line.startsWith('```') && header) {
fence = [];
}
}
return { intro, entries: [...extra, ...crates] };
}
// ---------- app/renderer/vendor/THIRD_PARTY_NOTICES.txt (scripts/vendor-chat-notices.mjs) ----------
const VENDOR_HEADER = /^===== (.+)@([^@\s]+) \((.*)\) =====$/;
function parseVendorNotices(text) {
const lines = String(text).split(/\r?\n/);
const preface = [];
const entries = [];
let current = null;
for (const line of lines) {
const header = VENDOR_HEADER.exec(line);
if (header) {
if (current) entries.push(current);
current = { name: header[1], version: header[2], license: header[3].replace(/^\((.*)\)$/, '$1'), lines: [] };
} else if (current) current.lines.push(line);
else if (line.trim()) preface.push(line.trim());
}
if (current) entries.push(current);
return {
// The first line is the file title; the rest states the inventory's scope.
intro: preface.slice(1).join(' '),
entries: entries.map(({ lines: body, ...entry }) => ({ ...entry, text: body.join('\n').trim() })),
};
}
// ---------- Electron LICENSES.chromium.html ----------
const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: '\u00a0' };
function decodeEntities(text) {
return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (all, code) => {
if (code[0] === '#') {
const n = code[1] === 'x' || code[1] === 'X' ? parseInt(code.slice(2), 16) : parseInt(code.slice(1), 10);
return Number.isInteger(n) && n >= 0 && n <= 0x10ffff ? String.fromCodePoint(n) : all;
}
return ENTITIES[code.toLowerCase()] ?? all;
});
}
const PRODUCT_TITLE = /^\s*<span class="title">([\s\S]*?)<\/span>/;
const PRODUCT_HOMEPAGE = /<span class="homepage"><a href="([^"]*)">/;
const PRODUCT_LICENSE = /<pre>([\s\S]*?)<\/pre>/;
/** Chromium credits page (tools/licenses/licenses.py): one product per <div class="product">. */
function parseChromiumCredits(html) {
const products = [];
for (const chunk of String(html).split('<div class="product">').slice(1)) {
const title = PRODUCT_TITLE.exec(chunk);
const license = PRODUCT_LICENSE.exec(chunk);
if (!title || !license) continue;
const homepage = PRODUCT_HOMEPAGE.exec(chunk);
const url = homepage ? decodeEntities(homepage[1]) : null;
products.push({
name: decodeEntities(title[1]).trim(),
repository: url && /^https?:\/\//i.test(url) ? url : null,
text: decodeEntities(license[1]),
});
}
return products;
}
// ---------- production npm dependencies ----------
/** package.json "repository" → https URL, or null when it is not a recognisable public URL. */
function npmRepository(repository) {
let url = typeof repository === 'string' ? repository : repository && typeof repository.url === 'string' ? repository.url : null;
if (!url) return null;
url = url.trim();
// npm shorthand: "user/repo" and "github:user/repo" denote GitHub.
const shorthand = /^(?:github:)?([\w.-]+)\/([\w.-]+)$/.exec(url);
if (shorthand) return `https://github.com/${shorthand[1]}/${shorthand[2].replace(/\.git$/, '')}`;
url = url.replace(/^git\+/, '')
.replace(/^git@([^:]+):/, 'https://$1/')
.replace(/^ssh:\/\/git@/, 'https://')
.replace(/^git:\/\//, 'https://')
.replace(/\.git$/, '');
return /^https:\/\/[^\s/]+\/\S+$/.test(url) ? url : null;
}
/** Node resolution of `name` required from `fromDir`, staying inside `rootDir`. */
function resolvePackage(fromDir, name, rootDir) {
let dir = fromDir;
for (;;) {
const candidate = path.join(dir, 'node_modules', name);
if (fs.existsSync(path.join(candidate, 'package.json'))) return candidate;
if (path.resolve(dir) === path.resolve(rootDir)) return null;
const parent = path.dirname(dir);
if (parent === dir) return null;
dir = parent;
}
}
/** Runtime `dependencies` (plus installed optional ones) reachable from the application's package.json. */
function collectProductionPackages(appDir) {
const found = new Map();
const missing = [];
const visit = (dir, manifest) => {
const names = new Set([...Object.keys(manifest.dependencies ?? {}), ...Object.keys(manifest.optionalDependencies ?? {})]);
for (const name of names) {
const location = resolvePackage(dir, name, appDir);
if (!location) {
if (!manifest.optionalDependencies?.[name]) missing.push(name);
continue;
}
if (found.has(location)) continue;
let pkg;
try { pkg = JSON.parse(fs.readFileSync(path.join(location, 'package.json'), 'utf8')); } catch { missing.push(name); continue; }
let files = [];
try { files = fs.readdirSync(location).filter((file) => LICENSE_FILE.test(file)).sort(); } catch { /* unreadable */ }
const license = typeof pkg.license === 'string' ? pkg.license
: Array.isArray(pkg.licenses) ? pkg.licenses.map((l) => l?.type ?? l).filter((l) => typeof l === 'string').join(' OR ') || null
: pkg.license?.type ?? null;
found.set(location, { name: pkg.name ?? name, version: pkg.version ?? null, license, repository: npmRepository(pkg.repository), location, files });
visit(location, pkg);
}
};
const root = JSON.parse(fs.readFileSync(path.join(appDir, 'package.json'), 'utf8'));
visit(appDir, root);
const packages = [...found.values()].sort((a, b) => a.name.localeCompare(b.name) || String(a.version).localeCompare(String(b.version)));
return { packages, missing: [...new Set(missing)].sort() };
}
// ---------- service ----------
const OS_DIR = { win32: 'win', darwin: 'mac', linux: 'linux' };
/** Fixed file locations for this installation; only main decides them. */
function informationPaths({ isPackaged, appRoot, appPath, resourcesPath, execPath, rendererDir, platform, arch }) {
const exeDir = path.dirname(execPath);
// Packaged: electron-builder renames Electron's LICENSE to LICENSE.electron.txt beside the executable
// (macOS: inside Contents/Resources). Development: node_modules/electron/dist (macOS: beside Electron.app).
const electronLicenses = isPackaged
? [path.join(exeDir, 'LICENSE.electron.txt'), path.join(resourcesPath, 'LICENSE.electron.txt')]
: [path.join(exeDir, 'LICENSE'), ...(platform === 'darwin' ? [path.resolve(exeDir, '..', '..', '..', 'LICENSE')] : [])];
const chromiumCredits = [path.join(exeDir, 'LICENSES.chromium.html'),
...(platform === 'darwin' ? [isPackaged ? path.join(resourcesPath, 'LICENSES.chromium.html') : path.resolve(exeDir, '..', '..', '..', 'LICENSES.chromium.html')] : [])];
const electronFiles = { electronLicenses, chromiumCredits };
if (isPackaged) {
return {
changelog: [path.join(resourcesPath, 'CHANGELOG.md')],
licensesDir: path.join(resourcesPath, 'licenses'),
coreNotices: [path.join(resourcesPath, 'licenses', 'teamspeach-core-THIRD_PARTY_NOTICES.md')],
appDir: appPath,
vendorDir: path.join(rendererDir, 'vendor'),
...electronFiles,
};
}
return {
changelog: [path.join(appRoot, 'CHANGELOG.md')],
licensesDir: path.join(appRoot, 'LICENSES'),
coreNotices: [
path.join(appRoot, 'core-bin', `${OS_DIR[platform] ?? platform}-${arch}`, 'THIRD_PARTY_NOTICES.md'),
path.join(appRoot, 'core', 'THIRD_PARTY_NOTICES.md'),
],
appDir: appRoot,
vendorDir: path.join(rendererDir, 'vendor'),
...electronFiles,
};
}
// Known files of the licenses folder (LICENSES/NOTICE.md describes each); others are listed by file name.
const LICENSE_DIR_NAMES = {
'NOTICE.md': { name: 'TeamsPeach', order: 0 },
'NotoSans-OFL.txt': { name: 'Noto Sans', license: 'OFL-1.1', order: 1 },
'sonora-NOTICE.txt': { name: 'sonora', license: 'BSD-3-Clause', order: 2 },
'teamspeak-client-icons-PROVENANCE.md': { name: 'TeamSpeak 6 client icons', order: 3 },
};
const CORE_NOTICES_FILE = 'teamspeach-core-THIRD_PARTY_NOTICES.md';
async function readFirst(candidates, maxBytes) {
for (const file of candidates) {
try {
const stat = await fsp.stat(file);
if (!stat.isFile()) continue;
if (stat.size > maxBytes) throw Object.assign(new Error(`${path.basename(file)} is too large`), { code: 'too_large' });
return { file, text: await fsp.readFile(file, 'utf8') };
} catch (err) {
if (err.code === 'too_large') throw err;
}
}
return null;
}
function missingError(candidates) {
return { code: 'missing', file: path.basename(candidates[0]) };
}
function createInformationService(options) {
const paths = informationPaths(options);
const electronVersion = options.electronVersion ?? null;
let changelog = null;
let index = null;
async function getChangelog() {
if (!changelog) {
changelog = (async () => {
const found = await readFirst(paths.changelog, MAX_CHANGELOG_BYTES);
if (!found) return { ok: false, error: missingError(paths.changelog) };
return { ok: true, entries: parseChangelog(found.text) };
})().catch((err) => { changelog = null; return { ok: false, error: { code: err.code === 'too_large' ? 'too_large' : 'unreadable', file: 'CHANGELOG.md' } }; });
}
return changelog;
}
// Each group: { id, note, error, entries: [{ name, version, license, repository, load: () => Promise<string> }] }
async function teamspeachGroup() {
let files;
try { files = await fsp.readdir(paths.licensesDir); } catch { return { id: 'teamspeach', error: missingError([paths.licensesDir]), entries: [] }; }
const entries = files
.filter((file) => file !== CORE_NOTICES_FILE && /\.(md|txt)$/i.test(file))
.map((file) => ({ file, known: LICENSE_DIR_NAMES[file] }))
.sort((a, b) => (a.known?.order ?? 99) - (b.known?.order ?? 99) || a.file.localeCompare(b.file))
.map(({ file, known }) => ({
name: known?.name ?? file,
version: null,
license: known?.license ?? null,
repository: null,
load: () => fsp.readFile(path.join(paths.licensesDir, file), 'utf8'),
}));
return { id: 'teamspeach', entries };
}
async function electronGroups() {
const { electronLicenses: electronLicense, chromiumCredits } = paths;
const electron = await readFirst(electronLicense, MAX_NOTICE_BYTES);
const electronGroup = electron
? { id: 'electron', entries: [{ name: 'Electron', version: electronVersion, license: 'MIT', repository: null, load: async () => electron.text }] }
: { id: 'electron', error: missingError(['LICENSE.electron.txt']), entries: [] };
const chromium = await readFirst(chromiumCredits, MAX_NOTICE_BYTES);
if (!chromium) return [electronGroup, { id: 'chromium', error: missingError(chromiumCredits), entries: [] }];
const products = parseChromiumCredits(chromium.text);
const chromiumGroup = {
id: 'chromium',
entries: products.map(({ name, repository, text }) => ({ name, version: null, license: null, repository, load: async () => text })),
};
if (!products.length) chromiumGroup.error = { code: 'unparsed', file: 'LICENSES.chromium.html' };
return [electronGroup, chromiumGroup];
}
function npmGroup() {
let result;
try { result = collectProductionPackages(paths.appDir); } catch { return { id: 'npm', error: missingError([path.join(paths.appDir, 'package.json')]), entries: [] }; }
const group = {
id: 'npm',
entries: result.packages.map((pkg) => ({
name: pkg.name,
version: pkg.version,
license: pkg.license,
repository: pkg.repository,
noLicenseFile: pkg.files.length === 0,
load: async () => {
const parts = [];
for (const file of pkg.files) parts.push(`--- ${file} ---\n${(await fsp.readFile(path.join(pkg.location, file), 'utf8')).trim()}`);
return parts.join('\n\n');
},
})),
};
if (result.missing.length) group.error = { code: 'missing_packages', file: result.missing.join(', ') };
return group;
}
async function coreGroup() {
const found = await readFirst(paths.coreNotices, MAX_NOTICE_BYTES);
if (!found) return { id: 'core', error: missingError(paths.coreNotices), entries: [] };
const parsed = parseCoreNotices(found.text);
return {
id: 'core',
note: parsed.intro,
entries: parsed.entries.map((crate) => ({
name: crate.name,
version: crate.version,
license: crate.license,
repository: crate.repository,
noLicenseFile: crate.texts.length === 0,
load: async () => crate.texts.map(({ label, text }) => (label ? `--- ${label} ---\n${text}` : text)).join('\n\n'),
})),
};
}
async function rendererGroup() {
const file = path.join(paths.vendorDir, 'THIRD_PARTY_NOTICES.txt');
let text;
try { text = await fsp.readFile(file, 'utf8'); } catch { return { id: 'renderer', error: missingError([file]), entries: [] }; }
const parsed = parseVendorNotices(text);
let fromRegistry = new Set();
try {
const deps = JSON.parse(await fsp.readFile(path.join(paths.vendorDir, 'DEPENDENCIES.json'), 'utf8'));
fromRegistry = new Set((deps.packages ?? []).filter((p) => typeof p.resolved === 'string' && p.resolved.startsWith('https://registry.npmjs.org/')).map((p) => `${p.name}@${p.version}`));
} catch { /* inventory without registry provenance: no links */ }
return {
id: 'renderer',
note: parsed.intro,
entries: parsed.entries.map((entry) => ({
name: entry.name,
version: entry.version,
license: entry.license,
repository: fromRegistry.has(`${entry.name}@${entry.version}`) ? `https://www.npmjs.com/package/${entry.name}/v/${entry.version}` : null,
load: async () => entry.text,
})),
};
}
async function buildIndex() {
const settle = (promise, id) => Promise.resolve().then(promise).catch(() => ({ id, error: { code: 'unreadable', file: id }, entries: [] }));
const results = await Promise.all([
settle(teamspeachGroup, 'teamspeach'),
settle(electronGroups, 'electron'),
settle(npmGroup, 'npm'),
settle(coreGroup, 'core'),
settle(rendererGroup, 'renderer'),
]);
const groups = results.flat().sort((a, b) => GROUP_ORDER.indexOf(a.id) - GROUP_ORDER.indexOf(b.id));
const byId = new Map();
for (const group of groups) {
group.entries.forEach((entry, i) => {
entry.id = `${group.id}:${i}`;
byId.set(entry.id, entry);
});
}
return { groups, byId };
}
async function ensureIndex() {
if (!index) index = buildIndex().catch((err) => { index = null; throw err; });
return index;
}
async function getLicenses() {
try {
const { groups } = await ensureIndex();
return {
ok: true,
groups: groups.map((group) => ({
id: group.id,
note: group.note ?? null,
error: group.error ?? null,
entries: group.entries.map(({ id, name, version, license, repository, noLicenseFile }) => ({ id, name, version, license, repository, noLicenseFile: noLicenseFile === true })),
})),
};
} catch {
return { ok: false, error: { code: 'unreadable', file: null } };
}
}
async function getLicenseText(id) {
if (typeof id !== 'string' || id.length > 64 || !/^[a-z]+:\d+$/.test(id)) return { ok: false, error: { code: 'bad_request', file: null } };
let entry;
try { entry = (await ensureIndex()).byId.get(id); } catch { entry = null; }
if (!entry) return { ok: false, error: { code: 'not_found', file: null } };
try {
return { ok: true, id, name: entry.name, version: entry.version, license: entry.license, text: await entry.load() };
} catch {
return { ok: false, error: { code: 'unreadable', file: null } };
}
}
return { getChangelog, getLicenses, getLicenseText, paths };
}
function registerInformationIpc({ ipcMain, trustedSender, service }) {
const forbidden = { ok: false, error: { code: 'forbidden', file: null } };
ipcMain.handle('about:changelog', (event) => (trustedSender(event) ? service.getChangelog() : forbidden));
ipcMain.handle('about:licenses', (event) => (trustedSender(event) ? service.getLicenses() : forbidden));
ipcMain.handle('about:license-text', (event, id) => (trustedSender(event) ? service.getLicenseText(id) : forbidden));
}
module.exports = {
parseChangelog,
parseCoreNotices,
parseVendorNotices,
parseChromiumCredits,
collectProductionPackages,
npmRepository,
informationPaths,
createInformationService,
registerInformationIpc,
};