SHA256
Включить диагностику ошибок браузера
This commit is contained in:
+84
-59
@@ -13,88 +13,113 @@ import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
|
|||||||
import server.logic.ws_protocol.WireCodes;
|
import server.logic.ws_protocol.WireCodes;
|
||||||
|
|
||||||
import java.net.SocketAddress;
|
import java.net.SocketAddress;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/** Единая точка диагностики ошибок браузера (доступна до авторизации). */
|
||||||
* ClientErrorLog — технический endpoint для фронтенд-ошибок.
|
|
||||||
* Не требует авторизации: клиент должен иметь возможность отправить ошибку
|
|
||||||
* даже если логин/сессия ещё не установлены.
|
|
||||||
*/
|
|
||||||
public class Net_ClientErrorLog_Handler implements JsonMessageHandler {
|
public class Net_ClientErrorLog_Handler implements JsonMessageHandler {
|
||||||
|
private static final Logger log = LoggerFactory.getLogger("client.frontend");
|
||||||
|
private static final long WINDOW_MS = 60_000L;
|
||||||
|
private static final int MAX_PER_SOURCE = 60;
|
||||||
|
private static final int MAX_ALL = 1200;
|
||||||
|
private static final int MAX_SOURCES = 4096;
|
||||||
|
private static final Map<String, Bucket> rateLimits = new HashMap<>();
|
||||||
|
private static long globalWindow = 0;
|
||||||
|
private static int globalCount = 0;
|
||||||
|
private static int cleanCounter = 0;
|
||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(Net_ClientErrorLog_Handler.class);
|
private static final class Bucket {
|
||||||
|
long start;
|
||||||
|
int count;
|
||||||
|
Bucket(long now) { start = now; }
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) {
|
public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) {
|
||||||
Net_ClientErrorLog_Request req = (Net_ClientErrorLog_Request) baseRequest;
|
Net_ClientErrorLog_Request req = (Net_ClientErrorLog_Request) baseRequest;
|
||||||
|
if (req.getMessage() == null || req.getMessage().isBlank() || invalidSize(req)) {
|
||||||
if (req.getMessage() == null || req.getMessage().isBlank()) {
|
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST,
|
||||||
return NetExceptionResponseFactory.error(
|
"BAD_FIELDS", "Недопустимый размер или отсутствие message в ClientErrorLog");
|
||||||
req,
|
|
||||||
WireCodes.Status.BAD_REQUEST,
|
|
||||||
"BAD_FIELDS",
|
|
||||||
"Поле message обязательно для ClientErrorLog"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
long serverTs = System.currentTimeMillis();
|
long serverTs = System.currentTimeMillis();
|
||||||
String login = safe(ctx != null ? ctx.getLogin() : null);
|
boolean accepted = allow(remoteAddress(ctx), serverTs);
|
||||||
String sessionId = safe(ctx != null ? ctx.getSessionId() : null);
|
if (accepted) {
|
||||||
String remote = safe(remoteAddress(ctx));
|
log.error("CLIENT_FRONTEND_ERROR id={} clientVersion={} kind={} clientTs={} serverTs={} login={} "
|
||||||
|
+ "route={} sourceUrl={} line={} column={} requestOp={} requestIdRef={} message={} "
|
||||||
log.error(
|
+ "userAgent={} context={} stack={}",
|
||||||
"CLIENT_FRONTEND_ERROR kind={} clientTs={} serverTs={} login={} sessionId={} remote={} route={} href={} sourceUrl={} line={} column={} requestOp={} requestIdRef={} message={} userAgent={} context={}",
|
clip(req.getErrorId(), 48), clip(req.getClientVersion(), 80),
|
||||||
clip(req.getKind(), 64),
|
clip(req.getKind(), 64), req.getClientTs(), serverTs,
|
||||||
req.getClientTs(),
|
clip(ctx != null ? ctx.getLogin() : null, 64), clip(req.getRoute(), 150),
|
||||||
serverTs,
|
clip(req.getSourceUrl(), 240), req.getLineNumber(), req.getColumnNumber(),
|
||||||
clip(login, 64),
|
clip(req.getRequestOp(), 64), clip(req.getRequestIdRef(), 128),
|
||||||
clip(sessionId, 128),
|
clip(req.getMessage(), 500), clip(req.getUserAgent(), 240),
|
||||||
clip(remote, 128),
|
clip(req.getContextJson(), 800), clip(req.getStack(), 6000));
|
||||||
clip(req.getRoute(), 200),
|
|
||||||
clip(req.getHref(), 240),
|
|
||||||
clip(req.getSourceUrl(), 240),
|
|
||||||
req.getLineNumber(),
|
|
||||||
req.getColumnNumber(),
|
|
||||||
clip(req.getRequestOp(), 64),
|
|
||||||
clip(req.getRequestIdRef(), 128),
|
|
||||||
clip(req.getMessage(), 500),
|
|
||||||
clip(req.getUserAgent(), 240),
|
|
||||||
clip(req.getContextJson(), 2000)
|
|
||||||
);
|
|
||||||
|
|
||||||
if (req.getStack() != null && !req.getStack().isBlank()) {
|
|
||||||
log.error("CLIENT_FRONTEND_ERROR_STACK requestId={} stack={}",
|
|
||||||
clip(req.getRequestId(), 128),
|
|
||||||
clip(req.getStack(), 8000));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Net_ClientErrorLog_Response resp = new Net_ClientErrorLog_Response();
|
Net_ClientErrorLog_Response resp = new Net_ClientErrorLog_Response();
|
||||||
resp.setOp(req.getOp());
|
resp.setOp(req.getOp());
|
||||||
resp.setRequestId(req.getRequestId());
|
resp.setRequestId(req.getRequestId());
|
||||||
resp.setStatus(WireCodes.Status.OK);
|
resp.setStatus(WireCodes.Status.OK);
|
||||||
resp.setAccepted(true);
|
resp.setAccepted(accepted); // false = ограничение частоты, отчёт не записан
|
||||||
resp.setServerTs(serverTs);
|
resp.setServerTs(serverTs);
|
||||||
return resp;
|
return resp;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String remoteAddress(ConnectionContext ctx) {
|
private static boolean invalidSize(Net_ClientErrorLog_Request req) {
|
||||||
if (ctx == null) return "";
|
return length(req.getMessage()) > 500 || length(req.getStack()) > 6000
|
||||||
Session ws = ctx.getWsSession();
|
|| length(req.getContextJson()) > 800 || length(req.getKind()) > 64
|
||||||
if (ws == null) return "";
|
|| length(req.getSourceUrl()) > 240 || length(req.getUserAgent()) > 240
|
||||||
SocketAddress remote = ws.getRemoteAddress();
|
|| length(req.getErrorId()) > 48 || length(req.getClientVersion()) > 80
|
||||||
return remote != null ? remote.toString() : "";
|
|| length(req.getRoute()) > 150 || length(req.getHref()) > 240
|
||||||
|
|| length(req.getRequestOp()) > 64 || length(req.getRequestIdRef()) > 128;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String safe(String value) {
|
private static int length(String value) { return value == null ? 0 : value.length(); }
|
||||||
return value == null ? "" : value.trim();
|
|
||||||
|
// Ограничение по IP WebSocket (не по полю JSON, которое клиент может подделать).
|
||||||
|
private static synchronized boolean allow(String source, long now) {
|
||||||
|
if (now - globalWindow >= WINDOW_MS) { globalWindow = now; globalCount = 0; }
|
||||||
|
if (globalCount >= MAX_ALL) return false;
|
||||||
|
if (rateLimits.size() >= MAX_SOURCES || ++cleanCounter % 128 == 0) {
|
||||||
|
Iterator<Map.Entry<String, Bucket>> it = rateLimits.entrySet().iterator();
|
||||||
|
while (it.hasNext()) {
|
||||||
|
if (now - it.next().getValue().start >= WINDOW_MS) it.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Bucket bucket = rateLimits.get(source);
|
||||||
|
if (bucket == null) {
|
||||||
|
if (rateLimits.size() >= MAX_SOURCES) return false;
|
||||||
|
bucket = new Bucket(now);
|
||||||
|
rateLimits.put(source, bucket);
|
||||||
|
}
|
||||||
|
if (now - bucket.start >= WINDOW_MS) { bucket.start = now; bucket.count = 0; }
|
||||||
|
if (bucket.count >= MAX_PER_SOURCE) return false;
|
||||||
|
bucket.count++;
|
||||||
|
globalCount++;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String remoteAddress(ConnectionContext ctx) {
|
||||||
|
if (ctx == null) return "unknown";
|
||||||
|
Session session = ctx.getWsSession();
|
||||||
|
if (session == null) return "unknown";
|
||||||
|
SocketAddress remote = session.getRemoteAddress();
|
||||||
|
// Адрес не записывается в журнал и хранится только как ключ лимита на 1 минуту.
|
||||||
|
if (remote instanceof InetSocketAddress inet) {
|
||||||
|
return inet.getAddress() != null ? inet.getAddress().getHostAddress() : inet.getHostString();
|
||||||
|
}
|
||||||
|
return remote != null ? remote.toString() : "unknown";
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String clip(String value, int maxLen) {
|
private static String clip(String value, int maxLen) {
|
||||||
String cleaned = safe(value)
|
if (value == null) return "";
|
||||||
.replace('\n', ' ')
|
String clean = value.replaceAll("[\\p{Cntrl}]", " ")
|
||||||
.replace('\r', ' ');
|
.replaceAll("(?i)\\bBearer\\s+[^\\s,;]+", "Bearer [REDACTED]")
|
||||||
if (cleaned.length() <= maxLen) {
|
.replaceAll("(?i)\\b(password|passwd|token|secret|privateKey|sessionId|authorization|apiKey|storagePwd)\\s*[:=]\\s*[^\\s,;}&]+", "$1=[REDACTED]")
|
||||||
return cleaned;
|
.replaceAll("[A-Za-z0-9_+/=-]{96,}", "[REDACTED_LONG_VALUE]")
|
||||||
}
|
.replaceAll("(?i)[?&](token|key|password|secret|session|auth|code|signature)=[^&#\\s]+", "[REDACTED_PARAM]");
|
||||||
return cleaned.substring(0, Math.max(0, maxLen - 3)) + "...";
|
return clean.length() <= maxLen ? clean : clean.substring(0, Math.max(0, maxLen - 3)) + "...";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+8
@@ -26,6 +26,8 @@ import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
|||||||
*/
|
*/
|
||||||
public class Net_ClientErrorLog_Request extends Net_Request {
|
public class Net_ClientErrorLog_Request extends Net_Request {
|
||||||
|
|
||||||
|
private String errorId;
|
||||||
|
private String clientVersion;
|
||||||
private String kind;
|
private String kind;
|
||||||
private String message;
|
private String message;
|
||||||
private String stack;
|
private String stack;
|
||||||
@@ -40,6 +42,12 @@ public class Net_ClientErrorLog_Request extends Net_Request {
|
|||||||
private String requestIdRef;
|
private String requestIdRef;
|
||||||
private String contextJson;
|
private String contextJson;
|
||||||
|
|
||||||
|
public String getErrorId() { return errorId; }
|
||||||
|
public void setErrorId(String errorId) { this.errorId = errorId; }
|
||||||
|
|
||||||
|
public String getClientVersion() { return clientVersion; }
|
||||||
|
public void setClientVersion(String clientVersion) { this.clientVersion = clientVersion; }
|
||||||
|
|
||||||
public String getKind() { return kind; }
|
public String getKind() { return kind; }
|
||||||
public void setKind(String kind) { this.kind = kind; }
|
public void setKind(String kind) { this.kind = kind; }
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,24 @@
|
|||||||
</encoder>
|
</encoder>
|
||||||
</appender>
|
</appender>
|
||||||
|
|
||||||
|
<!-- Отдельный журнал ошибок браузера: без дублирования в app.log. -->
|
||||||
|
<appender name="CLIENT_ERRORS" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||||
|
<file>${LOG_DIR}/client-errors.log</file>
|
||||||
|
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
|
||||||
|
<fileNamePattern>${LOG_DIR}/client-errors.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
|
||||||
|
<maxFileSize>10MB</maxFileSize>
|
||||||
|
<maxHistory>14</maxHistory>
|
||||||
|
<totalSizeCap>150MB</totalSizeCap>
|
||||||
|
</rollingPolicy>
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %msg%n</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<logger name="client.frontend" level="error" additivity="false">
|
||||||
|
<appender-ref ref="CLIENT_ERRORS" />
|
||||||
|
</logger>
|
||||||
|
|
||||||
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
|
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
<encoder>
|
<encoder>
|
||||||
<pattern>%highlight(%-5level) %cyan(%logger{20}) - %msg%n</pattern>
|
<pattern>%highlight(%-5level) %cyan(%logger{20}) - %msg%n</pattern>
|
||||||
|
|||||||
+2
-2
@@ -1,2 +1,2 @@
|
|||||||
client.version=1.20.51
|
client.version=1.20.52
|
||||||
server.version=1.16.26
|
server.version=1.16.27
|
||||||
|
|||||||
@@ -511,19 +511,21 @@
|
|||||||
"op": "ClientErrorLog",
|
"op": "ClientErrorLog",
|
||||||
"requestId": "err-001",
|
"requestId": "err-001",
|
||||||
"payload": {
|
"payload": {
|
||||||
|
"errorId": "ERR-A7F29C1201CD",
|
||||||
|
"clientVersion": "20261116-client-error-reporting-v1",
|
||||||
"kind": "global_error",
|
"kind": "global_error",
|
||||||
"message": "TypeError: failed",
|
"message": "TypeError: client exception",
|
||||||
"stack": "...",
|
"stack": "...",
|
||||||
"sourceUrl": "https://shineup.me/app.js",
|
"sourceUrl": "https://shineup.me/app.js",
|
||||||
"lineNumber": 10,
|
"lineNumber": 10,
|
||||||
"columnNumber": 20,
|
"columnNumber": 20,
|
||||||
"route": "#/channel-view/own-0",
|
"route": "/channels",
|
||||||
"href": "https://shineup.me/#/channel-view/own-0",
|
"href": "https://shineup.me",
|
||||||
"userAgent": "...",
|
"userAgent": "...",
|
||||||
"clientTs": 1774700000123,
|
"clientTs": 1774700000123,
|
||||||
"requestOp": "GetChannelMessages",
|
"requestOp": "GetChannelMessages",
|
||||||
"requestIdRef": "GetChannelMessages-123",
|
"requestIdRef": "GetChannelMessages-123",
|
||||||
"contextJson": "{\"screen\":\"channels\"}"
|
"contextJson": "{\"pageVisibility\":\"visible\",\"pageId\":\"channels\"}"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -545,7 +547,19 @@
|
|||||||
|
|
||||||
### Специфические коды ошибок `ClientErrorLog`
|
### Специфические коды ошибок `ClientErrorLog`
|
||||||
|
|
||||||
- `400 / BAD_FIELDS` — обязательные поля ошибки не заполнены.
|
- `400 / BAD_FIELDS` — нет `message` или превышены ограничения размеров полей.
|
||||||
|
- `200` + `payload.accepted=false` — отчёт **не записан** из-за ограничений частоты; повторов и очереди нет.
|
||||||
|
|
||||||
|
### Диагностика SHiNE UI v1 (16.11.2026)
|
||||||
|
|
||||||
|
- Критические JS-ошибки и неожиданные ответы WS API (статус `500–599`, кроме `507`) отправляются **автоматически**, без переключателя в инструментах разработчика; обычные `4xx` не считаются багом.
|
||||||
|
- Транспорт: только текущий WebSocket `ClientErrorLog`, без отдельного HTTP и без локальной очереди. При отсутствии соединения отчёт не отправляется; клиент не утверждает обратное.
|
||||||
|
- Серверный журнал: `logs/client-errors.log` (Logback `client.frontend`, без дублирования в `app.log`); ежедневная/размерная ротация, история 14 дней, до 150 MB суммарно. Диагностика звонков `CallDeliveryReport` остаётся в своём журнале.
|
||||||
|
- Поля `errorId` и `clientVersion` необязательные для внешних клиентов; `errorId` связывает уведомление пользователя с записью в журнале.
|
||||||
|
- Для необработанных ошибок/сбоев UI клиент передаёт тип исключения и кадры стека, но **не произвольный текст исключения**, который может содержать данные переписки. Клиент отбрасывает произвольный `context`, оставляя только технические поля: `pageId`, `reasonType`, `pageProtocol`, `timeoutMs`, `code`, `status`, `pendingOps`. URL передаются без query/hash, приватные ключи, содержимое сообщений, пароли и токены не должны включаться. Сервер дополнительно очищает и ограничивает строки; **не следует отправлять конфиденциальные данные даже при ручном вызове API**.
|
||||||
|
- Сервер ограничивает частоту: до 60 отчётов с одного IP и 1200 всего за 60 секунд; длины полей ограничены, число источников ограничено. IP используется временно для ограничения частоты и не записывается в отдельный журнал.
|
||||||
|
- Уведомление «отчёт принят» показывается только при `status=200` и `accepted=true`. Это означает, что сервер принял отчёт на обработку, но не является долговременной гарантией записи на диск.
|
||||||
|
- Отправка диагностики не инициирует повтор исходной операции, в том числе блокчейн-платежа или доната.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -39,7 +39,7 @@
|
|||||||
}());
|
}());
|
||||||
</script>
|
</script>
|
||||||
<script>
|
<script>
|
||||||
window.__SHINE_BUILD_HASH__ = '20261113-dm-security-note-01';
|
window.__SHINE_BUILD_HASH__ = '20261116-client-error-reporting-v1';
|
||||||
window.__SHINE_CLIENT_VERSION__ = '1.20.9';
|
window.__SHINE_CLIENT_VERSION__ = '1.20.9';
|
||||||
</script>
|
</script>
|
||||||
<script>
|
<script>
|
||||||
|
|||||||
+38
-19
@@ -338,13 +338,15 @@ const GUEST_ALLOWED_PAGES = new Set([
|
|||||||
'queue',
|
'queue',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
setClientErrorTransport((payload) => authService.reportClientUiError(payload));
|
setClientErrorTransport((payload) => authService.reportClientError(payload));
|
||||||
setClientErrorSentNotifier((payload) => {
|
setClientErrorSentNotifier((payload) => {
|
||||||
// Технические подробности – только с включёнными инструментами разработчика.
|
// Для сбоев операций показываем подтверждение. Глобальные ошибки и сбои
|
||||||
if (!isDeveloperToolsEnabled()) return;
|
// отрисовки показывают свой статус отдельно, без второго уведомления.
|
||||||
const login = String(state.session.login || 'guest').trim();
|
if (payload.kind === 'global_error' || payload.kind === 'unhandled_rejection'
|
||||||
const isoTs = new Date(Number(payload?.clientTs || Date.now())).toISOString();
|
|| payload.kind === 'page_render_failure') return;
|
||||||
showToast(t('remaining.app.error_sent_to_server_login_time', { login, time: isoTs }));
|
if (payload.kind === 'api_server_error' || isDeveloperToolsEnabled()) {
|
||||||
|
showToast(t('remaining.app.error_report_received', { id: payload.errorId }), { kind: 'info' });
|
||||||
|
}
|
||||||
});
|
});
|
||||||
window.__SHINE_SEND_CLIENT_ERROR_TO_SERVER__ = (payload) => authService.reportClientError(payload);
|
window.__SHINE_SEND_CLIENT_ERROR_TO_SERVER__ = (payload) => authService.reportClientError(payload);
|
||||||
window.__SHINE_SEND_CLIENT_ERROR__ = window.__SHINE_SEND_CLIENT_ERROR_TO_SERVER__;
|
window.__SHINE_SEND_CLIENT_ERROR__ = window.__SHINE_SEND_CLIENT_ERROR_TO_SERVER__;
|
||||||
@@ -1323,15 +1325,16 @@ async function ensureSessionAfterWsReconnect() {
|
|||||||
return wsSessionRestoreInFlight;
|
return wsSessionRestoreInFlight;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Без инструментов разработчика – спокойное сообщение вместо окна со стеком вызовов,
|
// Без инструментов разработчика показываем простой итог отправки, не чаще раза в 30 сек.
|
||||||
// не чаще раза в полминуты (ошибка уже записана в журнал и отправлена на сервер).
|
|
||||||
let lastCrashNoticeAt = 0;
|
let lastCrashNoticeAt = 0;
|
||||||
function showGlobalErrorAlert(title, details = {}) {
|
function showGlobalErrorAlert(title, details = {}, sent = false, reportId = '') {
|
||||||
if (!isDeveloperToolsEnabled()) {
|
if (!isDeveloperToolsEnabled()) {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
if (now - lastCrashNoticeAt < 30000) return;
|
if (now - lastCrashNoticeAt < 30000) return;
|
||||||
lastCrashNoticeAt = now;
|
lastCrashNoticeAt = now;
|
||||||
showToast(t('remaining.app.something_went_wrong_error_details_were_sent_to_the_devel'), { kind: 'error' });
|
showToast(sent
|
||||||
|
? t('remaining.app.error_report_received', { id: reportId })
|
||||||
|
: t('remaining.app.error_report_not_sent'), { kind: 'error' });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const lines = [title];
|
const lines = [title];
|
||||||
@@ -1359,7 +1362,7 @@ window.addEventListener('error', (event) => {
|
|||||||
stack: event.error?.stack || '',
|
stack: event.error?.stack || '',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
captureClientError({
|
const reportPromise = captureClientError({
|
||||||
kind: 'global_error',
|
kind: 'global_error',
|
||||||
message: event.message || 'Global JS error',
|
message: event.message || 'Global JS error',
|
||||||
stack: event.error?.stack || '',
|
stack: event.error?.stack || '',
|
||||||
@@ -1377,14 +1380,17 @@ window.addEventListener('error', (event) => {
|
|||||||
&& !event.filename && !(event.error?.stack);
|
&& !event.filename && !(event.error?.stack);
|
||||||
if (isOpaqueCrossOriginError) return;
|
if (isOpaqueCrossOriginError) return;
|
||||||
|
|
||||||
showGlobalErrorAlert('Поймана глобальная ошибка UI', {
|
const reportId = getLastClientErrorPayload()?.errorId || '';
|
||||||
|
const details = {
|
||||||
message: event.message || 'Global JS error',
|
message: event.message || 'Global JS error',
|
||||||
stack: event.error?.stack || '',
|
stack: event.error?.stack || '',
|
||||||
sourceUrl: event.filename || '',
|
sourceUrl: event.filename || '',
|
||||||
lineNumber: event.lineno,
|
lineNumber: event.lineno,
|
||||||
columnNumber: event.colno,
|
columnNumber: event.colno,
|
||||||
pageId,
|
pageId,
|
||||||
});
|
};
|
||||||
|
if (isDeveloperToolsEnabled()) showGlobalErrorAlert('Поймана глобальная ошибка UI', details);
|
||||||
|
else void reportPromise.then((sent) => showGlobalErrorAlert('Ошибка UI', details, sent, reportId));
|
||||||
});
|
});
|
||||||
|
|
||||||
window.addEventListener('unhandledrejection', (event) => {
|
window.addEventListener('unhandledrejection', (event) => {
|
||||||
@@ -1400,7 +1406,7 @@ window.addEventListener('unhandledrejection', (event) => {
|
|||||||
stack: reason?.stack || '',
|
stack: reason?.stack || '',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
captureClientError({
|
const reportPromise = captureClientError({
|
||||||
kind: 'unhandled_rejection',
|
kind: 'unhandled_rejection',
|
||||||
message: reason?.message || String(reason || 'Unhandled promise rejection'),
|
message: reason?.message || String(reason || 'Unhandled promise rejection'),
|
||||||
stack: reason?.stack || '',
|
stack: reason?.stack || '',
|
||||||
@@ -1410,16 +1416,19 @@ window.addEventListener('unhandledrejection', (event) => {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
showGlobalErrorAlert('Пойман необработанный Promise reject', {
|
const reportId = getLastClientErrorPayload()?.errorId || '';
|
||||||
|
const details = {
|
||||||
message: reason?.message || String(reason || 'Unhandled promise rejection'),
|
message: reason?.message || String(reason || 'Unhandled promise rejection'),
|
||||||
stack: reason?.stack || '',
|
stack: reason?.stack || '',
|
||||||
pageId,
|
pageId,
|
||||||
reasonType: reason?.constructor?.name || typeof reason,
|
reasonType: reason?.constructor?.name || typeof reason,
|
||||||
});
|
};
|
||||||
|
if (isDeveloperToolsEnabled()) showGlobalErrorAlert('Пойман необработанный Promise reject', details);
|
||||||
|
else void reportPromise.then((sent) => showGlobalErrorAlert('Ошибка UI', details, sent, reportId));
|
||||||
});
|
});
|
||||||
|
|
||||||
function renderPageFailureFallback(pageId, error) {
|
function renderPageFailureFallback(pageId, error) {
|
||||||
captureClientError({
|
const reportPromise = captureClientError({
|
||||||
kind: 'page_render_failure',
|
kind: 'page_render_failure',
|
||||||
message: error?.message || 'Page render failed',
|
message: error?.message || 'Page render failed',
|
||||||
stack: error?.stack || '',
|
stack: error?.stack || '',
|
||||||
@@ -1443,13 +1452,23 @@ function renderPageFailureFallback(pageId, error) {
|
|||||||
details.className = 'meta-muted';
|
details.className = 'meta-muted';
|
||||||
details.textContent = t('remaining.app.screen_render', { page: pageId || t('remaining.app.unknown') });
|
details.textContent = t('remaining.app.screen_render', { page: pageId || t('remaining.app.unknown') });
|
||||||
|
|
||||||
|
const reportStatus = document.createElement('p');
|
||||||
|
reportStatus.className = 'meta-muted';
|
||||||
|
reportStatus.textContent = t('remaining.app.error_report_pending');
|
||||||
|
const reportId = getLastClientErrorPayload()?.errorId || '';
|
||||||
|
void reportPromise.then((sent) => {
|
||||||
|
if (reportStatus.isConnected) reportStatus.textContent = sent
|
||||||
|
? t('remaining.app.error_report_received', { id: reportId })
|
||||||
|
: t('remaining.app.error_report_not_sent');
|
||||||
|
});
|
||||||
|
|
||||||
const retry = document.createElement('button');
|
const retry = document.createElement('button');
|
||||||
retry.type = 'button';
|
retry.type = 'button';
|
||||||
retry.className = 'primary-btn';
|
retry.className = 'primary-btn';
|
||||||
retry.textContent = t('remaining.app.retry');
|
retry.textContent = t('remaining.app.retry');
|
||||||
retry.addEventListener('click', () => renderApp());
|
retry.addEventListener('click', () => renderApp());
|
||||||
|
|
||||||
card.append(title, details, retry);
|
card.append(title, details, reportStatus, retry);
|
||||||
wrap.append(card);
|
wrap.append(card);
|
||||||
screenEl.append(wrap);
|
screenEl.append(wrap);
|
||||||
|
|
||||||
@@ -2144,7 +2163,7 @@ const SESSION_HANDSHAKE_OPS = new Set([
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
authService.ws.setRequestGuard(async (op) => {
|
authService.ws.setRequestGuard(async (op) => {
|
||||||
if (SESSION_HANDSHAKE_OPS.has(op)) return;
|
if (op === 'ClientErrorLog' || SESSION_HANDSHAKE_OPS.has(op)) return;
|
||||||
if (!state.session.isAuthorized || authService.ws.isSessionReady()) return;
|
if (!state.session.isAuthorized || authService.ws.isSessionReady()) return;
|
||||||
await ensureSessionAfterWsReconnect();
|
await ensureSessionAfterWsReconnect();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -362,7 +362,7 @@
|
|||||||
"label_007": "Upload",
|
"label_007": "Upload",
|
||||||
"label_008": "Copy TX ID",
|
"label_008": "Copy TX ID",
|
||||||
"label_009": "Sending UI errors to the server",
|
"label_009": "Sending UI errors to the server",
|
||||||
"label_010": "For developers: When an interface error is enabled, it will automatically be sent to the server for diagnosis."
|
"label_010": "Critical interface errors and unexpected server failures are reported automatically. Passwords, private keys, and message contents are not included. Reports are not queued when offline."
|
||||||
},
|
},
|
||||||
"network_view": {
|
"network_view": {
|
||||||
"label_001": "Enter your username",
|
"label_001": "Enter your username",
|
||||||
@@ -4666,6 +4666,9 @@
|
|||||||
"could_not_switch_profile": "Could not switch profile.",
|
"could_not_switch_profile": "Could not switch profile.",
|
||||||
"your_session_has_expired_please_sign_in_again": "Your session has expired. Please sign in again.",
|
"your_session_has_expired_please_sign_in_again": "Your session has expired. Please sign in again.",
|
||||||
"something_went_wrong_error_details_were_sent_to_the_devel": "Something went wrong. Error details were sent to the developers. Please try again.",
|
"something_went_wrong_error_details_were_sent_to_the_devel": "Something went wrong. Error details were sent to the developers. Please try again.",
|
||||||
|
"error_report_pending": "Sending technical error details…",
|
||||||
|
"error_report_received": "The action failed. The server received error report {id}. Please try again.",
|
||||||
|
"error_report_not_sent": "Something went wrong. The error report could not reach the server. Check your connection and try again.",
|
||||||
"could_not_display_this_screen": "Could not display this screen",
|
"could_not_display_this_screen": "Could not display this screen",
|
||||||
"unknown": "unknown",
|
"unknown": "unknown",
|
||||||
"retry": "Retry",
|
"retry": "Retry",
|
||||||
|
|||||||
@@ -456,7 +456,7 @@
|
|||||||
"label_007": "Загрузить",
|
"label_007": "Загрузить",
|
||||||
"label_008": "Скопировать TX ID",
|
"label_008": "Скопировать TX ID",
|
||||||
"label_009": "Отправка UI-ошибок на сервер",
|
"label_009": "Отправка UI-ошибок на сервер",
|
||||||
"label_010": "Для разработчиков: при включении ошибки интерфейса будут автоматически отправляться на сервер для диагностики.",
|
"label_010": "Критические ошибки интерфейса и неожиданные отказы сервера автоматически отправляются для диагностики. Пароли, приватные ключи и содержимое сообщений не передаются. При отсутствии связи отправка не выполняется.",
|
||||||
"label_011": "Отправлять ошибки на сервер",
|
"label_011": "Отправлять ошибки на сервер",
|
||||||
"label_012": "Отмена",
|
"label_012": "Отмена",
|
||||||
"label_013": "Сохранить"
|
"label_013": "Сохранить"
|
||||||
@@ -4666,6 +4666,9 @@
|
|||||||
"could_not_switch_profile": "Не удалось переключить профиль.",
|
"could_not_switch_profile": "Не удалось переключить профиль.",
|
||||||
"your_session_has_expired_please_sign_in_again": "Ваша сессия устарела. Авторизируйтесь заново.",
|
"your_session_has_expired_please_sign_in_again": "Ваша сессия устарела. Авторизируйтесь заново.",
|
||||||
"something_went_wrong_error_details_were_sent_to_the_devel": "Что-то пошло не так. Сведения об ошибке уже отправлены разработчикам – попробуйте ещё раз.",
|
"something_went_wrong_error_details_were_sent_to_the_devel": "Что-то пошло не так. Сведения об ошибке уже отправлены разработчикам – попробуйте ещё раз.",
|
||||||
|
"error_report_pending": "Отправляем техническую информацию об ошибке…",
|
||||||
|
"error_report_received": "Не удалось выполнить действие. Отчёт об ошибке принят сервером (№ {id}). Попробуйте ещё раз.",
|
||||||
|
"error_report_not_sent": "Возникла ошибка. Не удалось передать отчёт на сервер. Проверьте соединение и повторите попытку.",
|
||||||
"could_not_display_this_screen": "Не удалось отрисовать экран",
|
"could_not_display_this_screen": "Не удалось отрисовать экран",
|
||||||
"unknown": "неизвестно",
|
"unknown": "неизвестно",
|
||||||
"retry": "Повторить",
|
"retry": "Повторить",
|
||||||
|
|||||||
@@ -3,10 +3,6 @@ import { openPaletteEditor } from '../components/palette-editor.js';
|
|||||||
import { resolveThemeMode } from '../services/theme-service.js';
|
import { resolveThemeMode } from '../services/theme-service.js';
|
||||||
import { createTopBar } from '../components/topbar.js';
|
import { createTopBar } from '../components/topbar.js';
|
||||||
import { addAppLogEntry, authService, state } from '../state.js';
|
import { addAppLogEntry, authService, state } from '../state.js';
|
||||||
import {
|
|
||||||
isClientErrorReportingEnabled,
|
|
||||||
setClientErrorReportingEnabled,
|
|
||||||
} from '../services/client-error-reporter.js';
|
|
||||||
import {
|
import {
|
||||||
canInstallPwa,
|
canInstallPwa,
|
||||||
isStandalonePwaMode,
|
isStandalonePwaMode,
|
||||||
@@ -217,19 +213,13 @@ function openUiErrorReportingModal() {
|
|||||||
const root = document.getElementById('modal-root');
|
const root = document.getElementById('modal-root');
|
||||||
if (!root) return;
|
if (!root) return;
|
||||||
|
|
||||||
const enabled = isClientErrorReportingEnabled();
|
|
||||||
root.innerHTML = `
|
root.innerHTML = `
|
||||||
<div class="modal" id="settings-ui-error-reporting-modal">
|
<div class="modal" id="settings-ui-error-reporting-modal">
|
||||||
<div class="modal-card stack">
|
<div class="modal-card stack">
|
||||||
<h3 class="modal-title">${t('dialogs.modals.developer_settings_view.label_009')}</h3>
|
<h3 class="modal-title">${t('dialogs.modals.developer_settings_view.label_009')}</h3>
|
||||||
<p class="meta-muted">${t('dialogs.modals.developer_settings_view.label_010')}</p>
|
<p class="meta-muted">${t('dialogs.modals.developer_settings_view.label_010')}</p>
|
||||||
<label class="row wrap-row" for="ui-error-reporting-toggle">
|
|
||||||
<input id="ui-error-reporting-toggle" type="checkbox" ${enabled ? 'checked' : ''} />
|
|
||||||
<span>${t('dialogs.modals.developer_settings_view.label_011')}</span>
|
|
||||||
</label>
|
|
||||||
<div class="form-actions-grid">
|
<div class="form-actions-grid">
|
||||||
<button class="secondary-btn" id="ui-error-reporting-cancel" type="button">${t('dialogs.modals.developer_settings_view.label_012')}</button>
|
<button class="primary-btn" id="ui-error-reporting-cancel" type="button">${t('dialogs.modals.developer_settings_view.label_006')}</button>
|
||||||
<button class="primary-btn" id="ui-error-reporting-save" type="button">${t('dialogs.modals.developer_settings_view.label_013')}</button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -237,11 +227,6 @@ function openUiErrorReportingModal() {
|
|||||||
|
|
||||||
const close = () => { root.innerHTML = ''; };
|
const close = () => { root.innerHTML = ''; };
|
||||||
root.querySelector('#ui-error-reporting-cancel')?.addEventListener('click', close);
|
root.querySelector('#ui-error-reporting-cancel')?.addEventListener('click', close);
|
||||||
root.querySelector('#ui-error-reporting-save')?.addEventListener('click', () => {
|
|
||||||
const checked = root.querySelector('#ui-error-reporting-toggle')?.checked === true;
|
|
||||||
setClientErrorReportingEnabled(checked);
|
|
||||||
close();
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function render({navigate, chrome}) {
|
export function render({navigate, chrome}) {
|
||||||
|
|||||||
@@ -3543,26 +3543,11 @@ export class AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async reportClientError(details) {
|
async reportClientError(details) {
|
||||||
|
// Ошибки не запускают переподключение: без открытого WS отчёт не отправляем.
|
||||||
|
if (this.ws?.ws?.readyState !== WebSocket.OPEN) return false;
|
||||||
try {
|
try {
|
||||||
const response = await this.ws.request('ClientErrorLog', details || {}, 3000);
|
const response = await this.ws.request('ClientErrorLog', details || {}, 3000);
|
||||||
return response?.status === 200;
|
return response?.status === 200 && response?.accepted === true;
|
||||||
} 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;
|
|
||||||
} catch {
|
} catch {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,83 +1,109 @@
|
|||||||
const MAX_CONTEXT_LEN = 2000;
|
// Единая диагностика технических ошибок UI. Без очереди и без пользовательского выключателя.
|
||||||
const RECENT_WINDOW_MS = 5000;
|
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 transport = null;
|
||||||
let transportDepth = 0;
|
let inFlight = 0;
|
||||||
const recentFingerprints = new Map();
|
const recentFingerprints = new Map();
|
||||||
let notifySent = null;
|
let notifySent = null;
|
||||||
let lastCapturedPayload = null;
|
let lastCapturedPayload = null;
|
||||||
|
|
||||||
function nowTs() {
|
function nowTs() { return Date.now(); }
|
||||||
return Date.now();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
// Диагностические строки не должны включать токены, пароли и длинные ключевые данные.
|
||||||
function cleanString(value, maxLen = 1000) {
|
function cleanString(value, maxLen = 1000) {
|
||||||
if (value == null) return '';
|
if (value == null) return '';
|
||||||
const normalized = String(value).replace(/\s+/g, ' ').trim();
|
const cleaned = String(value)
|
||||||
if (normalized.length <= maxLen) return normalized;
|
.replace(/https?:\/\/[^\s)]+/gi, (url) => {
|
||||||
return `${normalized.slice(0, Math.max(0, maxLen - 3))}...`;
|
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) {
|
function safePagePath() {
|
||||||
if (context == null) return '';
|
try { return cleanString(window.location?.pathname || '', 150); } catch { return ''; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeSource(value) {
|
||||||
try {
|
try {
|
||||||
const raw = JSON.stringify(context);
|
const url = new URL(String(value || ''), window.location.origin);
|
||||||
if (!raw) return '';
|
return cleanString(`${url.origin}${url.pathname}`, 240); // без query/hash
|
||||||
if (raw.length <= MAX_CONTEXT_LEN) return raw;
|
} catch { return ''; }
|
||||||
return `${raw.slice(0, MAX_CONTEXT_LEN - 3)}...`;
|
|
||||||
} catch (error) {
|
|
||||||
return cleanString(`context_json_error:${error?.message || error}`, MAX_CONTEXT_LEN);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function makeFingerprint(payload) {
|
// Только разрешённые технические поля: произвольный context может содержать DM/ключи.
|
||||||
return [
|
function safeContext(raw) {
|
||||||
payload.kind,
|
const obj = raw && typeof raw === 'object' ? raw : {};
|
||||||
payload.message,
|
const result = {};
|
||||||
payload.sourceUrl,
|
for (const key of ['pageId', 'reasonType', 'pageProtocol', 'timeoutMs', 'code', 'status']) {
|
||||||
payload.lineNumber,
|
const value = obj[key];
|
||||||
payload.columnNumber,
|
if (typeof value === 'string' || typeof value === 'number') result[key] = cleanString(value, 80);
|
||||||
payload.requestOp,
|
}
|
||||||
].join('|');
|
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) {
|
function errorId() {
|
||||||
const ts = nowTs();
|
const bytes = new Uint8Array(6);
|
||||||
const prev = recentFingerprints.get(fingerprint);
|
if (globalThis.crypto?.getRandomValues) globalThis.crypto.getRandomValues(bytes);
|
||||||
recentFingerprints.set(fingerprint, ts);
|
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()}`;
|
||||||
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 buildPayload(details = {}) {
|
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 {
|
return {
|
||||||
kind: cleanString(details.kind || 'client_error', 64),
|
errorId: errorId(),
|
||||||
message: cleanString(details.message || details.reason || 'Unknown client error', 500),
|
clientVersion: cleanString(window.__SHINE_BUILD_HASH__ || '', 80),
|
||||||
stack: cleanString(details.stack || details.error?.stack || '', 8000),
|
kind,
|
||||||
sourceUrl: cleanString(details.sourceUrl || details.fileName || '', 240),
|
message: cleanString(message, 500),
|
||||||
|
stack: cleanString(stack, 6000),
|
||||||
|
sourceUrl: safeSource(details.sourceUrl || details.fileName || ''),
|
||||||
lineNumber: Number.isFinite(details.lineNumber) ? details.lineNumber : null,
|
lineNumber: Number.isFinite(details.lineNumber) ? details.lineNumber : null,
|
||||||
columnNumber: Number.isFinite(details.columnNumber) ? details.columnNumber : null,
|
columnNumber: Number.isFinite(details.columnNumber) ? details.columnNumber : null,
|
||||||
route: cleanString(details.route || window.location?.hash || '', 200),
|
route: safePagePath(),
|
||||||
href: cleanString(details.href || window.location?.href || '', 240),
|
href: window.location?.origin || '', // без query/hash и данных из URL
|
||||||
userAgent: cleanString(details.userAgent || navigator.userAgent || '', 240),
|
userAgent: cleanString(navigator.userAgent || '', 240),
|
||||||
clientTs: Number.isFinite(details.clientTs) ? details.clientTs : nowTs(),
|
clientTs: Number.isFinite(details.clientTs) ? details.clientTs : nowTs(),
|
||||||
requestOp: cleanString(details.requestOp || '', 64),
|
requestOp: cleanString(details.requestOp || '', 64),
|
||||||
requestIdRef: cleanString(details.requestIdRef || '', 128),
|
requestIdRef: cleanString(details.requestIdRef || '', 128),
|
||||||
contextJson: stringifyContext({
|
contextJson: safeContext(details.context),
|
||||||
title: document.title || '',
|
|
||||||
pageVisibility: document.visibilityState || '',
|
|
||||||
...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) {
|
export function setClientErrorTransport(fn) {
|
||||||
transport = typeof fn === 'function' ? fn : null;
|
transport = typeof fn === 'function' ? fn : null;
|
||||||
}
|
}
|
||||||
@@ -87,55 +113,29 @@ export function setClientErrorSentNotifier(fn) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function getLastClientErrorPayload() {
|
export function getLastClientErrorPayload() {
|
||||||
if (!lastCapturedPayload) return null;
|
return lastCapturedPayload ? { ...lastCapturedPayload } : 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
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function captureClientError(details = {}) {
|
export async function captureClientError(details = {}) {
|
||||||
const payload = buildPayload(details);
|
const payload = buildPayload(details);
|
||||||
if (!payload.message) return false;
|
|
||||||
lastCapturedPayload = payload;
|
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 (!transport || details.skipTransport === true || inFlight >= MAX_IN_FLIGHT) return false;
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
transportDepth += 1;
|
inFlight += 1;
|
||||||
await transport(payload);
|
// Только положительное подтверждение ClientErrorLog означает запись на сервере.
|
||||||
|
const accepted = await transport(payload);
|
||||||
|
if (accepted !== true) return false;
|
||||||
if (notifySent) {
|
if (notifySent) {
|
||||||
try {
|
try { notifySent(payload); } catch { /* уведомление не должно ломать диагностику */ }
|
||||||
notifySent(payload);
|
|
||||||
} catch {
|
|
||||||
// ignore notifier errors
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
} catch (error) {
|
} catch {
|
||||||
console.warn('client error transport failed', error);
|
// Ошибка отправки не создаёт новый отчёт и не запускает повторную отправку.
|
||||||
return false;
|
return false;
|
||||||
} finally {
|
} finally {
|
||||||
transportDepth = Math.max(0, transportDepth - 1);
|
inFlight -= 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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'));
|
const error = new Error(t('remaining.websocket.this_page_uses_https_but_the_server_uses_ws_use_wss_for_th'));
|
||||||
captureClientError({
|
captureClientError({
|
||||||
kind: 'ws_mixed_content_blocked',
|
kind: 'ws_mixed_content_blocked',
|
||||||
|
skipTransport: true,
|
||||||
message: error.message,
|
message: error.message,
|
||||||
context: { url: this.url, pageProtocol: window.location.protocol },
|
context: { url: this.url, pageProtocol: window.location.protocol },
|
||||||
});
|
});
|
||||||
@@ -107,7 +108,8 @@ export class WsJsonClient {
|
|||||||
ws.addEventListener('error', () => {
|
ws.addEventListener('error', () => {
|
||||||
captureClientError({
|
captureClientError({
|
||||||
kind: 'ws_open_error',
|
kind: 'ws_open_error',
|
||||||
message: `Failed to connect WebSocket ${this.url}`,
|
skipTransport: true,
|
||||||
|
message: 'WebSocket connection failed',
|
||||||
context: { url: this.url },
|
context: { url: this.url },
|
||||||
});
|
});
|
||||||
reject(new Error(`Не удалось подключиться к ${this.url}`));
|
reject(new Error(`Не удалось подключиться к ${this.url}`));
|
||||||
@@ -191,7 +193,7 @@ export class WsJsonClient {
|
|||||||
captureClientError({
|
captureClientError({
|
||||||
kind: 'ws_bad_json',
|
kind: 'ws_bad_json',
|
||||||
message: 'Received non-JSON message from server',
|
message: 'Received non-JSON message from server',
|
||||||
context: { raw: String(raw).slice(0, 1000) },
|
context: { code: 'invalid_json' },
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -207,6 +209,18 @@ export class WsJsonClient {
|
|||||||
const slot = this.pending.get(requestId);
|
const slot = this.pending.get(requestId);
|
||||||
if (!slot) return;
|
if (!slot) return;
|
||||||
this.pending.delete(requestId);
|
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);
|
slot.resolve(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -238,6 +252,7 @@ export class WsJsonClient {
|
|||||||
if (pendingOps.length > 0) {
|
if (pendingOps.length > 0) {
|
||||||
captureClientError({
|
captureClientError({
|
||||||
kind: 'ws_closed',
|
kind: 'ws_closed',
|
||||||
|
skipTransport: true,
|
||||||
message,
|
message,
|
||||||
context: { url: this.url, pendingOps },
|
context: { url: this.url, pendingOps },
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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>/);
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user