Files
Piik/tests/browser-debug.test.ts
T
AAA f92162b3bb feat: launch Piik with a unified interface and public website
Piik now has one public presentation and a coordinated App/Server release path. This phase unifies the room UI, rewrites the bilingual README and guides, adds a static website with an inline product film, and prepares matching GitHub/Gitee packages and update links.

The film uses the current homepage and shared product controls on one seekable timeline. Runtime fixes preserve presentation when the App opens a room, normalize Site origins, and keep capture and media-recovery status in the television indicator. New visits use Chinese for a Chinese system language and English otherwise; explicit language and visual-mode choices remain available. An optional site passphrase controls site entry, while room authorization remains enforced.

GitHub is the release authority. Gitee mirrors verified packages and provides update metadata when GitHub is unavailable. Reviewed PR release notes become the GitHub Release description. The separate public demo uses P2P only, with HTTPS and STUN verified.

Validation: 756 Web tests, TypeScript and production build; Go core tests, formatting, vet and available target builds; bounded Windows capture and App/Site interoperability; browser film checks, audible playback and narrow layouts; anonymous Gitee Windows-package download, checksum and launcher/update-link checks. Public demo acceptance covers authenticated WebSocket signaling, synthetic P2P video and room cleanup on one network. macOS/Linux physical capture and the wider device/network/endurance matrix remain explicitly deferred.

Publication builds every package from the merged source SHA. The repository is public, main protection is active, and Pages is configured for piik.tv. CI/publisher and Pages deployment records own publication results.

## Release notes

### 中文

Piik 是免费开源的屏幕共享工具。开个房间,发出邀请,最多 20 位朋友就能用浏览器加入观看。

- 使用浏览器或 Piik App 分享游戏、窗口和整个屏幕。
- 优先建立直连;自托管站点可开启媒体转发作为备用线路。
- Piik App 支持本地房间、临时公网邀请和已有站点。
- Piik Server 内置网页界面、房间管理和连接服务,方便自行部署。
- 提供中英文界面与使用指南,以及 GitHub、Gitee 两条下载线路。

[官网](https://piik.tv) · [在线体验](https://demo.piik.tv) · [使用指南](https://github.com/TNTcraftHIM/Piik/blob/main/docs/guide/getting-started.zh-CN.md) · [自行部署](https://github.com/TNTcraftHIM/Piik/blob/main/docs/operations/self-hosting.zh-CN.md) · [Gitee 下载](https://gitee.com/TNTcraftHIM/Piik/releases)

Windows App 和桌面浏览器是本次主要验证的平台。macOS 和 Linux 尚未经过实机测试,欢迎有设备的朋友测试并反馈。演示站和 App 公网邀请使用 P2P,受限网络下可能无法连接;自托管站点可开启媒体转发。

### English

Piik is free, open-source screen sharing for you and up to 20 viewers. Start a room, send an invitation, and your friends can join in a browser.

- Share games, windows or a whole screen from your browser or Piik App.
- Direct connections come first, with optional media forwarding on self-hosted sites.
- Piik App supports local rooms, temporary public invitations and existing sites.
- Piik Server includes the web interface, rooms and connection services for self-hosting.
- English and Chinese interfaces and guides are available, with GitHub and Gitee downloads.

[Website](https://piik.tv) · [Online demo](https://demo.piik.tv) · [User guide](https://github.com/TNTcraftHIM/Piik/blob/main/docs/guide/getting-started.md) · [Self-hosting](https://github.com/TNTcraftHIM/Piik/blob/main/docs/operations/self-hosting.md) · [Gitee downloads](https://gitee.com/TNTcraftHIM/Piik/releases)

Windows App and desktop browsers are the primary validated paths. macOS and Linux have not yet been tested on physical devices; testing and feedback are welcome. The demo and App public invitations rely on P2P and may not connect on restrictive networks. Self-hosted sites can enable media forwarding.
2026-09-12 22:09:12 +08:00

184 lines
10 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from "vitest";
function browser(search = "?debug=1") {
const page = Object.assign(new EventTarget(), {
location: new URL(`https://private.example/r/1234${search}#v=private-grant`),
setTimeout: globalThis.setTimeout, clearTimeout: globalThis.clearTimeout,
}) as unknown as Window;
vi.stubGlobal("window", page);
vi.stubGlobal("document", { visibilityState: "visible" });
vi.stubGlobal("navigator", { userAgent: "test-browser", language: "en", onLine: true });
vi.spyOn(console, "info").mockImplementation(() => undefined);
return page;
}
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
vi.restoreAllMocks();
vi.resetModules();
});
describe("opt-in Browser diagnostics", () => {
it("does no diagnostic collection without the explicit flag", async () => {
const page = browser("");
const debug = await import("../src/client/lib/debug");
expect(debug.installBrowserDebug()).toBeUndefined();
debug.debugEvent("capture", "requested", { resolution: "1080p" });
debug.debugError("capture", "failed", new Error("private detail"));
expect(console.info).not.toHaveBeenCalled();
expect(page.__PIIK_DEBUG__).toBeUndefined();
});
it("retains error causes, stacks and technical context while removing credentials and media", async () => {
const page = browser();
const debug = await import("../src/client/lib/debug");
const cleanup = debug.installBrowserDebug();
const error = new Error('Encoding failed: {"password":"secret-password"}', {
cause: new Error("fetch https://user:secret-auth@example.test/api?token=secret-query#secret-fragment failed; Bearer secret-bearer"),
});
debug.debugError("capture", "failed", error, {
connectionId: "connection-123", address: "192.0.2.1", requested: { width: 1920, fps: 60 },
hostToken: "secret-host", nested: { icePwd: "secret-ice", cookie: "secret-cookie", sdp: "secret-sdp", remoteSdp: "secret-remote-sdp" },
data: "secret-pixels", payload: "secret-audio",
viewerGrant: "secret-grant", passwordHash: "secret-hash",
transportError: "piik-client-v9.secret-capability Basic secret-basic\nCookie: session=secret-session; refresh=secret-refresh",
});
const report = await page.__PIIK_DEBUG__!.export();
for (const secret of ["secret-password", "secret-auth", "secret-query", "secret-fragment", "secret-bearer",
"secret-host", "secret-ice", "secret-cookie", "secret-sdp", "secret-remote-sdp", "secret-pixels", "secret-audio", "private-grant",
"secret-grant", "secret-hash", "secret-capability", "secret-basic", "secret-session", "secret-refresh"])
expect(report).not.toContain(secret);
for (const useful of ["Encoding failed", "fetch", "stack", "cause", "connection-123", "192.0.2.1", "1920"])
expect(report).toContain(useful);
cleanup?.();
});
it("bounds history and reports eviction, truncation, retained range and collector failure", async () => {
const page = browser();
const debug = await import("../src/client/lib/debug");
debug.installBrowserDebug();
for (let revision = 0; revision < 8_300; revision++) debug.debugEvent("signal", "route", { revision });
const saved = page.__PIIK_DEBUG__!.events();
expect(saved).toHaveLength(8_192);
saved[0]!.details.revision = -1;
expect(page.__PIIK_DEBUG__!.events()[0]!.details.revision).toBe(108);
// Exercise the byte limit separately from the event-count limit.
for (let index = 0; index < 1_100; index++) debug.debugEvent("capture", "state", { message: "界".repeat(9_000) });
debug.debugError("webrtc", "collector-failed", new Error("stats unavailable"), { collector: "getStats", connectionId: "edge" });
const report = JSON.parse(await debug.exportBrowserDebug());
expect(report.history.retainedBytes).toBeLessThanOrEqual(8 * 1024 * 1024);
expect(report.history.retainedEvents).toBeLessThan(1_100);
expect(report.history.evictedEvents).toBeGreaterThan(108);
expect(report.history.truncatedEvents).toBe(1_100);
expect(report.history.firstSequence).toBe(report.events[0].sequence);
expect(report.history.lastAt).toBe(report.events.at(-1).at);
expect(report.partial).toBe(true);
expect(report.collectorErrors).toContainEqual(expect.objectContaining({ collector: "getStats", connectionId: "edge" }));
});
it("returns retained evidence when optional Browser metadata never completes", async () => {
browser();
vi.useFakeTimers();
vi.stubGlobal("navigator", { userAgent: "known-browser", userAgentData: {
getHighEntropyValues: () => new Promise(() => undefined),
} });
const debug = await import("../src/client/lib/debug");
debug.debugEvent("capture", "active", { width: 1280 });
const exporting = debug.exportBrowserDebug();
await vi.advanceTimersByTimeAsync(1_000);
const report = JSON.parse(await exporting);
expect(report.environment.userAgent).toBe("known-browser");
expect(report.events).toHaveLength(1);
expect(report.partial).toBe(true);
expect(report.collectorErrors[0].collector).toBe("environment");
expect(vi.getTimerCount()).toBe(0);
});
it("correlates existing RTC samples and DTLS events without adding statistics polls", async () => {
const page = browser();
vi.useFakeTimers();
const debug = await import("../src/client/lib/debug");
const rtc = await import("../src/client/lib/debug-webrtc");
debug.installBrowserDebug();
const transport = Object.assign(new EventTarget(), { state: "connecting" });
const connection = Object.assign(new EventTarget(), {
connectionState: "connecting", iceConnectionState: "checking", iceGatheringState: "complete", signalingState: "stable",
getSenders: () => [{ transport }], getReceivers: () => [], getStats: vi.fn(),
});
const peer = connection as unknown as RTCPeerConnection;
rtc.observeDebugConnection(peer, { connectionId: "local-edge", role: "send" });
transport.state = "connected";
transport.dispatchEvent(new Event("statechange"));
rtc.debugRtcStats(peer, new Map([
["video", { id: "video", type: "outbound-rtp", framesEncoded: 60, totalEncodeTime: 0.3 }],
["codec", { id: "codec", type: "codec", mimeType: "video/H264", sdpFmtpLine: "packetization-mode=1;profile-level-id=42e01f" }],
["private", { id: "private", type: "certificate", base64Certificate: "private-certificate" }],
]) as unknown as RTCStatsReport);
await vi.advanceTimersByTimeAsync(5_000);
expect(connection.getStats).not.toHaveBeenCalled();
expect(vi.getTimerCount()).toBe(0);
const history = page.__PIIK_DEBUG__!.events();
expect(history.filter((event) => event.scope === "webrtc").every((event) => event.details.connectionId === "local-edge")).toBe(true);
expect(history).toContainEqual(expect.objectContaining({ event: "dtls-state", details: expect.objectContaining({ state: "connected" }) }));
const report = await debug.exportBrowserDebug();
expect(report).toContain("framesEncoded");
expect(report).toContain("packetization-mode=1;profile-level-id=42e01f");
expect(report).not.toContain("private-certificate");
});
it("correlates actual Native request and response using their existing wire identity", async () => {
const page = browser();
const token = "x".repeat(43);
class Socket extends EventTarget {
static OPEN = 1; static CLOSING = 2;
readyState = 1; protocol = `piik-client-v9.${token}`;
constructor() { super(); queueMicrotask(() => this.dispatchEvent(new Event("open"))); }
close() { this.readyState = 3; }
send(raw: string) {
const request = JSON.parse(raw);
queueMicrotask(() => this.dispatchEvent(Object.assign(new Event("message"), {
data: JSON.stringify({ version: 9, id: request.id,
type: request.type === "hello" ? "ready" : "share-updated",
...(request.shareId ? { shareId: request.shareId } : {}) }),
})));
}
}
vi.stubGlobal("WebSocket", Socket);
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({
protocol: 9, service: "piik-client", port: 39721, instanceToken: token,
nativeMedia: { video: true, processAudio: false, systemAudio: true, hardwareH264: true, softwareVP8: true },
}), { status: 200 })));
const debug = await import("../src/client/lib/debug");
debug.installBrowserDebug();
const { NativeClient } = await import("../src/client/native/client");
const { DEFAULT_QUALITY_SETTINGS } = await import("../src/shared/protocol");
const client = await NativeClient.connect();
expect(client).not.toBeNull();
try { await client!.updateShare("share_123456", DEFAULT_QUALITY_SETTINGS); }
finally { client!.close(); }
const history = page.__PIIK_DEBUG__!.events().filter((event) => event.details.type === "update-share");
expect(history.map((event) => event.event)).toEqual(["request", "response"]);
expect(history[1]!.details.requestId).toBe(history[0]!.details.requestId);
expect(history[1]!.details.durationMs).toBeGreaterThanOrEqual(0);
expect(history[0]!.details.requested).toMatchObject({ profile: DEFAULT_QUALITY_SETTINGS });
expect(await debug.exportBrowserDebug()).not.toContain(token);
});
it("reports an observed App mismatch without exposing its capability token", async () => {
const page = browser();
const token = "x".repeat(43);
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({
protocol: 8, service: "piik-client", port: 39721, instanceToken: token,
}))));
const debug = await import("../src/client/lib/debug");
debug.installBrowserDebug();
const { NativeClient } = await import("../src/client/native/client");
await expect(NativeClient.connect()).rejects.toMatchObject({ name: "NativeCompatibilityError" });
expect(page.__PIIK_DEBUG__!.events()).toContainEqual(expect.objectContaining({
scope: "native", event: "incompatible", details: { actualProtocol: 8, expectedProtocol: 9 },
}));
expect(await debug.exportBrowserDebug()).not.toContain(token);
});
});