Files
client/scripts/smoke-chat-offscreen.mjs
T
omar f618d8bce9
ci / linux-arm64-cross (push) Successful in 3m22s
ci / linux-x64 (push) Successful in 3m32s
chat: add safe hybrid Markdown editing with strict CSP
2026-11-02 11:32:31 +03:00

110 lines
9.7 KiB
JavaScript

// Hidden renderer + real main-process persistence. Synthetic messages only; no connection/capture/dialog/OS actions.
import { launchApp, waitForAsync } from './lib/electron-app.mjs';
import assert from 'node:assert/strict';
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { maliciousMessages, richMessage } from '../test/fixtures/chat-markup.mjs';
const args = process.argv.slice(2);
const option = (key, fallback) => args.includes(`--${key}`) ? args[args.indexOf(`--${key}`) + 1] : fallback;
const out = path.resolve(option('out', 'smoke-out/chat'));
const profile = mkdtempSync(path.join(tmpdir(), 'teamspeach-chat-'));
mkdirSync(out, { recursive: true });
const result = { scope: 'Synthetic hidden offscreen renderer; actual chat-history IPC and main-process restart on a disposable profile. No real server traffic, private data, native dialogs, microphone, clipboard or OS shell.', checks: [], errors: [], network: [] };
const scope = { identity: 'SyntheticIdentity=', server: 'SyntheticServer=', kind: 'client', key: 'SyntheticPartner=' };
let app;
async function launch() {
const helper = await launchApp({ exe: option('exe'), profile });
const page = await helper.firstWindow();
page.on('pageerror', (e) => result.errors.push(e.message));
await page.route(/^https?:\/\//, (route) => { result.network.push(route.request().url()); return route.abort(); });
await page.evaluate(() => {
for (const method of ['getUserMedia', 'getDisplayMedia']) navigator.mediaDevices[method] = async () => { throw new Error('Capture forbidden'); };
});
return { helper, page };
}
try {
let started = await launch(); app = started.helper; let page = started.page;
await page.waitForFunction(() => Boolean(window.teamspeach));
const storage = await page.evaluate(async (scope) => {
const tp = window.teamspeach;
for (let i = 0; i < 621; i++) {
const reply = await tp.chatHistoryAppend(scope, { time: 1700000000000 + i, type: 'text', from_uid: scope.key, from_name: 'Synthetic partner', own: false, text: `persisted ${i}` }, 'Synthetic partner');
if (!reply.ok) throw new Error(reply.error.message);
}
await tp.chatHistorySetOpen(scope, true, 'Synthetic partner');
return tp.chatHistoryPage(scope, -1, 100);
}, scope);
assert.equal(storage.total, 621); assert.equal(storage.messages.length, 100); result.checks.push('621 rows through real main IPC, bounded 100-row page');
const render = await page.evaluate(async ({ maliciousMessages, richMessage }) => {
const { renderMarkdownInto, linkHref, parseTs3File } = await import('./js/markdown/render.js');
const { checkLink } = await import('./js/external-links.js');
const host = document.createElement('section'); host.id = 'synthetic-markdown-test'; document.body.append(host);
for (const source of [...maliciousMessages, richMessage]) { const node = document.createElement('div'); host.append(node); renderMarkdownInto(node, source); }
return { scripts: host.querySelectorAll('script,iframe,object,embed,svg,foreignObject').length,
remoteImages: [...host.querySelectorAll('img')].filter((n) => /^https?:/.test(n.src)).length,
unsafeLinks: [...host.querySelectorAll('a[href]')].filter((n) => !/^(https?:|mailto:)/.test(n.href)).length,
handlers: [...host.querySelectorAll('*')].flatMap((n) => [...n.attributes]).filter((a) => /^on/i.test(a.name)).length,
rejected: ['javascript:alert(1)', 'data:text/html,hi', 'file:///private'].map((s) => linkHref(s)),
phishing: checkLink('https://twitch.tv/teamspeak_tv.evil'), trusted: checkLink('https://twitch.tv/teamspeak_tv'),
malformedFile: parseTs3File('ts3file://host?channel=1&filename=..%2Fprivate'),
details: host.querySelectorAll('details').length, tables: host.querySelectorAll('table').length };
}, { maliciousMessages, richMessage });
assert.equal(render.scripts, 0); assert.equal(render.remoteImages, 0); assert.equal(render.unsafeLinks, 0); assert.equal(render.handlers, 0);
assert.deepEqual(render.rejected, [null, null, null]); assert.equal(render.phishing, 'warn'); assert.equal(render.trusted, 'pass'); assert.equal(render.malformedFile, null);
assert.ok(render.details > 0); assert.ok(render.tables > 0); result.checks.push({ maliciousRenderer: render });
await page.waitForSelector('#synthetic-markdown-test .katex', { state: 'attached' });
await page.waitForSelector('#synthetic-markdown-test .md-offline-mermaid-preview[data-state="success"] img', { state: 'attached', timeout: 30000 });
assert.equal(await page.evaluate(() => globalThis.CHAT_XSS ?? null), null);
result.checks.push('Real local KaTeX and Mermaid hydrated; generated attacks did not execute');
const integrated = await page.evaluate(async () => {
const { S, newConnection } = await import('./js/state.js'); const chat = await import('./js/chat.js');
const make = (id, uid) => {
const conn = newConnection(id); conn.conn = { state: 'connected', address: 'synthetic.invalid' };
conn.snap = { own_client_id: 1, own_channel_id: 7, server: { uid, features: {} }, channels: [{ id: 7, name: 'Synthetic' }], clients: [{ id: 1, uid: 'Self=', nickname: 'Self' }, { id: 2, uid: 'Peer=', nickname: 'Peer' }] };
S.connections.set(id, conn); return conn;
};
const a = make('synthetic-a', 'ServerA='); const b = make('synthetic-b', 'ServerB='); S.view = 'main'; S.viewId = a.id;
chat.onSnapshot(a); chat.onSnapshot(b); chat.onViewChanged();
for (let i = 0; i < 510; i++) chat.onText({ target: 'channel', from_client_id: 2, from_nickname: 'Peer', message: `A ${i}` }, a);
chat.onText({ target: 'channel', from_client_id: 2, from_nickname: 'Peer', message: 'B isolated' }, b);
const systemName = '<img src=x onerror=alert(1)>';
chat.addSystem(a, 'channel', () => `Joined ${systemName}`, { emphasis: [systemName] });
const system = document.querySelector('#chat-log > .msg-system:last-child');
const systemRow = { name: system?.querySelector('strong')?.textContent, text: system?.querySelector('.msg-system-text')?.textContent, time: system?.querySelector('time.msg-system-time')?.getAttribute('datetime'), images: system?.querySelectorAll('img').length };
const aText = document.querySelector('#chat-log').textContent; const rows = document.querySelectorAll('#chat-log > .msg').length; const unreadB = chat.unreadCount(b);
// History paging controls exist only when there is something to page: none for a live-only channel.
const historyButtons = [...document.querySelectorAll('.chat-history-controls button')].filter((n) => n.checkVisibility()).map((n) => n.textContent);
S.viewId = b.id; chat.onViewChanged(); const bText = document.querySelector('#chat-log').textContent;
chat.openPrivate(b, 2); b.snap.clients[1] = { id: 2, uid: 'ReusedIdDifferentPeer=', nickname: 'Different' }; chat.onSnapshot(b);
// The real editable surface refuses input: adapter state, contentEditable and the accessible state agree.
const input = document.querySelector('#chat-input');
const reusedDisabled = chat.composerEditor().disabled && input.contentEditable === 'false' && input.getAttribute('aria-disabled') === 'true';
return { rows, aIsolated: !aText.includes('B isolated'), bIsolated: !bText.includes('A 509'), unreadB, reusedDisabled, systemRow, historyButtons };
});
assert.ok(integrated.rows <= 500); assert.equal(integrated.aIsolated, true); assert.equal(integrated.bIsolated, true); assert.equal(integrated.unreadB, 1); assert.equal(integrated.reusedDisabled, true);
assert.deepEqual(integrated.historyButtons, [], 'no permanent history buttons without older history');
assert.equal(integrated.systemRow.name, '<img src=x onerror=alert(1)>');
assert.equal(integrated.systemRow.text, 'Joined <img src=x onerror=alert(1)>');
assert.ok(Number.isFinite(Date.parse(integrated.systemRow.time))); assert.equal(integrated.systemRow.images, 0);
result.checks.push({ integrated });
// Wait for all queued renderer history writes before closing the owned helper.
await waitForAsync(page, async () => {
const page = await window.teamspeach.chatHistoryPage({ identity: 'Self=', server: 'ServerA=', kind: 'channel', key: '7' }, -1, 1);
return page.total === 510;
}, null, { timeout: 60000 });
await app.close(); app = null;
started = await launch(); app = started.helper; page = started.page;
const reopened = await page.evaluate(async (scope) => {
const tp = window.teamspeach;
return { page: await tp.chatHistoryPage(scope, -1, 100), other: await tp.chatHistoryPage({ ...scope, identity: 'OtherIdentity=' }, -1, 100), list: await tp.chatHistoryList(scope) };
}, scope);
assert.equal(reopened.page.total, 621); assert.equal(reopened.page.messages[99].text, 'persisted 620'); assert.equal(reopened.other.total, 0); assert.equal(reopened.list.conversations[0].open, true);
result.checks.push('Main-process restart restores exact history/open conversation; other identity remains empty');
assert.deepEqual(result.network, []); assert.deepEqual(result.errors, []);
const safety = await app.evaluate(({ BrowserWindow }) => { const win = BrowserWindow.getAllWindows()[0]; return { visible: win.isVisible(), focused: win.isFocused(), focusable: win.isFocusable(), offscreen: win.webContents.isOffscreen(), muted: win.webContents.isAudioMuted() }; });
assert.deepEqual(safety, { visible: false, focused: false, focusable: false, offscreen: true, muted: true }); result.checks.push({ safety });
result.ok = true;
} catch (err) { result.ok = false; result.error = err.stack; process.exitCode = 1; }
finally { if (app) await app.close(); rmSync(profile, { recursive: true, force: true }); writeFileSync(path.join(out, 'result.json'), JSON.stringify(result, null, 2)); console.log(JSON.stringify(result, null, 2)); }