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

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
+3 -18
View File
@@ -3543,26 +3543,11 @@ export class AuthService {
}
async reportClientError(details) {
// Ошибки не запускают переподключение: без открытого WS отчёт не отправляем.
if (this.ws?.ws?.readyState !== WebSocket.OPEN) return false;
try {
const response = await this.ws.request('ClientErrorLog', details || {}, 3000);
return response?.status === 200;
} catch {
return false;
}
}
async reportClientUiError(details = {}) {
try {
const payload = {
source: 'ui_error',
code: 'UI_RUNTIME_ERROR',
...details,
};
const response = await this.sendCallDeliveryReport({
type: 'ui_error',
value: JSON.stringify(payload),
});
return !!response;
return response?.status === 200 && response?.accepted === true;
} catch {
return false;
}
+90 -90
View File
@@ -1,83 +1,109 @@
const MAX_CONTEXT_LEN = 2000;
// Единая диагностика технических ошибок UI. Без очереди и без пользовательского выключателя.
const RECENT_WINDOW_MS = 5000;
const UI_ERROR_REPORTING_KEY = 'shine-ui-send-errors-to-server-v1';
const MAX_CONTEXT_LEN = 800;
const MAX_IN_FLIGHT = 3;
let transport = null;
let transportDepth = 0;
let inFlight = 0;
const recentFingerprints = new Map();
let notifySent = null;
let lastCapturedPayload = null;
function nowTs() {
return Date.now();
}
function nowTs() { return Date.now(); }
// Диагностические строки не должны включать токены, пароли и длинные ключевые данные.
function cleanString(value, maxLen = 1000) {
if (value == null) return '';
const normalized = String(value).replace(/\s+/g, ' ').trim();
if (normalized.length <= maxLen) return normalized;
return `${normalized.slice(0, Math.max(0, maxLen - 3))}...`;
const cleaned = String(value)
.replace(/https?:\/\/[^\s)]+/gi, (url) => {
const line = url.match(/:(\d+):(\d+)$/);
const path = url.replace(/[?#].*$/, '');
return `${path}${line && path !== url ? `:${line[1]}:${line[2]}` : ''}`;
})
.replace(/\bBearer\s+[^\s,;]+/gi, 'Bearer [REDACTED]')
.replace(/\b(password|passwd|token|secret|privateKey|sessionId|authorization|apiKey|storagePwd)\s*[:=]\s*["']?[^\s,;}&"']+/gi, '$1=[REDACTED]')
.replace(/([?&](?:token|key|password|secret|session|auth|code|signature)=[^&#\s]+)/gi, '[REDACTED_PARAM]')
.replace(/\b[A-Za-z0-9_+\/=-]{96,}\b/g, '[REDACTED_LONG_VALUE]')
.replace(/[\u0000-\u001f\u007f]+/g, ' ')
.trim();
return cleaned.length <= maxLen ? cleaned : `${cleaned.slice(0, Math.max(0, maxLen - 3))}...`;
}
function stringifyContext(context) {
if (context == null) return '';
function safePagePath() {
try { return cleanString(window.location?.pathname || '', 150); } catch { return ''; }
}
function safeSource(value) {
try {
const raw = JSON.stringify(context);
if (!raw) return '';
if (raw.length <= MAX_CONTEXT_LEN) return raw;
return `${raw.slice(0, MAX_CONTEXT_LEN - 3)}...`;
} catch (error) {
return cleanString(`context_json_error:${error?.message || error}`, MAX_CONTEXT_LEN);
}
const url = new URL(String(value || ''), window.location.origin);
return cleanString(`${url.origin}${url.pathname}`, 240); // без query/hash
} catch { return ''; }
}
function makeFingerprint(payload) {
return [
payload.kind,
payload.message,
payload.sourceUrl,
payload.lineNumber,
payload.columnNumber,
payload.requestOp,
].join('|');
// Только разрешённые технические поля: произвольный context может содержать DM/ключи.
function safeContext(raw) {
const obj = raw && typeof raw === 'object' ? raw : {};
const result = {};
for (const key of ['pageId', 'reasonType', 'pageProtocol', 'timeoutMs', 'code', 'status']) {
const value = obj[key];
if (typeof value === 'string' || typeof value === 'number') result[key] = cleanString(value, 80);
}
if (Array.isArray(obj.pendingOps)) {
result.pendingOps = obj.pendingOps.slice(0, 8).map((op) => cleanString(op, 48));
}
const json = JSON.stringify({ pageVisibility: document.visibilityState || '', ...result });
return cleanString(json, MAX_CONTEXT_LEN);
}
function isDuplicate(fingerprint) {
const ts = nowTs();
const prev = recentFingerprints.get(fingerprint);
recentFingerprints.set(fingerprint, ts);
for (const [key, time] of recentFingerprints.entries()) {
if (ts - time > RECENT_WINDOW_MS) {
recentFingerprints.delete(key);
}
}
return prev != null && ts - prev < RECENT_WINDOW_MS;
function errorId() {
const bytes = new Uint8Array(6);
if (globalThis.crypto?.getRandomValues) globalThis.crypto.getRandomValues(bytes);
else return `ERR-${nowTs().toString(16)}-${Math.random().toString(16).slice(2, 8)}`;
return `ERR-${[...bytes].map((value) => value.toString(16).padStart(2, '0')).join('').toUpperCase()}`;
}
function buildPayload(details = {}) {
const kind = cleanString(details.kind || 'client_error', 64);
const runtime = ['global_error', 'unhandled_rejection', 'page_render_failure',
'channels_thread_runtime'].includes(kind);
const originalMessage = String(details.message || details.reason || 'Unknown client error');
const type = originalMessage.match(/\b(TypeError|ReferenceError|SyntaxError|RangeError|URIError|EvalError|AggregateError)\b/);
// Произвольные исключения могут содержать приватный текст DM. Для них передаём
// только тип и адреса кадров стека, но не текст исключения/первую строку stack.
const message = runtime ? `${type?.[1] || 'RuntimeError'}: client exception` : originalMessage;
const originalStack = String(details.stack || details.error?.stack || '');
const stack = runtime ? originalStack.split('\n').slice(1).join('\n') : originalStack;
return {
kind: cleanString(details.kind || 'client_error', 64),
message: cleanString(details.message || details.reason || 'Unknown client error', 500),
stack: cleanString(details.stack || details.error?.stack || '', 8000),
sourceUrl: cleanString(details.sourceUrl || details.fileName || '', 240),
errorId: errorId(),
clientVersion: cleanString(window.__SHINE_BUILD_HASH__ || '', 80),
kind,
message: cleanString(message, 500),
stack: cleanString(stack, 6000),
sourceUrl: safeSource(details.sourceUrl || details.fileName || ''),
lineNumber: Number.isFinite(details.lineNumber) ? details.lineNumber : null,
columnNumber: Number.isFinite(details.columnNumber) ? details.columnNumber : null,
route: cleanString(details.route || window.location?.hash || '', 200),
href: cleanString(details.href || window.location?.href || '', 240),
userAgent: cleanString(details.userAgent || navigator.userAgent || '', 240),
route: safePagePath(),
href: window.location?.origin || '', // без query/hash и данных из URL
userAgent: cleanString(navigator.userAgent || '', 240),
clientTs: Number.isFinite(details.clientTs) ? details.clientTs : nowTs(),
requestOp: cleanString(details.requestOp || '', 64),
requestIdRef: cleanString(details.requestIdRef || '', 128),
contextJson: stringifyContext({
title: document.title || '',
pageVisibility: document.visibilityState || '',
...details.context,
}),
contextJson: safeContext(details.context),
};
}
function isDuplicate(payload, key) {
const ts = nowTs();
const fingerprint = key || [payload.kind, payload.message, payload.sourceUrl,
payload.lineNumber, payload.requestOp, payload.stack.slice(0, 180)].join('|');
const prev = recentFingerprints.get(fingerprint);
for (const [name, last] of recentFingerprints) {
if (ts - last > RECENT_WINDOW_MS) recentFingerprints.delete(name);
}
if (recentFingerprints.size >= 128) recentFingerprints.delete(recentFingerprints.keys().next().value);
recentFingerprints.set(fingerprint, ts);
return prev != null && ts - prev < RECENT_WINDOW_MS;
}
export function setClientErrorTransport(fn) {
transport = typeof fn === 'function' ? fn : null;
}
@@ -87,55 +113,29 @@ export function setClientErrorSentNotifier(fn) {
}
export function getLastClientErrorPayload() {
if (!lastCapturedPayload) return null;
return { ...lastCapturedPayload };
}
export function isClientErrorReportingEnabled() {
try {
return localStorage.getItem(UI_ERROR_REPORTING_KEY) === '1';
} catch {
return false;
}
}
export function setClientErrorReportingEnabled(enabled) {
try {
localStorage.setItem(UI_ERROR_REPORTING_KEY, enabled ? '1' : '0');
} catch {
// ignore storage errors
}
return lastCapturedPayload ? { ...lastCapturedPayload } : null;
}
export async function captureClientError(details = {}) {
const payload = buildPayload(details);
if (!payload.message) return false;
lastCapturedPayload = payload;
if (isDuplicate(payload, details.dedupeKey)) return false;
console.error('[client-error]', payload.kind, payload.message); // без исходного error/context
const fingerprint = details.dedupeKey || makeFingerprint(payload);
if (isDuplicate(fingerprint)) return false;
console.error('[client-error]', payload.kind, payload.message, details.error || '');
if (!transport || details.skipTransport === true || transportDepth > 0 || !isClientErrorReportingEnabled()) {
return false;
}
if (!transport || details.skipTransport === true || inFlight >= MAX_IN_FLIGHT) return false;
try {
transportDepth += 1;
await transport(payload);
inFlight += 1;
// Только положительное подтверждение ClientErrorLog означает запись на сервере.
const accepted = await transport(payload);
if (accepted !== true) return false;
if (notifySent) {
try {
notifySent(payload);
} catch {
// ignore notifier errors
}
try { notifySent(payload); } catch { /* уведомление не должно ломать диагностику */ }
}
return true;
} catch (error) {
console.warn('client error transport failed', error);
} catch {
// Ошибка отправки не создаёт новый отчёт и не запускает повторную отправку.
return false;
} finally {
transportDepth = Math.max(0, transportDepth - 1);
inFlight -= 1;
}
}
+17 -2
View File
@@ -89,6 +89,7 @@ export class WsJsonClient {
const error = new Error(t('remaining.websocket.this_page_uses_https_but_the_server_uses_ws_use_wss_for_th'));
captureClientError({
kind: 'ws_mixed_content_blocked',
skipTransport: true,
message: error.message,
context: { url: this.url, pageProtocol: window.location.protocol },
});
@@ -107,7 +108,8 @@ export class WsJsonClient {
ws.addEventListener('error', () => {
captureClientError({
kind: 'ws_open_error',
message: `Failed to connect WebSocket ${this.url}`,
skipTransport: true,
message: 'WebSocket connection failed',
context: { url: this.url },
});
reject(new Error(`Не удалось подключиться к ${this.url}`));
@@ -191,7 +193,7 @@ export class WsJsonClient {
captureClientError({
kind: 'ws_bad_json',
message: 'Received non-JSON message from server',
context: { raw: String(raw).slice(0, 1000) },
context: { code: 'invalid_json' },
});
return;
}
@@ -207,6 +209,18 @@ export class WsJsonClient {
const slot = this.pending.get(requestId);
if (!slot) return;
this.pending.delete(requestId);
// Обработанные 4xx — обычные отказы. Только неожиданные 5xx диагностируем.
const status = Number(data?.status);
if (slot.op !== 'ClientErrorLog' && Number.isInteger(status)
&& status >= 500 && status < 600 && status !== 507) {
captureClientError({
kind: 'api_server_error',
message: `Server returned HTTP-like status ${status} for ${slot.op}`,
requestOp: slot.op,
requestIdRef: requestId,
context: { status },
});
}
slot.resolve(data);
}
@@ -238,6 +252,7 @@ export class WsJsonClient {
if (pendingOps.length > 0) {
captureClientError({
kind: 'ws_closed',
skipTransport: true,
message,
context: { url: this.url, pendingOps },
});