Files
Piik/scripts/client-loopback-gate.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

284 lines
11 KiB
TypeScript

import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { mkdtemp } from "node:fs/promises";
import { createServer } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
CdpConnection,
cleanupRun,
createPage,
evaluate,
launchChrome,
waitForVersion,
} from "./browser-gate-harness";
import {
readClientEndpoint,
type ClientEndpoint as Endpoint,
} from "./client-gate-endpoint";
import {
NATIVE_CLIENT_PORT_END,
NATIVE_CLIENT_PORT_START,
NATIVE_CLIENT_PROTOCOL,
NATIVE_CLIENT_SUBPROTOCOL,
} from "../src/client/native/wire";
const NATIVE_PROTOCOL = NATIVE_CLIENT_PROTOCOL;
const NATIVE_SUBPROTOCOL = NATIVE_CLIENT_SUBPROTOCOL;
interface GateReport {
passed: boolean;
platform: NodeJS.Platform;
browser: string | null;
hostedExpectation: "blocked" | "connected";
clientStarted: boolean;
localPageConnected: boolean;
localPageError: string | null;
localPageEvents: string[];
hostedPageConnected: boolean;
hostedPageError: string | null;
hostedPageEvents: string[];
hostedPageBlockedByBrowser: boolean;
clientExited: boolean;
browserExited: boolean;
profileRemoved: boolean;
}
async function browserHandshake(
cdp: CdpConnection,
page: { sessionId: string },
endpoint: Endpoint,
): Promise<{ health: boolean; responses: string[]; error: string | null; events: string[] }> {
const endpointJSON = JSON.stringify({
host: "127.0.0.1",
expectedPort: endpoint.port,
portStart: NATIVE_CLIENT_PORT_START,
portEnd: NATIVE_CLIENT_PORT_END,
});
return await evaluate(
cdp,
page,
`(() => new Promise((resolve) => {
const expected = ${endpointJSON};
const result = { health: false, responses: [], error: null, events: [] };
const finish = () => resolve(result);
const discover = async () => {
for (let port = expected.portStart; port <= expected.portEnd; port += 1) {
const probeController = new AbortController();
const probeTimer = setTimeout(() => probeController.abort(), 500);
try {
const response = await fetch("http://" + expected.host + ":" + port + "/health", {
cache: "no-store", signal: probeController.signal, targetAddressSpace: "loopback",
});
if (!response.ok) continue;
const health = await response.json();
if (health.protocol === ${NATIVE_PROTOCOL} && health.service === "piik-client" &&
health.port === port && typeof health.instanceToken === "string" &&
typeof health.nativeMedia?.video === "boolean" &&
typeof health.nativeMedia?.processAudio === "boolean" &&
typeof health.nativeMedia?.systemAudio === "boolean" &&
typeof health.nativeMedia?.hardwareH264 === "boolean") {
return { port, instanceToken: health.instanceToken };
}
} catch {} finally {
clearTimeout(probeTimer);
}
}
throw new Error("Client not found");
};
discover()
.then((endpoint) => {
result.health = endpoint.port === expected.expectedPort;
const socket = new WebSocket(
"ws://" + expected.host + ":" + endpoint.port + "/control",
["${NATIVE_SUBPROTOCOL}." + endpoint.instanceToken],
);
let settled = false;
const settle = () => {
if (settled) return;
settled = true;
clearTimeout(timer);
finish();
};
const timer = setTimeout(() => { result.events.push("timeout"); result.error = "control timeout"; socket.close(); settle(); }, 8000);
socket.onopen = () => {
const expectedProtocol = "${NATIVE_SUBPROTOCOL}." + endpoint.instanceToken;
result.events.push(socket.protocol === expectedProtocol ? "open" : "protocol-mismatch");
if (socket.protocol !== expectedProtocol) {
result.error = "control protocol mismatch";
socket.close();
settle();
return;
}
socket.send(JSON.stringify({ version: ${NATIVE_PROTOCOL}, id: "request_hello", type: "hello" }));
};
socket.onclose = (event) => { result.events.push("close:" + event.code); if (!settled && !result.error) result.error = "control closed"; settle(); };
socket.onmessage = (event) => {
const message = JSON.parse(event.data);
result.events.push("message:" + message.type);
result.responses.push(message.type);
if (message.type === "ready") {
try { socket.send(JSON.stringify({ version: ${NATIVE_PROTOCOL}, id: "request_ping", type: "ping" })); } catch (error) { result.error = String(error?.message || error); settle(); }
} else if (message.type === "pong") {
socket.close(1000, "gate complete");
settle();
}
};
socket.onerror = () => { result.events.push("error"); result.error = "control socket error"; socket.close(); settle(); };
})
.catch((error) => { result.error = String(error?.message || error); finish(); });
}))()`,
Date.now() + 15_000,
);
}
async function main(): Promise<void> {
if (process.platform !== "win32" && process.platform !== "darwin" && process.platform !== "linux") {
throw new Error("loopback gate requires a desktop platform");
}
if (process.env.PIIK_CLIENT_LOOPBACK_GATE !== "true") {
throw new Error("loopback gate was not explicitly enabled");
}
const browserPath = process.env.CHROME_PATH?.trim();
const clientPath = process.env.PIIK_CLIENT_EXE?.trim();
const pageUrl = process.env.PIIK_CLIENT_GATE_SITE_URL?.trim();
if (!browserPath || !clientPath || !pageUrl) {
throw new Error("CHROME_PATH, PIIK_CLIENT_EXE and PIIK_CLIENT_GATE_SITE_URL are required");
}
const pageOrigin = new URL(pageUrl).origin;
const disposableNoSandbox =
process.env.PIIK_CLIENT_GATE_NO_SANDBOX === "true";
const grantLoopback =
process.env.PIIK_CLIENT_GATE_GRANT_LOOPBACK === "true";
const report: GateReport = {
passed: false,
platform: process.platform,
browser: null,
hostedExpectation: grantLoopback ? "connected" : "blocked",
clientStarted: false,
localPageConnected: false,
localPageError: null,
localPageEvents: [],
hostedPageConnected: false,
hostedPageError: null,
hostedPageEvents: [],
hostedPageBlockedByBrowser: false,
clientExited: false,
browserExited: false,
profileRemoved: false,
};
let profile: string | null = null;
let client: ChildProcessWithoutNullStreams | null = null;
let browser: ChildProcessWithoutNullStreams | null = null;
let cdp: CdpConnection | null = null;
let debugPort = 0;
try {
profile = await mkdtemp(join(tmpdir(), "piik-client-loopback-"));
client = spawn(clientPath, [
"--site", pageUrl,
"--config", join(profile, "client.json"),
], {
stdio: "pipe",
windowsHide: true,
env: { ...process.env, PIIK_CLIENT_GATE_NO_BROWSER: "true" },
});
client.stderr.resume();
const endpoint = await readClientEndpoint(client, { timeoutMs: 8_000 });
report.clientStarted = true;
const portServer = createServer();
debugPort = await new Promise<number>((resolvePort, rejectPort) => {
portServer.once("error", rejectPort);
portServer.listen(0, "127.0.0.1", () => {
const address = portServer.address();
if (!address || typeof address === "string") {
rejectPort(new Error("debug port reservation failed"));
return;
}
portServer.close((error) => error ? rejectPort(error) : resolvePort(address.port));
});
});
browser = launchChrome(browserPath, debugPort, profile, [
"--headless=new",
...(disposableNoSandbox ? ["--no-sandbox"] : []),
"--no-first-run",
"--no-proxy-server",
"--disable-logging",
]);
browser.stdout.resume();
browser.stderr.resume();
const version = await waitForVersion(debugPort, browser);
report.browser = version.Browser;
cdp = await CdpConnection.connect(version.webSocketDebuggerUrl, Date.now() + 10_000);
if (grantLoopback) {
await cdp.call(
"Browser.setPermission",
{
permission: { name: "loopback-network" },
setting: "granted",
origin: pageOrigin,
},
undefined,
Date.now() + 5_000,
);
}
const localPage = await createPage(cdp, endpoint.url + "/health");
const localResult = await browserHandshake(cdp, localPage, endpoint);
report.localPageConnected = localResult.health &&
localResult.responses.join(",") === "ready,pong";
report.localPageError = localResult.error;
report.localPageEvents = localResult.events;
const hostedPage = await createPage(cdp, pageUrl);
// A failed navigation or cross-origin redirect is not LNA rejection evidence.
if (await evaluate(cdp, hostedPage, "location.origin", Date.now() + 5_000) !== pageOrigin) {
throw new Error("Hosted page did not load at the configured Site origin");
}
const hostedResult = await browserHandshake(cdp, hostedPage, endpoint);
report.hostedPageConnected = hostedResult.health &&
hostedResult.responses.join(",") === "ready,pong";
report.hostedPageError = hostedResult.error;
report.hostedPageEvents = hostedResult.events;
report.hostedPageBlockedByBrowser = !report.hostedPageConnected &&
hostedResult.error !== null;
} finally {
const cleanup = await cleanupRun({
cdp,
native: client,
chrome: browser,
server: null,
profile,
ports: debugPort > 0 ? [debugPort] : [],
});
report.browserExited = cleanup.browserExited;
report.clientExited = cleanup.nativeExited;
if (profile) {
report.profileRemoved = cleanup.profileRemoved;
if (!report.profileRemoved) {
await new Promise((resolveDelay) => setTimeout(resolveDelay, 250));
const retry = await cleanupRun({
cdp: null,
native: null,
chrome: null,
server: null,
profile,
ports: [],
});
report.profileRemoved = retry.profileRemoved;
}
}
}
const hostedExpectationMet = grantLoopback
? report.hostedPageConnected
: report.hostedPageBlockedByBrowser;
report.passed = report.clientStarted && report.localPageConnected &&
hostedExpectationMet &&
report.clientExited && report.browserExited && report.profileRemoved;
process.stdout.write(`${JSON.stringify(report)}\n`);
if (!report.passed) process.exitCode = 1;
}
await main();