Skip to content

armgit / Piik

Public Imported from GitHub
0

Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。

feat(web): export privacy-safe connection diagnostics (#171)

AAAf9ecf92c34a3
diff --git a/docs/research/low-server-media-routes.md b/docs/research/low-server-media-routes.md
index c5730106..2f3c4295 100644
--- a/docs/research/low-server-media-routes.md
+++ b/docs/research/low-server-media-routes.md
@@ -352,6 +352,18 @@ old connection or ICE-restart history from being attributed to a new route.
Use opaque generations only. This is a bounded diagnostic manifest, not a
backend telemetry schema or controller input.
+### Local Diagnostic Export Boundary
+
+The local report is a projection of current sanitized metrics, not a serialized
+stats object or signaling snapshot. It uses a fixed field allowlist and writes
+unavailable values as `null`; selected addresses/ports, internal IDs, participant
+identity, raw SDP/candidates, media-service URLs, and credentials never enter the
+report input. The file is created only after a user click with a local JSON
+`Blob`, is not uploaded or persisted, and its object URL is explicitly revoked.
+The [W3C File API](https://www.w3.org/TR/FileAPI/) (accessed 2026-08-22) defines
+Blob URLs for locally generated downloads and requires explicit revocation to
+release their backing store.
+
### Pre-Share Self-Check Boundary
A temporary, unpaired `RTCPeerConnection` can create a data channel, set its
diff --git a/docs/status.md b/docs/status.md
index ae219c2a..09cd612c 100644
--- a/docs/status.md
+++ b/docs/status.md
@@ -15,6 +15,7 @@ This file is the current execution index. Load [verification status](./verificat
- Capture precedes room creation. Balanced, automatic codec, and 128 kbps screen audio are defaults; clarity/fluid, H.264/VP8, and 64/128/256 kbps audio are deployed next-share choices. Codec and audio quality lock during a share.
- Local-only connection details expose current Host SFU sender evidence, actual codec/fmtp and encoder fields, media-source/encode FPS evidence, A/V playout/jitter/concealment evidence, and selected candidate endpoints. These fields do not enter quality signaling, server state, logs, persistence, or route selection.
+- The source candidate adds click-only, versioned JSON export beside expanded connection details. A fixed allowlist excludes candidate addresses/ports, participant and room identity, raw signaling, URLs, and credentials; no report is uploaded or persisted. Production rollout is pending.
- Private fragment grants enter directly; code-only Viewers need site access and private rooms additionally need their password. Credentials remain unstored. Web names and presence are session-only; duplicate names alone show an ID suffix.
- Rooms default to eight Viewers and accept an explicit admission limit from one through sixteen. Roots and ordinary Web relays are bounded to two downstream edges, Viewer upstream receive is free, and source permits an explicit endpoint cap from one through three. SFU root capacity remains separate.
- Relay quality handling compares fresh child FPS with parent input. Two current corroborating children can pause one Viewer relay for 30 seconds and request peer-only reassignment; no candidate keeps the old edge.
diff --git "a/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md" "b/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"
index 23f36d8b..65d63a6d 100644
--- "a/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"
+++ "b/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"
@@ -295,6 +295,8 @@ hop 按[低服务器成本媒体路由](./research/low-server-media-routes.md)
每两秒在本地采集一次 `getStats()`。首版不上传原始统计。折叠详情可在产生该连接的本机显示 selected local/remote candidate 的 `address`/`port`,但浏览器未暴露时保持未知;地址不得进入信令、Viewer C、日志、诊断导出、持久化或路由/质量决策。在 peer 边中它只是当前连接端点,在 SFU 边中通常是 SFU 端点,不能标成参与者的权威公网 IP。
+Host 与 Viewer 复用同一个连接详情开关;展开后且至少存在一组本地 metrics 时显示下载图标。点击才把当前内存快照投影为 `schemaVersion: 1` JSON 并创建本地 Blob 下载,随后回收 object URL;不上传、不写 browser storage。投影器只按固定字段白名单读取 route/direction、连接状态、protocol/candidate type、codec、分辨率/FPS/码率/loss/jitter/RTT、限制、encoder 和音视频播放/修复指标,所有缺失值写为 `null`。它不接受或输出 candidate address/port、stats/connection/media ID、peer/client/room/name、raw candidate/SDP、STUN/TURN URL、username、credential 或 token。Host 的 peer-relay 接收项必须先经过已有 `ViewerQualityEvidence` 脱敏转换,不能序列化 evidence guard 或原消息。
+
质量诊断必须能按顺序区分:捕获源设置、sender 实际参数、CPU 或带宽 `qualityLimitationReason`、selected candidate/TURN 路径、outbound 与 inbound 差异,以及接收端 dropped/freeze。当前有界实现显示 sender 参数的 requested/applied 读回;同一个非 `none` 原生 `qualityLimitationReason` 连续出现三个采样周期后显示单条原因提示,原因变化、缺失或恢复为 `none` 即重新计数。这只是去抖后的观察,不组合评分、不触发调档或迁移。完整跨路径分类仍由后续真实矩阵验收;首轮使用浏览器 WebRTC internals 导出和一份脱敏 run manifest,不新增服务端遥测。
分享者逐观看者显示:
diff --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 e86be217..b44ae325 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"
@@ -56,7 +56,7 @@
- [ ] 连接自检:开始分享前的本地自检先用无房间、无媒体、无凭据的临时资源验证站点健康、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 仍不得仅凭压缩率推断默认启用。
-- [ ] 诊断页面:用户可导出不含敏感地址和凭据的连接诊断信息。
+- [x] 诊断导出:Host 与 Viewer 在展开现有连接详情且存在本地 metrics 时可点击下载图标导出版本化 JSON。导出只逐字段白名单包含 route、direction、连接状态、protocol/candidate type、codec、分辨率、帧率、码率、丢包、jitter、RTT、限制、encoder 与音视频播放/修复指标;缺失值为 `null`。禁止导出 local/remote candidate address/port、连接或媒体内部 ID、peer/client/room/name、raw candidate/SDP、STUN/TURN URL、username、credential 或 token。文件只在点击时以本地 Blob 生成并立即回收 URL,不上传或持久化;Host 收到的 peer-relay 数据只可使用已有脱敏 evidence 字段。
### P2 - 可选功能
diff --git a/src/client/components/ConnectionDetailsToggle.tsx b/src/client/components/ConnectionDetailsToggle.tsx
index f94d5dbe..af690172 100644
--- a/src/client/components/ConnectionDetailsToggle.tsx
+++ b/src/client/components/ConnectionDetailsToggle.tsx
@@ -1,27 +1,42 @@
+import { Download } from "lucide-react";
import type { ChangeEvent } from "react";
interface ConnectionDetailsToggleProps {
checked: boolean;
onChange: (checked: boolean) => void;
+ onExport?: () => void;
}
export function ConnectionDetailsToggle({
checked,
onChange,
+ onExport,
}: ConnectionDetailsToggleProps) {
return (
- <label
- className="connection-details-toggle"
- title="展开或隐藏连接的技术指标"
- >
- <input
- type="checkbox"
- checked={checked}
- onChange={(event: ChangeEvent<HTMLInputElement>) =>
- onChange(event.currentTarget.checked)
- }
- />
- <span>显示连接详情</span>
- </label>
+ <div className="connection-details-toggle">
+ <label
+ title="展开或隐藏连接的技术指标"
+ >
+ <input
+ type="checkbox"
+ checked={checked}
+ onChange={(event: ChangeEvent<HTMLInputElement>) =>
+ onChange(event.currentTarget.checked)
+ }
+ />
+ <span>显示连接详情</span>
+ </label>
+ {checked && onExport && (
+ <button
+ className="icon-button"
+ type="button"
+ title="下载脱敏连接诊断"
+ aria-label="下载脱敏连接诊断"
+ onClick={onExport}
+ >
+ <Download size={17} aria-hidden="true" />
+ </button>
+ )}
+ </div>
);
}
diff --git a/src/client/lib/diagnostic-export.ts b/src/client/lib/diagnostic-export.ts
new file mode 100644
index 00000000..b502d9d0
--- /dev/null
+++ b/src/client/lib/diagnostic-export.ts
@@ -0,0 +1,80 @@
+import type { ConnectionMetrics } from "../types";
+
+export const DIAGNOSTIC_SCHEMA_VERSION = 1;
+
+const DIAGNOSTIC_METRIC_KEYS = [
+ "sampleWindowMs", "captureWidth", "captureHeight",
+ "captureFramesPerSecond", "mediaSourceFramesPerSecond", "path",
+ "iceProtocol", "localRelayProtocol", "localCandidateType",
+ "remoteCandidateType", "rttMs", "bitrateKbps", "availableOutgoingKbps",
+ "framesPerSecond", "frameWidth", "frameHeight", "resolution",
+ "packetsLost", "intervalPacketsSent", "intervalPacketsReceived",
+ "intervalPacketsLost", "packetLossPercent", "jitterMs", "framesDropped",
+ "intervalFramesDecoded", "intervalFramesDropped", "intervalFreezeCount",
+ "intervalFreezeDurationMs", "intervalRetransmittedPackets",
+ "intervalRetransmittedBytes", "codec", "codecProfile", "codecParameters",
+ "audioBitrateKbps", "audioPacketLossPercent", "audioJitterMs",
+ "audioVideoPlayoutDeltaMs", "videoJitterBufferDelayMs",
+ "audioJitterBufferDelayMs", "audioConcealedSamplesPercent",
+ "intervalAudioConcealmentEvents", "audioCodec", "audioCodecClockRate",
+ "audioCodecChannels", "audioCodecParameters", "scalabilityMode",
+ "encoderImplementation", "powerEfficientEncoder", "intervalFramesEncoded",
+ "intervalEncodeTimeMs", "intervalEncodeMs", "intervalDecodeMs",
+ "qualityLimitationReason",
+] as const satisfies readonly (keyof ConnectionMetrics)[];
+
+export interface DiagnosticConnectionInput {
+ scope: "host-sfu" | "upstream" | "viewer-edge" | "relay-edge";
+ route: "p2p" | "sfu";
+ direction: "send" | "receive";
+ connectionState?: RTCPeerConnectionState | "reconnecting" | null;
+ iceConnectionState?: RTCIceConnectionState | null;
+ metrics: ConnectionMetrics;
+}
+
+export function createDiagnosticReport(
+ role: "host" | "viewer",
+ connections: readonly DiagnosticConnectionInput[],
+ exportedAt = new Date(),
+) {
+ return {
+ schemaVersion: DIAGNOSTIC_SCHEMA_VERSION,
+ exportedAt: exportedAt.toISOString(),
+ role,
+ connections: connections.map((connection) => ({
+ scope: connection.scope,
+ route: connection.route,
+ direction: connection.direction,
+ connectionState: connection.connectionState ?? null,
+ iceConnectionState: connection.iceConnectionState ?? null,
+ metrics: Object.fromEntries(
+ DIAGNOSTIC_METRIC_KEYS.map((key) => [
+ key,
+ connection.metrics[key] ?? null,
+ ]),
+ ),
+ })),
+ };
+}
+
+export function downloadDiagnosticReport(
+ role: "host" | "viewer",
+ connections: readonly DiagnosticConnectionInput[],
+): void {
+ const exportedAt = new Date();
+ const report = createDiagnosticReport(role, connections, exportedAt);
+ const blob = new Blob([`${JSON.stringify(report, null, 2)}\n`], {
+ type: "application/json;charset=utf-8",
+ });
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = `screener-diagnostics-${role}-${exportedAt
+ .toISOString()
+ .replace(/[:.]/g, "-")}.json`;
+ link.hidden = true;
+ document.body.append(link);
+ link.click();
+ link.remove();
+ window.setTimeout(() => URL.revokeObjectURL(url), 0);
+}
diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsx
index 14683766..ca131b55 100644
--- a/src/client/pages/HostPage.tsx
+++ b/src/client/pages/HostPage.tsx
@@ -49,6 +49,7 @@ import { TopologyView } from "../components/TopologyView";
import { hasPeerRouteEvidence } from "../components/status-badge-model";
import { ApiError, createRoom } from "../lib/api";
import { createOpaqueId } from "../lib/opaque-id";
+import { downloadDiagnosticReport, type DiagnosticConnectionInput } from "../lib/diagnostic-export";
import {
defaultHostDisplayName,
readDisplayName,
@@ -308,6 +309,45 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
) ?? null,
[participantPresence],
);
+ const diagnosticConnections: DiagnosticConnectionInput[] = [];
+ if (sfuPublisherSnapshot) {
+ diagnosticConnections.push({
+ scope: "host-sfu",
+ route: "sfu",
+ direction: "send",
+ metrics: sfuPublisherSnapshot.metrics,
+ });
+ }
+ for (const viewer of viewers) {
+ const snapshot =
+ viewer.upstream.kind === "peer" &&
+ viewer.upstream.peerId ===
+ (hostPresence?.peerId ?? hostPeerIdRef.current)
+ ? peerSnapshots.get(viewer.peerId)
+ : undefined;
+ if (snapshot && hasPeerRouteEvidence(snapshot)) {
+ diagnosticConnections.push({
+ scope: "viewer-edge",
+ route: "p2p",
+ direction: "send",
+ connectionState: snapshot.connectionState,
+ iceConnectionState: snapshot.iceConnectionState,
+ metrics: snapshot.metrics,
+ });
+ }
+ const evidence = viewerQualityEvidence.get(viewer.peerId);
+ if (
+ viewer.upstream.kind === "peer" &&
+ evidence?.parentPeerId === viewer.upstream.peerId
+ ) {
+ diagnosticConnections.push({
+ scope: "viewer-edge",
+ route: "p2p",
+ direction: "receive",
+ metrics: metricsFromQualityEvidence(evidence),
+ });
+ }
+ }
const selectedQualityProfileId = useMemo(
() => matchingQualityProfileId(qualitySettings),
[qualitySettings],
@@ -1910,6 +1950,9 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
<ConnectionDetailsToggle
checked={showConnectionDetails}
onChange={setShowConnectionDetails}
+ onExport={diagnosticConnections.length > 0
+ ? () => downloadDiagnosticReport("host", diagnosticConnections)
+ : undefined}
/>
<div className="setup-controls">
diff --git a/src/client/pages/ViewerPage.tsx b/src/client/pages/ViewerPage.tsx
index 47c4a747..4a66dd8b 100644
--- a/src/client/pages/ViewerPage.tsx
+++ b/src/client/pages/ViewerPage.tsx
@@ -42,6 +42,7 @@ import { readDisplayName, saveDisplayName } from "../lib/display-name";
import { clearViewerGrant, getStableClientId } from "../lib/session";
import { SignalingClient } from "../lib/signaling";
import { labelParticipantSnapshot } from "../lib/viewer-presence";
+import { downloadDiagnosticReport, type DiagnosticConnectionInput } from "../lib/diagnostic-export";
import type { QualitySettings } from "../media/quality";
import {
ParentEdgeQualityEvidenceReporter,
@@ -198,6 +199,37 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
routePresentation.evidence?.connectionState ??
(hostOnline ? "routing" : "waiting");
const routeMetrics = routePresentation.evidence?.metrics ?? null;
+ const diagnosticConnections: DiagnosticConnectionInput[] = [];
+ if (routePresentation.route && routeMetrics) {
+ diagnosticConnections.push({
+ scope: "upstream",
+ route: routePresentation.route,
+ direction: "receive",
+ connectionState: routePresentation.evidence?.connectionState,
+ iceConnectionState: peerSnapshot && routePresentation.evidence === peerSnapshot
+ ? peerSnapshot.iceConnectionState
+ : null,
+ metrics: routeMetrics,
+ });
+ }
+ if (relaySnapshot) {
+ diagnosticConnections.push({
+ scope: "relay-edge",
+ route: "p2p",
+ direction: "send",
+ connectionState: relaySnapshot.connectionState,
+ iceConnectionState: relaySnapshot.iceConnectionState,
+ metrics: relaySnapshot.metrics,
+ });
+ }
+ if (relayChildEvidence) {
+ diagnosticConnections.push({
+ scope: "relay-edge",
+ route: "p2p",
+ direction: "receive",
+ metrics: metricsFromQualityEvidence(relayChildEvidence),
+ });
+ }
function acceptAssignedRoute(
revision: number,
@@ -1638,6 +1670,9 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
<ConnectionDetailsToggle
checked={showConnectionDetails}
onChange={setShowConnectionDetails}
+ onExport={diagnosticConnections.length > 0
+ ? () => downloadDiagnosticReport("viewer", diagnosticConnections)
+ : undefined}
/>
{routePresentation.evidence === peerSnapshot && peerSnapshot?.error && (
diff --git a/src/client/styles.css b/src/client/styles.css
index f8d4a3e6..948826dd 100644
--- a/src/client/styles.css
+++ b/src/client/styles.css
@@ -620,6 +620,12 @@ h3 {
color: var(--text);
}
+.connection-details-toggle > label {
+ display: inline-flex;
+ gap: 9px;
+ align-items: center;
+}
+
.connection-details-toggle input {
width: 18px;
height: 18px;
diff --git a/tests/connection-details-toggle.test.ts b/tests/connection-details-toggle.test.ts
new file mode 100644
index 00000000..7d588bba
--- /dev/null
+++ b/tests/connection-details-toggle.test.ts
@@ -0,0 +1,28 @@
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, it, vi } from "vitest";
+
+import { ConnectionDetailsToggle } from "../src/client/components/ConnectionDetailsToggle.tsx";
+
+describe("ConnectionDetailsToggle diagnostic export", () => {
+ it("offers the familiar download action only with expanded exportable details", () => {
+ const expanded = renderToStaticMarkup(
+ createElement(ConnectionDetailsToggle, {
+ checked: true,
+ onChange: vi.fn(),
+ onExport: vi.fn(),
+ }),
+ );
+ const collapsed = renderToStaticMarkup(
+ createElement(ConnectionDetailsToggle, {
+ checked: false,
+ onChange: vi.fn(),
+ onExport: vi.fn(),
+ }),
+ );
+
+ expect(expanded).toContain("下载脱敏连接诊断");
+ expect(expanded).toContain("lucide-download");
+ expect(collapsed).not.toContain("下载脱敏连接诊断");
+ });
+});
diff --git a/tests/diagnostic-export.test.ts b/tests/diagnostic-export.test.ts
new file mode 100644
index 00000000..98de8f39
--- /dev/null
+++ b/tests/diagnostic-export.test.ts
@@ -0,0 +1,182 @@
+import { describe, expect, it, vi } from "vitest";
+
+import {
+ createDiagnosticReport,
+ DIAGNOSTIC_SCHEMA_VERSION,
+ downloadDiagnosticReport,
+ type DiagnosticConnectionInput,
+} from "../src/client/lib/diagnostic-export.ts";
+import { EMPTY_METRICS } from "../src/client/types.ts";
+
+describe("diagnostic export privacy boundary", () => {
+ it("exports a versioned allowlist and preserves unavailable values as null", () => {
+ const report = createDiagnosticReport(
+ "viewer",
+ [
+ {
+ scope: "upstream",
+ route: "p2p",
+ direction: "receive",
+ connectionState: "connected",
+ iceConnectionState: "connected",
+ metrics: {
+ ...EMPTY_METRICS,
+ path: "direct",
+ iceProtocol: "udp",
+ localCandidateType: "srflx",
+ remoteCandidateType: "host",
+ bitrateKbps: 4_200,
+ framesPerSecond: 59.8,
+ codec: "video/VP8",
+ audioVideoPlayoutDeltaMs: -12.5,
+ },
+ },
+ ],
+ new Date("2026-08-22T12:00:00.000Z"),
+ );
+
+ expect(report.schemaVersion).toBe(DIAGNOSTIC_SCHEMA_VERSION);
+ expect(report.exportedAt).toBe("2026-08-22T12:00:00.000Z");
+ expect(report.connections[0]).toMatchObject({
+ scope: "upstream",
+ route: "p2p",
+ direction: "receive",
+ connectionState: "connected",
+ iceConnectionState: "connected",
+ metrics: {
+ iceProtocol: "udp",
+ localCandidateType: "srflx",
+ bitrateKbps: 4_200,
+ framesPerSecond: 59.8,
+ codec: "video/VP8",
+ audioVideoPlayoutDeltaMs: -12.5,
+ audioJitterMs: null,
+ },
+ });
+ });
+
+ it("cannot serialize addresses, identities, raw signaling, URLs, or credentials", () => {
+ const secrets = {
+ localCandidateAddress: "sensitive-local-address",
+ localCandidatePort: 50_000,
+ remoteCandidateAddress: "sensitive-remote-address",
+ remoteCandidatePort: 50_001,
+ selectedCandidatePairId: "sensitive-pair-id",
+ rtpStatsId: "sensitive-rtp-id",
+ rtpSsrc: 4_242,
+ rtpMid: "sensitive-mid",
+ rtpRid: "sensitive-rid",
+ trackIdentifier: "sensitive-track-id",
+ rawCandidate: "candidate-sensitive",
+ sdp: "sdp-sensitive",
+ turnUrl: "turn:secret.example",
+ stunUrl: "stun:secret.example",
+ username: "username-sensitive",
+ credential: "credential-sensitive",
+ token: "token-sensitive",
+ errorText: "error-sensitive",
+ };
+ const unsafeInput = {
+ scope: "viewer-edge",
+ route: "p2p",
+ direction: "send",
+ connectionState: "connected",
+ iceConnectionState: "connected",
+ peerId: "peer-sensitive",
+ clientId: "client-sensitive",
+ roomCode: "room-sensitive",
+ roomId: "room-id-sensitive",
+ name: "name-sensitive",
+ hostToken: "host-token-sensitive",
+ viewerGrant: "viewer-grant-sensitive",
+ roomPassword: "password-sensitive",
+ metrics: { ...EMPTY_METRICS, ...secrets },
+ } as unknown as DiagnosticConnectionInput;
+
+ const json = JSON.stringify(createDiagnosticReport("host", [unsafeInput]));
+ for (const value of [
+ ...Object.values(secrets).map(String),
+ "peer-sensitive",
+ "client-sensitive",
+ "room-sensitive",
+ "room-id-sensitive",
+ "name-sensitive",
+ "host-token-sensitive",
+ "viewer-grant-sensitive",
+ "password-sensitive",
+ ]) {
+ expect(json).not.toContain(value);
+ }
+ for (const key of [
+ "localCandidateAddress",
+ "localCandidatePort",
+ "remoteCandidateAddress",
+ "remoteCandidatePort",
+ "selectedCandidatePairId",
+ "rtpStatsId",
+ "rtpSsrc",
+ "rtpMid",
+ "rtpRid",
+ "trackIdentifier",
+ "peerId",
+ "clientId",
+ "roomCode",
+ "roomId",
+ "name",
+ "hostToken",
+ "viewerGrant",
+ "roomPassword",
+ "rawCandidate",
+ "sdp",
+ "turnUrl",
+ "stunUrl",
+ "username",
+ "credential",
+ "token",
+ "errorText",
+ ]) {
+ expect(json).not.toContain(`"${key}"`);
+ }
+ });
+
+ it("creates one local JSON Blob and revokes its URL after download", async () => {
+ let createdBlob: Blob | null = null;
+ const link = { href: "", download: "", hidden: false, click: vi.fn(), remove: vi.fn() };
+ const append = vi.fn();
+ const revokeObjectURL = vi.fn();
+ vi.stubGlobal("document", {
+ createElement: vi.fn(() => link),
+ body: { append },
+ });
+ vi.stubGlobal("URL", {
+ createObjectURL: vi.fn((blob: Blob) => {
+ createdBlob = blob;
+ return "blob:diagnostic";
+ }),
+ revokeObjectURL,
+ });
+ vi.stubGlobal("window", {
+ setTimeout: (callback: () => void) => {
+ callback();
+ return 1;
+ },
+ });
+
+ try {
+ downloadDiagnosticReport("host", [{
+ scope: "host-sfu",
+ route: "sfu",
+ direction: "send",
+ metrics: EMPTY_METRICS,
+ }]);
+ expect(link.click).toHaveBeenCalledOnce();
+ expect(link.remove).toHaveBeenCalledOnce();
+ expect(append).toHaveBeenCalledWith(link);
+ expect(link.download).toMatch(/^screener-diagnostics-host-.*\.json$/);
+ expect(revokeObjectURL).toHaveBeenCalledWith("blob:diagnostic");
+ expect(await createdBlob!.text()).toContain(`"schemaVersion": 1`);
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+});