Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。
fix(recovery): preserve exact client authority intents (#283)
AAAba9c579f195a
diff --git a/src/client/lib/signaling.ts b/src/client/lib/signaling.tsindex 3d97ee03..dcf59628 100644--- a/src/client/lib/signaling.ts+++ b/src/client/lib/signaling.ts@@ -4,9 +4,11 @@ import {SIGNALING_PROTOCOL,type ClientMessage,type DisplayName,+ type QualitySettings,type ServerMessage,} from "../../shared/protocol";import type { SignalConnectionState } from "../types";+import { qualitySettingsEqual } from "../media/quality";type WithoutProtocolEnvelope<T> = T extends {type: string;@@ -51,6 +53,11 @@ interface PendingSignalingChallenge {confirm: boolean;}+interface HostQualityIntent {+ shareGeneration: string;+ qualitySettings: QualitySettings;+}+export function shouldReconnectSignaling(code: number): boolean {return (code !== SIGNAL_CLOSE_CODES.sessionReplaced &&@@ -83,6 +90,7 @@ export class SignalingClient {private watchdogDeadlineMs = 0;private pendingChallenge: PendingSignalingChallenge | null = null;private visibilityListenerAttached = false;+ private hostQualityIntent: HostQualityIntent | null = null;constructor(private readonly identity: SignalingIdentity,@@ -105,6 +113,7 @@ export class SignalingClient {this.clearTimers();this.detachVisibilityListener();this.terminalMessage = null;+ this.hostQualityIntent = null;const socket = this.socket;this.socket = null;if (socket && socket.readyState < WebSocket.CLOSING) {@@ -165,6 +174,28 @@ export class SignalingClient {}}+ setHostQualitySettings(qualitySettings: QualitySettings): boolean {+ if (this.identity.role !== "host" || !this.identity.shareGeneration) {+ return false;+ }+ const intent: HostQualityIntent = {+ shareGeneration: this.identity.shareGeneration,+ qualitySettings: { ...qualitySettings },+ };+ this.identity.qualitySettings = { ...qualitySettings };+ this.hostQualityIntent = intent;+ return this.flushHostQualityIntent();+ }++ pendingHostQualitySettings(+ shareGeneration: string,+ ): QualitySettings | null {+ const intent = this.hostQualityIntent;+ return intent?.shareGeneration === shareGeneration+ ? { ...intent.qualitySettings }+ : null;+ }+sendThenStop(message: ClientMessage): void {if (this.stopped) {return;@@ -268,6 +299,9 @@ export class SignalingClient {}this.updateAuthoritativeActivity(message);this.events.onMessage(message);+ if (message.type === "authenticated") {+ this.reconcileHostQualityIntent(message);+ }});socket.addEventListener("close", (event) => {@@ -320,6 +354,53 @@ export class SignalingClient {this.events.onTerminated("STALE_CLIENT");}+ private flushHostQualityIntent(): boolean {+ const intent = this.hostQualityIntent;+ if (+ !intent ||+ this.identity.role !== "host" ||+ this.identity.shareGeneration !== intent.shareGeneration+ ) {+ return false;+ }+ try {+ if (+ !this.send({+ type: "set-quality-settings",+ qualitySettings: intent.qualitySettings,+ })+ ) {+ return false;+ }+ } catch {+ return false;+ }+ return true;+ }++ private reconcileHostQualityIntent(+ message: Extract<ServerMessage, { type: "authenticated" }>,+ ): void {+ const intent = this.hostQualityIntent;+ if (+ !intent ||+ this.identity.role !== "host" ||+ this.identity.shareGeneration !== intent.shareGeneration+ ) {+ return;+ }+ if (+ "qualitySettings" in message &&+ qualitySettingsEqual(message.qualitySettings, intent.qualitySettings)+ ) {+ if (this.hostQualityIntent === intent) {+ this.hostQualityIntent = null;+ }+ return;+ }+ this.flushHostQualityIntent();+ }+private clearAuthenticationTimer(): void {if (this.authenticationTimer !== null) {window.clearTimeout(this.authenticationTimer);diff --git a/src/client/media/viewer-presentation.ts b/src/client/media/viewer-presentation.tsindex 1d5d2d4b..85345393 100644--- a/src/client/media/viewer-presentation.ts+++ b/src/client/media/viewer-presentation.ts@@ -1,3 +1,4 @@+import type { ServerMessage } from "../../shared/protocol";import type { SignalConnectionState } from "../types";export type ViewerHostState =@@ -16,7 +17,6 @@ export type ViewerFailureCode =| "ROOM_CLOSED"| "ROOM_EXPIRED"| "ROOM_FULL"- | "ROOM_LOST"| "STALE_CLIENT"| "SERVER_ERROR"| "SESSION_REPLACED"@@ -35,7 +35,6 @@ export type ViewerStage =| "room-closed"| "room-expired"| "room-full"- | "room-lost"| "stale-client"| "server-error"| "session-replaced"@@ -469,13 +468,6 @@ export function deriveViewerPresentation(return presentation("room-closed", "房间已关闭", "blocking", state);case "ROOM_FULL":return presentation("room-full", "当前无法加入房间", "blocking", state);- case "ROOM_LOST":- return presentation(- "room-lost",- "服务器已重启,房间已失效",- "blocking",- state,- );case "STALE_CLIENT":return presentation("stale-client",@@ -683,6 +675,28 @@ export function deriveViewerPresentation();}+export function viewerFailureFromServerCode(+ code: Extract<ServerMessage, { type: "error" }>["code"],+): ViewerFailureCode | null {+ switch (code) {+ case "ROOM_NOT_FOUND":+ return "ROOM_NOT_FOUND";+ case "ROOM_ACCESS_DENIED":+ return "ROOM_ACCESS_DENIED";+ case "INVALID_TOKEN":+ case "AUTH_REQUIRED":+ return "INVALID_TOKEN";+ case "ROOM_EXPIRED":+ return "ROOM_EXPIRED";+ case "ROOM_FULL":+ return "ROOM_FULL";+ case "SERVER_ERROR":+ return "SERVER_ERROR";+ default:+ return null;+ }+}+function hasCurrentFrame(state: ViewerPresentationState): boolean {return Boolean(state.media?.framePresented && state.media.revision === state.revision,diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsxindex 0ee1042c..5e5a5f7b 100644--- a/src/client/pages/HostPage.tsx+++ b/src/client/pages/HostPage.tsx@@ -929,12 +929,9 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {if (captureChanged) {setDetails(captureDetails(activeStream));}- const roomSettingsSent =- !peerAssistedRef.current ||- signalRef.current?.send({- type: "set-quality-settings",- qualitySettings: nextProfile,- }) === true;+ if (peerAssistedRef.current) {+ signalRef.current?.setHostQualitySettings(nextProfile);+ }const activeSfuRoute = hostSfuRouteRef.current;const [results, sfuUpdated] = await Promise.all([Promise.all(@@ -963,12 +960,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {failed > 0 || !sfuUpdated? "分享设置已更新,但部分观看连接未能应用新参数": null;- const syncWarning = roomSettingsSent- ? null- : "房间画质同步将在服务器重连后继续";- const warning = [sfuWarning ?? connectionWarning, syncWarning]- .filter((message): message is string => message !== null)- .join(";");+ const warning = sfuWarning ?? connectionWarning;const successNotice =audioChanged && !videoChanged? `音频质量已切换为 ${SCREEN_AUDIO_QUALITY_LABELS[resolveScreenAudioQuality(nextProfile.screenAudioQuality)]}`@@ -1286,6 +1278,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {generation: number,activeRoom: HostRoomState,reauthenticated: boolean,+ pendingQualitySettings: QualitySettings | null,): void {if (!isCurrentGeneration(generation)) {return;@@ -1323,21 +1316,23 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {"mediaMode" in message &&message.mediaMode === "peer-assisted") {+ const currentQualitySettings =+ pendingQualitySettings ?? message.qualitySettings;activeRouteRevisionRef.current = message.routeRevision;activeHostChildPeerIdsRef.current = [...message.routeAssignment.childPeerIds,];peerAssistedRef.current = true;if (reauthenticated) {- commitQuality(message.qualitySettings);+ commitQuality(currentQualitySettings);const endpointUpdates = [...[...peersRef.current.values()].map((peer) =>- peer.updateProfile(message.qualitySettings),+ peer.updateProfile(currentQualitySettings),),...(hostProvisionalChildRef.current? [hostProvisionalChildRef.current.updateProfile(- message.qualitySettings,+ currentQualitySettings,),]: []),@@ -1353,7 +1348,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {}).then(async () => {if (reauthenticated && hostSfuRouteRef.current === route) {- await route.updateProfile(message.qualitySettings);+ await route.updateProfile(currentQualitySettings);}showHostSfuQualityWarning(route, generation);});@@ -1690,6 +1685,9 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {generation,activeRoom,reauthenticated,+ reauthenticated+ ? signal.pendingHostQualitySettings(shareGeneration)+ : null,);},},diff --git a/src/client/pages/ViewerPage.tsx b/src/client/pages/ViewerPage.tsxindex e1d11402..db1cc555 100644--- a/src/client/pages/ViewerPage.tsx+++ b/src/client/pages/ViewerPage.tsx@@ -62,7 +62,7 @@ import {INITIAL_VIEWER_PRESENTATION_STATE,deriveViewerPresentation,reduceViewerPresentation,- type ViewerFailureCode,+ viewerFailureFromServerCode,type ViewerRouteKind,type ViewerStage,} from "../media/viewer-presentation";@@ -352,7 +352,6 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {useEffect(() => {let active = true;- let hadAuthenticated = false;let currentIceConfig: IceConfig | null = null;let currentHostOnline = false;let currentHostPaused = false;@@ -1151,7 +1150,6 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {authorityToken: number,): Promise<void> {if (message.type === "authenticated") {- hadAuthenticated = true;dispatchPresentation({ type: "access", access: "ready" });setViewerPasswordDraft("");setViewerPasswordError(null);@@ -1548,13 +1546,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {clearViewerSfuRoute();clearPeerState(true);clearParticipantPresence();- const failure =- hadAuthenticated &&- (message.code === "INVALID_TOKEN" ||- message.code === "ROOM_NOT_FOUND" ||- message.code === "ROOM_ACCESS_DENIED")- ? "ROOM_LOST"- : viewerFailureFromServerCode(message.code);+ const failure = viewerFailureFromServerCode(message.code);dispatchPresentation({type: "access",access: "denied",@@ -1749,7 +1741,6 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {const codeOnlyDenied =!viewerGrant && presentationState.failure === "ROOM_ACCESS_DENIED";const canRefresh = [- "ROOM_LOST","STALE_CLIENT","SERVER_ERROR","SESSION_REPLACED",@@ -2147,25 +2138,3 @@ function connectionFact(return "failed";}}--function viewerFailureFromServerCode(- code: Extract<ServerMessage, { type: "error" }>["code"],-): ViewerFailureCode | null {- switch (code) {- case "ROOM_NOT_FOUND":- return "ROOM_NOT_FOUND";- case "ROOM_ACCESS_DENIED":- return "ROOM_ACCESS_DENIED";- case "INVALID_TOKEN":- case "AUTH_REQUIRED":- return "INVALID_TOKEN";- case "ROOM_EXPIRED":- return "ROOM_EXPIRED";- case "ROOM_FULL":- return "ROOM_FULL";- case "SERVER_ERROR":- return "SERVER_ERROR";- default:- return null;- }-}diff --git a/tests/client-state.test.ts b/tests/client-state.test.tsindex 4d29d30f..7c637068 100644--- a/tests/client-state.test.ts+++ b/tests/client-state.test.ts@@ -1,5 +1,7 @@import { afterEach, describe, expect, it, vi } from "vitest";+import type { QualitySettings } from "../src/shared/protocol.ts";+import {ApiError,authenticateSiteAccess,@@ -954,6 +956,159 @@ describe("client signaling recovery policy", () => {signal.stop();});+ it("replays the latest exact Host quality intent after reauthentication", () => {+ vi.useFakeTimers();+ const sockets: FakeWebSocket[] = [];+ class FakeWebSocket extends EventTarget {+ static readonly OPEN = 1;+ static readonly CLOSING = 2;+ readyState = FakeWebSocket.OPEN;+ readonly send = vi.fn();+ readonly close = vi.fn(() => {+ this.readyState = FakeWebSocket.CLOSING;+ });++ constructor(readonly url: string) {+ super();+ sockets.push(this);+ }+ }+ vi.stubGlobal("WebSocket", FakeWebSocket);+ vi.stubGlobal("window", {+ location: new URL("https://share.test/"),+ setTimeout: globalThis.setTimeout,+ clearTimeout: globalThis.clearTimeout,+ });+ const shareGeneration = "share_generation_12345678";+ const initialQuality = {+ resolution: "1080p",+ maxFramerate: 30,+ maxBitrate: 5_000_000,+ degradationPreference: "balanced",+ screenAudioQuality: "music",+ } as const;+ const firstPending = {+ ...initialQuality,+ resolution: "720p",+ maxBitrate: 3_000_000,+ } as const;+ const latestPending = {+ ...firstPending,+ maxFramerate: 60,+ maxBitrate: 8_000_000,+ } as const;+ let authenticatedCount = 0;+ let pendingDuringReauthentication: typeof latestPending | null = null;+ let signal!: SignalingClient;+ signal = new SignalingClient(+ {+ roomId: "1234",+ role: "host",+ token: "h".repeat(43),+ clientId: "host-client",+ shareGeneration,+ qualitySettings: initialQuality,+ },+ {+ onMessage: (message) => {+ if (message.type !== "authenticated") {+ return;+ }+ authenticatedCount += 1;+ if (authenticatedCount === 2) {+ pendingDuringReauthentication =+ signal.pendingHostQualitySettings(shareGeneration) as+ | typeof latestPending+ | null;+ }+ },+ onStatus: () => undefined,+ onTerminated: () => undefined,+ onAccessRequired: () => undefined,+ },+ );+ const receiveAuthenticated = (+ socket: FakeWebSocket,+ qualitySettings: QualitySettings = initialQuality,+ ) => {+ const event = new Event("message");+ Object.defineProperty(event, "data", {+ value: JSON.stringify({+ type: "authenticated",+ protocol: "screener-v12",+ role: "host",+ peerId: "host_12345678",+ roomExpiresAt: null,+ maxViewers: 8,+ endpointMediaCopyCapacity: 2,+ hostOnline: true,+ hostPaused: false,+ connectionId: null,+ viewerPeerIds: [],+ iceConfig: { iceServers: [] },+ codeEntryPolicy: "open",+ viewerPasswordEnabled: false,+ viewerAuthorizationGeneration: "viewer_generation_12345678",+ mediaMode: "peer-assisted",+ mediaAssignment: { parentPeerId: null, childPeerIds: [] },+ routeRevision: 1,+ routeAssignment: {+ upstream: { kind: "none" },+ childPeerIds: [],+ sfuPublicationGeneration: null,+ },+ qualitySettings,+ }),+ });+ socket.dispatchEvent(event);+ };++ signal.start();+ sockets[0]!.dispatchEvent(new Event("open"));+ receiveAuthenticated(sockets[0]!);+ const close = new Event("close");+ Object.defineProperties(close, {+ code: { value: 1006 },+ reason: { value: "network interrupted" },+ });+ sockets[0]!.dispatchEvent(close);++ expect(signal.setHostQualitySettings(firstPending)).toBe(false);+ expect(signal.setHostQualitySettings(latestPending)).toBe(false);+ expect(+ signal.pendingHostQualitySettings("other_share_generation_12345678"),+ ).toBeNull();+ expect(signal.pendingHostQualitySettings(shareGeneration)).toEqual(+ latestPending,+ );++ vi.advanceTimersByTime(750);+ sockets[1]!.dispatchEvent(new Event("open"));+ expect(JSON.parse(String(sockets[1]!.send.mock.calls[0]![0]))).toMatchObject({+ type: "authenticate",+ shareGeneration,+ qualitySettings: latestPending,+ });+ receiveAuthenticated(sockets[1]!);++ expect(pendingDuringReauthentication).toEqual(latestPending);+ expect(sockets[1]!.send).toHaveBeenCalledTimes(2);+ expect(+ JSON.parse(String(sockets[1]!.send.mock.calls[1]![0])),+ ).toEqual({+ type: "set-quality-settings",+ qualitySettings: latestPending,+ });+ expect(signal.pendingHostQualitySettings(shareGeneration)).toEqual(+ latestPending,+ );++ receiveAuthenticated(sockets[1]!, latestPending);+ expect(sockets[1]!.send).toHaveBeenCalledTimes(2);+ expect(signal.pendingHostQualitySettings(shareGeneration)).toBeNull();+ signal.stop();+ });+it("confirms an exact silent partition before replacing the socket immediately", () => {vi.useFakeTimers();let now = 0;diff --git a/tests/viewer-presentation.test.ts b/tests/viewer-presentation.test.tsindex 2002a47f..f1354b1e 100644--- a/tests/viewer-presentation.test.ts+++ b/tests/viewer-presentation.test.ts@@ -4,6 +4,7 @@ import {INITIAL_VIEWER_PRESENTATION_STATE,deriveViewerPresentation,reduceViewerPresentation,+ viewerFailureFromServerCode,type ViewerPresentationAction,type ViewerPresentationState,} from "../src/client/media/viewer-presentation.ts";@@ -457,6 +458,16 @@ describe("Viewer presentation reducer", () => {});});+ it("preserves exact Viewer access failures without inferring a restart", () => {+ expect(viewerFailureFromServerCode("INVALID_TOKEN")).toBe("INVALID_TOKEN");+ expect(viewerFailureFromServerCode("ROOM_NOT_FOUND")).toBe(+ "ROOM_NOT_FOUND",+ );+ expect(viewerFailureFromServerCode("ROOM_ACCESS_DENIED")).toBe(+ "ROOM_ACCESS_DENIED",+ );+ });+it("starts a fresh route revision namespace after sharing stops", () => {const previousShare = apply({ type: "access", access: "ready" },