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): add one-share P2P debug mode [skip ci]

AAA91df9b7c8905
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 cfc63ab1..1020666a 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"
@@ -124,6 +124,8 @@ WebSocket 使用无 query/fragment 的同源 `/signal`。upgrade 只记录 site-
Zod 在服务边界拒绝未知类型、超长字符串、非法 SDP/candidate 结构和越权目标。服务端根据已认证会话决定路由:观看者不能给另一名观看者发信令,分享者也不能向本房间以外的 peerId 发送。
+Host 新 share generation 的首次 `authenticate` 可选带 `debugP2pOnly: true`。服务端在 participant 进入 router 前把它绑定为当前进程内的 room/share-generation 状态;Viewer schema 严格拒绝该字段。同 generation 信令重连保持权威状态,不能借重连中途切换;`stop-sharing`、新 generation、room 删除和进程重启清除。新进程可从 Host 不可变认证 identity 重新接受该 generation 的请求,`authenticated.debugP2pOnly` 回显服务端实际状态,避免 UI 与路由状态分叉。启用时 router 仍执行 STUN-only direct、ICE restart/rebuild 与 alternate peer,但不创建 SFU prepare/config/token/publication、不发 standby URL,也不签发 `peer-selected` 或 `host-sfu-ingress` TURN;路径耗尽沿现有 `PEER_NOT_FOUND` 有界失败。它不持久化、不改变默认自动路由,也不充当 NAT 类型判断器;Hard NAT、TCP 与生日探测边界继续以[低服务器成本媒体路由](./research/low-server-media-routes.md)为准。
+
该授权迁移把唯一 literal 从 `screener-v1` 原子改为 `screener-v2`,不做版本协商。旧页面的首条消息在任何角色进入 room lookup 前得到同一个 fatal refresh 终态、停止自动重连;服务端不解析 v1、不双写、不维护 translator。缺失、过期、跨房、已 rotate 或 revoked 的 v2 Viewer grant 则使用同一个通用“邀请无效或已失效”结果,不区分房间不存在与凭据错误。
## WebRTC 协商
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 ccce72c9..c1fd7210 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"
@@ -42,6 +42,7 @@
- [ ] 私密房间双入口:private room 接受现有 `/r/{code}#v={grant}` 合法邀请直接进入,或“站点访问 + 房间号 + 该房间观看密码”。没有 grant 的 `/join` 或 `/r/{code}` 先显示明确标为“站点访问”的整站验证,通过后才显示明确标为“加入房间”的当前房间密码输入;有效 site-access cookie 直接跳过第一步,但两类密码不得复用、代填或互相替代。Host 可设置、轮换或移除房间观看密码。密码接受 1 至 64 个可见 ASCII 字符;异步 scrypt 全局最多执行 2 个、等待 16 个派生。站点口令和房间密码都不得进入 URL/query/storage/log/SQLite;不存在、错误密码、队满和正确密码后的满房都返回通用结果。
- [ ] 统一自动路由:旗舰部署开启 `PEER_ASSISTED_MEDIA` 后,所有正常房间都进入同一个 direct/peer -> SFU -> selected-edge controller;每个房间独立保存 assignment/session/revision/connection generation 和容量状态。合格父节点构成网状候选关系,但实际媒体保持无环且每个 Viewer 只有一个 active upstream;加入、容量变化、掉线和当前边失败触发有界重选,切换重叠必须受现有边预算与当前代媒体证据约束,不做常驻多源分片。`PEER_ASSISTED_ROOM_IDS` 已退役,room `1` 只作为历史 smoke fixture,不能作为功能开关。未启用总开关的开发/轻量部署仍可保留 ordinary P2P;普通 peer 始终 STUN-only。selected-edge TURN 只能复用当前 controller 选中的异常 edge,不能向普通 peer edge 预发 candidates。该能力不增加 UI、用户选择、百分比发布或第二套路由器。
+- [ ] 纯 P2P 调试会话:Host 可在高级设置中为下一次分享临时选择“仅测试 P2P”。该选择只允许 Host 在新 share generation 的首次鉴权中请求,服务端权威阻止本次分享的 SFU prepare/config/publication、standby 和 selected-edge TURN,同时保留 STUN-only direct、ICE restart/rebuild 与一个 alternate peer;耗尽后明确失败。同 generation 信令重连保持且不能中途切换;停止分享、新 share generation、room 删除或服务端进程重启才清除。新进程可从 Host 不可变认证 identity 重新接受请求,并在 `authenticated` 中回显实际状态。设置不持久化,Viewer 不能设置。它只用于收集真实连接结果,不得宣称能稳定穿透 endpoint-dependent NAT。
- [ ] 质量控制扩展:推荐档位仍是默认入口;折叠高级区只允许 720p/1080p/1440p 分辨率 ceiling、15 至 60 的整数 FPS ceiling、2 至 12 Mbps 视频码率 ceiling,以及清晰/平衡/流畅三种偏好。直播中显式应用后才生效,避免滑杆产生连续控制流量。Web 不提供音频声道、采样率、Opus 码率、stereo、DTX 或 FEC 控件;每个实际浏览器音频 sender 固定请求并读回 128 kbps ceiling,SFU 音频发布使用同值 preset 且关闭 DTX。该值只是标准 API/SDK 支持的发送上限,实际码率仍以 stats 为准。display capture 未把声道和采样率定义为可移植控制,其他项依赖 codec/fmtp 协商而没有可移植 sender setter。不得为这些控件新增应用层 SDP munging 或用默认值制造伪控制。实际质量持续低于所选上限时必须显示可解释的限制原因;在真实拥塞、编码器和接收端证据完成前,不把任一组合称为“完美平衡”。
- [ ] 本地预览性能候选:在相同动态场景中 A/B 测量 Host 动态预览开/关的 CPU、GPU、encode time 和实际 FPS。只有稳定收益且捕获、编码和远端画面不受影响时,才允许直播开始后默认显示静止缩略图或隐藏动态预览并提供按需展开;未测前不宣称收益。
- [ ] Peer-assisted 媒体实验:分享端最多两个 child、每名 viewer 最多一个 child;信令服务只按深度和服务端加入序号确定性地形成两条 sticky 平衡链,不加入综合评分或主动重平衡。每个 viewer 将收到的标准 remote track 通过新的 `RTCPeerConnection` 转发,因此会逐跳解码和重编码;必须测量而不能称为 shared encode。服务端只在受房间数限制的内存状态中保存当前严格校验的质量设置,不写入 SQLite;host 鉴权后先重报设置,在线 viewers 接收更新,后加入者从鉴权快照取得当前值。该功能在 ADR-0004 的实验门槛通过并由后续 ADR 正式接受前不得成为产品路径。
diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsx
index 6364336f..3413622f 100644
--- a/src/client/pages/HostPage.tsx
+++ b/src/client/pages/HostPage.tsx
@@ -229,6 +229,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
const [copied, setCopied] = useState(false);
const [switchingSource, setSwitchingSource] = useState(false);
const [changingQuality, setChangingQuality] = useState(false);
+ const [p2pOnlyDebug, setP2pOnlyDebug] = useState(false);
const [sharingPaused, setSharingPaused] = useState(false);
const [localPreviewPaused, setLocalPreviewPaused] = useState(false);
const [showConnectionDetails, setShowConnectionDetails] = useState(false);
@@ -477,6 +478,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
setSignalStatus("offline");
setSwitchingSource(false);
setChangingQuality(false);
+ setP2pOnlyDebug(false);
sharingPausedRef.current = false;
setSharingPaused(false);
}
@@ -1197,6 +1199,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
token: activeRoom.hostToken,
clientId: hostClientId,
shareGeneration,
+ ...(p2pOnlyDebug ? { debugP2pOnly: true } : {}),
viewerPresence: true,
viewerPasswordSettings: true,
displayName: initialDisplayName,
@@ -1235,6 +1238,9 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
return;
}
if (message.type === "authenticated" && message.role === "host") {
+ setP2pOnlyDebug(
+ "debugP2pOnly" in message && message.debugP2pOnly === true,
+ );
iceConfigRef.current = message.iceConfig;
peersRef.current.forEach((peer) =>
peer.updateIceConfig(message.iceConfig),
@@ -1816,7 +1822,21 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
</fieldset>
<details className="advanced-quality">
- <summary>高级视频设置</summary>
+ <summary>高级设置</summary>
+ <label className="viewer-policy-toggle">
+ <input
+ type="checkbox"
+ checked={p2pOnlyDebug}
+ disabled={phase === "starting" || phase === "live"}
+ onChange={(event) => setP2pOnlyDebug(event.target.checked)}
+ />
+ <span>仅测试 P2P</span>
+ </label>
+ {p2pOnlyDebug && (
+ <WarningBanner>
+ 本次分享不使用 SFU 或 TURN;P2P 路径耗尽后直接报错
+ </WarningBanner>
+ )}
<div className="advanced-quality-grid">
<label>
<span>分辨率上限</span>
diff --git a/src/server/hybrid-media-router.ts b/src/server/hybrid-media-router.ts
index 16f4ed76..37ae479a 100644
--- a/src/server/hybrid-media-router.ts
+++ b/src/server/hybrid-media-router.ts
@@ -193,6 +193,7 @@ export class HybridMediaRouter {
string,
Map<string, string>
>();
+ private readonly p2pOnlyGenerationByRoom = new Map<string, string>();
private readonly sfuDisabledRoomIds = new Set<string>();
private readonly viewerQualityEvidenceStates = new Map<
string,
@@ -242,11 +243,31 @@ export class HybridMediaRouter {
this.viewerRouteIntentsByRoom.clear();
this.consumedSfuRefreshesByRoom.clear();
this.relayCapacitySessionsByRoom.clear();
+ this.p2pOnlyGenerationByRoom.clear();
this.sfuDisabledRoomIds.clear();
this.viewerQualityEvidenceStates.clear();
this.roomQualityMigrationCooldownUntilMs.clear();
}
+ setP2pOnly(
+ roomId: string,
+ shareGeneration: string,
+ enabled: boolean,
+ ): void {
+ if (enabled) {
+ this.p2pOnlyGenerationByRoom.set(roomId, shareGeneration);
+ return;
+ }
+ this.p2pOnlyGenerationByRoom.delete(roomId);
+ }
+
+ isP2pOnly(roomId: string, shareGeneration?: string): boolean {
+ const activeGeneration = this.p2pOnlyGenerationByRoom.get(roomId);
+ return shareGeneration === undefined
+ ? activeGeneration !== undefined
+ : activeGeneration === shareGeneration;
+ }
+
connectParticipant(input: AuthenticatedRouteParticipant): HybridAuthenticationState {
this.clearRoomViewerQualityEvidenceStates(input.roomId);
this.clearSfuRefreshesForPeer(input.roomId, input.peerId);
@@ -917,12 +938,14 @@ export class HybridMediaRouter {
}
stopRoom(roomId: string): void {
+ this.p2pOnlyGenerationByRoom.delete(roomId);
this.clearRoomMediaRouteState(roomId);
}
deleteRoom(roomId: string): void {
this.peerRelayTopology.deleteRoom(roomId);
this.relayCapacitySessionsByRoom.delete(roomId);
+ this.p2pOnlyGenerationByRoom.delete(roomId);
this.clearRoomMediaRouteState(roomId);
}
@@ -1014,6 +1037,7 @@ export class HybridMediaRouter {
return false;
}
if (
+ this.isP2pOnly(roomId) ||
!config ||
!active ||
!intent ||
@@ -1168,6 +1192,7 @@ export class HybridMediaRouter {
);
}
if (
+ this.isP2pOnly(roomId) ||
!config ||
!fallback ||
(pending !== undefined &&
@@ -1594,6 +1619,7 @@ export class HybridMediaRouter {
if (
intent.sfuAttempts === 0 &&
this.options.sfuFallback &&
+ !this.isP2pOnly(roomId) &&
!this.sfuDisabledRoomIds.has(roomId)
) {
if (
@@ -1723,7 +1749,7 @@ export class HybridMediaRouter {
): SfuPrepareResult {
const fallback = this.options.sfuFallback;
const controller = this.mediaRouteControllers.get(roomId);
- if (!fallback || !controller) {
+ if (!fallback || !controller || this.isP2pOnly(roomId)) {
return "unavailable";
}
if (controller.getPendingRoute()) {
@@ -1904,7 +1930,7 @@ export class HybridMediaRouter {
expectedSessionIds: ReadonlyMap<string, string>,
): Promise<void> {
const fallback = this.options.sfuFallback;
- if (!fallback) {
+ if (!fallback || this.isP2pOnly(roomId)) {
return;
}
try {
@@ -1928,6 +1954,7 @@ export class HybridMediaRouter {
const pendingRoute = controller.getPendingRoute();
if (
this.mediaRouteControllers.get(roomId) !== controller ||
+ this.isP2pOnly(roomId) ||
pending?.revision !== revision ||
pendingRoute?.route.revision !== revision
) {
@@ -2136,6 +2163,7 @@ export class HybridMediaRouter {
if (
!fallback ||
!controller ||
+ this.isP2pOnly(roomId) ||
!active ||
active.revision !== revision ||
!active.sfu.publicationGeneration ||
diff --git a/src/server/signaling.ts b/src/server/signaling.ts
index 8c4c6748..c8c75078 100644
--- a/src/server/signaling.ts
+++ b/src/server/signaling.ts
@@ -435,12 +435,19 @@ export class SignalingServer {
);
shareGeneration =
message.shareGeneration ?? currentGeneration ?? state.sessionId;
- if (
+ const generationChanged =
currentGeneration !== undefined &&
- currentGeneration !== shareGeneration
- ) {
+ currentGeneration !== shareGeneration;
+ if (generationChanged) {
this.stopSharing(participant.roomId);
}
+ if (currentGeneration === undefined || generationChanged) {
+ this.hybridMediaRouter?.setP2pOnly(
+ participant.roomId,
+ shareGeneration,
+ message.debugP2pOnly === true,
+ );
+ }
this.shareGenerationsByRoom.set(participant.roomId, shareGeneration);
}
state.authenticated = {
@@ -520,7 +527,14 @@ export class SignalingServer {
qualitySettings:
this.qualitySettingsByRoom.get(participant.roomId) ??
DEFAULT_QUALITY_SETTINGS,
- ...(this.options.sfuFallback
+ ...(this.hybridMediaRouter?.isP2pOnly(
+ participant.roomId,
+ shareGeneration ?? undefined,
+ )
+ ? { debugP2pOnly: true as const }
+ : {}),
+ ...(this.options.sfuFallback &&
+ !this.hybridMediaRouter?.isP2pOnly(participant.roomId)
? { sfuStandbyUrl: this.options.sfuFallback.url }
: {}),
});
diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts
index 68524e49..6eaf0dd1 100644
--- a/src/shared/protocol.ts
+++ b/src/shared/protocol.ts
@@ -483,6 +483,7 @@ const authenticateMessageSchema = z.discriminatedUnion("role", [
token: tokenSchema,
clientId: opaqueIdSchema,
shareGeneration: opaqueIdSchema.optional(),
+ debugP2pOnly: z.literal(true).optional(),
viewerPresence: z.literal(true).optional(),
viewerPasswordSettings: z.literal(true).optional(),
displayName: displayNameSchema.optional(),
@@ -620,6 +621,7 @@ const authenticatedMessageSchema = z.union([
routeRevision: mediaRouteRevisionSchema,
routeAssignment: participantRouteAssignmentSchema,
qualitySettings: qualitySettingsSchema,
+ debugP2pOnly: z.literal(true).optional(),
sfuStandbyUrl: liveKitWebSocketUrlSchema.optional(),
})
.strict(),
diff --git a/tests/protocol.test.ts b/tests/protocol.test.ts
index e4e205c4..42760ed0 100644
--- a/tests/protocol.test.ts
+++ b/tests/protocol.test.ts
@@ -402,6 +402,19 @@ describe("client signaling protocol", () => {
);
});
+ it("rejects a Viewer request for the Host-only P2P debug mode", () => {
+ expect(
+ clientMessageSchema.safeParse({
+ type: "authenticate",
+ protocol: SIGNALING_PROTOCOL,
+ roomId,
+ role: "viewer",
+ clientId: "client_12345678",
+ debugP2pOnly: true,
+ }).success,
+ ).toBe(false);
+ });
+
it("accepts only strict, bounded quality settings", () => {
expect(
clientMessageSchema.safeParse({
@@ -798,6 +811,8 @@ describe("server signaling protocol", () => {
};
expect(serverMessageSchema.safeParse(peerAssisted).success).toBe(true);
+ expect(serverMessageSchema.safeParse({ ...peerAssisted, debugP2pOnly: true }).success).toBe(true);
+ expect(serverMessageSchema.safeParse({ ...peerAssisted, debugP2pOnly: false }).success).toBe(false);
expect(
serverMessageSchema.safeParse({
...peerAssisted,
diff --git a/tests/server-signal.test.ts b/tests/server-signal.test.ts
index 05c1b6fc..21cc5cc4 100644
--- a/tests/server-signal.test.ts
+++ b/tests/server-signal.test.ts
@@ -444,6 +444,7 @@ async function authenticate(
viewerPresence?: true;
viewerPasswordSettings?: true;
viewerPassword?: string;
+ debugP2pOnly?: true;
} = {},
) {
client.socket.send(
@@ -457,6 +458,7 @@ async function authenticate(
token: room.hostToken,
clientId,
...(shareGeneration ? { shareGeneration } : {}),
+ ...(presence.debugP2pOnly ? { debugP2pOnly: true } : {}),
...(presence.viewerPresence ? { viewerPresence: true } : {}),
...(presence.viewerPasswordSettings
? { viewerPasswordSettings: true }
@@ -4096,6 +4098,108 @@ describe("WebSocket signaling", () => {
expect(issued.length).toBeGreaterThan(issuedBeforeFailback);
});
+ it("binds the Host-only P2P debug mode to one share generation", async () => {
+ const issueToken = vi.fn(async ({ peerId }: { peerId: string }) =>
+ `token-${peerId}`,
+ );
+ const harness = await startSfuHarness({
+ tokenIssuer: { issueToken },
+ selectedEdgeTurn: true,
+ stunUrls: ["stun:stun.example.test:3478"],
+ });
+ const shareGeneration = "debug-p2p-only-share";
+ // Empty generation state is also the first authentication after a restart.
+ const initialHost = await openClient(harness.webSocketUrl);
+ const hostAuth = peerAssisted(
+ await authenticate(
+ initialHost, harness.room, "host", "debug-p2p-host", 1, shareGeneration,
+ { debugP2pOnly: true },
+ ),
+ );
+ expect(hostAuth.debugP2pOnly).toBe(true);
+ expect(hostAuth.sfuStandbyUrl).toBeUndefined();
+ expect(hostAuth.iceConfig.iceServers).toEqual([
+ { urls: ["stun:stun.example.test:3478"] },
+ ]);
+
+ await closeClient(initialHost);
+ const host = await openClient(harness.webSocketUrl);
+ const resumedAuth = peerAssisted(
+ await authenticate(
+ host, harness.room, "host", "debug-p2p-host", 1, shareGeneration,
+ ),
+ );
+ expect(resumedAuth.debugP2pOnly).toBe(true);
+ expect(resumedAuth.sfuStandbyUrl).toBeUndefined();
+
+ const failedViewer = await openClient(harness.webSocketUrl);
+ const failedAuth = peerAssisted(
+ await authenticate(
+ failedViewer, harness.room, "viewer", "debug-p2p-failed",
+ ),
+ );
+ expect(failedAuth.debugP2pOnly).toBe(true);
+ expect(failedAuth.sfuStandbyUrl).toBeUndefined();
+ host.socket.send(JSON.stringify({
+ type: "signal",
+ targetPeerId: failedAuth.peerId,
+ payload: {
+ kind: "description",
+ connectionId: "debug-direct-connection",
+ description: { type: "offer", sdp: "v=0\r\n" },
+ },
+ }));
+ await failedViewer.inbox.next("signal");
+ failedViewer.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: failedAuth.routeRevision,
+ phase: "active",
+ connectionId: "debug-direct-connection",
+ }));
+ expect((await failedViewer.inbox.next("error")).code).toBe("PEER_NOT_FOUND");
+ for (const [client, type] of [
+ [host, "sfu-config"],
+ [failedViewer, "sfu-config"],
+ [host, "selected-edge-turn"],
+ [failedViewer, "selected-edge-turn"],
+ ] as const) {
+ await expect(client.inbox.next(type, 40)).rejects.toThrow("Timed out");
+ }
+ expect(issueToken).not.toHaveBeenCalled();
+
+ await closeClient(host);
+ const nextHost = await openClient(harness.webSocketUrl);
+ const nextAuth = peerAssisted(
+ await authenticate(
+ nextHost, harness.room, "host", "debug-p2p-host", 1,
+ "next-share-generation",
+ ),
+ );
+ expect(nextAuth.debugP2pOnly).toBeUndefined();
+ expect(nextAuth.sfuStandbyUrl).toBe("wss://sfu.example.test");
+
+ await closeClient(nextHost);
+ const stoppedHost = await openClient(harness.webSocketUrl);
+ const stoppedGeneration = "stopped-debug-generation";
+ expect(peerAssisted(await authenticate(
+ stoppedHost, harness.room, "host", "debug-p2p-host", 1,
+ stoppedGeneration, { debugP2pOnly: true },
+ )).debugP2pOnly).toBe(true);
+ const stopped = new Promise<void>((resolve) =>
+ stoppedHost.socket.once("close", () => resolve()),
+ );
+ stoppedHost.socket.send(JSON.stringify({ type: "stop-sharing" }));
+ await stopped;
+
+ const afterStop = await openClient(harness.webSocketUrl);
+ const afterStopAuth = peerAssisted(await authenticate(
+ afterStop, harness.room, "host", "debug-p2p-host", 1,
+ stoppedGeneration, { debugP2pOnly: true },
+ ));
+ expect(afterStopAuth.debugP2pOnly).toBeUndefined();
+ expect(afterStopAuth.sfuStandbyUrl).toBe("wss://sfu.example.test");
+ });
+
it("falls through to selected TURN when SFU prepare is unavailable", async () => {
const harness = await startSfuHarness({
tokenIssuer: { async issueToken() { throw new Error("offline"); } },