Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。
feat(web): add bounded connection self-check (#169)
AAA42397e18ce03
diff --git a/docs/research/low-server-media-routes.md b/docs/research/low-server-media-routes.mdindex c0649b72..9ccc87c5 100644--- a/docs/research/low-server-media-routes.md+++ b/docs/research/low-server-media-routes.md@@ -351,6 +351,25 @@ old connection or ICE-restart history from being attributed to a new route.Use opaque generations only. This is a bounded diagnostic manifest, not abackend telemetry schema or controller input.+### Pre-Share Self-Check Boundary++A temporary, unpaired `RTCPeerConnection` can create a data channel, set its+local offer, and inspect only `RTCIceCandidate.type`. Gathering a `srflx`+candidate proves that the browser received a STUN response for this generation;+it proves neither a usable peer candidate pair nor bandwidth, latency, NAT type,+or media quality. A same-origin WebSocket open followed by immediate close proves+only the signaling handshake. Neither probe creates a Screener room or media+edge, and both discard their temporary resources.++Pinned LiveKit `Room.prepareConnection(url)` without a token performs an HTTP+`HEAD`; it does not establish ICE/UDP. A real LiveKit transport requires a token+and participant connection, which would create the room/SFU state this pre-share+check deliberately avoids. The UI therefore reports configured SFU as unknown+until an actual controller-selected route proves current-generation media. The+public, `no-store` self-check config returns only the existing STUN-only+`iceConfig` and an SFU-configured boolean. It returns no SFU or TURN URL, token,+username, credential, address, candidate, or selected-edge grant.+## SFU/UDP And Selected-Edge TURNEvery ordinary bounded peer `RTCPeerConnection` uses STUN-only ICE. Failurediff --git "a/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md" "b/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"index a6019fdb..e86be217 100644--- "a/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"+++ "b/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"@@ -53,7 +53,7 @@- [ ] SFU-root 中央兜底:产品部署目标必须提供经 canary 验收的单节点 SFU 资源;系统在 direct/peer UDP 不可用或明确拓扑预算无法接纳时自动把它作为主要中央兜底,不要求用户选模式。它只向总计一至两个必要 roots 出口;root 优先承担受限 peer descendants,没有可靠 relay root 时必要 viewer 只作为同一总上限内的零 descendants root。已关闭 PR #12 的显式整房 SFU 模式已被取代。room `1` 的历史 smoke 没有 retained SFU media;公网媒体、资源和恢复门禁仍适用于全站路由。- [ ] 分享端桌面封装:用 Electron 固定 Chromium 版本、改善选源/热键/系统音频体验,同时保留 Web 观看端。- [ ] Windows 应用音频:Windows 11 Native sender 使用本地 opaque window target 绑定 HWND、PID 与进程创建时间,只捕获所选游戏及其子进程的音频,避免把语音聊天或通知声一并分享;“全部系统声音”只能由分享者显式选择。普通 Windows 10 不具备当前 process-loopback API 门槛,必须明确标为未解决/不支持而不是伪兼容。浏览器无法证明或隔离任意进程音频时必须如实提示,原生捕获失败、无声或进程退出不得静默扩大为整机捕获。-- [ ] 连接自检:在开始分享前验证信令、STUN 和 SFU ICE/UDP 可达性,并给出不暴露地址或凭据的诊断结果。启用 selected-edge TURN canary 时只报告脱敏的授权阶段与 selected candidate type,不输出 URL、username、credential、地址或原始 candidate;自检只覆盖当前 UDP 媒体梯级。+- [ ] 连接自检:开始分享前的本地自检先用无房间、无媒体、无凭据的临时资源验证站点健康、WSS 握手和当前部署 STUN 是否实际 gathered `srflx`;结果不得显示地址、URL、原始 candidate 或把 candidate gathering 称为带宽、性能或端到端可达。仅配置 SFU 时必须显示“已配置,需实际路由验证”,因为 token-free HTTP 预热不能证明 SFU ICE/UDP,真实 SFU/UDP canary 仍是未完成验收。启用 selected-edge TURN canary 时只报告脱敏的授权阶段与 selected candidate type,不输出 URL、username、credential、地址或原始 candidate;自检只覆盖当前 UDP 媒体梯级。- [ ] 受限网络增强:短期鉴权 TURN 只能由完整、默认关闭的部署 tuple 与当前 room controller 启用,并且只能在 direct/peer UDP 与 SFU/UDP 均已按有界梯级失败后,向 controller 选中的当前异常 edge 一次性授权。普通 peer PC 从创建起保持 STUN-only;不得向整个 participant、房间或所有 peer connections 预发 TURN candidates。凭据必须绑定当前授权 session 与 route/connection generation、短期有效、内存态、一次性消费且不进入 URL、日志、浏览器持久化或 SQLite。媒体保持 UDP-only,全部路径耗尽后明确失败;TURN 不得被描述为更高清的传输方式。- [x] Web 编码选择:高级视频设置提供 `自动 | H.264 | VP8`,默认自动使用浏览器/LiveKit 协商;显式选择只在下一次分享前用标准 codec preference 生效。直播中控件锁定并明确提示停止分享后可修改。P2P/浏览器 relay 保留完整 repair 与其他 codec 回退列表,SFU 保持 `backupCodec = false`,不维护第二套应用编码链。实际 codec/profile、encoder implementation 与 stats 是结果真相;H.264 可选不等于浏览器必走硬编,AV1 仍不得仅凭压缩率推断默认启用。- [ ] 诊断页面:用户可导出不含敏感地址和凭据的连接诊断信息。diff --git a/src/client/components/ConnectionSelfCheck.tsx b/src/client/components/ConnectionSelfCheck.tsxnew file mode 100644index 00000000..dae74072--- /dev/null+++ b/src/client/components/ConnectionSelfCheck.tsx@@ -0,0 +1,94 @@+import { Check, CircleHelp, LoaderCircle, Network, X } from "lucide-react";+import { useLayoutEffect, useRef, useState } from "react";++import {+ runConnectionSelfCheck,+ type ConnectionProbeResult,+ type ConnectionSelfCheckResult,+} from "../media/connection-self-check";++const labels: Record<keyof ConnectionSelfCheckResult, string> = {+ site: "站点",+ signaling: "信令",+ stun: "STUN",+ sfu: "SFU/UDP",+};++function ProbeIcon({ result }: { result: ConnectionProbeResult }) {+ if (result.status === "passed") return <Check size={14} aria-hidden="true" />;+ if (result.status === "failed") return <X size={14} aria-hidden="true" />;+ return <CircleHelp size={14} aria-hidden="true" />;+}++export function ConnectionSelfCheck() {+ const [running, setRunning] = useState(false);+ const [result, setResult] = useState<ConnectionSelfCheckResult | null>(null);+ const runGeneration = useRef(0);+ const controller = useRef<AbortController | null>(null);+ useLayoutEffect(+ () => () => {+ ++runGeneration.current;+ controller.current?.abort();+ controller.current = null;+ },+ [],+ );++ async function run(): Promise<void> {+ controller.current?.abort();+ const nextController = new AbortController();+ controller.current = nextController;+ const generation = ++runGeneration.current;+ setRunning(true);+ try {+ const next = await runConnectionSelfCheck({+ signal: nextController.signal,+ });+ if (+ !nextController.signal.aborted &&+ runGeneration.current === generation+ ) {+ setResult(next);+ }+ } finally {+ if (controller.current === nextController) {+ controller.current = null;+ setRunning(false);+ }+ }+ }++ return (+ <div className="connection-self-check">+ <button+ className="button button-secondary"+ type="button"+ disabled={running}+ onClick={() => void run()}+ >+ {running ? (+ <LoaderCircle className="spin" size={16} aria-hidden="true" />+ ) : (+ <Network size={16} aria-hidden="true" />+ )}+ {running ? "正在自检" : "连接自检"}+ </button>+ {result && (+ <div className="connection-self-check-results" role="status">+ {(Object.keys(labels) as Array<keyof ConnectionSelfCheckResult>).map(+ (key) => (+ <div+ className={`connection-self-check-result is-${result[key].status}`}+ key={key}+ >+ <ProbeIcon result={result[key]} />+ <strong>{labels[key]}</strong>+ <span>{result[key].detail}</span>+ </div>+ ),+ )}+ </div>+ )}+ </div>+ );+}diff --git a/src/client/media/connection-self-check.ts b/src/client/media/connection-self-check.tsnew file mode 100644index 00000000..2b28f6f3--- /dev/null+++ b/src/client/media/connection-self-check.ts@@ -0,0 +1,263 @@+import { iceConfigSchema, type IceConfig } from "../../shared/protocol";++export type ConnectionProbeStatus = "passed" | "failed" | "unknown";++export interface ConnectionProbeResult {+ status: ConnectionProbeStatus;+ detail: string;+}++export interface ConnectionSelfCheckResult {+ site: ConnectionProbeResult;+ signaling: ConnectionProbeResult;+ stun: ConnectionProbeResult;+ sfu: ConnectionProbeResult;+}++interface SelfCheckConfig {+ iceConfig: IceConfig;+ sfuConfigured: boolean;+}++interface ConnectionSelfCheckOptions {+ baseUrl?: string;+ fetcher?: typeof fetch;+ socketFactory?: (url: string) => WebSocket;+ peerFactory?: (configuration: RTCConfiguration) => RTCPeerConnection;+ signal?: AbortSignal;+ timeoutMs?: number;+}++const passed = (detail: string): ConnectionProbeResult => ({+ status: "passed",+ detail,+});+const failed = (detail: string): ConnectionProbeResult => ({+ status: "failed",+ detail,+});+const unknown = (detail: string): ConnectionProbeResult => ({+ status: "unknown",+ detail,+});+const cancelled = () => failed("自检已取消");++function cancelledCheck(): ConnectionSelfCheckResult {+ return {+ site: cancelled(),+ signaling: cancelled(),+ stun: cancelled(),+ sfu: unknown("配置状态未知"),+ };+}++async function readSelfCheckConfig(+ fetcher: typeof fetch,+ signal: AbortSignal,+): Promise<SelfCheckConfig> {+ const response = await fetcher("/api/connection-self-check", {+ cache: "no-store",+ headers: { Accept: "application/json" },+ signal,+ });+ if (!response.ok) throw new Error("self-check config unavailable");+ const value: unknown = await response.json();+ if (!value || typeof value !== "object") {+ throw new Error("invalid self-check config");+ }+ const record = value as Record<string, unknown>;+ const iceConfig = iceConfigSchema.safeParse(record.iceConfig);+ if (!iceConfig.success || typeof record.sfuConfigured !== "boolean") {+ throw new Error("invalid self-check config");+ }+ return { iceConfig: iceConfig.data, sfuConfigured: record.sfuConfigured };+}++async function probeSite(+ fetcher: typeof fetch,+ signal: AbortSignal,+): Promise<ConnectionProbeResult> {+ try {+ const response = await fetcher("/healthz", {+ cache: "no-store",+ headers: { Accept: "application/json" },+ signal,+ });+ const body: unknown = await response.json();+ return response.ok &&+ !!body &&+ typeof body === "object" &&+ (body as Record<string, unknown>).status === "ok"+ ? passed("站点健康")+ : failed("站点健康检查失败");+ } catch {+ return failed("站点不可达");+ }+}++function probeSignaling(+ url: string,+ socketFactory: (url: string) => WebSocket,+ signal: AbortSignal,+ timeoutMs: number,+): Promise<ConnectionProbeResult> {+ return new Promise((resolve) => {+ let settled = false;+ let socket: WebSocket | null = null;+ let timer: ReturnType<typeof setTimeout> | null = null;+ const finish = (result: ConnectionProbeResult) => {+ if (settled) return;+ settled = true;+ if (timer) clearTimeout(timer);+ signal.removeEventListener("abort", onAbort);+ const activeSocket = socket;+ socket = null;+ activeSocket?.close(1000, "self-check");+ resolve(result);+ };+ const onAbort = () => finish(cancelled());+ signal.addEventListener("abort", onAbort, { once: true });+ if (signal.aborted) {+ onAbort();+ return;+ }+ timer = setTimeout(() => finish(failed("WSS 握手超时")), timeoutMs);+ try {+ const createdSocket = socketFactory(url);+ if (settled) {+ createdSocket.close(1000, "self-check");+ return;+ }+ socket = createdSocket;+ socket.addEventListener("open", () => finish(passed("WSS 可达")), {+ once: true,+ });+ socket.addEventListener("error", () => finish(failed("WSS 不可达")), {+ once: true,+ });+ socket.addEventListener("close", () => finish(failed("WSS 不可达")), {+ once: true,+ });+ } catch {+ finish(failed("WSS 不可达"));+ }+ });+}++function probeStun(+ iceConfig: IceConfig,+ peerFactory: (configuration: RTCConfiguration) => RTCPeerConnection,+ signal: AbortSignal,+ timeoutMs: number,+): Promise<ConnectionProbeResult> {+ if (signal.aborted) {+ return Promise.resolve(cancelled());+ }+ if (iceConfig.iceServers.length === 0) {+ return Promise.resolve(unknown("当前未配置 STUN"));+ }+ return new Promise((resolve) => {+ let settled = false;+ let peer: RTCPeerConnection | null = null;+ let timer: ReturnType<typeof setTimeout> | null = null;+ const finish = (result: ConnectionProbeResult) => {+ if (settled) return;+ settled = true;+ if (timer) clearTimeout(timer);+ signal.removeEventListener("abort", onAbort);+ const activePeer = peer;+ peer = null;+ activePeer?.close();+ resolve(result);+ };+ const onAbort = () => finish(cancelled());+ signal.addEventListener("abort", onAbort, { once: true });+ if (signal.aborted) {+ onAbort();+ return;+ }+ timer = setTimeout(+ () => finish(failed("未获得 STUN 候选")),+ timeoutMs,+ );+ try {+ const createdPeer = peerFactory({ iceServers: iceConfig.iceServers });+ if (settled) {+ createdPeer.close();+ return;+ }+ peer = createdPeer;+ peer.addEventListener("icecandidate", (event) => {+ if (event.candidate?.type === "srflx") {+ finish(passed("已获得 srflx 候选"));+ }+ });+ peer.addEventListener("icegatheringstatechange", () => {+ if (peer?.iceGatheringState === "complete") {+ finish(failed("未获得 STUN 候选"));+ }+ });+ peer.createDataChannel("self-check");+ void peer+ .createOffer()+ .then((offer) => peer?.setLocalDescription(offer))+ .catch(() => finish(failed("STUN 自检失败")));+ } catch {+ finish(failed("浏览器无法启动 STUN 自检"));+ }+ });+}++export async function runConnectionSelfCheck(+ options: ConnectionSelfCheckOptions = {},+): Promise<ConnectionSelfCheckResult> {+ const fetcher = options.fetcher ?? fetch;+ const timeoutMs = options.timeoutMs ?? 6_000;+ const startedAt = Date.now();+ const timeoutSignal = AbortSignal.timeout(timeoutMs);+ const lifecycleSignal = options.signal ?? new AbortController().signal;+ const requestSignal = options.signal+ ? AbortSignal.any([lifecycleSignal, timeoutSignal])+ : timeoutSignal;+ if (lifecycleSignal.aborted) return cancelledCheck();+ const signalUrl = new URL("/signal", options.baseUrl ?? window.location.href);+ signalUrl.protocol = signalUrl.protocol === "https:" ? "wss:" : "ws:";+ const socketFactory = options.socketFactory ?? ((url) => new WebSocket(url));+ const peerFactory =+ options.peerFactory ?? ((configuration) => new RTCPeerConnection(configuration));++ const [site, signaling, config] = await Promise.all([+ probeSite(fetcher, requestSignal),+ probeSignaling(+ signalUrl.toString(),+ socketFactory,+ lifecycleSignal,+ timeoutMs,+ ),+ readSelfCheckConfig(fetcher, requestSignal).catch(() => null),+ ]);+ if (lifecycleSignal.aborted) {+ return { ...cancelledCheck(), site, signaling };+ }+ const remainingMs = Math.max(0, timeoutMs - (Date.now() - startedAt));+ const stun = config && remainingMs > 0+ ? await probeStun(+ config.iceConfig,+ peerFactory,+ lifecycleSignal,+ remainingMs,+ )+ : config+ ? failed("未获得 STUN 候选")+ : failed("STUN 配置不可用");+ return {+ site,+ signaling,+ stun,+ sfu: !config+ ? unknown("配置状态未知")+ : config.sfuConfigured+ ? unknown("已配置,需实际路由验证")+ : unknown("当前未配置"),+ };+}diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsxindex 98bd6c95..14683766 100644--- a/src/client/pages/HostPage.tsx+++ b/src/client/pages/HostPage.tsx@@ -32,6 +32,7 @@ import {type ViewerAccessPolicy,} from "../../shared/protocol";import { AppHeader } from "../components/AppHeader";+import { ConnectionSelfCheck } from "../components/ConnectionSelfCheck";import { ConnectionDetailsToggle } from "../components/ConnectionDetailsToggle";import { RoomCode } from "../components/RoomCode";import { RoomCodeEntry } from "../components/RoomCodeEntry";@@ -1882,6 +1883,10 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {)}</div>+ {(phase === "idle" || phase === "ended" || phase === "error") && (+ <ConnectionSelfCheck />+ )}+{showConnectionDetails && details && stream && (<div className="capture-strip" aria-label="实际捕获参数"><span>{details.resolution}</span>diff --git a/src/client/styles.css b/src/client/styles.cssindex 44a4277c..f8d4a3e6 100644--- a/src/client/styles.css+++ b/src/client/styles.css@@ -403,6 +403,47 @@ h3 {content: "";}+.connection-self-check {+ display: grid;+ width: 100%;+ gap: 8px;+ justify-items: start;+}++.connection-self-check-results {+ display: grid;+ width: 100%;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 5px 14px;+}++.connection-self-check-result {+ display: grid;+ min-width: 0;+ grid-template-columns: 16px 58px minmax(0, 1fr);+ gap: 5px;+ align-items: center;+ color: var(--muted);+ font-size: 12px;+}++.connection-self-check-result svg {+ color: var(--faint);+}++.connection-self-check-result.is-passed svg {+ color: var(--green);+}++.connection-self-check-result.is-failed svg {+ color: var(--red);+}++.connection-self-check-result span {+ min-width: 0;+ overflow-wrap: anywhere;+}+.room-code-entry.is-inline {display: grid;min-width: 0;@@ -1336,6 +1377,10 @@ h3 {}@media (max-width: 520px) {+ .connection-self-check-results {+ grid-template-columns: minmax(0, 1fr);+ }+.room-code-entry.is-inline {grid-column: 1 / -1;}diff --git a/src/server/app.ts b/src/server/app.tsindex e0ecc71d..f06639ac 100644--- a/src/server/app.ts+++ b/src/server/app.ts@@ -10,6 +10,7 @@ import {} from "../shared/protocol.js";import { SiteAccess } from "./access-session.js";import { loadConfig, type ServerConfig } from "./config.js";+import { createIceConfig } from "./ice.js";import type { SfuTokenIssuer } from "./livekit-token.js";import { RoomDatabase } from "./room-database.js";import { RoomStore, RoomStoreError } from "./room-store.js";@@ -228,6 +229,21 @@ async function handleRequest(return;}+ if (url.pathname === "/api/connection-self-check") {+ response.setHeader("Cache-Control", "no-store");+ response.setHeader("X-Content-Type-Options", "nosniff");+ if (request.method !== "GET") {+ response.setHeader("Allow", "GET");+ sendJson(response, 405, { error: "Method not allowed" });+ return;+ }+ sendJson(response, 200, {+ iceConfig: createIceConfig({ stunUrls: config.stunUrls }),+ sfuConfigured: config.livekitFallback !== undefined,+ });+ return;+ }+if (url.pathname === "/api/site-access") {handleSiteAccessRequest(request, response, config, siteAccess);return;diff --git a/tests/connection-self-check.test.ts b/tests/connection-self-check.test.tsnew file mode 100644index 00000000..670b9c84--- /dev/null+++ b/tests/connection-self-check.test.ts@@ -0,0 +1,220 @@+import { describe, expect, it, vi } from "vitest";++import { runConnectionSelfCheck } from "../src/client/media/connection-self-check.ts";++type Listener = (event: unknown) => void;++class FakeSocket {+ private readonly listeners = new Map<string, Listener[]>();+ readonly close = vi.fn();++ addEventListener(type: string, listener: Listener): void {+ const listeners = this.listeners.get(type) ?? [];+ listeners.push(listener);+ this.listeners.set(type, listeners);+ }++ emit(type: "open" | "error"): void {+ this.listeners.get(type)?.forEach((listener) => listener({}));+ }+}++class FakePeer {+ iceGatheringState: RTCIceGatheringState = "gathering";+ private readonly listeners = new Map<string, Listener[]>();+ readonly close = vi.fn();+ readonly createDataChannel = vi.fn();+ readonly createOffer = vi.fn(async () => ({ type: "offer", sdp: "test" }));++ constructor(+ private readonly candidateType: RTCIceCandidateType | null,+ private readonly completes = true,+ ) {}++ addEventListener(type: string, listener: Listener): void {+ const listeners = this.listeners.get(type) ?? [];+ listeners.push(listener);+ this.listeners.set(type, listeners);+ }++ async setLocalDescription(): Promise<void> {+ if (this.candidateType) {+ this.listeners.get("icecandidate")?.forEach((listener) =>+ listener({ candidate: { type: this.candidateType } }),+ );+ }+ if (this.completes) {+ this.iceGatheringState = "complete";+ this.listeners+ .get("icegatheringstatechange")+ ?.forEach((listener) => listener({}));+ }+ }+}++function response(value: unknown, status = 200): Response {+ return new Response(JSON.stringify(value), {+ status,+ headers: { "Content-Type": "application/json" },+ });+}++describe("connection self-check", () => {+ it("passes only a gathered srflx candidate and keeps SFU/UDP unknown", async () => {+ const socket = new FakeSocket();+ const peer = new FakePeer("srflx");+ const socketFactory = vi.fn((url: string) => {+ void url;+ queueMicrotask(() => socket.emit("open"));+ return socket as unknown as WebSocket;+ });+ const fetcher = vi.fn(async (input: RequestInfo | URL) =>+ String(input) === "/healthz"+ ? response({ status: "ok" })+ : response({+ iceConfig: {+ iceServers: [{ urls: ["stun:stun.example.test:3478"] }],+ },+ sfuConfigured: true,+ }),+ ) as unknown as typeof fetch;++ const result = await runConnectionSelfCheck({+ baseUrl: "https://share.example.test/",+ fetcher,+ socketFactory,+ peerFactory: () => peer as unknown as RTCPeerConnection,+ timeoutMs: 50,+ });++ expect(socketFactory).toHaveBeenCalledWith("wss://share.example.test/signal");+ expect(result).toEqual({+ site: { status: "passed", detail: "站点健康" },+ signaling: { status: "passed", detail: "WSS 可达" },+ stun: { status: "passed", detail: "已获得 srflx 候选" },+ sfu: { status: "unknown", detail: "已配置,需实际路由验证" },+ });+ expect(peer.close).toHaveBeenCalledOnce();+ expect(socket.close).toHaveBeenCalledWith(1000, "self-check");+ });++ it("does not treat host gathering or SFU configuration absence as success", async () => {+ const socket = new FakeSocket();+ const peer = new FakePeer("host");+ const result = await runConnectionSelfCheck({+ baseUrl: "http://localhost:5173/",+ fetcher: (async (input: RequestInfo | URL) =>+ String(input) === "/healthz"+ ? response({ status: "ok" })+ : response({+ iceConfig: { iceServers: [{ urls: "stun:localhost:3478" }] },+ sfuConfigured: false,+ })) as typeof fetch,+ socketFactory: () => {+ queueMicrotask(() => socket.emit("error"));+ return socket as unknown as WebSocket;+ },+ peerFactory: () => peer as unknown as RTCPeerConnection,+ timeoutMs: 50,+ });++ expect(result.signaling.status).toBe("failed");+ expect(result.stun).toEqual({+ status: "failed",+ detail: "未获得 STUN 候选",+ });+ expect(result.sfu).toEqual({ status: "unknown", detail: "当前未配置" });+ });++ it("closes a temporary peer connection when STUN gathering times out", async () => {+ const socket = new FakeSocket();+ const peer = new FakePeer(null, false);+ const result = await runConnectionSelfCheck({+ baseUrl: "https://share.example.test/",+ fetcher: (async (input: RequestInfo | URL) =>+ String(input) === "/healthz"+ ? response({ status: "ok" })+ : response({+ iceConfig: { iceServers: [{ urls: "stun:localhost:3478" }] },+ sfuConfigured: true,+ })) as typeof fetch,+ socketFactory: () => {+ queueMicrotask(() => socket.emit("open"));+ return socket as unknown as WebSocket;+ },+ peerFactory: () => peer as unknown as RTCPeerConnection,+ timeoutMs: 100,+ });++ expect(result.stun).toEqual({+ status: "failed",+ detail: "未获得 STUN 候选",+ });+ expect(peer.close).toHaveBeenCalledOnce();+ });++ it("closes WSS and skips STUN when the caller unmounts as config settles", async () => {+ const controller = new AbortController();+ const socket = new FakeSocket();+ const peerFactory = vi.fn();+ const socketFactory = vi.fn(() => socket as unknown as WebSocket);+ let resolveConfig!: (value: unknown) => void;+ const config = new Promise<unknown>((resolve) => {+ resolveConfig = resolve;+ });+ const fetcher = (async (input: RequestInfo | URL) =>+ String(input) === "/healthz"+ ? response({ status: "ok" })+ : ({ ok: true, json: () => config }) as Response) as typeof fetch;++ const pending = runConnectionSelfCheck({+ baseUrl: "https://share.example.test/",+ fetcher,+ signal: controller.signal,+ socketFactory,+ peerFactory,+ timeoutMs: 1_000,+ });+ await vi.waitFor(() => expect(socketFactory).toHaveBeenCalledOnce());+ resolveConfig({+ iceConfig: { iceServers: [{ urls: "stun:localhost:3478" }] },+ sfuConfigured: true,+ });+ controller.abort();++ const result = await pending;+ expect(socket.close).toHaveBeenCalledWith(1000, "self-check");+ expect(peerFactory).not.toHaveBeenCalled();+ expect(result.stun.detail).toBe("自检已取消");+ });++ it("immediately closes an active STUN peer when the caller cancels", async () => {+ const controller = new AbortController();+ const socket = new FakeSocket();+ const peer = new FakePeer(null, false);+ const peerFactory = vi.fn(() => peer as unknown as RTCPeerConnection);+ const pending = runConnectionSelfCheck({+ baseUrl: "https://share.example.test/",+ fetcher: (async (input: RequestInfo | URL) =>+ String(input) === "/healthz"+ ? response({ status: "ok" })+ : response({+ iceConfig: { iceServers: [{ urls: "stun:localhost:3478" }] },+ sfuConfigured: true,+ })) as typeof fetch,+ signal: controller.signal,+ socketFactory: () => {+ queueMicrotask(() => socket.emit("open"));+ return socket as unknown as WebSocket;+ },+ peerFactory,+ timeoutMs: 1_000,+ });+ await vi.waitFor(() => expect(peerFactory).toHaveBeenCalledOnce());+ controller.abort();++ const result = await pending;+ expect(peer.close).toHaveBeenCalledOnce();+ expect(result.stun.detail).toBe("自检已取消");+ });+});diff --git a/tests/server-http.test.ts b/tests/server-http.test.tsindex a8f99b32..025f9410 100644--- a/tests/server-http.test.ts+++ b/tests/server-http.test.ts@@ -377,6 +377,39 @@ describe("room HTTP API", () => {});describe("server HTTP listener and health", () => {+ it("serves only non-secret connection self-check configuration", async () => {+ const baseUrl = await start(+ testConfig({+ peerAssistedMedia: true,+ stunUrls: ["stun:stun.example.test:3478"],+ livekitFallback: {+ url: "ws://livekit.test:7880",+ apiKey: "test-key",+ apiSecret: "s".repeat(32),+ maxSfuRootsPerRoom: 2,+ },+ }),+ { sfuTokenIssuer: { issueToken: async () => "unused-test-token" } },+ );++ const response = await fetch(`${baseUrl}/api/connection-self-check`);+ expect(response.status).toBe(200);+ expect(response.headers.get("cache-control")).toBe("no-store");+ expect(response.headers.get("x-content-type-options")).toBe("nosniff");+ expect(await response.json()).toEqual({+ iceConfig: {+ iceServers: [{ urls: ["stun:stun.example.test:3478"] }],+ },+ sfuConfigured: true,+ });++ const rejected = await fetch(`${baseUrl}/api/connection-self-check`, {+ method: "POST",+ });+ expect(rejected.status).toBe(405);+ expect(rejected.headers.get("allow")).toBe("GET");+ });+it("starts with an injected optional SFU token issuer", async () => {const baseUrl = await start(testConfig({