import test from 'node:test'; import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; const read = (path) => readFileSync(new URL(path, import.meta.url), 'utf8'); globalThis.window = { location: { origin: 'https://shineup.me', pathname: '/app', hash: '#/chat?token=DONT_LOG', href: 'https://shineup.me/app?password=DONT_LOG', }, __SHINE_BUILD_HASH__: 'build-test', }; globalThis.document = { visibilityState: 'visible', title: 'Secret chat title' }; Object.defineProperty(globalThis, 'navigator', { value: { userAgent: 'Test browser' }, configurable: true }); const reporter = await import(`data:text/javascript,${encodeURIComponent(read('../js/services/client-error-reporter.js'))}`); test('автоматическая отправка без переключателя: только при accepted=true', async () => { const received = []; const notified = []; reporter.setClientErrorTransport(async (payload) => { received.push(payload); return true; }); reporter.setClientErrorSentNotifier((payload) => notified.push(payload)); assert.equal(await reporter.captureClientError({ kind: 'unit_accept', message: 'Unexpected failure' }), true); assert.equal(received.length, 1); assert.match(received[0].errorId, /^ERR-/); assert.equal(received[0].clientVersion, 'build-test'); assert.equal(notified.length, 1); reporter.setClientErrorTransport(async () => false); assert.equal(await reporter.captureClientError({ kind: 'unit_reject', message: 'not accepted' }), false); assert.equal(notified.length, 1); }); test('ошибки не отправляются повторно и не создают локальную очередь', async () => { let calls = 0; reporter.setClientErrorTransport(async () => { calls++; throw new Error('offline'); }); assert.equal(await reporter.captureClientError({ kind: 'unit_offline', message: 'Failed to send' }), false); assert.equal(await reporter.captureClientError({ kind: 'unit_offline', message: 'Failed to send' }), false); assert.equal(calls, 1); assert.equal(await reporter.captureClientError({ kind: 'unit_local', message: 'Local only', skipTransport: true }), false); assert.equal(calls, 1); }); test('контекст ограничен и URL/пароли/ключи не передаются', async () => { let payload; reporter.setClientErrorTransport(async (value) => { payload = value; return true; }); assert.equal(await reporter.captureClientError({ kind: 'unit_privacy', message: 'password=VerySensitive token=DoNotStore Bearer ABCDEFG', stack: 'TypeError at https://shineup.me/a?token=SECRET', sourceUrl: 'https://shineup.me/asset.js?token=SECRET#password=other', context: { pageId: 'channel', status: 500, secret: 'DO_NOT_SEND', raw: 'PRIVATE_MESSAGE', password: 'passphrase', token: 'tokenvalue', }, }), true); const json = JSON.stringify(payload); for (const secret of ['VerySensitive', 'DoNotStore', 'ABCDEFG', 'DO_NOT_SEND', 'PRIVATE_MESSAGE', 'passphrase', 'tokenvalue', 'SECRET', 'DONT_LOG', 'Secret chat title']) { assert.ok(!json.includes(secret), `leaked ${secret}`); } assert.equal(payload.sourceUrl, 'https://shineup.me/asset.js'); assert.equal(payload.route, '/app'); assert.equal(JSON.parse(payload.contextJson).status, '500'); }); test('все 5xx кроме 507 отслеживаются, ожидаемые 4xx и ответ логгера — нет', async () => { const captured = []; const source = read('../js/services/ws-client.js') .replace("import { t } from '../i18n/index.js';", "const t = (s) => s;") .replace("import { captureClientError } from './client-error-reporter.js';", 'const captureClientError = (value) => globalThis.__wsCaptured.push(value);') .replace("import { defaultServerWs } from '../deploy-config.js';", "const defaultServerWs = 'wss://shineup.me/ws';"); globalThis.__wsCaptured = captured; const { WsJsonClient } = await import(`data:text/javascript,${encodeURIComponent(source)}`); const ws = new WsJsonClient('wss://shineup.me/ws'); for (const [op, status] of [['GetChannels', 500], ['GetChannels', 501], ['GetChannels', 400], ['GetChannels', 507], ['ClientErrorLog', 500]]) { const requestId = `${op}-${status}`; let resolved; ws.pending.set(requestId, { op, resolve: (value) => { resolved = value; } }); ws.handleMessage(JSON.stringify({ op, requestId, status })); assert.equal(resolved.status, status); } assert.deepEqual(captured.map((item) => item.context.status), [500, 501]); assert.deepEqual(captured.map((item) => item.kind), ['api_server_error', 'api_server_error']); }); test('конфиг сервера изолирует client-errors.log на 14 дней', () => { const xml = read('../../SHiNE-server/src/main/resources/logback.xml'); assert.match(xml, /client-errors\.log/); assert.match(xml, /14<\/maxHistory>/); assert.match(xml, //); assert.match(xml, /150MB<\/totalSizeCap>/); }); test('ClientErrorLog подтверждается по payload.accepted, а не по корневому полю', async () => { const src = read('../js/services/auth-service.js'); const match = src.match(/async reportClientError\(details\) \{([\s\S]*?)\n \}/); assert.ok(match, 'reportClientError method exists'); const report = new Function('details', `return (async function () {${match[1]}\n}).call(this);`); globalThis.WebSocket = { OPEN: 1 }; const request = async () => ({ status: 200, payload: { accepted: true } }); const ws = { ws: { readyState: 1 }, request }; assert.equal(await report.call({ ws }, { kind: 'global_error', message: 'Test' }), true); ws.request = async () => ({ status: 200, payload: { accepted: false } }); assert.equal(await report.call({ ws }, { kind: 'global_error', message: 'Test' }), false); ws.request = async () => ({ status: 500, payload: { accepted: true } }); assert.equal(await report.call({ ws }, { kind: 'global_error', message: 'Test' }), false); ws.ws.readyState = 3; assert.equal(await report.call({ ws }, { kind: 'global_error', message: 'Test' }), false); }); test('BOOT ERROR отключает аварийную плашку после подключения штатного обработчика', () => { const index = read('../index.html'); const app = read('../js/app.js'); assert.match(app, /window\.__SHINE_APP_ERROR_HANDLERS_READY__ = true;/); const handlers = [...index.matchAll(/window\.addEventListener\('(error|unhandledrejection)', \(e\) => \{\s*([\s\S]*?)\n \}\);/g)]; assert.equal(handlers.length, 2); for (const match of handlers) { assert.match(match[2], /if \(window\.__SHINE_APP_ERROR_HANDLERS_READY__ === true\) return;/); } }); test('аварийный экран нейтральный, с причиной, источником и кнопкой перезагрузки', () => { const index = read('../index.html'); assert.match(index, /Не удалось запустить SHiNE/); assert.match(index, /Причина: \$/); assert.match(index, /Источник: \$/); assert.match(index, /Обновить страницу/); assert.match(index, /Подробности/); assert.match(index, /Отправка отчёта не подтверждена/); assert.match(index, /state\.sentToServer === true/); assert.match(index, /sentToServer: true/); assert.doesNotMatch(index, /rgba\(120, 0, 0/); assert.doesNotMatch(index, /\[BOOT ERROR\] \$/); }); test('аварийный экран не показывает stack и произвольный текст исключения', () => { const index = read('../index.html'); const match = index.match(/const updateBootOverlay = \(\) => \{([\s\S]*?)\n \};/); assert.ok(match, 'есть функция обновления аварийного экрана'); assert.doesNotMatch(match[1], /\.stack|state\.message\s*;/); assert.match(index, /Ошибка выполнения JavaScript \(TypeError\)/); assert.match(index, /if \(window\.__SHINE_APP_ERROR_HANDLERS_READY__ === true\) return;/); }); test('BOOT ERROR показывает краткую причину без приватного текста и позволяет перезагрузить страницу', async () => { const { runInNewContext } = await import('node:vm'); const index = read('../index.html'); const match = index.match(/\(function attachBootErrorOverlay\(\) \{[\s\S]*?\}\(\)\);/); assert.ok(match, 'загрузочный обработчик найден'); class FakeElement { constructor(tag = 'div') { this.tag = tag; this.children = []; this.style = {}; this.dataset = {}; this.handlers = {}; this.attributes = {}; this.textContent = ''; } setAttribute(name, value) { this.attributes[name] = value; } append(...els) { this.children.push(...els); } appendChild(el) { this.children.push(el); } addEventListener(name, handler) { this.handlers[name] = handler; } querySelector(selector) { const key = selector.match(/^\[data-boot-error="(.*?)"\]$/)?.[1]; const descend = (el) => { if (key && el.dataset?.bootError === key) return el; for (const child of el.children) { const found = descend(child); if (found) return found; } return null; }; return descend(this); } } const body = new FakeElement('body'); const handlers = {}; let reloads = 0; const fakeWindow = { addEventListener: (type, handler) => { handlers[type] = handler; }, location: { origin: 'https://shineup.me', reload: () => reloads++ }, }; const fakeDocument = { documentElement: { dataset: { theme: 'dark' } }, body, createElement: (tag) => new FakeElement(tag), getElementById: (id) => body.children.find((el) => el.id === id) || null, }; runInNewContext(match[0], { window: fakeWindow, document: fakeDocument, navigator: { userAgent: 'test' }, console, URL, Date, Number, String, Math }); handlers.error({ message: 'TypeError: private message text: NEVER_SHOW_ME', filename: 'https://shineup.me/js/app.js?password=NEVER_SHOW_ME', lineno: 42, colno: 9, error: { stack: 'TypeError: NEVER_SHOW_ME' }, }); const overlay = fakeDocument.getElementById('boot-error-overlay'); assert.ok(overlay); assert.equal(overlay.querySelector('[data-boot-error="cause"]').textContent, 'Причина: Ошибка выполнения JavaScript (TypeError).'); assert.equal(overlay.querySelector('[data-boot-error="source"]').textContent, 'Источник: app.js:42'); assert.match(overlay.querySelector('[data-boot-error="status"]').textContent, /не подтверждена/); const rendered = JSON.stringify(body, (k, v) => k === 'handlers' ? undefined : v); assert.ok(!rendered.includes('NEVER_SHOW_ME')); const buttons = overlay.children[0].children.at(-1).children; assert.equal(buttons[0].textContent, 'Обновить страницу'); buttons[0].handlers.click(); assert.equal(reloads, 1); });