Files
piik/scripts/network-lab/endpoint.ts
T
AAA da7218bf44 feat(voice): add room voice and secure local invitations
## Problem and outcome / 问题与结果

Planned release: **v2.3.0**, preserving the published 2.x sharing contracts.

Friends can now talk in a Piik room before, during or after screen sharing. Room
voice, media forwarding and the picture retain separate lifetimes under the
existing room authority and route controller. This phase also improves direct LAN
entry, native capture startup, interaction controls and first-use documentation.

Related: #484, #437, #486, #488, #485 and #489. These references do not declare
all reported hardware or distribution problems fixed.

## Release notes

**Less typing. More talking.**

Piik now supports room voice, with or without screen sharing.

**聊不够?开麦吧!**

Piik 现已支持房间语音,不开播也能聊。

### English

This update adds room voice alongside sharing, chat and reactions, with clearer
controls and direct HTTPS invitations for local and virtual networks.

#### Highlights

- Create a room before sharing. The Host opens or closes room voice; friends
  can join, control their own microphone and listening, or mute someone locally.
  Joining voice keeps the microphone off until you enable it.
- Choose your microphone, adjust microphone, master and individual listening
  volumes from 0% to 200%, and enable voice processing in the interaction window.
  Audio icons offer quick volume sliders. The microphone icon shows live input
  level. Voice continues when the picture stops.
- Use a local HTTPS invitation for microphone and remote-control features on a
  LAN or virtual LAN. A temporary local certificate requires a browser warning
  confirmation; a self-hosted Server can also use supplied certificate files.
- Rotate your local picture, optionally volunteer more relay capacity, and
  download a native Windows x64 Server package.

#### Fixes and polish

- Align Windows automatic encoder probes with the surfaces used during actual
  capture; keep video capture progressing while optional source audio starts.
- Correct Linux desktop pixel-aspect negotiation and accept fitted native
  source dimensions without forcing a different aspect ratio.
- Avoid retaining false media queue congestion when producer and consumer
  clocks disagree.
- Distinguish chat authors with identical names, clarify remote permissions,
  and keep floating tools, contextual hints and microphone indicators aligned.
- Separate first-use guides, room tools and troubleshooting so help is easier
  to find.

Use updated Server/Web pages for room voice and update the App for the native
capture and local HTTPS improvements. Established 2.x sharing remains supported.
macOS builds do not yet carry Developer ID signing or Apple notarization; see the first-launch instructions.
The macOS audio-startup changes still need confirmation on an affected Mac.

### 中文

本次更新为分享、聊天和表情互动加入房间语音,同时打磨操作控件,并为局域网和虚拟局域网提供直接 HTTPS 邀请。

#### 主要变化

- 不开播也能创建房间。房主开启或关闭房间语音;朋友可以加入、自行开关麦克风和收听,或仅在自己这边静音某人。加入语音时默认不开麦。
- 在互动窗口选择麦克风、分别调整 0%–200% 的麦克风、总收听与个人音量,并设置语音处理。音频图标可展开快捷音量条,麦克风图标显示实时输入音量。停止画面分享后,语音仍可继续。
- 局域网和虚拟局域网可使用本地 HTTPS 邀请,启用麦克风和远程控制;临时本地证书需要在浏览器确认警告。自部署服务端也可使用自行提供的证书文件。
- 可旋转本地观看画面、自愿增加转发容量,并提供 Windows x64 服务端下载包。

#### 修复与打磨

- Windows 自动编码探测使用与实际采集一致的输入;可选来源音频启动期间,画面采集继续运行。
- 修正 Linux 桌面采集的像素比例协商;原生来源保留实际画幅,不再要求固定比例的尺寸。
- 避免生产者和消费者时钟不一致时,错误保留媒体队列拥塞状态。
- 区分同名聊天作者,明确远控授权,并统一浮窗、上下文提示与麦克风指示器的细节。
- 分开首次使用、房间工具和故障排查文档,让帮助更容易查找。

房间语音需使用更新后的服务端和网页;原生采集与本地 HTTPS 改进需更新 App。既有 2.x 分享仍保持兼容。
macOS 构建仍未正式签名和公证,首次启动请参照文档;音频启动调整仍需在受影响的 Mac 上确认。

## Verification / 验证

Full Web checks, Go tests/vet/build/native probes, reachable vulnerability checks,
normal-page P2P/SFU voice and compatible sharing, LAN HTTPS, detached interaction
tools, responsive controls and tooltip/pure-visual checks provide acceptance
evidence. Physical macOS/Linux capture and acoustic behavior on arbitrary devices
are not established by these controls.

Scoped contributions from #488 (Linux pixel aspect) and #485 (Windows Server
packaging) are retained as their original authors' patch commits in this PR.
The remaining implementation and integration belong to the maintainer.

## Impact / 影响

Preserve the published 2.x sharing contract. New room-voice behavior is opt-in;
Host voice activation, capture and picture lifetimes remain distinct. Local
certificate material remains in memory; no system trust installation is performed.
2026-10-21 06:51:22 -04:00

157 lines
11 KiB
TypeScript

import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { once } from "node:events";
import { readFile, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { createInterface } from "node:readline";
import { CdpConnection, cleanupRun, createPage, evaluate, fetchJsonBefore, launchChrome, reservePort, waitForSample,
waitForVersion, type PageHandle } from "../browser-gate-harness";
import { readAppEndpoint } from "../app-gate-endpoint";
import { pageProbe, type MediaSample } from "./page";
import { filteringProbe, preparePeerProbe, udpProbe } from "./udp";
export async function endpointWorker(): Promise<void> {
let chrome: ChildProcessWithoutNullStreams | null = null, app: ChildProcessWithoutNullStreams | null = null;
let cdp: CdpConnection | null = null, page: PageHandle | null = null;
const profile = process.env.PIIK_NETWORK_LAB_PROFILE;
if (!profile) throw new Error("Parent-owned browser profile is required");
const ports: number[] = [];
let rendezvous: Awaited<ReturnType<typeof preparePeerProbe>> | null = null;
const logs: Record<string, string> = {};
const log = (name: string, data: Buffer) => { logs[name] = ((logs[name] ?? "") + data).slice(-64_000); };
let closed = false;
const cleanup = async () => {
if (closed) return;
closed = true;
rendezvous?.close();
return cleanupRun({ chrome, native: app, cdp, server: null, profile, ports });
};
const sample = () => evaluate<MediaSample>(cdp!, page!, "networkLab.sample()", Date.now() + 5000);
const click = async (selector: string) => {
await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
`(()=>{const node=document.querySelector(${JSON.stringify(selector)});return !!node&&!node.disabled&&node.getAttribute('aria-disabled')!=='true';})()`, deadline), Boolean, 10_000);
await evaluate(cdp!, page!, `document.querySelector(${JSON.stringify(selector)}).click()`, Date.now() + 5000);
};
try {
for await (const line of createInterface({ input: process.stdin })) {
const request = JSON.parse(line) as { id: number; action: string; origin?: string; app?: boolean;
url?: string; output?: string; delayMs?: number; load?: boolean; ipv6?: boolean; prediction?: boolean; sfuOnly?: boolean; peer?: { address: string; port: number } };
try {
let result: unknown;
if (request.action === "probe") {
result = await udpProbe(request.load === true, request.ipv6 === true);
} else if (request.action === "filter-probe") {
result = await filteringProbe();
} else if (request.action === "peer-prepare") {
rendezvous?.close(); rendezvous = await preparePeerProbe(); result = rendezvous.mapping;
} else if (request.action === "peer-probe") {
if (!rendezvous) throw new Error("Survey must precede peer probing");
result = await rendezvous.run(request.peer!);
} else if (request.action === "start") {
const origin = new URL(request.origin!).origin;
await waitForSample(deadline => fetchJsonBefore<{ status: string }>(`${origin}/healthz`, deadline),
value => value.status === "ok", 10_000);
if (request.app) {
app = spawn(resolve(`build/network-lab/bin/piik-app${process.platform === "win32" ? ".exe" : ""}`), ["--site", origin, "--debug", "--config", join(profile, "app.json")],
{ stdio: "pipe", windowsHide: true, env: { ...process.env, PIIK_CLIENT_GATE_NO_BROWSER: "true", PIIK_LOG_DIR: join(profile, "logs") } });
app.stderr.on("data", data => log("app", data));
await once(app, "spawn");
ports.push((await readAppEndpoint(app)).port); app.stdout.resume();
}
const debugPort = await reservePort(); ports.push(debugPort);
chrome = await launchChrome(process.env.CHROME_PATH!, debugPort, profile, [
"--headless=new", "--no-sandbox", "--disable-dev-shm-usage", "--no-first-run", "--no-default-browser-check",
"--no-proxy-server", "--autoplay-policy=no-user-gesture-required", "--disable-background-timer-throttling",
"--use-fake-device-for-media-stream", "--use-fake-ui-for-media-stream",
"--disable-renderer-backgrounding", "--disable-backgrounding-occluded-windows",
`--unsafely-treat-insecure-origin-as-secure=${origin}`,
]);
chrome.stdout.resume(); chrome.stderr.on("data", data => log("browser", data));
const version = await waitForVersion(debugPort, chrome);
cdp = await CdpConnection.connect(version.webSocketDebuggerUrl, Date.now() + 10_000);
await cdp.call("Browser.setPermission", { origin, permission: { name: "loopback-network" }, setting: "granted" }, undefined, Date.now() + 5000);
result = { browser: version.Browser, app: request.app === true, appPort: request.app ? ports[0] : null };
} else if (request.action === "navigate") {
if (page) {
const oldTimeOrigin = await evaluate<number>(cdp!, page!, "performance.timeOrigin", Date.now() + 5000);
const navigation = await cdp!.call<{ loaderId?: string; errorText?: string }>("Page.navigate", { url: request.url! }, page.sessionId, Date.now() + 5000);
if (navigation.errorText) throw new Error(navigation.errorText);
await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
`${navigation.loaderId ? `performance.timeOrigin !== ${oldTimeOrigin} && ` : ""}document.readyState === 'complete' && Boolean(window.networkLab)`, deadline), Boolean, 10_000);
} else page = await createPage(cdp!, request.url!, pageProbe);
result = true;
} else if (request.action === "reload") {
const oldTimeOrigin = await evaluate<number>(cdp!, page!, "performance.timeOrigin", Date.now() + 5000);
await cdp!.call("Page.reload", {}, page!.sessionId, Date.now() + 5000);
await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
`performance.timeOrigin !== ${oldTimeOrigin} && document.readyState === 'complete' && Boolean(window.networkLab)`, deadline), Boolean, 10_000);
result = true;
} else if (request.action === "share") {
const advanced = 'button[aria-controls="host-advanced-door"]';
await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
`Boolean(document.querySelector(${JSON.stringify(advanced)}))`, deadline), Boolean, 10_000);
if (await evaluate<boolean>(cdp!, page!, `document.querySelector(${JSON.stringify(advanced)}).getAttribute('aria-expanded') !== 'true'`, Date.now() + 5000)) await click(advanced);
if (request.sfuOnly) {
if (request.prediction) throw new Error("SFU-only cannot request NAT enhancement");
await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
`Boolean(document.querySelector('button[role="switch"][aria-label^="Server media"][aria-disabled="true"][aria-checked="true"]'))`, deadline), Boolean, 10_000);
}
// Browser-to-App encoded fanout is the production H264 path. VP8
// deliberately stays in the Browser and must not masquerade as App WAN.
await click(app ? 'button[aria-label^="H264"]' : 'button[aria-label^="VP8"]');
await click('button[aria-label="720p"]');
await click("button.lr-tv-big.is-action");
// Selecting Browser before App discovery completes intentionally uses
// Browser fanout. An App scenario waits for the real control session.
if (app) await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
`Boolean(document.querySelector('.lr-source-picker-refresh:not(:disabled)')) && networkLab.sample().then(value => value.controlOpen)`,
deadline), Boolean, 10_000);
await click('button[data-source-tab="browser"]');
await click(".lr-source-option.is-browser");
await waitForSample(sample, value => value.sharing && value.width > 0 &&
(request.prediction === undefined || value.natPrediction === request.prediction), 30_000);
result = await evaluate<string>(cdp!, page!, "document.querySelector('.lr-invite-url').value", Date.now() + 5000);
} else if (request.action === "sample") {
result = await sample();
} else if (request.action === "delay-peer-signals") {
if (!Number.isInteger(request.delayMs) || request.delayMs! < 0 || request.delayMs! > 30_000) throw new Error("Invalid signal delay");
await evaluate(cdp!, page!, `networkLab.delayPeerSignals(${request.delayMs})`, Date.now() + 5000);
result = true;
} else if (request.action === "reset-playback-progress") {
await evaluate(cdp!, page!, "networkLab.resetPlaybackProgress()", Date.now() + 5000);
result = true;
} else if (request.action === "freeze-picture") {
result = await evaluate(cdp!, page!, "networkLab.freezeCapture()", Date.now() + 5000);
} else if (request.action === "resume-picture") {
result = await evaluate(cdp!, page!, "networkLab.resumeCapture()", Date.now() + 5000);
} else if (request.action === "signal-probe") {
result = await evaluate(cdp!, page!, "networkLab.signalProbe()", Date.now() + 5000);
} else if (request.action === "logs") {
if (app) logs.app = await readFile(join(profile, "logs", "client.log"), "utf8")
.then(text => text.slice(-64_000), error => String(error));
result = logs;
} else if (request.action === "stop") {
await click('button[aria-label="Stop sharing"]'); result = true;
} else if (request.action === "voice-open" || request.action === "voice-join") {
await click('button[aria-label="Interact"]');
await click('[role="tab"][id$="-voice-tab"]');
await click(`button[aria-label="${request.action === "voice-open" ? "Open room voice" : "Join voice"}"]`);
await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
`Boolean(document.querySelector('button[aria-label="Microphone"][aria-pressed="false"]'))`, deadline), Boolean, 10_000);
await click('button[aria-label="Microphone"][aria-pressed="false"]'); result = true;
} else if (request.action === "voice-sample") {
result = await evaluate(cdp!, page!, "networkLab.voiceSample()", Date.now() + 5000);
} else if (request.action === "screenshot") {
const shot = await cdp!.call<{ data: string }>("Page.captureScreenshot", { format: "png" }, page!.sessionId, Date.now() + 5000);
await writeFile(request.output!, Buffer.from(shot.data, "base64")); result = true;
} else if (request.action === "close") {
result = await cleanup();
} else throw new Error("Unknown endpoint action");
process.stdout.write(JSON.stringify({ id: request.id, result }) + "\n");
if (closed) break;
} catch (error) {
process.stdout.write(JSON.stringify({ id: request.id, error: error instanceof Error ? error.message : String(error) }) + "\n");
}
}
} finally { await cleanup(); }
}