webRemoteControlTransport.test.ts 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import { WebSocket, WebSocketServer } from "ws";
  3. import type { AddressInfo } from "node:net";
  4. import {
  5. WEB_REMOTE_CONTROL_RPC_TRANSPORT_LIMITS,
  6. encodeWebRemoteControlRpcTransportMessage,
  7. type WebRemoteControlAppPayload,
  8. } from "@zcode/shared";
  9. import {
  10. WebRemoteControlDeviceTransport,
  11. type WebRemoteControlDeviceTransportState,
  12. } from "../src/main/webRemoteControlTransport.js";
  13. const servers: WebSocketServer[] = [];
  14. // 相关测试会与其他单测并发启动多个 WebSocket/SQLite worker;2 秒阈值在 pre-push
  15. // 的高负载调度下会把正常的协议回调延迟误判为失败,等待上限只影响测试收敛时间。
  16. function waitUntil(assertion: () => boolean, timeoutMs = 5_000): Promise<void> {
  17. return new Promise((resolve, reject) => {
  18. const startedAt = Date.now();
  19. const tick = () => {
  20. if (assertion()) {
  21. resolve();
  22. return;
  23. }
  24. if (Date.now() - startedAt > timeoutMs) {
  25. reject(new Error("Timed out waiting for assertion"));
  26. return;
  27. }
  28. setTimeout(tick, 10);
  29. };
  30. tick();
  31. });
  32. }
  33. function createRelayDataJsonWithExactBytes(targetBytes: number): string {
  34. const multibytePrefix = "中🙂";
  35. const createJson = (error: string) =>
  36. JSON.stringify({
  37. type: "data",
  38. payload: {
  39. zcode_type: "app-error",
  40. reason: "unexpected-error",
  41. error,
  42. },
  43. });
  44. const empty = createJson(multibytePrefix);
  45. const paddingBytes = targetBytes - Buffer.byteLength(empty, "utf8");
  46. if (paddingBytes < 0) throw new Error("target relay frame is smaller than its fixed envelope");
  47. const result = createJson(`${multibytePrefix}${"x".repeat(paddingBytes)}`);
  48. if (Buffer.byteLength(result, "utf8") !== targetBytes) {
  49. throw new Error("failed to construct exact relay frame bytes");
  50. }
  51. return result;
  52. }
  53. function createLogger() {
  54. return {
  55. info: vi.fn(),
  56. warn: vi.fn(),
  57. error: vi.fn(),
  58. };
  59. }
  60. async function createRelayServer(
  61. onMessage: (context: { message: any; socket: import("ws").WebSocket; messages: any[] }) => void,
  62. options?: { perMessageDeflate?: boolean },
  63. ) {
  64. const server = new WebSocketServer({
  65. port: 0,
  66. perMessageDeflate: options?.perMessageDeflate ?? false,
  67. });
  68. servers.push(server);
  69. const messages: any[] = [];
  70. const rawMessages: string[] = [];
  71. const clientCompressedFrames: boolean[] = [];
  72. let deviceHeader: string | string[] | undefined;
  73. let requestUrl: string | undefined;
  74. let requestExtensions: string | string[] | undefined;
  75. let connectionCount = 0;
  76. let rawBuffer = Buffer.alloc(0);
  77. function collectClientFrameCompression(chunk: Buffer): void {
  78. rawBuffer = Buffer.concat([rawBuffer, chunk]);
  79. while (rawBuffer.length >= 2) {
  80. const firstByte = rawBuffer[0];
  81. const secondByte = rawBuffer[1];
  82. let offset = 2;
  83. let payloadLength = secondByte & 0x7f;
  84. if (payloadLength === 126) {
  85. if (rawBuffer.length < offset + 2) {
  86. return;
  87. }
  88. payloadLength = rawBuffer.readUInt16BE(offset);
  89. offset += 2;
  90. } else if (payloadLength === 127) {
  91. if (rawBuffer.length < offset + 8) {
  92. return;
  93. }
  94. const longLength = rawBuffer.readBigUInt64BE(offset);
  95. if (longLength > BigInt(Number.MAX_SAFE_INTEGER)) {
  96. throw new Error("WebSocket frame too large for test parser");
  97. }
  98. payloadLength = Number(longLength);
  99. offset += 8;
  100. }
  101. const masked = (secondByte & 0x80) !== 0;
  102. if (masked) {
  103. offset += 4;
  104. }
  105. const frameLength = offset + payloadLength;
  106. if (rawBuffer.length < frameLength) {
  107. return;
  108. }
  109. clientCompressedFrames.push((firstByte & 0x40) !== 0);
  110. rawBuffer = rawBuffer.subarray(frameLength);
  111. }
  112. }
  113. server.on("connection", (socket, request) => {
  114. connectionCount += 1;
  115. deviceHeader = request.headers["x-device-id"];
  116. requestUrl = request.url;
  117. requestExtensions = request.headers["sec-websocket-extensions"];
  118. request.socket.on("data", collectClientFrameCompression);
  119. socket.on("message", (raw) => {
  120. rawMessages.push(raw.toString());
  121. const message = JSON.parse(raw.toString());
  122. messages.push(message);
  123. onMessage({ message, socket, messages });
  124. });
  125. });
  126. await new Promise<void>((resolve) => server.once("listening", resolve));
  127. const address = server.address() as AddressInfo;
  128. return {
  129. messages,
  130. rawMessages,
  131. url: `ws://127.0.0.1:${address.port}`,
  132. getDeviceHeader: () => deviceHeader,
  133. getRequestUrl: () => requestUrl,
  134. getRequestExtensions: () => requestExtensions,
  135. getClientCompressedFrames: () => [...clientCompressedFrames],
  136. getConnectionCount: () => connectionCount,
  137. };
  138. }
  139. afterEach(async () => {
  140. await Promise.all(
  141. servers.splice(0).map(
  142. (server) =>
  143. new Promise<void>((resolve) => {
  144. server.close(() => resolve());
  145. }),
  146. ),
  147. );
  148. });
  149. describe("WebRemoteControlDeviceTransport", () => {
  150. it("uses the measured final JSON verbatim for initial send and replay", async () => {
  151. const states: WebRemoteControlDeviceTransportState[] = [];
  152. const relay = await createRelayServer(({ message, socket }) => {
  153. if (message.type === "auth_init") {
  154. socket.send(
  155. JSON.stringify({ type: "auth_ack", device_sid: "sid-1", pair_status: "matched" }),
  156. );
  157. }
  158. });
  159. const transport = new WebRemoteControlDeviceTransport({
  160. relayWsUrl: relay.url,
  161. deviceMid: "mid-1",
  162. auth: { mode: "persisted", deviceSid: "sid-1", passHash: "hash-1" },
  163. meta: { platform: "darwin", version: "1.0.0", name: "Mac" },
  164. authProvider: {
  165. createPassword: () => "password",
  166. createPassHash: () => "hash-1",
  167. calculateProof: () => "proof",
  168. },
  169. logger: createLogger(),
  170. onRegisteredAuth: () => {},
  171. onStateChange: (state) => states.push(state),
  172. onPayload: () => {},
  173. onError: () => {},
  174. onInvalidPersistedAuth: async () => {},
  175. });
  176. try {
  177. transport.start();
  178. await waitUntil(() => states.includes("paired"));
  179. const [frame] = encodeWebRemoteControlRpcTransportMessage(new Uint8Array([1, 2, 3]), {
  180. bridgeSessionId: "bridge-1",
  181. firstPhysicalSeq: 1,
  182. messageSeq: 1,
  183. });
  184. const measuredBytes = transport.measurePayloadBytes(frame);
  185. expect(transport.sendPayloadResult(frame)).toMatchObject({
  186. kind: "sent",
  187. bytes: measuredBytes,
  188. });
  189. expect(transport.sendPayloadResult(frame)).toMatchObject({
  190. kind: "sent",
  191. bytes: measuredBytes,
  192. });
  193. await waitUntil(
  194. () => relay.messages.filter((message) => message.type === "data").length === 2,
  195. );
  196. const dataJson = relay.rawMessages.filter(
  197. (raw) => (JSON.parse(raw) as { type?: string }).type === "data",
  198. );
  199. expect(dataJson).toHaveLength(2);
  200. expect(dataJson[1]).toBe(dataJson[0]);
  201. expect(Buffer.byteLength(dataJson[0]!, "utf8")).toBe(measuredBytes);
  202. } finally {
  203. transport.dispose();
  204. }
  205. });
  206. it("accepts exactly 1MiB inbound JSON and faults 1MiB+1 before app routing", async () => {
  207. const payloads: WebRemoteControlAppPayload[] = [];
  208. const rawFaults: string[] = [];
  209. const exact = createRelayDataJsonWithExactBytes(
  210. WEB_REMOTE_CONTROL_RPC_TRANSPORT_LIMITS.maxPhysicalFrameBytes,
  211. );
  212. const oversize = createRelayDataJsonWithExactBytes(
  213. WEB_REMOTE_CONTROL_RPC_TRANSPORT_LIMITS.maxPhysicalFrameBytes + 1,
  214. );
  215. const relay = await createRelayServer(({ message, socket }) => {
  216. if (message.type === "auth_init") {
  217. socket.send(
  218. JSON.stringify({ type: "auth_ack", device_sid: "sid-1", pair_status: "matched" }),
  219. );
  220. socket.send(exact);
  221. socket.send(oversize);
  222. }
  223. });
  224. const transport = new WebRemoteControlDeviceTransport({
  225. relayWsUrl: relay.url,
  226. deviceMid: "mid-1",
  227. auth: { mode: "persisted", deviceSid: "sid-1", passHash: "hash-1" },
  228. meta: { platform: "darwin", version: "1.0.0", name: "Mac" },
  229. authProvider: {
  230. createPassword: () => "password",
  231. createPassHash: () => "hash-1",
  232. calculateProof: () => "proof",
  233. },
  234. logger: createLogger(),
  235. onRegisteredAuth: () => {},
  236. onStateChange: () => {},
  237. onPayload: (payload) => payloads.push(payload),
  238. onRawTransportFault: (reasonCode) => rawFaults.push(reasonCode),
  239. onError: () => {},
  240. onInvalidPersistedAuth: async () => {},
  241. });
  242. try {
  243. transport.start();
  244. await waitUntil(() => payloads.length === 1 && rawFaults.length === 1, 5_000);
  245. expect(payloads[0]).toMatchObject({
  246. zcode_type: "app-error",
  247. reason: "unexpected-error",
  248. });
  249. expect(rawFaults).toEqual(["remote.rpcFrame.envelopeTooLarge"]);
  250. } finally {
  251. transport.dispose();
  252. }
  253. });
  254. it("distinguishes temporary unavailability from permanent envelope oversize", () => {
  255. const transport = new WebRemoteControlDeviceTransport({
  256. relayWsUrl: "ws://127.0.0.1:1/ws",
  257. deviceMid: "mid-1",
  258. auth: { mode: "persisted", deviceSid: "sid-1", passHash: "hash-1" },
  259. meta: { platform: "darwin", version: "1.0.0", name: "Mac" },
  260. authProvider: {
  261. createPassword: () => "password",
  262. createPassHash: () => "hash-1",
  263. calculateProof: () => "proof",
  264. },
  265. logger: createLogger(),
  266. onRegisteredAuth: () => {},
  267. onStateChange: () => {},
  268. onPayload: () => {},
  269. onError: () => {},
  270. onInvalidPersistedAuth: async () => {},
  271. });
  272. expect(
  273. transport.sendPayloadResult({
  274. zcode_type: "app-error",
  275. reason: "unexpected-error",
  276. error: "bounded",
  277. }),
  278. ).toEqual({ kind: "unavailable" });
  279. expect(
  280. transport.sendPayloadResult({
  281. zcode_type: "app-error",
  282. reason: "unexpected-error",
  283. error: "x".repeat(WEB_REMOTE_CONTROL_RPC_TRANSPORT_LIMITS.maxPhysicalFrameBytes),
  284. }),
  285. ).toMatchObject({ kind: "oversize" });
  286. });
  287. it("does not write relay message trace in local development runtime", async () => {
  288. const logger = createLogger();
  289. const relayMessageLogger = { info: vi.fn() };
  290. const states: WebRemoteControlDeviceTransportState[] = [];
  291. const relay = await createRelayServer(({ message, socket }) => {
  292. if (message.type === "auth_init") {
  293. socket.send(
  294. JSON.stringify({ type: "auth_ack", device_sid: "sid-1", pair_status: "matched" }),
  295. );
  296. }
  297. });
  298. const transport = new WebRemoteControlDeviceTransport({
  299. relayWsUrl: relay.url,
  300. deviceMid: "mid-1",
  301. auth: { mode: "persisted", deviceSid: "sid-1", passHash: "hash-1" },
  302. meta: { platform: "darwin", version: "1.0.0", name: "Mac" },
  303. authProvider: {
  304. createPassword: () => "password",
  305. createPassHash: () => "hash-1",
  306. calculateProof: () => "proof",
  307. },
  308. heartbeatIntervalMs: 20,
  309. logger,
  310. relayMessageLogger,
  311. onRegisteredAuth: () => {},
  312. onStateChange: (state) => states.push(state),
  313. onPayload: () => {},
  314. onError: () => {},
  315. onInvalidPersistedAuth: async () => {},
  316. });
  317. try {
  318. transport.start();
  319. await waitUntil(() => states.includes("paired"));
  320. expect(relayMessageLogger.info).not.toHaveBeenCalled();
  321. expect(JSON.stringify(logger.info.mock.calls)).not.toContain(
  322. "[web-remote-control][relay-message]",
  323. );
  324. } finally {
  325. transport.dispose();
  326. }
  327. });
  328. it("negotiates permessage-deflate with relay and sends compressed data frames", async () => {
  329. const logger = createLogger();
  330. const states: WebRemoteControlDeviceTransportState[] = [];
  331. const relay = await createRelayServer(
  332. ({ message, socket }) => {
  333. if (message.type === "auth_init") {
  334. socket.send(JSON.stringify({ type: "auth_challenge", nonce: "nonce-1" }));
  335. }
  336. if (message.type === "auth_response") {
  337. socket.send(
  338. JSON.stringify({ type: "auth_ack", device_sid: "sid-1", pair_status: "matched" }),
  339. );
  340. }
  341. },
  342. { perMessageDeflate: true },
  343. );
  344. const transport = new WebRemoteControlDeviceTransport({
  345. relayWsUrl: relay.url,
  346. deviceMid: "mid-1",
  347. auth: { mode: "persisted", deviceSid: "sid-1", passHash: "hash-1" },
  348. meta: { platform: "darwin", version: "1.0.0", name: "Mac" },
  349. authProvider: {
  350. createPassword: () => "password",
  351. createPassHash: () => "hash-1",
  352. calculateProof: () => "proof",
  353. },
  354. heartbeatIntervalMs: 20,
  355. logger,
  356. onRegisteredAuth: () => {},
  357. onStateChange: (state) => states.push(state),
  358. onPayload: () => {},
  359. onError: () => {},
  360. onInvalidPersistedAuth: async () => {},
  361. });
  362. transport.start();
  363. await waitUntil(() => relay.messages.some((message) => message.type === "auth_response"));
  364. await waitUntil(() => states.includes("paired"));
  365. transport.sendPayload({
  366. zcode_type: "workspace-list-request",
  367. requestId: "req-compressed",
  368. padding: "x".repeat(4096),
  369. } as WebRemoteControlAppPayload);
  370. await waitUntil(() => relay.messages.some((message) => message.type === "data"));
  371. expect(String(relay.getRequestExtensions())).toContain("permessage-deflate");
  372. expect(logger.info).toHaveBeenCalledWith(
  373. "[web-remote-control] external relay negotiated extensions",
  374. expect.objectContaining({ perMessageDeflate: true }),
  375. );
  376. expect(relay.getClientCompressedFrames()).toContain(true);
  377. transport.dispose();
  378. });
  379. it("registers without persisted auth and authenticates after register ack", async () => {
  380. const states: WebRemoteControlDeviceTransportState[] = [];
  381. const registered: { deviceSid: string; passHash: string }[] = [];
  382. const relay = await createRelayServer(({ message, socket }) => {
  383. if (message.type === "device_register_init") {
  384. socket.send(JSON.stringify({ type: "device_register_ack", device_sid: "sid-1" }));
  385. }
  386. if (message.type === "auth_init") {
  387. socket.send(JSON.stringify({ type: "auth_challenge", nonce: "nonce-1" }));
  388. }
  389. if (message.type === "auth_response") {
  390. socket.send(
  391. JSON.stringify({ type: "auth_ack", device_sid: "sid-1", pair_status: "waiting" }),
  392. );
  393. }
  394. });
  395. const transport = new WebRemoteControlDeviceTransport({
  396. relayWsUrl: relay.url,
  397. deviceMid: "mid-1",
  398. auth: { mode: "register", passHash: "hash-1" },
  399. meta: { platform: "darwin", version: "1.0.0", name: "Mac" },
  400. authProvider: {
  401. createPassword: () => "password",
  402. createPassHash: () => "hash-1",
  403. calculateProof: () => "proof-1",
  404. },
  405. logger: createLogger(),
  406. onRegisteredAuth: (auth) => registered.push(auth),
  407. onStateChange: (state) => states.push(state),
  408. onPayload: () => {},
  409. onError: () => {},
  410. onInvalidPersistedAuth: async () => {},
  411. });
  412. transport.start();
  413. await waitUntil(() => states.includes("waiting_terminal"));
  414. expect(relay.getDeviceHeader()).toBe("mid-1");
  415. expect(relay.getRequestUrl()).toBe("/?mid=mid-1");
  416. expect(relay.messages.map((message) => message.type)).toEqual([
  417. "device_register_init",
  418. "auth_init",
  419. "auth_response",
  420. ]);
  421. expect(registered).toEqual([{ deviceSid: "sid-1", passHash: "hash-1" }]);
  422. transport.dispose();
  423. });
  424. it("uses persisted auth directly and heartbeats after pairing", async () => {
  425. const states: WebRemoteControlDeviceTransportState[] = [];
  426. const relay = await createRelayServer(({ message, socket }) => {
  427. if (message.type === "auth_init") {
  428. socket.send(JSON.stringify({ type: "auth_challenge", nonce: "nonce-1" }));
  429. }
  430. if (message.type === "auth_response") {
  431. socket.send(
  432. JSON.stringify({ type: "auth_ack", device_sid: "sid-1", pair_status: "matched" }),
  433. );
  434. }
  435. });
  436. const transport = new WebRemoteControlDeviceTransport({
  437. relayWsUrl: relay.url,
  438. deviceMid: "mid-1",
  439. auth: { mode: "persisted", deviceSid: "sid-1", passHash: "hash-1" },
  440. meta: { platform: "darwin", version: "1.0.0", name: "Mac" },
  441. authProvider: {
  442. createPassword: () => "password",
  443. createPassHash: () => "hash-1",
  444. calculateProof: (_passHash, nonce, role, deviceSid) =>
  445. `${nonce}:${role}:${deviceSid}:proof`,
  446. },
  447. heartbeatIntervalMs: 20,
  448. logger: createLogger(),
  449. onRegisteredAuth: () => {},
  450. onStateChange: (state) => states.push(state),
  451. onPayload: () => {},
  452. onError: () => {},
  453. onInvalidPersistedAuth: async () => {},
  454. });
  455. transport.start();
  456. // Bugfix: 全量 pre-push 并发运行时,WebSocket message 回调和 setInterval 可能被同进程测试挤压。
  457. // 心跳是 paired 之后的真实 timer 行为,先等协议完成配对,避免把正常调度延迟误判为没有发心跳。
  458. await waitUntil(() => states.includes("paired"));
  459. await waitUntil(() => relay.messages.some((message) => message.type === "pair_status_query"));
  460. expect(relay.messages[0]).toMatchObject({
  461. type: "auth_init",
  462. role: "device",
  463. device_sid: "sid-1",
  464. });
  465. expect(relay.messages.find((message) => message.type === "auth_response")).toMatchObject({
  466. proof: "nonce-1:device:sid-1:proof",
  467. });
  468. expect(states).toContain("paired");
  469. transport.dispose();
  470. });
  471. it("keeps waiting_terminal sessions alive with pair status heartbeats", async () => {
  472. const states: WebRemoteControlDeviceTransportState[] = [];
  473. const relay = await createRelayServer(({ message, socket }) => {
  474. if (message.type === "auth_init") {
  475. socket.send(JSON.stringify({ type: "auth_challenge", nonce: "nonce-1" }));
  476. }
  477. if (message.type === "auth_response") {
  478. socket.send(
  479. JSON.stringify({ type: "auth_ack", device_sid: "sid-1", pair_status: "waiting" }),
  480. );
  481. }
  482. if (message.type === "pair_status_query") {
  483. socket.send(
  484. JSON.stringify({ type: "pair_status_ack", device_sid: "sid-1", pair_status: "waiting" }),
  485. );
  486. }
  487. });
  488. const transport = new WebRemoteControlDeviceTransport({
  489. relayWsUrl: relay.url,
  490. deviceMid: "mid-1",
  491. auth: { mode: "persisted", deviceSid: "sid-1", passHash: "hash-1" },
  492. meta: { platform: "darwin", version: "1.0.0", name: "Mac" },
  493. authProvider: {
  494. createPassword: () => "password",
  495. createPassHash: () => "hash-1",
  496. calculateProof: (_passHash, nonce, role, deviceSid) =>
  497. `${nonce}:${role}:${deviceSid}:proof`,
  498. },
  499. heartbeatIntervalMs: 100,
  500. logger: createLogger(),
  501. onRegisteredAuth: () => {},
  502. onStateChange: (state) => states.push(state),
  503. onPayload: () => {},
  504. onError: () => {},
  505. onInvalidPersistedAuth: async () => {},
  506. });
  507. transport.start();
  508. await waitUntil(() => states.includes("waiting_terminal"));
  509. await waitUntil(() => relay.messages.some((message) => message.type === "pair_status_query"));
  510. expect(relay.messages.find((message) => message.type === "pair_status_query")).toMatchObject({
  511. type: "pair_status_query",
  512. device_sid: "sid-1",
  513. });
  514. transport.dispose();
  515. });
  516. it("uses the ACK deadline independently from the next jittered heartbeat", async () => {
  517. const relay = await createRelayServer(({ message, socket }) => {
  518. if (message.type === "auth_init") {
  519. socket.send(JSON.stringify({ type: "auth_challenge", nonce: "nonce-1" }));
  520. }
  521. if (message.type === "auth_response") {
  522. socket.send(
  523. JSON.stringify({ type: "auth_ack", device_sid: "sid-1", pair_status: "matched" }),
  524. );
  525. }
  526. });
  527. const transport = new WebRemoteControlDeviceTransport({
  528. relayWsUrl: relay.url,
  529. deviceMid: "mid-1",
  530. auth: { mode: "persisted", deviceSid: "sid-1", passHash: "hash-1" },
  531. meta: { platform: "darwin", version: "1.0.0", name: "Mac" },
  532. authProvider: {
  533. createPassword: () => "password",
  534. createPassHash: () => "hash-1",
  535. calculateProof: () => "proof",
  536. },
  537. heartbeatIntervalMs: 5_000,
  538. heartbeatJitterMs: 0,
  539. heartbeatAckTimeoutMs: 50,
  540. reconnectJitterMs: 0,
  541. logger: createLogger(),
  542. onRegisteredAuth: () => {},
  543. onStateChange: () => {},
  544. onPayload: () => {},
  545. onError: () => {},
  546. onInvalidPersistedAuth: async () => {},
  547. });
  548. try {
  549. transport.start();
  550. await waitUntil(() => relay.getConnectionCount() > 1, 5_000);
  551. } finally {
  552. transport.dispose();
  553. }
  554. });
  555. it("enters connecting before closing the stale socket during jittered recovery", async () => {
  556. const stateHistory: WebRemoteControlDeviceTransportState[] = [];
  557. let paired = false;
  558. let postPairConnecting = false;
  559. let firstSocketClosedAt = 0;
  560. let firstRelaySocket: import("ws").WebSocket | undefined;
  561. let staleAckInjected = false;
  562. const random = vi.spyOn(Math, "random").mockReturnValue(0.5);
  563. const originalClose = WebSocket.prototype.close;
  564. const closeSpy = vi.spyOn(WebSocket.prototype, "close").mockImplementation(function (this) {
  565. if (!staleAckInjected && firstRelaySocket) {
  566. staleAckInjected = true;
  567. firstRelaySocket.send(
  568. JSON.stringify({ type: "pair_status_ack", device_sid: "sid-1", pair_status: "matched" }),
  569. );
  570. }
  571. return originalClose.call(this);
  572. });
  573. const relay = await createRelayServer(({ message, socket }) => {
  574. firstRelaySocket ??= socket;
  575. if (!firstSocketClosedAt) {
  576. socket.once("close", () => {
  577. firstSocketClosedAt = Date.now();
  578. });
  579. }
  580. if (message.type === "auth_init") {
  581. socket.send(JSON.stringify({ type: "auth_challenge", nonce: "nonce-1" }));
  582. }
  583. if (message.type === "auth_response") {
  584. socket.send(
  585. JSON.stringify({ type: "auth_ack", device_sid: "sid-1", pair_status: "matched" }),
  586. );
  587. }
  588. });
  589. const transport = new WebRemoteControlDeviceTransport({
  590. relayWsUrl: relay.url,
  591. deviceMid: "mid-1",
  592. auth: { mode: "persisted", deviceSid: "sid-1", passHash: "hash-1" },
  593. meta: { platform: "darwin", version: "1.0.0", name: "Mac" },
  594. authProvider: {
  595. createPassword: () => "password",
  596. createPassHash: () => "hash-1",
  597. calculateProof: () => "proof",
  598. },
  599. heartbeatIntervalMs: 5_000,
  600. heartbeatJitterMs: 0,
  601. heartbeatAckTimeoutMs: 50,
  602. reconnectJitterMs: 250,
  603. logger: createLogger(),
  604. onRegisteredAuth: () => {},
  605. onStateChange: (state) => {
  606. stateHistory.push(state);
  607. if (state === "paired") {
  608. paired = true;
  609. }
  610. if (paired && state === "connecting") {
  611. postPairConnecting = true;
  612. }
  613. },
  614. onPayload: () => {},
  615. onError: () => {},
  616. onInvalidPersistedAuth: async () => {},
  617. });
  618. try {
  619. transport.start();
  620. await waitUntil(() => stateHistory.includes("paired"));
  621. await waitUntil(() => firstSocketClosedAt > 0, 5_000);
  622. await new Promise((resolve) => setTimeout(resolve, 20));
  623. expect(postPairConnecting).toBe(true);
  624. expect(staleAckInjected).toBe(true);
  625. expect(stateHistory.at(-1)).toBe("connecting");
  626. } finally {
  627. transport.dispose();
  628. closeSpy.mockRestore();
  629. random.mockRestore();
  630. }
  631. });
  632. it("pauses business payloads after a stale waiting heartbeat once paired", async () => {
  633. let heartbeatCount = 0;
  634. const relay = await createRelayServer(({ message, socket }) => {
  635. if (message.type === "auth_init") {
  636. socket.send(JSON.stringify({ type: "auth_challenge", nonce: "nonce-1" }));
  637. }
  638. if (message.type === "auth_response") {
  639. socket.send(
  640. JSON.stringify({ type: "auth_ack", device_sid: "sid-1", pair_status: "matched" }),
  641. );
  642. }
  643. if (message.type === "pair_status_query") {
  644. heartbeatCount += 1;
  645. // First heartbeat returns "waiting" (stale), second returns "matched" (recovered).
  646. // This avoids triggering reconnectBeforePairing, which would close the socket
  647. // before sendPayload can send on it.
  648. socket.send(
  649. JSON.stringify({
  650. type: "pair_status_ack",
  651. device_sid: "sid-1",
  652. pair_status: heartbeatCount === 1 ? "waiting" : "matched",
  653. }),
  654. );
  655. }
  656. });
  657. const transport = new WebRemoteControlDeviceTransport({
  658. relayWsUrl: relay.url,
  659. deviceMid: "mid-1",
  660. auth: { mode: "persisted", deviceSid: "sid-1", passHash: "hash-1" },
  661. meta: { platform: "darwin", version: "1.0.0", name: "Mac" },
  662. authProvider: {
  663. createPassword: () => "password",
  664. createPassHash: () => "hash-1",
  665. calculateProof: () => "proof",
  666. },
  667. heartbeatIntervalMs: 100,
  668. logger: createLogger(),
  669. onRegisteredAuth: () => {},
  670. onStateChange: () => {},
  671. onPayload: () => {},
  672. onError: () => {},
  673. onInvalidPersistedAuth: async () => {},
  674. });
  675. transport.start();
  676. await waitUntil(() => heartbeatCount >= 1, 5_000);
  677. await new Promise((resolve) => setTimeout(resolve, 20));
  678. const sentWhileSuspect = transport.sendPayload({
  679. zcode_type: "workspace-list-response",
  680. requestId: "req-1",
  681. success: true,
  682. result: {
  683. workspaces: [],
  684. activeWorkspaceKey: null,
  685. activeTaskId: null,
  686. },
  687. });
  688. await new Promise((resolve) => setTimeout(resolve, 30));
  689. expect(sentWhileSuspect).toBe(false);
  690. expect(relay.messages.some((message) => message.type === "data")).toBe(false);
  691. await waitUntil(() => heartbeatCount >= 2, 5_000);
  692. await new Promise((resolve) => setTimeout(resolve, 20));
  693. const sentAfterMatched = transport.sendPayload({
  694. zcode_type: "workspace-list-response",
  695. requestId: "req-2",
  696. success: true,
  697. result: {
  698. workspaces: [],
  699. activeWorkspaceKey: null,
  700. activeTaskId: null,
  701. },
  702. });
  703. await waitUntil(() => relay.messages.some((message) => message.type === "data"));
  704. expect(sentAfterMatched).toBe(true);
  705. expect(relay.messages.find((message) => message.type === "data")).toMatchObject({
  706. payload: { zcode_type: "workspace-list-response", requestId: "req-2" },
  707. });
  708. transport.dispose();
  709. });
  710. it("notifies send readiness when a stale waiting heartbeat recovers to matched", async () => {
  711. let heartbeatCount = 0;
  712. const sendReady = vi.fn();
  713. const relay = await createRelayServer(({ message, socket }) => {
  714. if (message.type === "auth_init") {
  715. socket.send(JSON.stringify({ type: "auth_challenge", nonce: "nonce-1" }));
  716. }
  717. if (message.type === "auth_response") {
  718. socket.send(
  719. JSON.stringify({ type: "auth_ack", device_sid: "sid-1", pair_status: "matched" }),
  720. );
  721. }
  722. if (message.type === "pair_status_query") {
  723. heartbeatCount += 1;
  724. socket.send(
  725. JSON.stringify({
  726. type: "pair_status_ack",
  727. device_sid: "sid-1",
  728. pair_status: heartbeatCount === 1 ? "waiting" : "matched",
  729. }),
  730. );
  731. }
  732. });
  733. const transport = new WebRemoteControlDeviceTransport({
  734. relayWsUrl: relay.url,
  735. deviceMid: "mid-1",
  736. auth: { mode: "persisted", deviceSid: "sid-1", passHash: "hash-1" },
  737. meta: { platform: "darwin", version: "1.0.0", name: "Mac" },
  738. authProvider: {
  739. createPassword: () => "password",
  740. createPassHash: () => "hash-1",
  741. calculateProof: () => "proof",
  742. },
  743. heartbeatIntervalMs: 100,
  744. logger: createLogger(),
  745. onRegisteredAuth: () => {},
  746. onStateChange: () => {},
  747. onPayload: () => {},
  748. onError: () => {},
  749. onSendReady: sendReady,
  750. onInvalidPersistedAuth: async () => {},
  751. });
  752. transport.start();
  753. // Bugfix: 服务端收到第 2 次 heartbeat 不代表客户端已经处理 matched ACK。
  754. // 这里直接等待 onSendReady,避免全量并发测试时断言抢在 WebSocket message 回调前执行。
  755. await waitUntil(() => sendReady.mock.calls.length === 1, 5_000);
  756. expect(sendReady).toHaveBeenCalledOnce();
  757. expect(sendReady).toHaveBeenCalledWith({ kind: "same-socket" });
  758. transport.dispose();
  759. });
  760. it("keeps the desktop socket during a waiting window longer than one production heartbeat", async () => {
  761. let heartbeatCount = 0;
  762. const relay = await createRelayServer(({ message, socket }) => {
  763. if (message.type === "auth_init") {
  764. socket.send(JSON.stringify({ type: "auth_challenge", nonce: "nonce-1" }));
  765. }
  766. if (message.type === "auth_response") {
  767. socket.send(
  768. JSON.stringify({ type: "auth_ack", device_sid: "sid-1", pair_status: "matched" }),
  769. );
  770. }
  771. if (message.type === "pair_status_query") {
  772. heartbeatCount += 1;
  773. if (heartbeatCount === 1) {
  774. socket.send(
  775. JSON.stringify({
  776. type: "pair_status_ack",
  777. device_sid: "sid-1",
  778. pair_status: "waiting",
  779. }),
  780. );
  781. }
  782. }
  783. });
  784. const transport = new WebRemoteControlDeviceTransport({
  785. relayWsUrl: relay.url,
  786. deviceMid: "mid-1",
  787. auth: { mode: "persisted", deviceSid: "sid-1", passHash: "hash-1" },
  788. meta: { platform: "darwin", version: "1.0.0", name: "Mac" },
  789. authProvider: {
  790. createPassword: () => "password",
  791. createPassHash: () => "hash-1",
  792. calculateProof: () => "proof",
  793. },
  794. heartbeatIntervalMs: 200,
  795. logger: createLogger(),
  796. onRegisteredAuth: () => {},
  797. onStateChange: () => {},
  798. onPayload: () => {},
  799. onError: () => {},
  800. onInvalidPersistedAuth: async () => {},
  801. });
  802. transport.start();
  803. await waitUntil(() => heartbeatCount >= 1, 5_000);
  804. await new Promise((resolve) => setTimeout(resolve, 20));
  805. const sent = transport.sendPayload({
  806. zcode_type: "workspace-list-response",
  807. requestId: "req-waiting",
  808. success: true,
  809. result: {
  810. workspaces: [],
  811. activeWorkspaceKey: null,
  812. activeTaskId: null,
  813. },
  814. });
  815. await new Promise((resolve) => setTimeout(resolve, 10_500));
  816. expect(sent).toBe(false);
  817. expect(relay.getConnectionCount()).toBe(1);
  818. expect(
  819. relay.messages.some(
  820. (message) =>
  821. message.type === "data" &&
  822. typeof message.payload === "object" &&
  823. message.payload &&
  824. "requestId" in message.payload &&
  825. message.payload.requestId === "req-waiting",
  826. ),
  827. ).toBe(false);
  828. transport.dispose();
  829. });
  830. it("reconnects when paired heartbeat stays waiting", async () => {
  831. const sendReady = vi.fn();
  832. const relay = await createRelayServer(({ message, socket }) => {
  833. if (message.type === "auth_init") {
  834. socket.send(JSON.stringify({ type: "auth_challenge", nonce: "nonce-1" }));
  835. }
  836. if (message.type === "auth_response") {
  837. socket.send(
  838. JSON.stringify({ type: "auth_ack", device_sid: "sid-1", pair_status: "matched" }),
  839. );
  840. }
  841. if (message.type === "pair_status_query") {
  842. socket.send(
  843. JSON.stringify({ type: "pair_status_ack", device_sid: "sid-1", pair_status: "waiting" }),
  844. );
  845. }
  846. });
  847. const transport = new WebRemoteControlDeviceTransport({
  848. relayWsUrl: relay.url,
  849. deviceMid: "mid-1",
  850. auth: { mode: "persisted", deviceSid: "sid-1", passHash: "hash-1" },
  851. meta: { platform: "darwin", version: "1.0.0", name: "Mac" },
  852. authProvider: {
  853. createPassword: () => "password",
  854. createPassHash: () => "hash-1",
  855. calculateProof: () => "proof",
  856. },
  857. heartbeatIntervalMs: 20,
  858. logger: createLogger(),
  859. onRegisteredAuth: () => {},
  860. onStateChange: () => {},
  861. onPayload: () => {},
  862. onError: () => {},
  863. onSendReady: sendReady,
  864. onInvalidPersistedAuth: async () => {},
  865. });
  866. transport.start();
  867. await waitUntil(() => relay.messages.some((message) => message.type === "pair_status_query"));
  868. await waitUntil(() => relay.getConnectionCount() > 1, 5_000);
  869. await waitUntil(() => sendReady.mock.calls.length === 1, 5_000);
  870. expect(sendReady).toHaveBeenCalledWith({ kind: "reconnected-socket" });
  871. transport.dispose();
  872. });
  873. it("reuses registered device auth instead of registering again after reconnect", async () => {
  874. const relay = await createRelayServer(({ message, socket }) => {
  875. if (message.type === "device_register_init") {
  876. socket.send(JSON.stringify({ type: "device_register_ack", device_sid: "sid-registered" }));
  877. }
  878. if (message.type === "auth_init") {
  879. socket.send(JSON.stringify({ type: "auth_challenge", nonce: "nonce-1" }));
  880. }
  881. if (message.type === "auth_response") {
  882. socket.send(
  883. JSON.stringify({
  884. type: "auth_ack",
  885. device_sid: "sid-registered",
  886. pair_status: "matched",
  887. }),
  888. );
  889. }
  890. if (message.type === "pair_status_query") {
  891. socket.send(
  892. JSON.stringify({
  893. type: "pair_status_ack",
  894. device_sid: "sid-registered",
  895. pair_status: "waiting",
  896. }),
  897. );
  898. }
  899. });
  900. const transport = new WebRemoteControlDeviceTransport({
  901. relayWsUrl: relay.url,
  902. deviceMid: "mid-1",
  903. auth: { mode: "register", passHash: "hash-1" },
  904. meta: { platform: "darwin", version: "1.0.0", name: "Mac" },
  905. authProvider: {
  906. createPassword: () => "password",
  907. createPassHash: () => "hash-1",
  908. calculateProof: () => "proof",
  909. },
  910. heartbeatIntervalMs: 20,
  911. logger: createLogger(),
  912. onRegisteredAuth: () => {},
  913. onStateChange: () => {},
  914. onPayload: () => {},
  915. onError: () => {},
  916. onInvalidPersistedAuth: async () => {},
  917. });
  918. transport.start();
  919. await waitUntil(() => relay.getConnectionCount() > 1, 5_000);
  920. await waitUntil(
  921. () => relay.messages.filter((message) => message.type === "auth_init").length >= 2,
  922. 5_000,
  923. );
  924. // Bugfix: 全量 pre-push 并发跑测试时,第二次 auth_init 到 auth_response 中间存在异步间隙。
  925. // 这里等待第二次响应完成后再断言,避免把正常的中间态误判为认证复用失败。
  926. await waitUntil(
  927. () => relay.messages.filter((message) => message.type === "auth_response").length >= 2,
  928. 5_000,
  929. );
  930. expect(
  931. relay.messages.filter((message) => message.type === "device_register_init"),
  932. ).toHaveLength(1);
  933. expect(relay.messages.filter((message) => message.type === "auth_init")).toHaveLength(2);
  934. expect(relay.messages.at(-1)).toMatchObject({
  935. type: "auth_response",
  936. device_sid: "sid-registered",
  937. });
  938. transport.dispose();
  939. });
  940. it("clears invalid persisted auth and retries registration once", async () => {
  941. const invalidations: string[] = [];
  942. const relay = await createRelayServer(({ message, socket, messages }) => {
  943. if (message.type === "auth_init") {
  944. socket.send(
  945. JSON.stringify({ type: "error", code: "AUTH_FAILED", message: "bad persisted auth" }),
  946. );
  947. socket.close();
  948. }
  949. if (messages.filter((item) => item.type === "device_register_init").length === 1) {
  950. socket.send(JSON.stringify({ type: "device_register_ack", device_sid: "sid-new" }));
  951. }
  952. });
  953. const transport = new WebRemoteControlDeviceTransport({
  954. relayWsUrl: relay.url,
  955. deviceMid: "mid-1",
  956. auth: { mode: "persisted", deviceSid: "sid-old", passHash: "hash-1" },
  957. meta: { platform: "darwin", version: "1.0.0", name: "Mac" },
  958. authProvider: {
  959. createPassword: () => "password",
  960. createPassHash: () => "hash-1",
  961. calculateProof: () => "proof",
  962. },
  963. reconnectDelayMs: 0,
  964. logger: createLogger(),
  965. onRegisteredAuth: () => {},
  966. onStateChange: () => {},
  967. onPayload: () => {},
  968. onError: () => {},
  969. onInvalidPersistedAuth: async () => {
  970. invalidations.push("cleared");
  971. },
  972. });
  973. transport.start();
  974. await waitUntil(() =>
  975. relay.messages.some((message) => message.type === "device_register_init"),
  976. );
  977. expect(invalidations).toEqual(["cleared"]);
  978. transport.dispose();
  979. });
  980. it("reconnects after a relay internal error", async () => {
  981. const errors: string[] = [];
  982. const relay = await createRelayServer(({ message, socket }) => {
  983. if (message.type === "auth_init") {
  984. socket.send(JSON.stringify({ type: "error", code: "INTERNAL", message: "relay bounced" }));
  985. socket.close();
  986. }
  987. });
  988. const transport = new WebRemoteControlDeviceTransport({
  989. relayWsUrl: relay.url,
  990. deviceMid: "mid-1",
  991. auth: { mode: "persisted", deviceSid: "sid-1", passHash: "hash-1" },
  992. meta: { platform: "darwin", version: "1.0.0", name: "Mac" },
  993. authProvider: {
  994. createPassword: () => "password",
  995. createPassHash: () => "hash-1",
  996. calculateProof: () => "proof",
  997. },
  998. reconnectDelayMs: 0,
  999. logger: createLogger(),
  1000. onRegisteredAuth: () => {},
  1001. onStateChange: () => {},
  1002. onPayload: () => {},
  1003. onError: (error) => errors.push(error.message),
  1004. onInvalidPersistedAuth: async () => {},
  1005. });
  1006. transport.start();
  1007. await waitUntil(() => relay.getConnectionCount() > 1);
  1008. expect(errors).toContain("relay bounced");
  1009. transport.dispose();
  1010. });
  1011. it("keeps the device socket open when paired data forwarding reports no pair", async () => {
  1012. const errors: string[] = [];
  1013. const states: WebRemoteControlDeviceTransportState[] = [];
  1014. let pairStatus: "matched" | "waiting" = "matched";
  1015. const relay = await createRelayServer(({ message, socket }) => {
  1016. if (message.type === "auth_init") {
  1017. socket.send(JSON.stringify({ type: "auth_challenge", nonce: "nonce-1" }));
  1018. }
  1019. if (message.type === "auth_response") {
  1020. socket.send(
  1021. JSON.stringify({ type: "auth_ack", device_sid: "sid-1", pair_status: "matched" }),
  1022. );
  1023. }
  1024. if (message.type === "data") {
  1025. pairStatus = "waiting";
  1026. socket.send(JSON.stringify({ type: "error", code: "INTERNAL", message: "no such pair" }));
  1027. }
  1028. if (message.type === "pair_status_query") {
  1029. socket.send(
  1030. JSON.stringify({ type: "pair_status_ack", device_sid: "sid-1", pair_status: pairStatus }),
  1031. );
  1032. }
  1033. });
  1034. const transport = new WebRemoteControlDeviceTransport({
  1035. relayWsUrl: relay.url,
  1036. deviceMid: "mid-1",
  1037. auth: { mode: "persisted", deviceSid: "sid-1", passHash: "hash-1" },
  1038. meta: { platform: "darwin", version: "1.0.0", name: "Mac" },
  1039. authProvider: {
  1040. createPassword: () => "password",
  1041. createPassHash: () => "hash-1",
  1042. calculateProof: () => "proof",
  1043. },
  1044. heartbeatIntervalMs: 20,
  1045. logger: createLogger(),
  1046. onRegisteredAuth: () => {},
  1047. onStateChange: (state) => states.push(state),
  1048. onPayload: () => {},
  1049. onError: (error) => errors.push(error.message),
  1050. onInvalidPersistedAuth: async () => {},
  1051. });
  1052. transport.start();
  1053. await waitUntil(() => states.includes("paired"));
  1054. // 修复原因:先到的心跳若直接回复 waiting,会在 data 转发前暂停发送,
  1055. // 导致用例未进入待验证的 no pair 分支;只有转发失败后才切换配对状态。
  1056. await waitUntil(() => relay.messages.some((message) => message.type === "pair_status_query"));
  1057. const sent = transport.sendPayload({
  1058. zcode_type: "workspace-list-response",
  1059. requestId: "req-1",
  1060. success: true,
  1061. result: {
  1062. workspaces: [],
  1063. activeWorkspaceKey: null,
  1064. activeTaskId: null,
  1065. },
  1066. });
  1067. await waitUntil(() => states.includes("waiting_terminal"));
  1068. expect(sent).toBe(true);
  1069. expect(errors).toEqual(["no such pair"]);
  1070. expect(relay.getConnectionCount()).toBe(1);
  1071. transport.dispose();
  1072. });
  1073. it("keeps the device socket open for paired WRONG_PARAM relay errors", async () => {
  1074. const errors: string[] = [];
  1075. const states: WebRemoteControlDeviceTransportState[] = [];
  1076. const relay = await createRelayServer(({ message, socket }) => {
  1077. if (message.type === "auth_init") {
  1078. socket.send(JSON.stringify({ type: "auth_challenge", nonce: "nonce-1" }));
  1079. }
  1080. if (message.type === "auth_response") {
  1081. socket.send(
  1082. JSON.stringify({ type: "auth_ack", device_sid: "sid-1", pair_status: "matched" }),
  1083. );
  1084. }
  1085. if (message.type === "pair_status_query") {
  1086. socket.send(JSON.stringify({ type: "error", code: "WRONG_PARAM", message: "bad request" }));
  1087. }
  1088. });
  1089. const transport = new WebRemoteControlDeviceTransport({
  1090. relayWsUrl: relay.url,
  1091. deviceMid: "mid-1",
  1092. auth: { mode: "persisted", deviceSid: "sid-1", passHash: "hash-1" },
  1093. meta: { platform: "darwin", version: "1.0.0", name: "Mac" },
  1094. authProvider: {
  1095. createPassword: () => "password",
  1096. createPassHash: () => "hash-1",
  1097. calculateProof: () => "proof",
  1098. },
  1099. heartbeatIntervalMs: 20,
  1100. logger: createLogger(),
  1101. onRegisteredAuth: () => {},
  1102. onStateChange: (state) => states.push(state),
  1103. onPayload: () => {},
  1104. onError: (error) => errors.push(error.message),
  1105. onInvalidPersistedAuth: async () => {},
  1106. });
  1107. transport.start();
  1108. await waitUntil(() => states.includes("paired"));
  1109. await waitUntil(() => errors.includes("bad request"));
  1110. await new Promise((resolve) => setTimeout(resolve, 60));
  1111. expect(states).not.toContain("error");
  1112. expect(relay.getConnectionCount()).toBe(1);
  1113. transport.dispose();
  1114. });
  1115. it("treats relay WRONG_PARAM as a terminal protocol error", async () => {
  1116. const errors: string[] = [];
  1117. const states: WebRemoteControlDeviceTransportState[] = [];
  1118. const relay = await createRelayServer(({ message, socket }) => {
  1119. if (message.type === "auth_init") {
  1120. socket.send(JSON.stringify({ type: "error", code: "WRONG_PARAM", message: "bad request" }));
  1121. }
  1122. });
  1123. const transport = new WebRemoteControlDeviceTransport({
  1124. relayWsUrl: relay.url,
  1125. deviceMid: "mid-1",
  1126. auth: { mode: "persisted", deviceSid: "sid-1", passHash: "hash-1" },
  1127. meta: { platform: "darwin", version: "1.0.0", name: "Mac" },
  1128. authProvider: {
  1129. createPassword: () => "password",
  1130. createPassHash: () => "hash-1",
  1131. calculateProof: () => "proof",
  1132. },
  1133. reconnectDelayMs: 0,
  1134. logger: createLogger(),
  1135. onRegisteredAuth: () => {},
  1136. onStateChange: (state) => states.push(state),
  1137. onPayload: () => {},
  1138. onError: (error) => errors.push(error.message),
  1139. onInvalidPersistedAuth: async () => {},
  1140. });
  1141. transport.start();
  1142. await waitUntil(() => states.includes("error"));
  1143. expect(errors).toEqual(["bad request"]);
  1144. expect(relay.getConnectionCount()).toBe(1);
  1145. transport.dispose();
  1146. });
  1147. it("recovers desktop device transport from relay KICKED without entering a terminal state", async () => {
  1148. const states: WebRemoteControlDeviceTransportState[] = [];
  1149. let authInitCount = 0;
  1150. const relay = await createRelayServer(({ message, socket }) => {
  1151. if (message.type === "auth_init") {
  1152. authInitCount += 1;
  1153. if (authInitCount === 1) {
  1154. socket.send(
  1155. JSON.stringify({
  1156. type: "error",
  1157. code: "KICKED",
  1158. message: "Another mobile controller replaced this one.",
  1159. }),
  1160. );
  1161. return;
  1162. }
  1163. socket.send(JSON.stringify({ type: "auth_challenge", nonce: "nonce-1" }));
  1164. }
  1165. if (message.type === "auth_response") {
  1166. socket.send(
  1167. JSON.stringify({ type: "auth_ack", device_sid: "sid-1", pair_status: "waiting" }),
  1168. );
  1169. }
  1170. });
  1171. const transport = new WebRemoteControlDeviceTransport({
  1172. relayWsUrl: relay.url,
  1173. deviceMid: "mid-1",
  1174. auth: { mode: "persisted", deviceSid: "sid-1", passHash: "hash-1" },
  1175. meta: { platform: "darwin", version: "1.0.0", name: "Mac" },
  1176. authProvider: {
  1177. createPassword: () => "password",
  1178. createPassHash: () => "hash-1",
  1179. calculateProof: () => "proof",
  1180. },
  1181. reconnectDelayMs: 0,
  1182. logger: createLogger(),
  1183. onRegisteredAuth: () => {},
  1184. onStateChange: (state) => states.push(state),
  1185. onPayload: () => {},
  1186. onError: () => {},
  1187. onInvalidPersistedAuth: async () => {},
  1188. });
  1189. try {
  1190. transport.start();
  1191. await waitUntil(() => states.includes("waiting_terminal"));
  1192. expect(states).not.toContain("kicked");
  1193. expect(states).not.toContain("error");
  1194. expect(relay.getConnectionCount()).toBeGreaterThanOrEqual(2);
  1195. } finally {
  1196. transport.dispose();
  1197. }
  1198. });
  1199. it("forwards only parsed data payloads after paired and redacts invalid payload logs", async () => {
  1200. const payloads: WebRemoteControlAppPayload[] = [];
  1201. const logger = createLogger();
  1202. const [validFrame] = encodeWebRemoteControlRpcTransportMessage(new Uint8Array([1, 2, 3]), {
  1203. bridgeSessionId: "bridge-1",
  1204. firstPhysicalSeq: 1,
  1205. messageSeq: 1,
  1206. });
  1207. const relay = await createRelayServer(({ message, socket }) => {
  1208. if (message.type === "auth_init") {
  1209. socket.send(
  1210. JSON.stringify({ type: "auth_ack", device_sid: "sid-1", pair_status: "matched" }),
  1211. );
  1212. }
  1213. if (message.type === "pair_status_query") {
  1214. socket.send(
  1215. JSON.stringify({
  1216. type: "data",
  1217. payload: { ...validFrame, seq: -1, raw: "secret" },
  1218. }),
  1219. );
  1220. socket.send(
  1221. JSON.stringify({
  1222. type: "data",
  1223. payload: validFrame,
  1224. }),
  1225. );
  1226. }
  1227. });
  1228. const transport = new WebRemoteControlDeviceTransport({
  1229. relayWsUrl: relay.url,
  1230. deviceMid: "mid-1",
  1231. auth: { mode: "persisted", deviceSid: "sid-1", passHash: "hash-1" },
  1232. meta: { platform: "darwin", version: "1.0.0", name: "Mac" },
  1233. authProvider: {
  1234. createPassword: () => "password",
  1235. createPassHash: () => "hash-1",
  1236. calculateProof: () => "proof",
  1237. },
  1238. heartbeatIntervalMs: 20,
  1239. logger,
  1240. onRegisteredAuth: () => {},
  1241. onStateChange: () => {},
  1242. onPayload: (payload) => payloads.push(payload),
  1243. onError: () => {},
  1244. onInvalidPersistedAuth: async () => {},
  1245. });
  1246. transport.start();
  1247. await waitUntil(() => payloads.length === 1);
  1248. expect(payloads[0]).toMatchObject({ zcode_type: "rpc-frame", seq: 1 });
  1249. expect(JSON.stringify(logger.warn.mock.calls)).not.toContain("secret");
  1250. transport.dispose();
  1251. });
  1252. });