forked from longtao.wu/droboticflow
🔧 Simplify diagnostics into anonymous connectivity checks
This commit is contained in:
parent
d586ffd0e6
commit
2379bd586c
@ -1,17 +1,27 @@
|
||||
# Customer connection diagnostics
|
||||
# Anonymous customer connectivity checks
|
||||
|
||||
The public `/diagnostics` route runs independently of account bootstrap, plugin initialization and browser storage. It sends no requests until the user starts a check. The platform header links to it; the login form does not display a diagnostic link; the annotation/review workbench opens it in a new tab with the current task IDs, leaving the editor untouched.
|
||||
`/diagnostics` is a public page independent of account/plugin initialization and browser storage. The login form has no diagnostic link; the platform/task entries and direct URL remain available.
|
||||
|
||||
Checks use the current same-origin session and fixed GET endpoints: health, identity, role-appropriate project listing, task status, compact left-camera timeline and a minimal authorized human-item diagnostic view. Task details and customer annotations are not downloaded by the human-item diagnostic view. Missing authentication skips protected checks. Supplier managers are identified explicitly rather than treated as annotators with a bad password. Existing tenant/task permissions remain authoritative.
|
||||
The page now runs the same three checks whether the customer is logged in or not:
|
||||
|
||||
Video verification uses native metadata loading, without autoplay or a `crossOrigin` attribute, so BOS fetch-CORS restrictions are not mistaken for playback failure. It stops on metadata, error, cancellation, or after eight seconds and detaches the source. A browser may read part of the media to obtain metadata; this is not a fixed-byte throughput benchmark and does not certify sustained playback or concurrent capacity. Aggregate acceptance items without a direct subject video are reported as skipped, not broken.
|
||||
1. A tiny fixed `/diagnostics-probe.json` resource with an expected marker.
|
||||
2. `/api/health`, verifying the expected healthy JSON response.
|
||||
3. `/api/auth/bootstrap-status`, verifying the public authentication-route response shape.
|
||||
|
||||
Each API check has an eight-second deadline and a two-MiB decoded JSON cap. The user can stop checks. No login attempts, password resets, task claiming, leases, annotation writes, submissions, customer-data creation/deletion or load tests are performed. Timeline reads can use the normal derived timeline cache; no business records are updated by diagnostics.
|
||||
Every request is a fixed GET with `credentials: omit`, no-store and a cache-busting parameter. No `/auth/me`, account, project, task, timeline or customer-media request is made. An unsigned session is not a fault and does not block any check. HTTP 200 alone is not sufficient: an HTML fallback or unrelated JSON fails the content check. Each attempt is bounded to eight seconds and 64 KiB; transient errors retry once and successful recovery is displayed as normal, with both attempts retained in the report. Cancellation stops remaining checks.
|
||||
|
||||
Reports are explicitly constructed from allowlisted fields: time, site origin, browser version/capabilities, frontend/API commit, task IDs, status, duration, static explanations and request IDs. They omit account names/phones, response bodies, cookies, authorization headers, signed URLs and annotations. Clipboard failures (including ordinary HTTP) have a download/manual-copy fallback. Reports remain in page memory until copied/downloaded; there is no automatic upload.
|
||||
Customer UI has only start/stop, a concise result and report download/copy. A successful result says **基础连接正常**, not that credentials or all business functions have passed. Technical details are confined to the downloadable report: timestamps, origin, frontend/API commit, browser identification, status, latency, attempt outcome and request IDs. Raw responses, account names/phones, credentials, task identifiers and private/signed video URLs are not exported. Reports are not automatically uploaded.
|
||||
|
||||
Server-generated 128-bit request IDs are returned on API responses. Only diagnostic-marked requests and login attempts get an additional structured log line containing ID, fixed category, HTTP status and elapsed time. Neither request URLs/bodies nor credentials are logged. Incoming request IDs are ignored. Login errors display the request ID for support correlation. This provides correlation for future reports, not retroactive proof of why an earlier password failed. Login policy, authorization and passwords are unchanged.
|
||||
No browser-version allowlist is used. HTTP, unavailable Web Locks, unavailable clipboard and blocked local storage do not mark connectivity as abnormal. Clipboard has download/manual-copy fallbacks; non-streaming fetch responses are supported. Missing essential checking APIs is reported as an incomplete check, not a proven network failure. Passing on one browser does not certify every old browser engine can render the application.
|
||||
|
||||
Validation: TypeScript, relevant Go regressions (including authorization and unchanged task contents), frontend unit checks (no writes, no secret export, timeouts, cancellation, denied roles/tasks, oversized responses), and synthetic browser checks for public access, authenticated checks, native video metadata, downloadable reports, blocked local storage and the absence of a diagnostic link in the login form. Existing unrelated frontend failures are compared against the pre-change baseline. Online verification is GET-only using existing authorized sessions, with all browser writes blocked.
|
||||
Scope limitations are recorded in the report: account/password validation, project permissions, private BOS video storage and concurrent capacity are not tested by this anonymous check. The authentication-route probe establishes reachability of the public auth route; it does not attempt login or prove that a specific password is correct. A genuine anonymous BOS video-path test would require a dedicated non-customer test object, separately approved before any storage upload. Do not expose customer videos or call a platform-hosted sample a successful BOS test.
|
||||
|
||||
Release: only the API image (which includes the web bundle) is changed. Save the preceding immutable image, deployment/config snapshots, source archive, checksums and a guarded inverse image patch under the private local verification directory. Do not restore whole deployments or customer data to roll back this feature. Push and PR remain separate approvals.
|
||||
Request tracing and the existing authorized minimal task-diagnostic API remain unchanged. Diagnostic-marked API requests and login attempts receive server-generated request IDs and sanitized log lines. No database mutation, account changes, task claiming, submission or load test is performed.
|
||||
|
||||
Validation uses synthetic browser responses and node tests: cookie-free requests even with an existing browser session, identical public checks without login/task gates, schema validation, bounded retries/timeouts/cancellation, secret-free export, ordinary HTTP with optional capabilities missing, clipboard fallback, compact layout and real outage reporting. Deployment and PR creation require separate user approval.
|
||||
|
||||
## 本地验证(2026-09-26)
|
||||
|
||||
- 免登录诊断单元测试 7 项通过;浏览器验证覆盖无登录、禁止存储、缺少可选功能、真实失败及检查能力缺失。
|
||||
- 前端类型检查、生产构建通过。完整前端测试 619 项,606 项通过,13 项既有基线失败(均不属于诊断模块)。
|
||||
- 本次仅本地修改,未部署公司集群、未改动客户数据。
|
||||
|
||||
1
public/diagnostics-probe.json
Normal file
1
public/diagnostics-probe.json
Normal file
@ -0,0 +1 @@
|
||||
{"diagnosticProbe":"droboticflow-connectivity-v1"}
|
||||
@ -1,224 +1,104 @@
|
||||
// Read-only, fixed-endpoint checks. Reports contain only explicitly selected
|
||||
// fields; never serialize an API payload, Error, URL, headers or browser storage.
|
||||
export const diagnosticID = (value, prefix) =>
|
||||
new RegExp(`^${prefix}-[a-zA-Z0-9-]{1,120}$`).test(String(value || "")) ? String(value) : "";
|
||||
// Public, fixed-endpoint checks. No identity, task, cookie or signed media data
|
||||
// is collected. A successful check proves connectivity, not valid credentials.
|
||||
export const traceID = (value) => (/^[a-f0-9]{32}$/.test(String(value || "")) ? String(value) : "");
|
||||
const roles = {
|
||||
admin: "管理员",
|
||||
supplier_manager: "供应商管理员",
|
||||
annotator: "标注员",
|
||||
quality_reviewer: "质检审核员",
|
||||
acceptance_reviewer: "最终验收员",
|
||||
};
|
||||
|
||||
export function httpDiagnosis(status) {
|
||||
if (status === 401) return "当前会话未通过验证,请重新登录;不能据此判断密码是否被修改。";
|
||||
if (status === 403) return "当前账号无此接口或任务权限,请核对角色及项目授权。";
|
||||
if (status === 404) return "目标不存在或接口不可用,请核对任务及页面版本。";
|
||||
if (status === 429) return "请求过于频繁,请稍后重试。";
|
||||
if (status >= 500) return "服务端返回异常,需要管理员结合请求编号排查。";
|
||||
return `接口返回 HTTP ${status},原因尚未确定。`;
|
||||
}
|
||||
|
||||
async function limitedJSON(response) {
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) throw new Error("invalid_body");
|
||||
async function boundedJSON(response) {
|
||||
if (!response.body?.getReader || typeof TextDecoder === "undefined") {
|
||||
const text = await response.text();
|
||||
if (text.length > 65536) throw new Error("unexpected_response");
|
||||
return JSON.parse(text);
|
||||
}
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let text = "",
|
||||
bytes = 0;
|
||||
size = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const part = await reader.read();
|
||||
if (part.done) break;
|
||||
bytes += part.value.byteLength;
|
||||
if (bytes > 2 * 1024 * 1024) throw new Error("large_body");
|
||||
text += decoder.decode(part.value, { stream: true });
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
size += value.byteLength;
|
||||
if (size > 65536) throw new Error("unexpected_response");
|
||||
text += decoder.decode(value, { stream: true });
|
||||
}
|
||||
text += decoder.decode();
|
||||
return JSON.parse(text);
|
||||
return JSON.parse(text + decoder.decode());
|
||||
} finally {
|
||||
await reader.cancel().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
export function probeVideoMetadata(path, signal, timeoutMs = 8000) {
|
||||
return new Promise((resolve) => {
|
||||
const video = document.createElement("video");
|
||||
video.preload = "metadata";
|
||||
video.muted = true;
|
||||
let finished = false;
|
||||
const finish = (result) => {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener("abort", cancelled);
|
||||
video.onloadedmetadata = null;
|
||||
video.onerror = null;
|
||||
video.pause();
|
||||
video.removeAttribute("src");
|
||||
video.load();
|
||||
resolve(result);
|
||||
};
|
||||
const cancelled = () => finish({ state: "skipped", message: "检查已停止。" });
|
||||
const timer = setTimeout(
|
||||
() => finish({ state: "warn", message: "8 秒内未读到视频信息;可能是网络、存储或媒体问题,尚不能确定原因。" }),
|
||||
timeoutMs,
|
||||
);
|
||||
video.onloadedmetadata = () =>
|
||||
finish({ state: "pass", message: "浏览器已读到视频信息;这不代表持续播放或多人并发已经通过。" });
|
||||
video.onerror = () =>
|
||||
finish({ state: "fail", message: `视频加载失败(媒体错误 ${video.error?.code || 0});需要结合接口结果排查。` });
|
||||
if (signal?.aborted) cancelled();
|
||||
else {
|
||||
signal?.addEventListener("abort", cancelled, { once: true });
|
||||
// Native video follows authorized redirects without requiring BOS fetch CORS.
|
||||
// No autoplay, crossOrigin attribute, arbitrary URL or signed URL export.
|
||||
video.src = path;
|
||||
video.load();
|
||||
}
|
||||
});
|
||||
}
|
||||
const probes = [
|
||||
{
|
||||
label: "网页资源",
|
||||
path: "/diagnostics-probe.json",
|
||||
accepts: (d) => d?.diagnosticProbe === "droboticflow-connectivity-v1",
|
||||
},
|
||||
{ label: "平台接口", path: "/api/health", accepts: (d) => d?.status === "ok" },
|
||||
{ label: "登录接口", path: "/api/auth/bootstrap-status", accepts: (d) => typeof d?.bootstrapRequired === "boolean" },
|
||||
];
|
||||
|
||||
/** @param {{ signal?: AbortSignal, onResult?: (entry: any) => void, fetcher?: typeof fetch, timeoutMs?: number }} options */
|
||||
export async function runConnectionDiagnostics({
|
||||
taskId = "",
|
||||
itemId = "",
|
||||
signal,
|
||||
onResult = (_entry) => {},
|
||||
fetcher = fetch,
|
||||
mediaProbe = probeVideoMetadata,
|
||||
timeoutMs = 8000,
|
||||
}) {
|
||||
} = {}) {
|
||||
const results = [];
|
||||
const add = (entry) => {
|
||||
results.push(entry);
|
||||
onResult(entry);
|
||||
};
|
||||
async function check(label, path, describe) {
|
||||
if (signal?.aborted) return null;
|
||||
const controller = new AbortController();
|
||||
const abort = () => controller.abort();
|
||||
signal?.addEventListener("abort", abort, { once: true });
|
||||
const timer = setTimeout(abort, timeoutMs);
|
||||
const started = performance.now();
|
||||
let status,
|
||||
requestId = "";
|
||||
try {
|
||||
const response = await fetcher(path, {
|
||||
method: "GET",
|
||||
credentials: "same-origin",
|
||||
cache: "no-store",
|
||||
redirect: "error",
|
||||
headers: { "X-Diagnostic-Request": "1", Accept: "application/json" },
|
||||
signal: controller.signal,
|
||||
});
|
||||
status = response.status;
|
||||
requestId = traceID(response.headers.get("X-Request-ID"));
|
||||
if (!response.ok) {
|
||||
await response.body?.cancel();
|
||||
add({
|
||||
label,
|
||||
state: status === 401 ? "warn" : "fail",
|
||||
status,
|
||||
requestId,
|
||||
ms: Math.round(performance.now() - started),
|
||||
message: httpDiagnosis(status),
|
||||
for (const probe of probes) {
|
||||
if (signal?.aborted) break;
|
||||
const attempts = [];
|
||||
// Retry a failed connection once to avoid treating a transient packet loss
|
||||
// as a permanent outage. Preserve both observations only in the report.
|
||||
for (let attempt = 0; attempt < 2 && !signal?.aborted; attempt++) {
|
||||
const controller = new AbortController();
|
||||
const abort = () => controller.abort();
|
||||
signal?.addEventListener("abort", abort, { once: true });
|
||||
const timer = setTimeout(abort, timeoutMs);
|
||||
const started = performance.now();
|
||||
const entry = { state: "fail", status: undefined, requestId: "", ms: 0, reason: "", buildCommit: undefined };
|
||||
try {
|
||||
const response = await fetcher(`${probe.path}?probe=${Date.now()}-${attempt}`, {
|
||||
method: "GET",
|
||||
credentials: "omit",
|
||||
cache: "no-store",
|
||||
redirect: "error",
|
||||
headers: { "X-Diagnostic-Request": "1", Accept: "application/json" },
|
||||
signal: controller.signal,
|
||||
});
|
||||
return null;
|
||||
entry.status = response.status;
|
||||
entry.requestId = traceID(response.headers.get("X-Request-ID"));
|
||||
if (!response.ok) {
|
||||
entry.reason = "http_status";
|
||||
await response.body?.cancel?.();
|
||||
} else {
|
||||
const data = await boundedJSON(response);
|
||||
entry.state = probe.accepts(data) ? "pass" : "fail";
|
||||
entry.reason = entry.state === "pass" ? "" : "unexpected_response";
|
||||
if (probe.path === "/api/health" && /^[a-f0-9]{7,40}$/.test(data?.buildCommit || ""))
|
||||
entry.buildCommit = data.buildCommit;
|
||||
}
|
||||
} catch {
|
||||
entry.reason = signal?.aborted ? "cancelled" : controller.signal.aborted ? "timeout" : "network_or_response";
|
||||
if (signal?.aborted) entry.state = "skipped";
|
||||
} finally {
|
||||
entry.ms = Math.round(performance.now() - started);
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener("abort", abort);
|
||||
}
|
||||
const value = await limitedJSON(response);
|
||||
const entry = describe(value);
|
||||
add({ label, ...entry, status, requestId, ms: Math.round(performance.now() - started) });
|
||||
return value;
|
||||
} catch (error) {
|
||||
add({
|
||||
label,
|
||||
state: signal?.aborted ? "skipped" : "warn",
|
||||
status,
|
||||
requestId,
|
||||
ms: Math.round(performance.now() - started),
|
||||
message: signal?.aborted
|
||||
? "检查已停止。"
|
||||
: error?.message === "large_body"
|
||||
? "响应超过 2 MB,已停止读取;不能据此认定任务损坏。"
|
||||
: controller.signal.aborted
|
||||
? "检查超时,尚不能区分网络或服务端延迟。"
|
||||
: "连接失败或响应无法读取,原因尚未确定。",
|
||||
});
|
||||
return null;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener("abort", abort);
|
||||
attempts.push(entry);
|
||||
if (entry.state === "pass" || entry.state === "skipped" || (entry.status >= 400 && entry.status < 500)) break;
|
||||
}
|
||||
if (!attempts.length) break;
|
||||
const last = attempts[attempts.length - 1];
|
||||
const result = {
|
||||
label: probe.label,
|
||||
state: last.state,
|
||||
message:
|
||||
last.state === "pass" ? "连接正常" : last.state === "skipped" ? "已停止" : "暂未连通,请将报告发给维护人员。",
|
||||
attempts,
|
||||
};
|
||||
results.push(result);
|
||||
onResult(result);
|
||||
}
|
||||
await check("平台连接", "/api/health", (data) => ({
|
||||
state: data.status === "ok" ? "pass" : "warn",
|
||||
message: data.status === "ok" ? "平台接口可达。" : "平台健康状态异常。",
|
||||
buildCommit: /^[a-f0-9]{7,40}$/.test(data.buildCommit || "") ? data.buildCommit : "unknown",
|
||||
}));
|
||||
const session = await check("登录状态", "/api/auth/me", (data) => ({
|
||||
state: data.user?.id ? "pass" : "warn",
|
||||
message: data.user?.id ? "当前浏览器登录会话有效。" : "未返回有效身份。",
|
||||
}));
|
||||
if (!session?.user?.id || signal?.aborted) {
|
||||
add({ label: "权限与任务", state: "skipped", message: "会话未验证,后续检查已跳过;请在同一网址登录后重试。" });
|
||||
return results;
|
||||
}
|
||||
const role = session.user.role;
|
||||
add({
|
||||
label: "账号角色",
|
||||
state: roles[role] ? "pass" : "warn",
|
||||
message:
|
||||
role === "supplier_manager"
|
||||
? "当前为供应商管理员,不能按标注员身份领取任务;这不是密码错误。"
|
||||
: `当前为${roles[role] || "未识别角色"}。`,
|
||||
});
|
||||
await check(
|
||||
"项目访问",
|
||||
role === "annotator" ? "/api/plugins/annotation-qa/claim-projects" : "/api/projects",
|
||||
(data) => {
|
||||
if (!Array.isArray(data.items)) return { state: "warn", message: "项目接口响应格式异常。" };
|
||||
return {
|
||||
state: data.items.length ? "pass" : "warn",
|
||||
message: `当前可见 ${data.items.length} 个项目${data.items.length ? ";具体领取或审查权限仍由对应接口判断。" : ",请核对项目授权。"}`,
|
||||
};
|
||||
},
|
||||
);
|
||||
const task = diagnosticID(taskId, "annotation-task");
|
||||
const item = diagnosticID(itemId, "human-item");
|
||||
if (task) {
|
||||
const data = await check("标注任务读取", `/api/plugins/annotation-qa/tasks/${task}?view=status`, () => ({
|
||||
state: "pass",
|
||||
message: "任务摘要可读取;未保存或修改任务。",
|
||||
}));
|
||||
if (data)
|
||||
await check(
|
||||
"左相机帧范围",
|
||||
`/api/plugins/annotation-qa/tasks/${task}/frame-timeline?camera=left&encoding=compact`,
|
||||
() => ({ state: "pass", message: "帧范围接口可读取。" }),
|
||||
);
|
||||
}
|
||||
if (item) {
|
||||
const data = await check("当前任务权限", `/api/human-items/${item}?view=diagnostics`, () => ({
|
||||
state: "pass",
|
||||
message: "任务可读取;报告不包含任务内容。",
|
||||
}));
|
||||
if (data?.item?.videoAvailable && !signal?.aborted) {
|
||||
const start = performance.now();
|
||||
const result = await mediaProbe(`/api/human-items/${item}/subject-content`, signal);
|
||||
add({ label: "左相机视频连接", ...result, ms: Math.round(performance.now() - start) });
|
||||
} else if (data && !signal?.aborted) {
|
||||
add({
|
||||
label: "左相机视频连接",
|
||||
state: "skipped",
|
||||
message: "该任务没有直接主视频(可能是汇总验收任务),请从具体切片或标注任务检查。",
|
||||
});
|
||||
}
|
||||
}
|
||||
if (!task && !item)
|
||||
add({
|
||||
label: "任务与视频",
|
||||
state: "skipped",
|
||||
message: "未提供有效任务编号。请从出问题的任务点击“当前任务连接诊断”。",
|
||||
});
|
||||
return results;
|
||||
}
|
||||
|
||||
@ -1,29 +1,10 @@
|
||||
import React, { useEffect, useRef, useState } from "react";
|
||||
import { diagnosticID, runConnectionDiagnostics, traceID } from "../lib/connection-diagnostics.js";
|
||||
import { runConnectionDiagnostics, traceID } from "../lib/connection-diagnostics.js";
|
||||
|
||||
type Result = {
|
||||
label: string;
|
||||
state: string;
|
||||
message: string;
|
||||
status?: number;
|
||||
requestId?: string;
|
||||
ms?: number;
|
||||
buildCommit?: string;
|
||||
};
|
||||
const labels: Record<string, string> = { pass: "正常", warn: "需核对", fail: "异常", skipped: "未检查" };
|
||||
const colors: Record<string, string> = {
|
||||
pass: "text-emerald-700",
|
||||
warn: "text-amber-700",
|
||||
fail: "text-red-600",
|
||||
skipped: "text-slate-500",
|
||||
};
|
||||
type Result = { label: string; state: string; message: string };
|
||||
const button = "rounded-lg border border-slate-300 px-4 py-2 disabled:opacity-40";
|
||||
|
||||
export default function Diagnostics() {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const [itemId, setItemId] = useState(diagnosticID(params.get("itemId"), "human-item"));
|
||||
const [taskId, setTaskId] = useState(diagnosticID(params.get("taskId"), "annotation-task"));
|
||||
const loginRequestId = traceID(params.get("requestId"));
|
||||
const [results, setResults] = useState<Result[]>([]);
|
||||
const [running, setRunning] = useState(false);
|
||||
const [report, setReport] = useState("");
|
||||
@ -40,44 +21,37 @@ export default function Diagnostics() {
|
||||
|
||||
async function start() {
|
||||
if (controller.current) return;
|
||||
const run = new AbortController();
|
||||
controller.current = run;
|
||||
setRunning(true);
|
||||
setResults([]);
|
||||
setReport("");
|
||||
setNotice("");
|
||||
const startedAt = new Date().toISOString();
|
||||
const browser = navigator.userAgent.match(/(?:Edg|Chrome|Firefox|Version)\/[\d.]+/g)?.join(" ") || "unknown";
|
||||
let storageAvailable = true;
|
||||
try {
|
||||
window.localStorage.getItem("droboticflow.theme");
|
||||
} catch {
|
||||
storageAvailable = false;
|
||||
}
|
||||
const environment = {
|
||||
storageAvailable,
|
||||
site: window.location.origin,
|
||||
browser,
|
||||
secureContext: window.isSecureContext,
|
||||
onlineHint: navigator.onLine,
|
||||
viewport: `${window.innerWidth}×${window.innerHeight}`,
|
||||
webLocksAvailable: Boolean(navigator.locks),
|
||||
browser: navigator.userAgent.match(/(?:Edg|Chrome|Firefox|Version|Safari|OPR)\/[\d.]+/g)?.join(" ") || "unknown",
|
||||
pageBuild: import.meta.env.VITE_APP_BUILD_COMMIT || "local",
|
||||
};
|
||||
try {
|
||||
const browserResult: Result = {
|
||||
label: "浏览器环境",
|
||||
state: storageAvailable && window.isSecureContext && navigator.locks ? "pass" : "warn",
|
||||
message: !storageAvailable
|
||||
? "浏览器阻止了本地存储访问,可能影响平台加载;诊断仍可继续。"
|
||||
: window.isSecureContext && navigator.locks
|
||||
? `浏览器 ${browser},工作台锁定功能可用。`
|
||||
: `浏览器 ${browser};当前页面缺少安全上下文或工作台锁定功能,部分专注操作可能不可用。这不代表密码错误。`,
|
||||
if (typeof fetch !== "function" || typeof AbortController !== "function") {
|
||||
const failure = {
|
||||
label: "基础连接",
|
||||
state: "skipped",
|
||||
message: "浏览器缺少检查所需功能,请下载报告交给维护人员。",
|
||||
};
|
||||
setResults([browserResult]);
|
||||
setResults([failure]);
|
||||
setNotice(failure.message);
|
||||
setReport(
|
||||
JSON.stringify(
|
||||
{ schema: 2, startedAt, environment, checks: [failure], reason: "missing_fetch_or_abort" },
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const run = new AbortController();
|
||||
controller.current = run;
|
||||
setRunning(true);
|
||||
try {
|
||||
const checks = await runConnectionDiagnostics({
|
||||
taskId,
|
||||
itemId,
|
||||
signal: run.signal,
|
||||
onResult: (row: Result) => {
|
||||
if (mounted.current) setResults((old) => [...old, row]);
|
||||
@ -87,84 +61,62 @@ export default function Diagnostics() {
|
||||
setReport(
|
||||
JSON.stringify(
|
||||
{
|
||||
schema: 1,
|
||||
schema: 2,
|
||||
startedAt,
|
||||
completedAt: new Date().toISOString(),
|
||||
cancelled: run.signal.aborted,
|
||||
environment,
|
||||
loginRequestId: loginRequestId || undefined,
|
||||
taskId: diagnosticID(taskId, "annotation-task") || undefined,
|
||||
itemId: diagnosticID(itemId, "human-item") || undefined,
|
||||
checks: [browserResult, ...checks],
|
||||
loginRequestId: traceID(new URLSearchParams(window.location.search).get("requestId")) || undefined,
|
||||
scope: "anonymous_connectivity",
|
||||
checks,
|
||||
notTested: ["account_password", "project_permissions", "private_video_storage", "concurrent_capacity"],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
} catch {
|
||||
if (mounted.current) setNotice("诊断未完成,请重试;尚不能确定故障原因。");
|
||||
if (mounted.current) setNotice("检查未完成,请重试。");
|
||||
} finally {
|
||||
controller.current = null;
|
||||
if (mounted.current) setRunning(false);
|
||||
}
|
||||
}
|
||||
function download() {
|
||||
const url = URL.createObjectURL(new Blob([report], { type: "application/json" }));
|
||||
const anchor = document.createElement("a");
|
||||
anchor.href = url;
|
||||
anchor.download = `connection-diagnostics-${Date.now()}.json`;
|
||||
anchor.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
try {
|
||||
const url = URL.createObjectURL(new Blob([report], { type: "application/json" }));
|
||||
const anchor = document.createElement("a");
|
||||
anchor.href = url;
|
||||
anchor.download = `connection-diagnostics-${Date.now()}.json`;
|
||||
document.body.appendChild(anchor);
|
||||
anchor.click();
|
||||
anchor.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
} catch {
|
||||
setNotice("请展开报告,手动复制发送给维护人员。");
|
||||
}
|
||||
}
|
||||
async function copy() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(report);
|
||||
setNotice("脱敏报告已复制。");
|
||||
setNotice("报告已复制。");
|
||||
} catch {
|
||||
setNotice("浏览器不支持自动复制,请下载报告,或展开下方报告手动复制。");
|
||||
setNotice("请下载报告,或展开报告手动复制。");
|
||||
}
|
||||
}
|
||||
const passed = !!report && results.length === 3 && results.every((r) => r.state === "pass");
|
||||
const failed = results.some((r) => r.state === "fail");
|
||||
return (
|
||||
<main className="min-h-screen bg-slate-50 p-4 text-slate-900 sm:p-8">
|
||||
<div className="mx-auto max-w-3xl space-y-5">
|
||||
<div className="mx-auto max-w-xl space-y-5">
|
||||
<header className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-semibold">连接诊断</h1>
|
||||
<h1 className="text-2xl font-semibold">连接检查</h1>
|
||||
<a href="/" className="text-sm text-blue-600 underline">
|
||||
返回平台
|
||||
</a>
|
||||
</header>
|
||||
<p className="text-sm leading-6 text-slate-600">
|
||||
请使用出现问题的同一个浏览器。仅检查连接及当前账号已有权限,不修改账号、领取任务或保存标注。不需要输入密码。
|
||||
</p>
|
||||
<section className="space-y-3 rounded-xl border border-slate-200 bg-white p-5">
|
||||
<details>
|
||||
<summary className="cursor-pointer text-sm">当前任务编号(从任务页进入时自动填写)</summary>
|
||||
<label className="mt-3 block text-sm">
|
||||
人工任务编号
|
||||
<input
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
value={itemId}
|
||||
disabled={running}
|
||||
onChange={(e) => setItemId(e.target.value)}
|
||||
placeholder="human-item-…"
|
||||
/>
|
||||
</label>
|
||||
<label className="mt-3 block text-sm">
|
||||
标注任务编号
|
||||
<input
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
value={taskId}
|
||||
disabled={running}
|
||||
onChange={(e) => setTaskId(e.target.value)}
|
||||
placeholder="annotation-task-…"
|
||||
/>
|
||||
</label>
|
||||
</details>
|
||||
<p className="text-xs leading-5 text-slate-500">
|
||||
有任务编号时会尝试读取左相机视频信息,最多等待 8
|
||||
秒,不自动播放。浏览器可能读取部分视频数据;此检查不是带宽或多人并发测试。
|
||||
</p>
|
||||
{loginRequestId && <p className="break-all text-xs">关联登录请求:{loginRequestId}</p>}
|
||||
<p className="text-sm text-slate-600">无需登录。请在出现问题的浏览器中检查,并将报告发送给维护人员。</p>
|
||||
<section className="space-y-4 rounded-xl border border-slate-200 bg-white p-5">
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<button className={`${button} bg-blue-600 text-white`} onClick={start} disabled={running}>
|
||||
{running ? "正在检查…" : "开始检查"}
|
||||
@ -174,49 +126,54 @@ export default function Diagnostics() {
|
||||
停止检查
|
||||
</button>
|
||||
)}
|
||||
<button className={button} disabled={!report || running} onClick={copy}>
|
||||
复制脱敏报告
|
||||
</button>
|
||||
<button className={button} disabled={!report || running} onClick={download}>
|
||||
下载脱敏报告
|
||||
</button>
|
||||
{!running && report && (
|
||||
<>
|
||||
<button className={button} onClick={download}>
|
||||
下载报告
|
||||
</button>
|
||||
<button className={button} onClick={copy}>
|
||||
复制报告
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
<section aria-live="polite" aria-label="检查结果" className="space-y-3">
|
||||
{results.map((row, index) => (
|
||||
<article key={index} className="rounded-xl border border-slate-200 bg-white p-4">
|
||||
<div className="flex justify-between gap-4">
|
||||
<h2 className="font-medium">{row.label}</h2>
|
||||
<span className={colors[row.state]}>{labels[row.state]}</span>
|
||||
<div aria-live="polite" aria-label="检查结果" className="space-y-3">
|
||||
{passed && <p className="font-medium text-emerald-700">基础连接正常</p>}
|
||||
{!running && failed && <p className="font-medium text-red-600">检测到连接问题,请发送报告协助排查。</p>}
|
||||
{results.map((row) => (
|
||||
<div key={row.label} className="flex justify-between gap-4 text-sm">
|
||||
<span>{row.label}</span>
|
||||
<span
|
||||
className={
|
||||
row.state === "pass" ? "text-emerald-700" : row.state === "fail" ? "text-red-600" : "text-slate-500"
|
||||
}
|
||||
>
|
||||
{row.state === "pass" ? "正常" : row.state === "fail" ? "未连通" : "未完成"}
|
||||
</span>
|
||||
</div>
|
||||
<p className="mt-2 text-sm leading-6">{row.message}</p>
|
||||
<p className="mt-1 break-all text-xs text-slate-500">
|
||||
{row.status ? `HTTP ${row.status} · ` : ""}
|
||||
{row.ms !== undefined ? `${row.ms} ms` : ""}
|
||||
{row.requestId ? ` · 请求编号 ${row.requestId}` : ""}
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
))}
|
||||
{!!report && !passed && !failed && (
|
||||
<p className="text-sm text-slate-500">检查未完成,可下载报告或重新检查。</p>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
{notice && (
|
||||
<p role="status" className="text-sm text-blue-700">
|
||||
{notice}
|
||||
</p>
|
||||
)}
|
||||
{passed && <p className="text-sm text-slate-600">若仍无法登录,请将报告和登录报错截图一起发送。</p>}
|
||||
{report && (
|
||||
<details>
|
||||
<summary className="cursor-pointer text-sm">查看脱敏报告</summary>
|
||||
<summary className="cursor-pointer text-sm text-slate-500">查看报告</summary>
|
||||
<textarea
|
||||
aria-label="脱敏报告"
|
||||
className="mt-2 h-64 w-full rounded border bg-white p-3 font-mono text-xs"
|
||||
aria-label="诊断报告"
|
||||
className="mt-2 h-52 w-full rounded border bg-white p-3 font-mono text-xs"
|
||||
readOnly
|
||||
value={report}
|
||||
/>
|
||||
</details>
|
||||
)}
|
||||
<p className="text-xs leading-6 text-slate-500">
|
||||
报告仅包含检查时间、版本、浏览器功能、任务编号和请求结果,不包含密码、登录凭证、标注内容或视频签名地址。它不能确定密码修改原因,也不会把连接失败直接归因于客户网络。
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
|
||||
@ -1,147 +1,91 @@
|
||||
// Synthetic local fixtures only. No customer data or mutating requests.
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs/promises";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { chromium } from "playwright";
|
||||
const base = process.env.DIAGNOSTICS_TEST_URL || "http://127.0.0.1:5197";
|
||||
assert(["127.0.0.1", "localhost"].includes(new URL(base).hostname));
|
||||
const output = "local-data/verification/customer-diagnostics-20260926";
|
||||
await fs.mkdir(output, { recursive: true });
|
||||
const out = "local-data/verification/anonymous-diagnostics-20260926";
|
||||
await fs.mkdir(out, { recursive: true });
|
||||
const browser = await chromium.launch({
|
||||
executablePath: "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
|
||||
headless: true,
|
||||
args: ["--no-proxy-server"],
|
||||
});
|
||||
const sample = output + "/synthetic-video.mp4";
|
||||
try { await fs.access(sample); } catch {
|
||||
execFileSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc2=size=160x120:rate=25:duration=1", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-movflags", "+faststart", sample]);
|
||||
}
|
||||
const video = await fs.readFile(sample);
|
||||
try {
|
||||
const page = await browser.newPage({ viewport: { width: 1050, height: 850 } });
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
let mode = "anonymous";
|
||||
const calls = [];
|
||||
await page.route(base + "/api/**", async (route) => {
|
||||
const request = route.request(),
|
||||
url = new URL(request.url());
|
||||
calls.push({ path: url.pathname, method: request.method() });
|
||||
assert.equal(request.method(), "GET", "diagnostics must never send writes");
|
||||
let data = {},
|
||||
status = 200;
|
||||
if (url.pathname === "/api/health") data = { status: "ok", buildCommit: "b".repeat(40) };
|
||||
else if (url.pathname === "/api/auth/me") {
|
||||
status = mode === "anonymous" ? 401 : 200;
|
||||
data =
|
||||
status === 401
|
||||
? { error: "private error" }
|
||||
: {
|
||||
user: {
|
||||
id: "user-fixture",
|
||||
role: mode === "supplier" ? "supplier_manager" : "annotator",
|
||||
phone: "13800000000",
|
||||
passwordHash: "SECRET_HASH",
|
||||
},
|
||||
};
|
||||
} else if (url.pathname.endsWith("projects")) data = { items: [{ name: "PRIVATE_PROJECT" }] };
|
||||
else if (url.pathname.endsWith("subject-content")) {
|
||||
return route.fulfill({
|
||||
status: 206,
|
||||
headers: {
|
||||
"Content-Type": "video/mp4",
|
||||
"Content-Range": `bytes 0-${video.length - 1}/${video.length}`,
|
||||
"Content-Length": String(video.length),
|
||||
"Accept-Ranges": "bytes",
|
||||
},
|
||||
body: video,
|
||||
});
|
||||
} else
|
||||
data = {
|
||||
item: {
|
||||
id: "human-item-fixture",
|
||||
videoAvailable: true,
|
||||
subject: { payload: { description: "PRIVATE_ANNOTATION" } },
|
||||
},
|
||||
task: { id: "annotation-task-fixture" },
|
||||
};
|
||||
return route.fulfill({ status, json: data, headers: { "X-Request-ID": "c".repeat(32) } });
|
||||
});
|
||||
await page.goto(
|
||||
base + "/diagnostics?itemId=human-item-fixture&taskId=annotation-task-fixture&requestId=" + "a".repeat(32),
|
||||
);
|
||||
await page
|
||||
.getByRole("heading", { name: "连接诊断", exact: true })
|
||||
.waitFor({ timeout: 15000 })
|
||||
.catch(async (e) => {
|
||||
console.error("page errors:", errors);
|
||||
console.error((await page.locator("body").innerText()).slice(0, 1600));
|
||||
await page.screenshot({ path: output + "/failure.png" });
|
||||
throw e;
|
||||
const ctx = await browser.newContext({ viewport: { width: 900, height: 740 } });
|
||||
await ctx.addCookies([{ name: "droboticflow_session", value: "PRIVATE_COOKIE", url: base }]);
|
||||
await ctx.addInitScript(() => {
|
||||
Object.defineProperty(window, "isSecureContext", { value: false });
|
||||
Object.defineProperty(navigator, "locks", { value: undefined });
|
||||
Object.defineProperty(navigator, "clipboard", { value: undefined });
|
||||
Object.defineProperty(window, "localStorage", {
|
||||
get() {
|
||||
throw new Error("blocked storage");
|
||||
},
|
||||
});
|
||||
assert.equal(calls.length, 0, "page must not invoke auth providers or automatic checks");
|
||||
});
|
||||
const page = await ctx.newPage(),
|
||||
calls = [],
|
||||
errors = [];
|
||||
let failed = false;
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const handle = async (route) => {
|
||||
const r = route.request(),
|
||||
u = new URL(r.url());
|
||||
assert.equal(r.method(), "GET");
|
||||
assert(!r.headers().cookie, "anonymous probes must not send session cookies");
|
||||
calls.push(u.pathname);
|
||||
assert(["/api/health", "/api/auth/bootstrap-status", "/diagnostics-probe.json"].includes(u.pathname));
|
||||
const data =
|
||||
u.pathname === "/api/health"
|
||||
? { status: "ok", buildCommit: "a".repeat(40) }
|
||||
: u.pathname.includes("bootstrap")
|
||||
? { bootstrapRequired: false }
|
||||
: { diagnosticProbe: "droboticflow-connectivity-v1" };
|
||||
await route.fulfill({ status: failed ? 503 : 200, json: data, headers: { "X-Request-ID": "a".repeat(32) } });
|
||||
};
|
||||
await page.route(base + "/api/**", handle);
|
||||
await page.route(base + "/diagnostics-probe.json*", handle);
|
||||
await page.goto(base + "/diagnostics?itemId=human-item-test&taskId=annotation-task-test");
|
||||
await page.getByRole("heading", { name: "连接检查" }).waitFor();
|
||||
assert.equal(calls.length, 0);
|
||||
await page.getByRole("button", { name: "开始检查", exact: true }).click();
|
||||
await page.getByRole("button", { name: "下载脱敏报告" }).waitFor();
|
||||
await page.waitForFunction(
|
||||
() =>
|
||||
!document.querySelector("button:nth-child(3)")?.disabled &&
|
||||
document.querySelector('textarea[aria-label="脱敏报告"]'),
|
||||
);
|
||||
let report = JSON.parse(await page.getByLabel("脱敏报告").inputValue());
|
||||
assert.equal(report.checks.find((r) => r.label === "登录状态").status, 401);
|
||||
assert.deepEqual(
|
||||
calls.map((r) => r.path),
|
||||
["/api/health", "/api/auth/me"],
|
||||
);
|
||||
mode = "annotator";
|
||||
calls.length = 0;
|
||||
await page.getByText("基础连接正常", { exact: true }).waitFor();
|
||||
assert.deepEqual(calls, ["/diagnostics-probe.json", "/api/health", "/api/auth/bootstrap-status"]);
|
||||
const report = JSON.parse(await page.getByLabel("诊断报告").inputValue());
|
||||
assert(report.checks.every((c) => c.state === "pass"));
|
||||
assert.doesNotMatch(await page.locator('[aria-label="检查结果"]').innerText(), /401|需核对|登录状态|锁定|版本/);
|
||||
assert.doesNotMatch(JSON.stringify(report), /PRIVATE_COOKIE|human-item-test|annotation-task-test/);
|
||||
await page.getByRole("button", { name: "复制报告" }).click();
|
||||
await page.getByRole("status").filter({ hasText: "请下载报告" }).waitFor();
|
||||
const event = page.waitForEvent("download");
|
||||
await page.getByRole("button", { name: "下载报告" }).click();
|
||||
const download = await event;
|
||||
assert.deepEqual(JSON.parse(await fs.readFile(await download.path(), "utf8")), report);
|
||||
await page.screenshot({ path: out + "/normal.png", fullPage: true });
|
||||
failed = true;
|
||||
await page.getByRole("button", { name: "开始检查", exact: true }).click();
|
||||
await page.waitForFunction(
|
||||
() => !Array.from(document.querySelectorAll("button")).find((x) => x.textContent === "下载脱敏报告")?.disabled,
|
||||
);
|
||||
report = JSON.parse(await page.getByLabel("脱敏报告").inputValue());
|
||||
assert.equal(report.checks.find((r) => r.label === "左相机视频连接").state, "pass");
|
||||
assert.doesNotMatch(JSON.stringify(report), /PRIVATE_|SECRET_HASH|13800000000|authorization=/);
|
||||
const downloadPromise = page.waitForEvent("download");
|
||||
await page.getByRole("button", { name: "下载脱敏报告" }).click();
|
||||
const download = await downloadPromise;
|
||||
const downloadPath = await download.path();
|
||||
assert.deepEqual(JSON.parse(await fs.readFile(downloadPath, "utf8")), report);
|
||||
await page.screenshot({ path: output + "/diagnostics.png", fullPage: true });
|
||||
mode = "supplier";
|
||||
await page.getByText("检测到连接问题,请发送报告协助排查。", { exact: true }).waitFor();
|
||||
assert.equal(await page.getByText("基础连接正常", { exact: true }).count(), 0);
|
||||
await page.setViewportSize({ width: 390, height: 740 });
|
||||
await page.screenshot({ path: out + "/failure-mobile.png", fullPage: true });
|
||||
await page.evaluate(() => {
|
||||
window.fetch = undefined;
|
||||
});
|
||||
await page.getByRole("button", { name: "开始检查", exact: true }).click();
|
||||
await page.waitForFunction(
|
||||
() => !Array.from(document.querySelectorAll("button")).find((x) => x.textContent === "下载脱敏报告")?.disabled,
|
||||
);
|
||||
report = JSON.parse(await page.getByLabel("脱敏报告").inputValue());
|
||||
assert.match(report.checks.find((r) => r.label === "账号角色").message, /供应商管理员/);
|
||||
mode = "anonymous";
|
||||
await page.goto(base + "/");
|
||||
await page.getByRole("heading", { name: "账号登录", exact: true }).waitFor();
|
||||
assert.equal(await page.getByRole("link", { name: "连接诊断(新窗口)" }).count(), 0);
|
||||
await page.addInitScript(() => { Object.defineProperty(window, "localStorage", { get() { throw new Error("blocked storage"); } }); });
|
||||
await page.goto(base + "/diagnostics");
|
||||
await page.getByRole("heading", { name: "连接诊断", exact: true }).waitFor();
|
||||
await page.getByRole("button", { name: "开始检查", exact: true }).click();
|
||||
await page.waitForFunction(() => !Array.from(document.querySelectorAll("button")).find(x => x.textContent === "下载脱敏报告")?.disabled);
|
||||
report = JSON.parse(await page.getByLabel("脱敏报告").inputValue());
|
||||
assert.equal(report.environment.storageAvailable, false);
|
||||
await page.getByText("检查未完成,可下载报告或重新检查。", { exact: true }).waitFor();
|
||||
assert.equal(await page.getByText("检测到连接问题,请发送报告协助排查。", { exact: true }).count(), 0);
|
||||
assert.equal(errors.length, 0, errors.join("\n"));
|
||||
await fs.writeFile(
|
||||
output + "/browser-report.json",
|
||||
out + "/browser-report.json",
|
||||
JSON.stringify(
|
||||
{
|
||||
passed: true,
|
||||
checks: [
|
||||
"public route bypasses auth providers",
|
||||
"no automatic requests",
|
||||
"anonymous checks",
|
||||
"authenticated role/projects/task/frames/media",
|
||||
"safe export and download",
|
||||
"supplier manager distinction",
|
||||
"GET only",
|
||||
"original login page without diagnostic link",
|
||||
"blocked local storage",
|
||||
"cookie-free public probes",
|
||||
"no login/task gate",
|
||||
"HTTP without optional features passes",
|
||||
"compact report and clipboard fallback",
|
||||
"real outages fail",
|
||||
"no render errors",
|
||||
],
|
||||
},
|
||||
@ -149,7 +93,7 @@ try {
|
||||
2,
|
||||
),
|
||||
);
|
||||
console.log("Diagnostic browser fixtures passed");
|
||||
console.log("Anonymous diagnostics browser regression passed");
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
@ -1,124 +1,85 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { runConnectionDiagnostics, diagnosticID } from "../../src/lib/connection-diagnostics.js";
|
||||
const json = (body, status = 200) =>
|
||||
new Response(JSON.stringify(body), { status, headers: { "X-Request-ID": "a".repeat(32) } });
|
||||
function fixture(role = "annotator") {
|
||||
import { runConnectionDiagnostics } from "../../src/lib/connection-diagnostics.js";
|
||||
const json = (data, status = 200) =>
|
||||
new Response(JSON.stringify(data), { status, headers: { "X-Request-ID": "a".repeat(32) } });
|
||||
const payload = (path) =>
|
||||
path.startsWith("/diagnostics-probe.json")
|
||||
? { diagnosticProbe: "droboticflow-connectivity-v1" }
|
||||
: path.startsWith("/api/health")
|
||||
? { status: "ok", buildCommit: "b".repeat(40) }
|
||||
: { bootstrapRequired: false };
|
||||
test("anonymous and authenticated browsers use identical public probes without cookies or account calls", async () => {
|
||||
const calls = [];
|
||||
const fetcher = async (path, options) => {
|
||||
calls.push({ path, ...options });
|
||||
if (path === "/api/health") return json({ status: "ok", buildCommit: "b".repeat(40), secret: "SECRET" });
|
||||
if (path === "/api/auth/me")
|
||||
return json({ user: { id: "user", role, phone: "13800000000", passwordHash: "HASH" } });
|
||||
if (path.endsWith("projects")) return json({ items: [{ name: "PRIVATE PROJECT" }] });
|
||||
return json({
|
||||
item: {
|
||||
videoAvailable: true,
|
||||
subject: {
|
||||
payload: { description: "PRIVATE ANNOTATION", signedUrl: "https://bos.test/private?authorization=SECRET" },
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
return { calls, fetcher };
|
||||
}
|
||||
test("authenticated diagnostics use only fixed GETs and never export payloads or signed links", async () => {
|
||||
const f = fixture();
|
||||
const results = await runConnectionDiagnostics({
|
||||
fetcher: f.fetcher,
|
||||
taskId: "annotation-task-test",
|
||||
itemId: "human-item-test",
|
||||
mediaProbe: async (path) => {
|
||||
assert.equal(path, "/api/human-items/human-item-test/subject-content");
|
||||
return { state: "pass", message: "media readable" };
|
||||
const checks = await runConnectionDiagnostics({
|
||||
fetcher: async (path, options) => {
|
||||
calls.push({ path, ...options });
|
||||
return json({ ...payload(path), passwordHash: "SECRET", phone: "13800000000" });
|
||||
},
|
||||
});
|
||||
assert.equal(results.length, 8);
|
||||
assert.ok(
|
||||
f.calls.every((c) => c.method === "GET" && !c.body && c.credentials === "same-origin" && c.redirect === "error"),
|
||||
);
|
||||
assert.ok(results.filter((r) => r.status).every((r) => r.requestId === "a".repeat(32)));
|
||||
assert.doesNotMatch(JSON.stringify(results), /SECRET|HASH|13800000000|PRIVATE|bos.test|authorization/);
|
||||
assert.equal(checks.length, 3);
|
||||
assert(checks.every((c) => c.state === "pass"));
|
||||
assert(calls.every((c) => c.method === "GET" && c.credentials === "omit" && !c.body && c.cache === "no-store"));
|
||||
assert(!calls.some((c) => /auth\/me|human-items|tasks|projects/.test(c.path)));
|
||||
assert.doesNotMatch(JSON.stringify(checks), /SECRET|13800000000|passwordHash/);
|
||||
});
|
||||
test("unauthenticated users can check health and session without requesting projects/tasks/media", async () => {
|
||||
const calls = [];
|
||||
const results = await runConnectionDiagnostics({
|
||||
itemId: "human-item-test",
|
||||
fetcher: async (p) => {
|
||||
calls.push(p);
|
||||
return p.endsWith("health") ? json({ status: "ok" }) : json({ error: "sensitive text" }, 401);
|
||||
test("a transient failure is retried and recovered connection passes while preserving evidence", async () => {
|
||||
let first = true;
|
||||
const checks = await runConnectionDiagnostics({
|
||||
fetcher: async (path) => {
|
||||
if (first) {
|
||||
first = false;
|
||||
throw new Error("private-secret-url");
|
||||
}
|
||||
return json(payload(path));
|
||||
},
|
||||
mediaProbe: async () => assert.fail("must not load media"),
|
||||
});
|
||||
assert.deepEqual(calls, ["/api/health", "/api/auth/me"]);
|
||||
assert.match(results[1].message, /会话/);
|
||||
assert.equal(results.at(-1).state, "skipped");
|
||||
assert.equal(checks[0].state, "pass");
|
||||
assert.equal(checks[0].attempts.length, 2);
|
||||
assert.equal(checks[0].attempts[0].reason, "network_or_response");
|
||||
assert.doesNotMatch(JSON.stringify(checks), /secret/);
|
||||
});
|
||||
test("supplier managers are not diagnosed as failed annotator login", async () => {
|
||||
const f = fixture("supplier_manager");
|
||||
const results = await runConnectionDiagnostics({ fetcher: f.fetcher });
|
||||
assert.ok(f.calls.some((c) => c.path === "/api/projects"));
|
||||
assert.ok(!f.calls.some((c) => c.path.includes("claim-projects")));
|
||||
assert.match(results.find((r) => r.label === "账号角色").message, /不能按标注员/);
|
||||
});
|
||||
test("403 task never triggers media and arbitrary task URLs cannot be fetched", async () => {
|
||||
const f = fixture();
|
||||
const results = await runConnectionDiagnostics({
|
||||
itemId: "human-item-test",
|
||||
taskId: "../../admin/users",
|
||||
fetcher: (p, o) => (p.includes("/human-items/") ? json({}, 403) : f.fetcher(p, o)),
|
||||
mediaProbe: async () => assert.fail("must not load media"),
|
||||
test("public route authorization failures are real failures, not mistaken for expected unsigned session", async () => {
|
||||
const checks = await runConnectionDiagnostics({
|
||||
fetcher: async (path) => (path.includes("bootstrap") ? json({}, 401) : json(payload(path))),
|
||||
});
|
||||
assert.equal(results.find((r) => r.label === "当前任务权限").status, 403);
|
||||
assert.equal(diagnosticID("human-item-test?secret=x", "human-item"), "");
|
||||
assert.ok(!f.calls.some((c) => c.path.includes("admin")));
|
||||
assert.equal(checks[2].state, "fail");
|
||||
assert.equal(checks[2].attempts.length, 1);
|
||||
});
|
||||
test("timeouts are bounded and cancellation stops subsequent checks", async () => {
|
||||
const controller = new AbortController();
|
||||
test("cancellation halts future checks and cannot become an all-pass report", async () => {
|
||||
const c = new AbortController();
|
||||
let calls = 0;
|
||||
const results = await runConnectionDiagnostics({
|
||||
signal: controller.signal,
|
||||
const checks = await runConnectionDiagnostics({
|
||||
signal: c.signal,
|
||||
timeoutMs: 20,
|
||||
fetcher: async (_p, o) => {
|
||||
calls++;
|
||||
return new Promise((_resolve, reject) =>
|
||||
o.signal.addEventListener("abort", () => reject(new DOMException("abort", "AbortError"))),
|
||||
);
|
||||
return new Promise((_, reject) => o.signal.addEventListener("abort", () => reject(new Error("abort"))));
|
||||
},
|
||||
onResult: () => controller.abort(),
|
||||
onResult: () => c.abort(),
|
||||
});
|
||||
assert.equal(calls, 1);
|
||||
assert.match(results[0].message, /超时/);
|
||||
assert.equal(calls, 2);
|
||||
assert.equal(checks.length, 1);
|
||||
assert.equal(checks[0].state, "fail");
|
||||
assert.equal(checks[0].attempts[1].reason, "timeout");
|
||||
});
|
||||
test("large customer payloads are cancelled and not copied into reports", async () => {
|
||||
const f = fixture();
|
||||
let cancelled = false;
|
||||
const results = await runConnectionDiagnostics({
|
||||
itemId: "human-item-test",
|
||||
fetcher: (p, o) =>
|
||||
!p.includes("/human-items/")
|
||||
? f.fetcher(p, o)
|
||||
: new Response(
|
||||
new ReadableStream({
|
||||
start(c) {
|
||||
c.enqueue(new Uint8Array(2 * 1024 * 1024 + 1));
|
||||
},
|
||||
cancel() {
|
||||
cancelled = true;
|
||||
},
|
||||
}),
|
||||
),
|
||||
mediaProbe: async () => assert.fail("must not load unverified media"),
|
||||
test("HTML fallback and oversized bodies never give false success", async () => {
|
||||
const checks = await runConnectionDiagnostics({ fetcher: async () => new Response("x".repeat(70000)) });
|
||||
assert(checks.every((c) => c.state === "fail"));
|
||||
assert.doesNotMatch(JSON.stringify(checks), /xxxx/);
|
||||
});
|
||||
test("browsers without streaming response readers still pass valid public checks", async () => {
|
||||
const checks = await runConnectionDiagnostics({
|
||||
fetcher: async (path) => ({
|
||||
ok: true,
|
||||
status: 200,
|
||||
headers: new Headers(),
|
||||
text: async () => JSON.stringify(payload(path)),
|
||||
}),
|
||||
});
|
||||
assert.equal(cancelled, true);
|
||||
assert.match(results.find((r) => r.label === "当前任务权限").message, /超过 2 MB/);
|
||||
assert(checks.every((c) => c.state === "pass"));
|
||||
});
|
||||
test("network failures do not blame customer or leak error details", async () => {
|
||||
const results = await runConnectionDiagnostics({
|
||||
fetcher: async () => {
|
||||
throw new Error("https://secret?token=PRIVATE");
|
||||
},
|
||||
});
|
||||
assert.doesNotMatch(JSON.stringify(results), /PRIVATE|secret/);
|
||||
assert.match(results[0].message, /原因尚未确定/);
|
||||
test("HTTP 200 with unrelated JSON is not mistaken for successful connectivity", async () => {
|
||||
const checks = await runConnectionDiagnostics({ fetcher: async () => json({ unrelated: true }) });
|
||||
assert(checks.every((c) => c.state === "fail"));
|
||||
});
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user