Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(remote-desktop): 支持动态 ICE 配置与自营 TURN 恢复 (#4194)

Dash1b6103eedffc
diff --git a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
index 1285bb7fbd..e91f25d288 100644
--- a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
+++ b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
@@ -16,6 +16,8 @@ vi.mock('electron', () => ({
ipcMain: { handle: vi.fn(), removeHandler: vi.fn() },
app: { getVersion: () => '1.0.0' },
}));
+// This suite exercises dispatch authorization, not authenticated ICE HTTP setup.
+vi.mock('../remote-desktop/iceConfig', () => ({ loadDesktopIceServers: vi.fn(async () => []) }));
// media:fetch 拦截走 mediaFetch.fetchLocalMediaToOss;mock 掉避免拉起 OSS/cache-store 真实依赖。
const fetchLocalMediaToOssMock = vi.hoisted(() => vi.fn());
vi.mock('../device-link/mediaFetch', () => ({ fetchLocalMediaToOss: fetchLocalMediaToOssMock }));
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/captureBoundary.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/captureBoundary.test.ts
index c350eae46b..e63bb147f1 100644
--- a/apps/desktop/src/main/remote-desktop/__tests__/captureBoundary.test.ts
+++ b/apps/desktop/src/main/remote-desktop/__tests__/captureBoundary.test.ts
@@ -16,7 +16,11 @@ const h = vi.hoisted(() => ({
nativeFrame: vi.fn(async () => 'frame'),
input: vi.fn(),
viewHeartbeat: vi.fn(),
+ iceConfig: vi.fn(async (): Promise<any[]> => [
+ { urls: ['turn:relay.example.test:3478'], username: 'temporary', credential: 'test-only' },
+ ]),
}));
+vi.mock('../iceConfig', () => ({ loadDesktopIceServers: h.iceConfig }));
vi.mock('electron', () => ({
app: { on: vi.fn() },
powerMonitor: { on: vi.fn() },
@@ -158,6 +162,7 @@ beforeEach(() => {
h.nativeFrame.mockClear();
h.input.mockReset();
h.viewHeartbeat.mockClear();
+ h.iceConfig.mockClear();
registerRemoteDesktopIpc();
});
afterEach(() => {
@@ -318,3 +323,63 @@ it('retains the capture owner on ICE timeout and rejects old-owner replies after
h.deps.stopVideo();
await nextRejected;
});
+
+it('passes freshly fetched ICE credentials only to the active capture owner', async () => {
+ const pending = offer();
+ h.handlers.get(DESKTOP_LOCAL.REGISTER)(event());
+ await flush();
+ const command = h.owner.send.mock.calls[0][1];
+ expect(command.iceServers).toEqual(await h.iceConfig());
+ h.handlers.get(DESKTOP_LOCAL.REPLY)(event(), command.id, 'answer');
+ await pending;
+});
+
+it('revocation while fetching ICE config prevents a late credential from starting capture', async () => {
+ let finish!: (servers: any[]) => void;
+ h.iceConfig.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const pending = offer();
+ const rejected = expect(pending).rejects.toThrow('DESKTOP_LEASE_EXPIRED');
+ const old = h.owner;
+ h.handlers.get(DESKTOP_LOCAL.REGISTER)(event());
+ await flush();
+ h.deps.stopVideo();
+ finish([]);
+ await rejected;
+ expect(old.send).not.toHaveBeenCalled();
+});
+
+it('keeps replacement capture and its in-flight ICE exchange when revoked config arrives late', async () => {
+ let finish!: (servers: any[]) => void;
+ h.iceConfig.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
+ const pending = offer();
+ const rejected = expect(pending).rejects.toThrow('DESKTOP_LEASE_EXPIRED');
+ const old = h.owner;
+ h.handlers.get(DESKTOP_LOCAL.REGISTER)(event());
+ await flush();
+ h.deps.stopVideo();
+ h.lease = 'replacement';
+ const next = offer();
+ h.handlers.get(DESKTOP_LOCAL.REGISTER)(event());
+ await flush();
+ const owner = h.owner;
+ const command = owner.send.mock.calls[0][1];
+ h.handlers.get(DESKTOP_LOCAL.REPLY)(event(), command.id, 'new-answer');
+ await expect(next).resolves.toBe('new-answer');
+ const ice = h.deps.ice({
+ op: 'ice', lease: 'replacement', attemptId: 'attempt', after: 0, candidates: [],
+ });
+ const exchange = owner.send.mock.calls.at(-1)[1];
+ finish([]);
+ await rejected;
+ expect(old.send).not.toHaveBeenCalled();
+ expect(h.owner).toBe(owner);
+ expect(owner.dead).toBe(false);
+ const reply = { attemptId: 'attempt', candidates: [], next: 0, complete: true };
+ h.handlers.get(DESKTOP_LOCAL.REPLY)(event(), exchange.id, reply);
+ await expect(ice).resolves.toEqual(reply);
+});
diff --git a/apps/desktop/src/main/remote-desktop/iceConfig.ts b/apps/desktop/src/main/remote-desktop/iceConfig.ts
new file mode 100644
index 0000000000..2bc66a5ede
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop/iceConfig.ts
@@ -0,0 +1,18 @@
+import {
+ REMOTE_DESKTOP_ICE_CONFIG_PATH,
+ REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS,
+ resolveDesktopIceServers,
+} from '@cindy/device-link';
+import { getClientEndpoint } from '../clientEndpointsService.js';
+import { serverApiFetch } from '../serverApiClient.js';
+
+export function loadDesktopIceServers() {
+ return resolveDesktopIceServers(() =>
+ serverApiFetch(REMOTE_DESKTOP_ICE_CONFIG_PATH, {
+ baseUrl: () => getClientEndpoint('deviceLinkApiBaseUrl'),
+ timeoutMs: REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS,
+ cache: 'no-store',
+ redactErrorDetails: true,
+ }),
+ );
+}
diff --git a/apps/desktop/src/main/remote-desktop/index.ts b/apps/desktop/src/main/remote-desktop/index.ts
index 3c5811f1aa..b5eb7ee9d4 100644
--- a/apps/desktop/src/main/remote-desktop/index.ts
+++ b/apps/desktop/src/main/remote-desktop/index.ts
@@ -13,6 +13,7 @@ import {
type DesktopCapturerSource,
} from 'electron';
import { randomUUID } from 'node:crypto';
+import { loadDesktopIceServers } from './iceConfig';
import {
isDesktopPermission,
REMOTE_DESKTOP_OFFER_BUDGET,
@@ -168,7 +169,7 @@ async function offer(
const ready = captureWindow.start();
host = captureWindow.contents;
const currentHost = host;
- await ready;
+ const [, iceServers] = await Promise.all([ready, loadDesktopIceServers()]);
if (!current() || host !== currentHost || !currentHost || currentHost.isDestroyed())
throw new Error('DESKTOP_LEASE_EXPIRED');
let source: DesktopCapturerSource | null = null;
@@ -216,6 +217,7 @@ async function offer(
sdp,
settings,
attemptId,
+ iceServers,
},
REMOTE_DESKTOP_OFFER_BUDGET.hostMs,
);
diff --git a/apps/desktop/src/renderer/features/remote-desktop/captureHost.ts b/apps/desktop/src/renderer/features/remote-desktop/captureHost.ts
index 8d1da17b1c..33c7c14f1b 100644
--- a/apps/desktop/src/renderer/features/remote-desktop/captureHost.ts
+++ b/apps/desktop/src/renderer/features/remote-desktop/captureHost.ts
@@ -214,7 +214,7 @@ export function startDesktopCaptureHost(api: DesktopCaptureApi): () => void {
}
stream = captured;
const rtc = new RTCPeerConnection({
- iceServers: REMOTE_DESKTOP_ICE_SERVERS,
+ iceServers: command.iceServers ?? REMOTE_DESKTOP_ICE_SERVERS,
});
peer = rtc;
rtc.onicecandidate = ({ candidate }) => {
diff --git a/apps/desktop/src/shared/remoteDesktop.ts b/apps/desktop/src/shared/remoteDesktop.ts
index 3d725ecc8f..205a051845 100644
--- a/apps/desktop/src/shared/remoteDesktop.ts
+++ b/apps/desktop/src/shared/remoteDesktop.ts
@@ -6,6 +6,7 @@ import type {
RemoteDesktopPermissions,
RemoteDesktopIceCandidate,
RemoteDesktopIceReply,
+ DesktopIceServer,
} from '@cindy/device-link';
export const DESKTOP_LOCAL = {
STATE: 'remote-desktop:state',
@@ -24,6 +25,7 @@ export const DESKTOP_LOCAL = {
DISMISS_GUIDE: 'remote-desktop:dismiss-permission-guide',
} as const;
export interface DesktopHostCommand {
+ iceServers?: DesktopIceServer[];
id: string;
op: 'offer' | 'stop' | 'capture-reset' | 'ice';
attemptId?: string;
diff --git a/apps/mobile/src/__tests__/apiClient.test.ts b/apps/mobile/src/__tests__/apiClient.test.ts
index 1f092bb023..ffe42df97f 100644
--- a/apps/mobile/src/__tests__/apiClient.test.ts
+++ b/apps/mobile/src/__tests__/apiClient.test.ts
@@ -63,6 +63,31 @@ describe('apiFetchRaw', () => {
}));
});
+ it('passes no-store to fetch and HTTP cache directives for native transports', async () => {
+ const fetchMock = vi.fn(async () => ({
+ ok: true,
+ json: async () => ({ iceServers: [], expiresAt: null }),
+ } as Response));
+ vi.stubGlobal('fetch', fetchMock);
+ await apiFetchRaw('/api/device-link/ice-servers', {
+ baseUrl: 'https://relay.example.com',
+ token: 'access-token',
+ cache: 'no-store',
+ });
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'https://relay.example.com/api/device-link/ice-servers',
+ expect.objectContaining({
+ cache: 'no-store',
+ headers: {
+ Authorization: 'Bearer access-token',
+ 'Content-Type': 'application/json',
+ 'Cache-Control': 'no-cache, no-store',
+ Pragma: 'no-cache',
+ },
+ }),
+ );
+ });
+
it('aborts hung requests instead of leaving the UI in a connecting state', async () => {
vi.useFakeTimers();
const fetchMock = vi.fn((_url: string, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
diff --git a/apps/mobile/src/api/client.ts b/apps/mobile/src/api/client.ts
index 7b2caa3bfb..155472fef4 100644
--- a/apps/mobile/src/api/client.ts
+++ b/apps/mobile/src/api/client.ts
@@ -18,6 +18,7 @@ export interface ApiFetchOptions {
token?: string | null;
body?: unknown;
timeoutMs?: number;
+ cache?: 'no-store';
}
const DEFAULT_API_TIMEOUT_MS = 20_000;
@@ -44,6 +45,11 @@ export async function apiFetchRaw<T>(
): Promise<T> {
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
if (opts.token) headers.Authorization = `Bearer ${opts.token}`;
+ if (opts.cache === 'no-store') {
+ // Also tell native HTTP caches not to reuse or store short-lived responses.
+ headers['Cache-Control'] = 'no-cache, no-store';
+ headers.Pragma = 'no-cache';
+ }
let response: Response;
let data: unknown = null;
@@ -57,6 +63,7 @@ export async function apiFetchRaw<T>(
headers,
body: opts.body === undefined ? undefined : JSON.stringify(opts.body),
signal: controller?.signal,
+ ...(opts.cache ? { cache: opts.cache } : {}),
});
let nextData: unknown = null;
try {
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
index da12ff5785..c532c11915 100644
--- a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
@@ -53,6 +53,13 @@ import {
type RemoteDesktopDisplayMode,
} from "@cindy/device-link";
import { useDeviceLink } from "@/device-link/DeviceLinkContext";
+import { useAuth } from "@/auth/AuthContext";
+import { DEVICE_LINK_API_BASE_URL } from "@/config/env";
+import {
+ REMOTE_DESKTOP_ICE_CONFIG_PATH,
+ REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS,
+ resolveDesktopIceServers,
+} from "@cindy/device-link";
import { Text } from "@/components/AppText";
import { useScreenEdgePadding } from "@/components/screenEdgeInsets";
import { goBackGuarded } from "@/utils/backGuard";
@@ -141,6 +148,7 @@ const LABELS: Record<string, string> = {
};
export default function RemoteDesktopScreen() {
+ const auth = useAuth();
const { deviceId: rawId, deviceName: rawName } = useLocalSearchParams<{
deviceId: string;
deviceName?: string;
@@ -754,6 +762,30 @@ export default function RemoteDesktopScreen() {
throw new Error("DESKTOP_VIDEO_STOPPED");
};
switch (message.type) {
+ case "iceConfig":
+ if (!isDesktopAttemptId(message.attemptId)) return;
+ mediaAttempt.current = message.attemptId;
+ void resolveDesktopIceServers(() =>
+ auth.apiFetch(REMOTE_DESKTOP_ICE_CONFIG_PATH, {
+ baseUrl: DEVICE_LINK_API_BASE_URL,
+ timeoutMs: REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS,
+ cache: "no-store",
+ }),
+ ).then((iceServers) => {
+ if (
+ !alive.current ||
+ active.current !== current ||
+ mediaAttempt.current !== message.attemptId
+ )
+ return;
+ send({
+ type: "iceConfig",
+ epoch: current.lease,
+ attemptId: message.attemptId,
+ iceServers,
+ });
+ });
+ break;
case "offer":
if (
typeof message.sdp !== "string" ||
diff --git a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
index 99f3e4f2a8..3b40a8456f 100644
--- a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
+++ b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
@@ -11,6 +11,7 @@ const fixture = vi.hoisted(() => ({
keyboardListeners: {} as Record<string, (event: unknown) => void>,
views: {} as Record<string, any>,
invoke: vi.fn(),
+ apiFetch: vi.fn(),
openLink: vi.fn(),
post: vi.fn(),
reload: vi.fn(),
@@ -154,6 +155,8 @@ vi.mock("@/device-link/DeviceLinkContext", () => ({
openLink: fixture.openLink,
}),
}));
+vi.mock("@/auth/AuthContext", () => ({ useAuth: () => ({ apiFetch: fixture.apiFetch }) }));
+vi.mock("@/config/env", () => ({ DEVICE_LINK_API_BASE_URL: 'https://relay.example.test' }));
vi.mock("../PermissionGuide", () => ({
PermissionGuide: (p: any) => {
fixture.retryPermissions = p.reconnect;
@@ -195,6 +198,7 @@ beforeEach(() => {
fixture.trickleIce = false;
fixture.size = { width: 390, height: 844 };
fixture.openLink.mockResolvedValue({});
+ fixture.apiFetch.mockReset().mockResolvedValue({ iceServers: [], expiresAt: null });
fixture.systemAudio = false;
fixture.playback.mockReset().mockResolvedValue(undefined);
fixture.invoke.mockImplementation(async (_device, _channel, [request]) => {
@@ -245,6 +249,70 @@ const connect = async () => {
};
describe("remote desktop controls", () => {
+ it("fetches ICE configuration only through native auth and sends sanitized short-term credentials", async () => {
+ await connect();
+ const iceServers = [
+ {
+ urls: ["turn:relay.example.test:3478"],
+ username: "temporary",
+ credential: "test-only",
+ },
+ ];
+ fixture.apiFetch.mockResolvedValue({
+ iceServers,
+ expiresAt: new Date(Date.now() + 3600_000).toISOString(),
+ secret: "must-not-cross-bridge",
+ });
+ await act(async () => {
+ fixture.message!({
+ nativeEvent: {
+ data: JSON.stringify({
+ type: "iceConfig",
+ epoch: "lease",
+ attemptId: "1",
+ url: "https://untrusted.example.test",
+ }),
+ },
+ });
+ });
+ expect(fixture.apiFetch).toHaveBeenCalledWith(
+ "/api/device-link/ice-servers",
+ { baseUrl: "https://relay.example.test", timeoutMs: 3000, cache: "no-store" },
+ );
+ expect(sent().find((m) => m.type === "iceConfig")).toEqual({
+ type: "iceConfig",
+ epoch: "lease",
+ attemptId: "1",
+ iceServers,
+ });
+ expect(JSON.stringify(sent())).not.toContain("must-not-cross-bridge");
+ });
+
+ it("drops a late ICE config response after the screen exits", async () => {
+ await connect();
+ let finish!: (value: unknown) => void;
+ fixture.apiFetch.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ await act(async () => {
+ fixture.message!({
+ nativeEvent: {
+ data: JSON.stringify({
+ type: "iceConfig",
+ epoch: "lease",
+ attemptId: "1",
+ }),
+ },
+ });
+ });
+ act(() => root.unmount());
+ mounted = false;
+ await act(async () => finish({ iceServers: [], expiresAt: null }));
+ expect(sent().filter((m) => m.type === "iceConfig")).toHaveLength(0);
+ });
it("keeps video and control when playback fails without changing the sound preference", async () => {
fixture.systemAudio = true;
fixture.playback.mockImplementation(async (enabled) => { if (enabled) throw new Error("audio interrupted"); });
diff --git a/apps/mobile/src/remote-desktop/__tests__/viewerRtc.test.ts b/apps/mobile/src/remote-desktop/__tests__/viewerRtc.test.ts
index 7b0b515eeb..51a678d7aa 100644
--- a/apps/mobile/src/remote-desktop/__tests__/viewerRtc.test.ts
+++ b/apps/mobile/src/remote-desktop/__tests__/viewerRtc.test.ts
@@ -4,7 +4,8 @@ import { REMOTE_DESKTOP_NETWORK as net } from "@cindy/device-link";
import { DESKTOP_RTC_SCRIPT } from "../viewerRtc";
// Executes the exact static script embedded in WKWebView, with only RTC/DOM replaced.
-function viewer(trickle = true) {
+function viewer(trickle = true, autoConfig = true) {
+ let api: any;
const messages: any[] = [];
const peers: any[] = [];
class Peer {
@@ -24,7 +25,7 @@ function viewer(trickle = true) {
setRemoteDescription = vi.fn(async (value: any) => {
this.remoteDescription = value;
});
- constructor() {
+ constructor(public configuration: any) {
peers.push(this);
}
createDataChannel() {
@@ -68,14 +69,18 @@ function viewer(trickle = true) {
render() {},
receiveCursor() {},
networkStats: () => ({ sample: null }),
- post: (message: any) => messages.push(message),
+ post: (message: any) => {
+ messages.push(message);
+ if (message.type === "iceConfig" && autoConfig)
+ return api.config({ ...message, iceServers: [] });
+ },
});
- const api = vm.runInContext(
+ api = vm.runInContext(
`
let pc=null,dc=null,generation=0,epoch='lease',statsTimer=null,statsSample=null;
${DESKTOP_RTC_SCRIPT}
trickleIce=${trickle};
- ({start:connect,answer:receiveAnswer,ice:receiveIce,fail:failRtc,
+ ({start:connect,answer:receiveAnswer,ice:receiveIce,config:receiveIceConfig,fail:failRtc,
stop:()=>{epoch=null;closeRtc();}})
`,
context,
@@ -257,3 +262,65 @@ it("does not retry an unavailable platform or a permanent host error", async ()
expect(h.peers).toHaveLength(1);
h.api.stop();
});
+
+it("reloads credentials on recovery and supplies the backup as well as the primary", async () => {
+ const h = viewer(true, false);
+ const nodes = [
+ {
+ urls: ["turn:primary.example.test:3478"],
+ username: "old",
+ credential: "test-only",
+ },
+ {
+ urls: ["turn:backup.example.test:3478"],
+ username: "old",
+ credential: "test-only",
+ },
+ ];
+ await h.api.start();
+ const first = h.latest("iceConfig");
+ expect(h.peers).toHaveLength(0);
+ await h.api.config({ ...first, iceServers: nodes });
+ expect(h.peers[0].configuration.iceServers).toEqual(nodes);
+ h.change("failed");
+ await vi.advanceTimersByTimeAsync(net.retryMs[0]);
+ const next = h.latest("iceConfig");
+ expect(next.attemptId).not.toBe(first.attemptId);
+ await h.api.config({ ...first, iceServers: nodes });
+ expect(h.peers).toHaveLength(1);
+ const renewed = nodes.map((n) => ({ ...n, username: "renewed" }));
+ await h.api.config({ ...next, iceServers: renewed });
+ expect(h.peers[1].configuration.iceServers).toEqual(renewed);
+ h.api.stop();
+});
+
+it("bounds native config wait, ignores late/duplicate config, and preserves another viewer", async () => {
+ const a = viewer(true, false),
+ b = viewer();
+ await a.api.start();
+ await b.api.start();
+ const pending = a.latest("iceConfig");
+ await vi.advanceTimersByTimeAsync(3500);
+ expect(a.peers).toHaveLength(1);
+ await a.api.config({
+ ...pending,
+ iceServers: [{ urls: ["turn:late.example.test:3478"] }],
+ });
+ expect(a.peers).toHaveLength(1);
+ a.api.stop();
+ await a.api.config({ ...pending, iceServers: [] });
+ expect(b.peers[0].close).not.toHaveBeenCalled();
+ b.api.stop();
+ expect(vi.getTimerCount()).toBe(0);
+});
+
+it("never starts media after exit while credentials are pending", async () => {
+ const h = viewer(true, false);
+ await h.api.start();
+ const pending = h.latest("iceConfig");
+ h.api.stop();
+ await h.api.config({ ...pending, iceServers: [] });
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(h.peers).toHaveLength(0);
+ expect(vi.getTimerCount()).toBe(0);
+});
diff --git a/apps/mobile/src/remote-desktop/viewerHtml.ts b/apps/mobile/src/remote-desktop/viewerHtml.ts
index f55d4758f4..ed69e89932 100644
--- a/apps/mobile/src/remote-desktop/viewerHtml.ts
+++ b/apps/mobile/src/remote-desktop/viewerHtml.ts
@@ -325,6 +325,7 @@ const VIEWER_SCRIPT = String.raw`
case 'init':followRest=null;cursorNeedsEntry=true;stopPanAnimation();resetCursor();control=false;release();pending=[];sending=false;seq=0;epoch=message.epoch;dw=message.width;dh=message.height;fillHeight=message.fillHeight===true;video.muted=!message.audio;trickleIce=message.trickleIce===true;retries=0;render();connect();break;
case 'viewport':fillHeight=message.fillHeight===true;release();render();break;
case 'answer':if(message.epoch===epoch)void receiveAnswer(message);break;
+ case 'iceConfig':if(message.epoch===epoch)void receiveIceConfig(message);break;
case 'ice':if(message.epoch===epoch)void receiveIce(message);break;
case 'fallback':if(message.epoch===epoch&&message.attemptId===attemptId)failRtc('host',message.retry!==false);break;
case 'frame':{if('cursor' in message)receiveCursor(message.cursor);else resetCursor();const frameEpoch=epoch;image.onload=()=>{if(epoch===frameEpoch)post({type:'framePresented'});};image.src='data:image/jpeg;base64,'+message.jpeg;break;}
diff --git a/apps/mobile/src/remote-desktop/viewerRtc.ts b/apps/mobile/src/remote-desktop/viewerRtc.ts
index eca56980cf..98dd2aac37 100644
--- a/apps/mobile/src/remote-desktop/viewerRtc.ts
+++ b/apps/mobile/src/remote-desktop/viewerRtc.ts
@@ -3,6 +3,7 @@
*/
export const DESKTOP_RTC_SCRIPT = String.raw`
let trickleIce=false,attemptId=null,retries=0,exchangeId=0;
+ let configPending=false;
let retryTimer=null,deadlineTimer=null,disconnectTimer=null,stableTimer=null,iceTimer=null,gatherTimer=null,gatherDone=null;
let localCandidates=[],localAck=0,remoteAfter=0,icePending=null,remoteSeen=new Set(),exchangeUntil=0,remoteComplete=false;
function clearRtcTimers(){
@@ -11,6 +12,7 @@ export const DESKTOP_RTC_SCRIPT = String.raw`
if(gatherDone){gatherDone();gatherDone=null;}
}
function closeRtc(preserveFrame=true){
+ configPending=false;
if(preserveFrame)retainFrame();generation++;clearRtcTimers();
localCandidates=[];localAck=remoteAfter=0;icePending=null;remoteSeen=new Set();attemptId=null;
clearInterval(statsTimer);statsTimer=null;statsSample=null;
@@ -69,8 +71,18 @@ export const DESKTOP_RTC_SCRIPT = String.raw`
async function connect(){
closeRtc();const g=generation;attemptId=String(g);
if(!window.RTCPeerConnection){failRtc('unsupported',false);return;}
+ configPending=true;
+ deadlineTimer=setTimeout(()=>{if(g===generation&&configPending){configPending=false;void startRtc(g,iceServers);}},3500);
+ return post({type:'iceConfig',attemptId});
+ }
+ async function receiveIceConfig(message){
+ if(!epoch||!configPending||message.attemptId!==attemptId)return;
+ configPending=false;clearTimeout(deadlineTimer);deadlineTimer=null;
+ await startRtc(generation,message.iceServers);
+ }
+ async function startRtc(g,servers){
try{
- const rtc=new RTCPeerConnection({iceServers});pc=rtc;
+ const rtc=new RTCPeerConnection({iceServers:servers});pc=rtc;
dc=rtc.createDataChannel('input-v1');rtc.addTransceiver('video',{direction:'recvonly'});rtc.addTransceiver('audio',{direction:'recvonly'});
rtc.onicecandidate=({candidate})=>{
if(g!==generation||!candidate?.candidate||!trickleIce)return;
diff --git a/docs/dev-rules/remote-desktop-connectivity.md b/docs/dev-rules/remote-desktop-connectivity.md
new file mode 100644
index 0000000000..fc0c064478
--- /dev/null
+++ b/docs/dev-rules/remote-desktop-connectivity.md
@@ -0,0 +1,100 @@
+# Remote desktop connectivity
+
+DeviceLink WSS remains the authorized signaling/control transport. WebRTC media
+and its input channel use ICE, with the existing JPEG path retained when video
+cannot connect. Object-storage transfer is unaffected.
+
+## ICE configuration
+
+Each viewer attempt requests `GET /api/device-link/ice-servers` from its authenticated
+device-link service. The controlled Desktop independently requests that same API
+while preparing its capture window. API credentials stay in Main / native Mobile;
+only short-term TURN allocation credentials cross the dedicated capture/WebView
+bridge. These scoped WebRTC credentials cannot authorize desktop input or invoke
+business APIs. They are never embedded in static HTML, persisted or logged.
+
+Response: `{iceServers: [{urls: string[], username: string, credential: string}],
+expiresAt: string | null}`. At most four entries and four STUN/TURN URLs per entry;
+URL scheme/length/ports and credential lifetime are checked before bridge delivery.
+Require two minutes of remaining lifetime for cold capture/SDP/ICE headroom.
+The owning backend supplies its deployment's node pool; no new user region setting.
+
+Missing endpoint, empty configuration, invalid response and a three-second timeout
+fall back to the old public STUN list. With a valid self-hosted list, public STUN
+is not added. All configured nodes participate in ICE checks; a dead first node
+does not prevent using candidates from the others. URI ordering is not a promise
+of priority. Candidate statistics already distinguish direct, relay and JPEG paths.
+
+Every existing bounded media retry fetches fresh configuration on both peers.
+No configuration cache, WSS reconnect or new global retry loop. The WebView bounds
+its native bridge wait at 3.5 seconds. Lease/generation/attempt checks reject stale
+responses; explicit stop takes precedence. A failed media attempt affects only its
+owner. Credential expiry may require rebuilding the connection; this change does
+not promise uninterrupted in-place renewal of TURN allocations.
+
+Old clients continue unchanged. New viewer + old Desktop can still use viewer-side
+TURN; old viewer + new Desktop can use host-side TURN. Existing full-SDP and trickle
+ICE capabilities stay unchanged. There are no new wire kinds, IPC entry points,
+native dependencies, fingerprint changes or file-transfer capabilities.
+
+## Verification
+
+Unit tests cover invalid/expired tickets, old/disabled backends, bounded requests,
+fresh credentials/backup lists on retries, and stop/late-response isolation.
+The Server repository contains the coturn deployment template and matching API
+contract (`docs/device-link-server.md`, `infra/turn/README.md`).
+
+For a real relay test, store an authenticated API response in a task-specific
+temporary directory outside this repository (mode 0600), then run:
+
+```sh
+node scripts/remote-desktop-turn-smoke.mjs /absolute/external/ice-config.json /absolute/path/to/chrome
+```
+
+The probe uses an isolated sandboxed browser, forces relay on both peers, checks
+16 KiB data round-trip and the selected relay pair for each TURN URL, then repeats
+with an unreachable first node. Output excludes URLs, IPs, credentials and SDP.
+Delete the temporary credential file after use. This operator probe makes real
+network requests and is intentionally excluded from unit tests.
+
+Local test evidence for this change: coturn 4.18.0, two loopback nodes, real Chrome,
+UDP/TCP for both nodes and unreachable-primary case passed. Separately, coturn's
+client verified a temporary test CA and received 40 TLS-relayed messages using the
+deployment template with loopback-only test overrides. This proves TURN data flow
+with the Server credential algorithm; it does not prove platform UI behavior,
+publicly trusted browser TLS, the Linux container deployment, or Mainland China reachability.
+For rollout, repeat on the deployed nodes and real Desktop/Mobile with trusted TLS,
+node failure, >1-hour sessions, two viewers and network switching. Compare STUN-only
+versus configured TURN on identical network pairs, recording sample count,
+connection success, first moving frame time, selected path, RTT and recovery time.
+
+## QA handoff
+
+Before external QA, deploy the matching ICE API to the test environment and inject
+its TURN node configuration through deployment secrets. Distribute Desktop and
+Mobile builds from this change that use that environment. Both devices must use
+the same account/session realm. A loopback proxy or an inspector-only endpoint
+override on a developer machine is not a usable QA environment. Keep login realm
+discovery intact; Desktop local-server mode pins both realms to the local manifest
+and is unsuitable for testing production enterprise SSO across realms.
+
+On 2026-09-09, a macOS Desktop and an iOS simulator on the same machine displayed
+real desktop video and delivered a pointer movement to the expected OS position.
+With a separately hosted public coturn node, forced UDP relay and TCP relay with
+an unreachable first candidate server connected. Closing an established media
+connection recovered via UDP relay in approximately 16 seconds. The deployed ACL
+was corrected to omit `denied-peer-ip=::`, which coturn interprets as an unbounded
+range; coturn already rejects unspecified peers before its ACL checks.
+
+These are functional probes, not a network-quality acceptance result. A direct
+sample had 1 ms RTT and a UDP-relay sample had 84 ms RTT; neither is an average or
+end-to-end input latency. Receiver loss and jitter were not collected. Publicly
+trusted TLS, Linux Compose, physical phones, Windows/Android, concurrent viewers,
+active-node failover, and hour-long sessions still need QA coverage.
+
+For each network pair, record client versions, session realm, transport, attempts,
+successes, first moving frame time, RTT p50/p95, receiver packet-loss deltas, jitter,
+frame rate/freezes and recovery duration. Distinguish connection recovery from
+initial selection of a reachable backup, and RTT from input-to-visible-response
+latency. Test the previous STUN-only behavior on the same pairs. Include JPEG and
+object-storage transfer regression checks; do not report unavailable metrics as zero.
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index bf03a844ea..0d276ddd25 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -26,6 +26,8 @@ import {
} from '../transport.js';
import { DL_CONTACTS_SYNC_CHANNEL } from '../contactsSyncProtocol.js';
import { SESSION_ACTIVITY_CHANNEL } from '../topics.js';
+import { resolveDesktopIceServers, REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS } from '../remoteDesktopIceConfig.js';
+import { REMOTE_DESKTOP_ICE_SERVERS } from '../remoteDesktopIce.js';
type Handler = (...args: unknown[]) => void;
@@ -378,6 +380,80 @@ function makeRelayClient(
}
describe('DeviceLinkClient', () => {
+ it('keeps a second controller link and in-flight invoke alive while shared host ICE config times out', async () => {
+ vi.useFakeTimers();
+ const relay = new MemoryRelay();
+ const sockets = vi.spyOn(relay, 'makeWebSocket');
+ const host = makeRelayClient(relay, 'desktop');
+ const a = makeRelayClient(relay, 'viewer-a');
+ const b = makeRelayClient(relay, 'viewer-b');
+ const pump = () => relay.settle(() => vi.advanceTimersByTimeAsync(1));
+ let finishConfig!: (value: unknown) => void;
+ const config = new Promise<unknown>((resolve) => { finishConfig = resolve; });
+ const fetchConfig = vi.fn(() => config);
+ const received: Envelope[] = [];
+ const off = host.onFrame((env) => {
+ if (!env.src || !env.id) return;
+ if (env.kind === 'link-open') {
+ host.sendLinkAccept(env.src, env.id, { appVersion: '1', allowlistHash: 'hash' });
+ } else if (env.kind === 'invoke') {
+ received.push(env);
+ if (env.src === 'viewer-a') {
+ const { src, id } = env;
+ void resolveDesktopIceServers(fetchConfig).then((iceServers) => {
+ host.sendInvokeResult(src, id, { ok: true, result: iceServers });
+ });
+ }
+ }
+ });
+ try {
+ for (const client of [host, a, b]) client.start();
+ await vi.advanceTimersByTimeAsync(1);
+ await pump();
+ for (const client of [a, b]) {
+ const opening = client.openLink('desktop', { controllerName: 'Viewer', protocolVersion: 1, appVersion: '1' });
+ await pump();
+ await opening;
+ }
+ const healthy = b.invoke('desktop', { channel: 'maker:test-inflight', args: [] }, 10_000);
+ let healthySettled = false;
+ void healthy.then(() => { healthySettled = true; });
+ await pump();
+ const stalled = a.invoke('desktop', { channel: 'maker:remote-desktop:video', args: [] }, 10_000);
+ await pump();
+ expect(fetchConfig).toHaveBeenCalledTimes(1);
+ expect(healthySettled).toBe(false);
+ await vi.advanceTimersByTimeAsync(REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS);
+ await pump();
+ await expect(stalled).resolves.toEqual({
+ ok: true, result: REMOTE_DESKTOP_ICE_SERVERS.map((server) => ({ urls: [server.urls] })),
+ });
+ expect(healthySettled).toBe(false);
+ const request = received.find((env) => env.src === 'viewer-b')!;
+ host.sendInvokeResult(request.src!, request.id!, { ok: true, result: 'preserved' });
+ await pump();
+ await expect(healthy).resolves.toEqual({ ok: true, result: 'preserved' });
+ const beforeLate = relay.deliveredTo.get('viewer-a')!.length;
+ finishConfig({ iceServers: [], expiresAt: null });
+ await pump();
+ expect(relay.deliveredTo.get('viewer-a')).toHaveLength(beforeLate);
+ expect(received.filter((env) => env.src === 'viewer-b')).toHaveLength(1);
+ expect(host.isLinkReady('viewer-b')).toBe(true);
+ expect(b.isLinkReady('desktop')).toBe(true);
+ expect(host.getStatus()).toBe('online');
+ expect(sockets).toHaveBeenCalledTimes(3);
+ for (const socket of sockets.mock.results) {
+ expect(socket.value.closed).toBeNull();
+ expect(socket.value.terminated).toBe(false);
+ }
+ } finally {
+ off();
+ for (const client of [host, a, b]) client.stop();
+ sockets.mockRestore();
+ vi.useRealTimers();
+ }
+ });
+
it('gives hello/ack a full window after a slow but successful socket upgrade', async () => {
vi.useFakeTimers();
const h = makeHarness({ timing: { handshakeTimeoutMs: 15, pingIntervalMs: 60_000 } });
diff --git a/packages/device-link/src/__tests__/remoteDesktopIceConfig.test.ts b/packages/device-link/src/__tests__/remoteDesktopIceConfig.test.ts
new file mode 100644
index 0000000000..39a58ac478
--- /dev/null
+++ b/packages/device-link/src/__tests__/remoteDesktopIceConfig.test.ts
@@ -0,0 +1,112 @@
+import { afterEach, expect, it, vi } from "vitest";
+import {
+ parseDesktopIceConfig,
+ resolveDesktopIceServers,
+ REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS,
+} from "../remoteDesktopIceConfig.js";
+
+const servers = [
+ {
+ urls: [
+ "stun:primary.example.test:3478",
+ "turn:primary.example.test:3478?transport=udp",
+ ],
+ username: "temporary",
+ credential: "test-only",
+ },
+ {
+ urls: ["turns:backup.example.test:5349?transport=tcp"],
+ username: "temporary2",
+ credential: "test-only2",
+ },
+];
+const config = () => ({
+ iceServers: servers,
+ expiresAt: new Date(Date.now() + 3600_000).toISOString(),
+});
+afterEach(() => vi.useRealTimers());
+
+it("passes all independent nodes to ICE, strips unrelated response secrets, and reloads on retry", async () => {
+ const fetchConfig = vi.fn(async () => ({
+ ...config(),
+ secret: "must-not-cross-bridge",
+ }));
+ expect(await resolveDesktopIceServers(fetchConfig)).toEqual(servers);
+ expect(await resolveDesktopIceServers(fetchConfig)).toEqual(servers);
+ expect(fetchConfig).toHaveBeenCalledTimes(2);
+});
+
+it.each([
+ "https://example.test/",
+ "turn:user:[email protected]:3478",
+ "stun:a.test:3478?transport=udp",
+ "turn:a.test:99999",
+ "turns:a.test:5349?transport=udp",
+ "turn:[::::]:3478?transport=udp",
+ "turn:a..test:3478?transport=udp",
+])("rejects invalid URL %s without echoing it", (url) => {
+ expect(() =>
+ parseDesktopIceConfig({
+ ...config(),
+ iceServers: [{ ...servers[0], urls: [url] }],
+ }),
+ ).toThrow("INVALID_DESKTOP_ICE_CONFIG");
+});
+
+it("rejects expired, oversized and missing credentials", () => {
+ expect(() =>
+ parseDesktopIceConfig({
+ ...config(),
+ expiresAt: new Date(Date.now() + 119_000).toISOString(),
+ }),
+ ).toThrow();
+ expect(() =>
+ parseDesktopIceConfig({ ...config(), expiresAt: new Date().toISOString() }),
+ ).toThrow();
+ expect(() =>
+ parseDesktopIceConfig({
+ ...config(),
+ iceServers: Array(5).fill(servers[0]),
+ }),
+ ).toThrow();
+ expect(() =>
+ parseDesktopIceConfig({
+ ...config(),
+ iceServers: [{ urls: servers[0].urls }],
+ }),
+ ).toThrow();
+});
+
+it("preserves legacy behavior on an old/disabled/broken server", async () => {
+ for (const fetchConfig of [
+ async () => {
+ throw new Error("404");
+ },
+ async () => ({ iceServers: [], expiresAt: null }),
+ async () => ({ malformed: true }),
+ ]) {
+ const result = await resolveDesktopIceServers(fetchConfig);
+ expect(result).toHaveLength(2);
+ expect(
+ result.every((s) => s.urls.every((url) => url.startsWith("stun:"))),
+ ).toBe(true);
+ }
+});
+
+it("bounds a stalled API independently of another peer and ignores late credentials", async () => {
+ vi.useFakeTimers();
+ let finish!: (value: unknown) => void;
+ const slow = resolveDesktopIceServers(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ expect(await resolveDesktopIceServers(async () => config())).toEqual(servers);
+ await vi.advanceTimersByTimeAsync(REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS);
+ const fallback = await slow;
+ finish(config());
+ await Promise.resolve();
+ expect(fallback[0].username).toBeUndefined();
+ expect(vi.getTimerCount()).toBe(0);
+});
diff --git a/packages/device-link/src/index.ts b/packages/device-link/src/index.ts
index 6f2431e6e8..930119b664 100644
--- a/packages/device-link/src/index.ts
+++ b/packages/device-link/src/index.ts
@@ -17,5 +17,6 @@ export * from './contactsSyncProtocol.js';
export * from './remoteResources.js';
export * from './remoteDesktop.js';
export * from './remoteDesktopIce.js';
+export * from './remoteDesktopIceConfig.js';
export * from './remoteClipboard.js';
export * from './remoteCursor.js';
diff --git a/packages/device-link/src/remoteDesktopIceConfig.ts b/packages/device-link/src/remoteDesktopIceConfig.ts
new file mode 100644
index 0000000000..5ce6db3560
--- /dev/null
+++ b/packages/device-link/src/remoteDesktopIceConfig.ts
@@ -0,0 +1,106 @@
+import { REMOTE_DESKTOP_ICE_SERVERS } from "./remoteDesktopIce.js";
+
+export const REMOTE_DESKTOP_ICE_CONFIG_PATH = "/api/device-link/ice-servers";
+export const REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS = 3000;
+export interface DesktopIceServer {
+ urls: string[];
+ username?: string;
+ credential?: string;
+}
+
+const ICE_URL =
+ /^(stun|turn|turns):(?:[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?|\[[0-9a-fA-F:]+\]):([0-9]{1,5})(\?transport=(udp|tcp))?$/;
+
+/** Strip unknown fields; only short-lived WebRTC credentials may cross the native bridge. */
+export function parseDesktopIceConfig(
+ value: unknown,
+ now = Date.now(),
+): DesktopIceServer[] {
+ const fail = (): never => {
+ throw new Error("INVALID_DESKTOP_ICE_CONFIG");
+ };
+ if (!value || typeof value !== "object") return fail();
+ const v = value as { iceServers?: unknown; expiresAt?: unknown };
+ if (!Array.isArray(v.iceServers) || v.iceServers.length > 4) return fail();
+ if (v.iceServers.length === 0 && v.expiresAt === null) return [];
+ const expires =
+ typeof v.expiresAt === "string" ? Date.parse(v.expiresAt) : NaN;
+ // Leave room for cold capture setup, SDP exchange and connection checks.
+ if (
+ !Number.isFinite(expires) ||
+ expires <= now + 120_000 ||
+ expires > now + 86_400_000
+ )
+ return fail();
+ return v.iceServers.map((server: unknown) => {
+ if (!server || typeof server !== "object") return fail();
+ const s = server as DesktopIceServer;
+ if (!Array.isArray(s.urls) || !s.urls.length || s.urls.length > 4)
+ return fail();
+ const urls = s.urls.map((url) => {
+ if (typeof url !== "string" || url.length > 512) return fail();
+ const match = ICE_URL.exec(url);
+ if (
+ !match ||
+ Number(match[2]) < 1 ||
+ Number(match[2]) > 65535 ||
+ (match[1] === "stun" && match[3]) ||
+ (match[1] === "turns" && match[4] !== "tcp")
+ )
+ return fail();
+ try {
+ const host = new URL(
+ "http://" + url.slice(url.indexOf(":") + 1).split("?")[0],
+ ).hostname;
+ if (
+ !host.startsWith("[") &&
+ host
+ .split(".")
+ .some(
+ (label) => !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(label),
+ )
+ )
+ return fail();
+ } catch {
+ return fail();
+ }
+ return url;
+ });
+ if (
+ !urls.some((url) => /^turns?:/.test(url)) ||
+ typeof s.username !== "string" ||
+ !s.username.length ||
+ s.username.length > 256 ||
+ typeof s.credential !== "string" ||
+ !s.credential.length ||
+ s.credential.length > 256
+ )
+ return fail();
+ return { urls, username: s.username, credential: s.credential };
+ });
+}
+
+/** Per attempt, no credential cache. A slow/missing API must not hold up legacy connectivity. */
+export async function resolveDesktopIceServers(
+ fetchConfig: () => Promise<unknown>,
+): Promise<DesktopIceServer[]> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ const value = await Promise.race([
+ Promise.resolve().then(fetchConfig),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () => reject(new Error("ICE_CONFIG_TIMEOUT")),
+ REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS,
+ );
+ }),
+ ]);
+ const servers = parseDesktopIceConfig(value);
+ if (servers.length) return servers;
+ } catch {
+ // No upstream body/error/credential logging. Existing JPEG fallback is independent.
+ } finally {
+ clearTimeout(timer);
+ }
+ return REMOTE_DESKTOP_ICE_SERVERS.map((server) => ({ urls: [server.urls] }));
+}
diff --git a/scripts/remote-desktop-turn-smoke.mjs b/scripts/remote-desktop-turn-smoke.mjs
new file mode 100644
index 0000000000..d86795fe08
--- /dev/null
+++ b/scripts/remote-desktop-turn-smoke.mjs
@@ -0,0 +1,151 @@
+// Explicit operator probe, not a unit test. Credentials must live outside the checkout.
+// node scripts/remote-desktop-turn-smoke.mjs <ice-config.json> <Chrome executable>
+import { readFile, realpath } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
+const [configPath, executablePath] = process.argv.slice(2);
+if (!configPath || !executablePath)
+ throw new Error(
+ "Usage: node scripts/remote-desktop-turn-smoke.mjs <external-ice-config.json> <Chrome executable>",
+ );
+const input = await realpath(configPath);
+if (input === root || input.startsWith(root + path.sep))
+ throw new Error("Keep credential files outside the checkout");
+let iceServers;
+try {
+ ({ iceServers } = JSON.parse(await readFile(input, "utf8")));
+} catch {
+ // JSON SyntaxError can echo input, including credentials.
+ throw new Error("INVALID_ICE_CONFIG");
+}
+if (!Array.isArray(iceServers) || !iceServers.length)
+ throw new Error("No ICE servers");
+const require = createRequire(
+ new URL("../packages/browser-control-runtime/package.json", import.meta.url),
+);
+const { chromium } = require("playwright-core");
+const browser = await chromium.launch({
+ executablePath,
+ headless: true,
+ chromiumSandbox: true,
+});
+try {
+ const page = await browser.newPage();
+ const cases = iceServers.flatMap((server, node) =>
+ (Array.isArray(server.urls) ? server.urls : [server.urls])
+ .filter((url) => /^turns?:/.test(url))
+ .map((url, transport) => ({
+ name: `node-${node + 1}-transport-${transport + 1}`,
+ servers: [{ ...server, urls: [url] }],
+ })),
+ );
+ cases.push({
+ name: "unreachable-primary-with-backup",
+ servers: [
+ {
+ urls: ["turn:192.0.2.1:9?transport=udp"],
+ username: "test-only",
+ credential: "test-only",
+ },
+ ...iceServers,
+ ],
+ });
+ for (const test of cases) {
+ const result = await page
+ .evaluate(async (servers) => {
+ const a = new RTCPeerConnection({
+ iceServers: servers,
+ iceTransportPolicy: "relay",
+ });
+ const b = new RTCPeerConnection({
+ iceServers: servers,
+ iceTransportPolicy: "relay",
+ });
+ const queues = new Map([
+ [a, []],
+ [b, []],
+ ]);
+ let timer;
+ try {
+ const outcome = new Promise((resolve, reject) => {
+ timer = setTimeout(() => reject(new Error("RELAY_TIMEOUT")), 20000);
+ const data = new Uint8Array(16384);
+ for (let i = 0; i < data.length; i++) data[i] = i % 251;
+ b.ondatachannel = ({ channel }) => {
+ channel.binaryType = "arraybuffer";
+ channel.onmessage = ({ data }) => channel.send(data);
+ };
+ const channel = a.createDataChannel("probe");
+ channel.binaryType = "arraybuffer";
+ channel.onopen = () => channel.send(data);
+ channel.onmessage = async ({ data: echoed }) => {
+ try {
+ const received = new Uint8Array(echoed);
+ if (
+ received.length !== data.length ||
+ received.some((v, i) => v !== data[i])
+ )
+ throw new Error("DATA_MISMATCH");
+ const stats = await a.getStats();
+ const rows = [...stats.values()];
+ const transport = rows.find(
+ (s) => s.type === "transport" && s.selectedCandidatePairId,
+ );
+ const pair =
+ transport && stats.get(transport.selectedCandidatePairId);
+ const local = pair && stats.get(pair.localCandidateId),
+ remote = pair && stats.get(pair.remoteCandidateId);
+ if (
+ local?.candidateType !== "relay" ||
+ remote?.candidateType !== "relay"
+ )
+ throw new Error("NOT_RELAY");
+ resolve({
+ bytesRoundTrip: received.length,
+ local: local.candidateType,
+ remote: remote.candidateType,
+ relayProtocol: local.relayProtocol ?? null,
+ });
+ } catch (error) {
+ reject(error);
+ }
+ };
+ });
+ // Attach rejection before negotiation awaits to avoid an unhandled timeout.
+ outcome.catch(() => {});
+ for (const [from, to] of [
+ [a, b],
+ [b, a],
+ ])
+ from.onicecandidate = ({ candidate }) => {
+ if (!candidate) return;
+ if (to.remoteDescription)
+ void to.addIceCandidate(candidate).catch(() => {});
+ else queues.get(to).push(candidate);
+ };
+ await a.setLocalDescription(await a.createOffer());
+ await b.setRemoteDescription(a.localDescription);
+ for (const candidate of queues.get(b))
+ await b.addIceCandidate(candidate);
+ await b.setLocalDescription(await b.createAnswer());
+ await a.setRemoteDescription(b.localDescription);
+ for (const candidate of queues.get(a))
+ await a.addIceCandidate(candidate);
+ return await outcome;
+ } finally {
+ clearTimeout(timer);
+ a.close();
+ b.close();
+ }
+ }, test.servers)
+ .catch(() => ({ error: "RELAY_PROBE_FAILED" }));
+ // No URL, IP, username, credential, SDP or raw browser error in probe output.
+ process.stdout.write(JSON.stringify({ case: test.name, ...result }) + "\n");
+ if (result.error) process.exitCode = 1;
+ }
+} finally {
+ await browser.close();
+}