Включить диагностику ошибок браузера

This commit is contained in:
AidarKC
2026-11-16 12:13:42 +03:00
parent 102feccb2e
commit d9fdaf1930
14 changed files with 382 additions and 214 deletions
@@ -0,0 +1,93 @@
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, /<maxHistory>14<\/maxHistory>/);
assert.match(xml, /<logger name="client\.frontend" level="error" additivity="false">/);
assert.match(xml, /<totalSizeCap>150MB<\/totalSizeCap>/);
});