227 lines
10 KiB
JavaScript
227 lines
10 KiB
JavaScript
'use strict';
|
|
|
|
/**
|
|
* Threat classification for external links, from the same source as the installed TS6 client's
|
|
* ExternalLinkGuard (client_ui/main.js class Ee): PHISHING_LIST_URLS = [PHISHING_LIST_URL], fetched at start
|
|
* and every FETCH_INTERVAL_MS (1 h), one domain per line, matched exactly against the link's lowercase
|
|
* hostname ("warn-malicious").
|
|
*
|
|
* Network policy (stricter than the official fetch):
|
|
* - one fixed public HTTPS URL, anonymous GET: no cookies or credentials, no referrer, no query, no
|
|
* identifiers; the request never contains a visited link — classification is a local Set lookup;
|
|
* - redirect:'error': the fixed endpoint is fetched directly and any redirect fails the request before a second
|
|
* request is made; the whole request is bounded by REQUEST_TIMEOUT_MS and MAX_BYTES, and a body with any
|
|
* non-domain line (other than blank or '#' comment lines) or over MAX_DOMAINS is rejected as a whole, so an
|
|
* error page mixed with domains can never replace a known good list;
|
|
* - stop() aborts an in-flight request and discards its result: no list or cache update after stop;
|
|
* - a failed refresh keeps the previous list; the last good list is cached in the profile so a restart
|
|
* while offline still classifies links;
|
|
* - disabled (no request, no cache) when the owner passes enabled=false, e.g. offscreen tests.
|
|
*/
|
|
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
|
|
const PHISHING_LIST_URL = 'https://files.teamspeak-services.com/client/phishing-domains/active.txt';
|
|
const FETCH_INTERVAL_MS = 60 * 60 * 1000;
|
|
const REQUEST_TIMEOUT_MS = 20000;
|
|
const MAX_BYTES = 16 * 1024 * 1024;
|
|
const MAX_DOMAINS = 1000000;
|
|
const CACHE_VERSION = 1;
|
|
|
|
// Lowercase DNS name as WHATWG URL serialises it (punycode for IDN); '_' occurs in real hostnames.
|
|
const LABEL = '[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?';
|
|
const DOMAIN = new RegExp(`^(?=.{1,253}$)${LABEL}(?:\\.${LABEL})*$`);
|
|
|
|
const validDomain = (value) => typeof value === 'string' && DOMAIN.test(value);
|
|
|
|
class ListError extends Error {
|
|
constructor(code, message) { super(message); this.code = code; }
|
|
}
|
|
|
|
/** Text → Set of domains. Empty and '#' lines are skipped; any other non-domain line rejects the whole body. */
|
|
function parseList(text) {
|
|
const domains = new Set();
|
|
for (const line of text.split('\n')) {
|
|
const entry = line.trim().toLowerCase().replace(/\.$/, '');
|
|
if (!entry || entry.startsWith('#')) continue;
|
|
if (!validDomain(entry)) throw new ListError('bad-response', 'phishing list contains a line that is not a domain');
|
|
domains.add(entry);
|
|
if (domains.size > MAX_DOMAINS) throw new ListError('too-large', `phishing list has more than ${MAX_DOMAINS} domains`);
|
|
}
|
|
return { domains };
|
|
}
|
|
|
|
/** Reads at most `max` bytes; an abort (stop or timeout) cancels the body even if the stream ignores it. */
|
|
async function readBounded(res, max, signal) {
|
|
const declared = Number(res.headers?.get?.('content-length'));
|
|
if (Number.isFinite(declared) && declared > max) throw new ListError('too-large', 'phishing list response too large');
|
|
if (!res.body || typeof res.body.getReader !== 'function') {
|
|
const text = await res.text();
|
|
if (signal.aborted) throw signal.reason;
|
|
if (Buffer.byteLength(text) > max) throw new ListError('too-large', 'phishing list response too large');
|
|
return text;
|
|
}
|
|
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 ListError('too-large', 'phishing list response too large');
|
|
}
|
|
chunks.push(Buffer.from(value.buffer, value.byteOffset, value.byteLength));
|
|
}
|
|
} finally {
|
|
signal.removeEventListener('abort', onAbort);
|
|
}
|
|
return Buffer.concat(chunks, total).toString('utf8');
|
|
}
|
|
|
|
class PhishingList {
|
|
/**
|
|
* @param {object} o
|
|
* @param {string} o.cacheFile profile file for the last good list
|
|
* @param {(url: string, init: object) => Promise<Response>} o.fetchImpl Electron net.fetch in the app
|
|
* @param {boolean} [o.enabled]
|
|
*/
|
|
constructor({ cacheFile, fetchImpl, enabled = true, now = Date.now, setIntervalImpl = setInterval, clearIntervalImpl = clearInterval, log = () => {} }) {
|
|
Object.assign(this, { cacheFile, fetchImpl, enabled, now, setIntervalImpl, clearIntervalImpl, log });
|
|
this.domains = new Set();
|
|
this.fetchedAt = null; // ms of the list in use (network or cache)
|
|
this.checkedAt = null; // ms of the last network attempt
|
|
this.fromCache = false;
|
|
this.error = null;
|
|
this.timer = null;
|
|
this.pending = null;
|
|
this.controller = null; // AbortController of the in-flight request
|
|
this.generation = 0; // bumped by stop(); results of an older generation are discarded
|
|
}
|
|
|
|
/** Exact hostname match, like the official `_phishingDomains.has(hostname)`. */
|
|
has(host) {
|
|
return typeof host === 'string' && this.domains.has(host.toLowerCase().replace(/\.$/, ''));
|
|
}
|
|
|
|
status() {
|
|
return {
|
|
enabled: this.enabled, source: PHISHING_LIST_URL, loaded: this.fetchedAt !== null, count: this.domains.size,
|
|
fetchedAt: this.fetchedAt, checkedAt: this.checkedAt, fromCache: this.fromCache, error: this.error,
|
|
};
|
|
}
|
|
|
|
start() {
|
|
if (!this.enabled || this.timer !== null) return;
|
|
this.loadCache();
|
|
void this.refresh();
|
|
this.timer = this.setIntervalImpl(() => { void this.refresh(); }, FETCH_INTERVAL_MS);
|
|
this.timer?.unref?.();
|
|
}
|
|
|
|
/** Ends the schedule, aborts an in-flight request and discards its result. refresh() may be called again later. */
|
|
stop() {
|
|
if (this.timer !== null) this.clearIntervalImpl(this.timer);
|
|
this.timer = null;
|
|
this.generation += 1;
|
|
this.controller?.abort(new ListError('stopped', 'phishing list refresh stopped'));
|
|
this.controller = null;
|
|
this.pending = null;
|
|
}
|
|
|
|
loadCache() {
|
|
try {
|
|
const stat = fs.statSync(this.cacheFile);
|
|
if (!stat.isFile() || stat.size > MAX_BYTES * 2) return;
|
|
const data = JSON.parse(fs.readFileSync(this.cacheFile, 'utf8'));
|
|
if (data?.version !== CACHE_VERSION || data.source !== PHISHING_LIST_URL || !Number.isFinite(data.fetchedAt)
|
|
|| !Array.isArray(data.domains) || data.domains.length > MAX_DOMAINS || !data.domains.every(validDomain)) return;
|
|
if (this.fetchedAt !== null && this.fetchedAt >= data.fetchedAt) return;
|
|
this.domains = new Set(data.domains);
|
|
this.fetchedAt = data.fetchedAt;
|
|
this.fromCache = true;
|
|
} catch {
|
|
// no cache yet, or unreadable: classification starts empty until the first fetch
|
|
}
|
|
}
|
|
|
|
/** Single-flight network refresh; never throws. Resolves to status(). */
|
|
refresh() {
|
|
if (!this.enabled) return Promise.resolve(this.status());
|
|
if (!this.pending) {
|
|
const pending = this.fetchOnce().finally(() => { if (this.pending === pending) this.pending = null; });
|
|
this.pending = pending;
|
|
}
|
|
return this.pending;
|
|
}
|
|
|
|
async fetchOnce() {
|
|
const generation = this.generation;
|
|
const stopped = () => generation !== this.generation;
|
|
const controller = new AbortController();
|
|
this.controller = controller;
|
|
const timer = setTimeout(() => controller.abort(new ListError('timeout', `phishing list: no answer in ${REQUEST_TIMEOUT_MS / 1000} s`)), REQUEST_TIMEOUT_MS);
|
|
timer.unref?.();
|
|
this.checkedAt = this.now();
|
|
try {
|
|
const res = await this.fetchImpl(PHISHING_LIST_URL, {
|
|
method: 'GET', signal: controller.signal, redirect: 'error', cache: 'no-store',
|
|
credentials: 'omit', referrerPolicy: 'no-referrer', headers: { Accept: 'text/plain' },
|
|
});
|
|
if (stopped()) return this.status();
|
|
// redirect:'error' already refuses redirects; a fetch implementation that followed one anyway is rejected.
|
|
if (res.redirected || (res.url && res.url !== PHISHING_LIST_URL)) throw new ListError('redirect', 'phishing list response did not come from the fixed endpoint');
|
|
if (!res.ok) throw new ListError('http', `phishing list: HTTP ${res.status}`);
|
|
const text = await readBounded(res, MAX_BYTES, controller.signal);
|
|
if (stopped()) return this.status();
|
|
const { domains } = parseList(text);
|
|
this.domains = domains;
|
|
this.fetchedAt = this.now();
|
|
this.fromCache = false;
|
|
this.error = null;
|
|
this.writeCache();
|
|
this.log('info', `phishing list: ${domains.size} domains`);
|
|
} catch (err) {
|
|
if (stopped()) return this.status();
|
|
const reason = controller.signal.aborted ? controller.signal.reason : null;
|
|
const code = err instanceof ListError ? err.code : reason instanceof ListError ? reason.code : 'network';
|
|
this.error = { code, message: String((reason instanceof ListError ? reason : err)?.message ?? err) };
|
|
this.log('warn', `phishing list: ${this.error.message} (keeping ${this.domains.size} known domains)`);
|
|
} finally {
|
|
clearTimeout(timer);
|
|
if (this.controller === controller) this.controller = null;
|
|
}
|
|
return this.status();
|
|
}
|
|
|
|
writeCache() {
|
|
try {
|
|
fs.mkdirSync(path.dirname(this.cacheFile), { recursive: true });
|
|
const tmp = `${this.cacheFile}.tmp`;
|
|
fs.writeFileSync(tmp, JSON.stringify({ version: CACHE_VERSION, source: PHISHING_LIST_URL, fetchedAt: this.fetchedAt, domains: [...this.domains] }));
|
|
fs.renameSync(tmp, this.cacheFile);
|
|
} catch (err) {
|
|
this.log('warn', `phishing list cache not written: ${err.message}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Renderer access: one exact-host lookup per external link, and the source state. */
|
|
function registerPhishingIpc({ ipcMain, trustedSender, list }) {
|
|
ipcMain.handle('privacy:link-threat', (event, host) => {
|
|
if (!trustedSender(event)) return { ok: false, error: { code: 'forbidden', message: 'forbidden' } };
|
|
if (typeof host !== 'string' || host.length > 253) return { ok: false, error: { code: 'bad_request', message: 'Invalid host' } };
|
|
return { ok: true, malicious: list.has(host), loaded: list.status().loaded };
|
|
});
|
|
ipcMain.handle('privacy:threat-status', (event) => (trustedSender(event) ? { ok: true, status: list.status() } : { ok: false, error: { code: 'forbidden', message: 'forbidden' } }));
|
|
}
|
|
|
|
module.exports = { PhishingList, registerPhishingIpc, parseList, PHISHING_LIST_URL, FETCH_INTERVAL_MS, MAX_BYTES, MAX_DOMAINS };
|