webRemoteControlManagerV2.test.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. import { setTimeout as delay } from "node:timers/promises";
  2. import { WebSocket } from "ws";
  3. import { afterEach, describe, expect, it, vi } from "vitest";
  4. import { createFakeRelayV2, type FakeRelayV2Options } from "@zcode/shared/testing/fake-relay-v2";
  5. import {
  6. buildZCodeEndpointUrls,
  7. type AppSettings,
  8. type WebRemoteControlContext,
  9. } from "@zcode/shared";
  10. import {
  11. parseWebRemoteControlRelayV2IncomingMessage,
  12. type WebRemoteControlRelayV2IncomingMessage,
  13. } from "@zcode/shared/web-remote-relay";
  14. import { createWebRemoteControlManager } from "@desktop/main/webRemoteControlManager.js";
  15. import { createWebRemoteControlDeviceStorage } from "#src/main/web-remote-relay/index.js";
  16. import { createWebRemoteControlFeatureGate } from "@desktop/main/webRemoteControlFeatureGate.js";
  17. import { createOAuthService } from "@zcode/services/node";
  18. const cleanups: Array<() => void | Promise<void>> = [];
  19. afterEach(async () => {
  20. for (const fn of cleanups.splice(0).reverse()) await fn();
  21. vi.useRealTimers();
  22. });
  23. async function fixture(
  24. options: Partial<FakeRelayV2Options> = {},
  25. initialSettings: Partial<AppSettings> = {},
  26. deviceSaveError?: Error,
  27. ) {
  28. const relay = await createFakeRelayV2({
  29. users: { jwt: "user", other: "other-user" },
  30. ...options,
  31. });
  32. cleanups.push(() => relay.close());
  33. const settings: AppSettings = {
  34. recentProjects: [],
  35. webRemoteControlExternalRelayDevice: { deviceSid: "v1-sid" },
  36. ...initialSettings,
  37. };
  38. const credentials = new Map([["web-remote-control:external-relay:pass_hash", "v1-hash"]]);
  39. let login: { jwt: string; userId: string } | undefined = { jwt: "jwt", userId: "user" };
  40. let endpoint = relay.httpUrl;
  41. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  42. const deviceStorage = createWebRemoteControlDeviceStorage({
  43. loadSettings: async () => settings,
  44. patchSettings: async (patch) => {
  45. if (deviceSaveError && Object.hasOwn(patch, "webRemoteControlRelayV2Device")) {
  46. throw deviceSaveError;
  47. }
  48. Object.assign(settings, patch);
  49. },
  50. deleteLegacyCredential: async () => {
  51. credentials.delete("web-remote-control:external-relay:pass_hash");
  52. },
  53. });
  54. const readLogin = vi.fn(async () => login);
  55. const loadEnabled = vi.fn(async () => settings.webRemoteControlLastEnabledContext);
  56. const attachWorkspaceHost = vi.fn(async () => {
  57. throw new Error("No bridge expected");
  58. });
  59. const manager = createWebRemoteControlManager({
  60. relayWsUrl: relay.wsUrl,
  61. mobileRemoteControlUrl: `${relay.httpUrl}/remote/v4`,
  62. getEndpointUrls: () => ({
  63. ...buildZCodeEndpointUrls(endpoint, { appVersion: "3.13.0" }),
  64. relayWsUrl: endpoint.replace("http", "ws") + "/api/v1/remote/ws2",
  65. }),
  66. getLogin: readLogin,
  67. deviceStorage,
  68. deviceMid: "desktop-mid",
  69. deviceName: "Desktop name",
  70. appVersion: "3.13.0",
  71. logger,
  72. featureGate: createWebRemoteControlFeatureGate(true),
  73. startupRestoreStorageProvider: {
  74. load: loadEnabled,
  75. save: async (context) => {
  76. settings.webRemoteControlLastEnabledContext = context;
  77. },
  78. clear: async () => {
  79. settings.webRemoteControlLastEnabledContext = undefined;
  80. },
  81. },
  82. platformHandlers: {
  83. isDockerAvailable: async () => false,
  84. listWSLDistros: async () => [],
  85. listDockerContainers: async () => [],
  86. listSSHConfigAliases: async () => [],
  87. loadMcpFromUserDirectory: async () => ({ servers: [] }),
  88. saveMcpToUserDirectory: async () => ({ success: true }),
  89. migrateLegacyCommonMcp: async () => ({
  90. servers: {},
  91. totalCount: 0,
  92. importedCount: 0,
  93. skippedCount: 0,
  94. }),
  95. },
  96. reconnectWorkspace: async () => {},
  97. attachWorkspaceHost,
  98. releaseWorkspaceHostAttachment: () => {},
  99. disposeWorkspaceHostAttachmentsForWindow: () => {},
  100. disposeWorkspaceHostAttachmentsForRemoteSession: () => {},
  101. });
  102. cleanups.push(async () => {
  103. await manager.suspend(1, "test-cleanup");
  104. await manager.suspend(2, "test-cleanup");
  105. });
  106. const context = { workspacePath: "/workspace" };
  107. const start = (target: WebRemoteControlContext = context) =>
  108. manager.startAuthorized(1, target, manager.authorizeStart(1, target));
  109. return {
  110. manager,
  111. start,
  112. settings,
  113. credentials,
  114. relay,
  115. logger,
  116. readLogin,
  117. loadEnabled,
  118. attachWorkspaceHost,
  119. setLogin: (value: typeof login) => {
  120. login = value;
  121. },
  122. setEndpoint: (value: string) => {
  123. endpoint = value;
  124. },
  125. };
  126. }
  127. async function connectTerminal(
  128. relay: Awaited<ReturnType<typeof createFakeRelayV2>>,
  129. jwt: string,
  130. deviceSid: string,
  131. ) {
  132. const response = await fetch(`${relay.httpUrl}/api/v1/remote/token`, {
  133. method: "POST",
  134. headers: { Authorization: `Bearer ${jwt}`, "Content-Type": "application/json" },
  135. body: JSON.stringify({ role: "terminal" }),
  136. });
  137. const { data } = await response.json();
  138. const socket = new WebSocket(`${relay.wsUrl}?token=${data.token}`);
  139. cleanups.push(() => socket.close());
  140. const messages: WebRemoteControlRelayV2IncomingMessage[] = [];
  141. socket.on("message", (raw) => {
  142. const message = parseWebRemoteControlRelayV2IncomingMessage(JSON.parse(raw.toString()));
  143. if (message) messages.push(message);
  144. });
  145. await new Promise<void>((resolve) => socket.once("open", resolve));
  146. socket.send(JSON.stringify({ type: "auth_init", device_sid: deviceSid }));
  147. await vi.waitFor(() =>
  148. expect(messages.some((message) => message.type === "auth_ack")).toBe(true),
  149. );
  150. return { socket, messages };
  151. }
  152. function requestBootstrap(socket: WebSocket) {
  153. socket.send(
  154. JSON.stringify({
  155. type: "data",
  156. payload: { zcode_type: "bootstrap-request", requestId: "account-isolation" },
  157. }),
  158. );
  159. }
  160. describe("V2 manager public API with real relay", () => {
  161. it.each([false, true])(
  162. "身份保存失败删除新设备并立即停止重注册(已有失效SID:%s)",
  163. async (invalidStoredSid) => {
  164. const saveError = Object.assign(new Error("device settings write failed"), {
  165. code: "ENOSPC",
  166. });
  167. const f = await fixture({}, {}, saveError);
  168. const headers = { Authorization: "Bearer jwt", "Content-Type": "application/json" };
  169. if (invalidStoredSid) {
  170. const response = await fetch(`${f.relay.httpUrl}/api/v1/remote/device`, {
  171. method: "POST",
  172. headers,
  173. body: JSON.stringify({ device_mid: "desktop-mid" }),
  174. });
  175. const { data } = await response.json();
  176. f.settings.webRemoteControlRelayV2Device = {
  177. deviceSid: data.device_sid,
  178. userId: "user",
  179. endpointOrigin: f.relay.httpUrl,
  180. };
  181. await fetch(`${f.relay.httpUrl}/api/v1/remote/device/delete`, {
  182. method: "POST",
  183. headers,
  184. body: JSON.stringify({ device_sid: data.device_sid }),
  185. });
  186. }
  187. const stored = f.settings.webRemoteControlRelayV2Device;
  188. const previousCalls = f.relay.httpCalls.length;
  189. const started = f.start().catch((error: unknown) => error);
  190. await vi.waitFor(() =>
  191. expect(f.manager.getStatus(1)).toMatchObject({
  192. status: "error",
  193. failure: { reason: "relay-unavailable" },
  194. }),
  195. );
  196. expect(await started).toMatchObject({ reason: "relay-unavailable", retryable: false });
  197. const devices = await (
  198. await fetch(`${f.relay.httpUrl}/api/v1/remote/device`, { headers })
  199. ).json();
  200. expect(devices.data).toEqual([]);
  201. // 覆盖首个网络退避窗口,证明终态不会继续产生新的远端设备。
  202. await delay(2500);
  203. expect(
  204. f.relay.httpCalls
  205. .slice(previousCalls)
  206. .filter((call) => call.path === "/api/v1/remote/device" && call.method === "POST"),
  207. ).toHaveLength(1);
  208. expect(f.settings.webRemoteControlRelayV2Device).toEqual(stored);
  209. expect(f.settings.webRemoteControlLastEnabledContext).toBeUndefined();
  210. expect(f.logger.error).toHaveBeenCalledWith(
  211. "[web-remote-control] V2 device identity persistence failed",
  212. saveError,
  213. );
  214. },
  215. );
  216. it("保存失败后的补偿删除503仍结束启动,不继续累积孤儿设备", async () => {
  217. const saveError = Object.assign(new Error("device settings write failed"), { code: "ENOSPC" });
  218. const f = await fixture(
  219. { onHttp: (call) => (call.path.endsWith("/delete") ? { status: 503 } : undefined) },
  220. {},
  221. saveError,
  222. );
  223. await expect(f.start()).rejects.toMatchObject({
  224. reason: "relay-unavailable",
  225. retryable: false,
  226. });
  227. expect(f.manager.getStatus(1)).toMatchObject({ status: "error" });
  228. expect(f.logger.warn).toHaveBeenCalledWith("[web-remote-control] V2 new device cleanup failed");
  229. await delay(2500);
  230. const devices = await (
  231. await fetch(`${f.relay.httpUrl}/api/v1/remote/device`, {
  232. headers: { Authorization: "Bearer jwt" },
  233. })
  234. ).json();
  235. expect(devices.data).toHaveLength(1);
  236. expect(devices.data[0].online).toBe(false);
  237. expect(
  238. f.relay.httpCalls.filter(
  239. (call) => call.path === "/api/v1/remote/device" && call.method === "POST",
  240. ),
  241. ).toHaveLength(1);
  242. });
  243. it("凭据清空后的 provider 清理失败仍撤销配对连接并保留启用记录", async () => {
  244. const f = await fixture();
  245. const credentials = new Map([
  246. ["oauth:active_provider", "zai"],
  247. [
  248. "oauth:zai:user_info",
  249. JSON.stringify({ id: "user", username: "User", displayName: "User" }),
  250. ],
  251. ["oauth:zai:access_token", "access"],
  252. ["zcodejwttoken", "jwt"],
  253. ]);
  254. f.readLogin.mockImplementation(async () =>
  255. credentials.has("zcodejwttoken") ? { jwt: "jwt", userId: "user" } : undefined,
  256. );
  257. const oauth = createOAuthService(
  258. {
  259. load: async (key) => credentials.get(key) ?? null,
  260. save: async (key, value) => {
  261. credentials.set(key, value);
  262. },
  263. delete: async (key) => {
  264. credentials.delete(key);
  265. },
  266. },
  267. {
  268. apiClient: { request: vi.fn<typeof fetch>() },
  269. onProviderLogout: async () => {
  270. throw new Error("derived settings failed");
  271. },
  272. },
  273. );
  274. const subscription = oauth.onDidChangeSession((state) => {
  275. void f.manager.notifyAuthStateChanged(1, { state });
  276. });
  277. cleanups.push(() => subscription.dispose());
  278. await f.start();
  279. const sid = f.settings.webRemoteControlRelayV2Device!.deviceSid;
  280. const terminal = await connectTerminal(f.relay, "jwt", sid);
  281. requestBootstrap(terminal.socket);
  282. await vi.waitFor(() =>
  283. expect(terminal.messages.some((message) => message.type === "data")).toBe(true),
  284. );
  285. await expect(oauth.logout()).rejects.toThrow("derived settings failed");
  286. await vi.waitFor(() => expect(terminal.socket.readyState).toBe(WebSocket.CLOSED));
  287. expect(f.manager.getStatus(1)).toEqual({ status: "auth-required" });
  288. expect(credentials.has("zcodejwttoken")).toBe(false);
  289. expect(f.settings.webRemoteControlLastEnabledContext).toEqual({ workspacePath: "/workspace" });
  290. });
  291. it("首次注册503交给连接退避恢复,无需再次点击启动", async () => {
  292. let registrations = 0;
  293. const f = await fixture({
  294. onHttp: (call) => {
  295. if (call.path === "/api/v1/remote/device" && ++registrations === 1) return { status: 503 };
  296. },
  297. });
  298. const result = await f.start();
  299. expect(result.status).toBe("running");
  300. expect(registrations).toBe(2);
  301. expect(f.settings.webRemoteControlLastEnabledContext).toEqual({ workspacePath: "/workspace" });
  302. });
  303. it("首次注册退避期间停止会撤销后续注册和启动", async () => {
  304. const f = await fixture({
  305. onHttp: (call) => (call.path === "/api/v1/remote/device" ? { status: 503 } : undefined),
  306. });
  307. const started = f.start().catch((error: unknown) => error);
  308. await vi.waitFor(() => expect(f.relay.httpCalls).toHaveLength(1));
  309. expect(f.manager.getStatus(1).status).toBe("starting");
  310. await f.manager.stop(1);
  311. expect(await started).toBeInstanceOf(Error);
  312. await delay(1400);
  313. expect(f.relay.httpCalls).toHaveLength(1);
  314. expect(f.manager.getStatus(1).status).toBe("idle");
  315. expect(f.settings.webRemoteControlLastEnabledContext).toBeUndefined();
  316. });
  317. it("直接换账号撤销旧身份,旧账号不能访问工作区,新账号可连接且重复通知幂等", async () => {
  318. const f = await fixture();
  319. const first = await f.start();
  320. f.manager.syncAvailableWorkspaces(1, [{ workspacePath: "/workspace", kind: "local" }]);
  321. f.setLogin({ userId: "other-user", jwt: "other" });
  322. await f.manager.notifyAuthStateChanged(1, { state: "signed-in" });
  323. const next = f.manager.getStatus(1);
  324. expect(next.status).toBe("running");
  325. expect(next.sessionId).not.toBe(first.sessionId);
  326. expect(f.settings.webRemoteControlRelayV2Device?.userId).toBe("other-user");
  327. const old = await connectTerminal(f.relay, "jwt", first.sessionId!);
  328. expect(old.messages).toContainEqual(
  329. expect.objectContaining({ type: "auth_ack", pair_status: "waiting" }),
  330. );
  331. requestBootstrap(old.socket);
  332. await vi.waitFor(() =>
  333. expect(old.messages).toContainEqual(
  334. expect.objectContaining({ type: "error", code: "INTERNAL" }),
  335. ),
  336. );
  337. expect(old.messages.some((message) => message.type === "data")).toBe(false);
  338. const current = await connectTerminal(f.relay, "other", next.sessionId!);
  339. requestBootstrap(current.socket);
  340. await vi.waitFor(() =>
  341. expect(current.messages).toContainEqual(
  342. expect.objectContaining({
  343. type: "data",
  344. payload: expect.objectContaining({ zcode_type: "bootstrap-response" }),
  345. }),
  346. ),
  347. );
  348. const calls = f.relay.httpCalls.length;
  349. await f.manager.notifyAuthStateChanged(1, { state: "signed-in" });
  350. expect(f.relay.httpCalls).toHaveLength(calls);
  351. });
  352. it("换账号同时撤销所有旧窗口,只恢复已同步的上次启用目标", async () => {
  353. const f = await fixture();
  354. await f.start();
  355. const second = { workspacePath: "/second" };
  356. f.manager.syncAvailableWorkspaces(1, [{ workspacePath: "/workspace", kind: "local" }]);
  357. f.manager.syncAvailableWorkspaces(2, [{ ...second, kind: "local" }]);
  358. await f.manager.startAuthorized(2, second, f.manager.authorizeStart(2, second));
  359. f.setLogin({ userId: "other-user", jwt: "other" });
  360. await f.manager.notifyAuthStateChanged(1, { state: "signed-in" });
  361. expect(f.manager.getStatus(1).status).toBe("idle");
  362. expect(f.manager.getStatus(2)).toMatchObject({ status: "running", workspacePath: "/second" });
  363. expect(f.settings.webRemoteControlRelayV2Device?.userId).toBe("other-user");
  364. const old = await fetch(`${f.relay.httpUrl}/api/v1/remote/device`, {
  365. headers: { Authorization: "Bearer jwt" },
  366. });
  367. const { data: oldDevices } = await old.json();
  368. expect(oldDevices.every((device: { online: boolean }) => !device.online)).toBe(true);
  369. });
  370. it("登录通知发生在首次身份读取期间时,丢弃旧读取并用新身份启动", async () => {
  371. const f = await fixture();
  372. const stale = Promise.withResolvers<{ userId: string; jwt: string }>();
  373. f.readLogin.mockReturnValueOnce(stale.promise);
  374. const started = f.start();
  375. await vi.waitFor(() => expect(f.readLogin).toHaveBeenCalledOnce());
  376. f.setLogin({ userId: "other-user", jwt: "other" });
  377. await f.manager.notifyAuthStateChanged(1, { state: "signed-in" });
  378. stale.resolve({ userId: "user", jwt: "jwt" });
  379. expect((await started).status).toBe("running");
  380. expect(f.settings.webRemoteControlRelayV2Device?.userId).toBe("other-user");
  381. expect(f.relay.httpCalls.every((call) => call.userId === "other-user")).toBe(true);
  382. });
  383. it("换账号撤销已绑定旧身份的待启动操作,迟到读取不能覆盖新连接", async () => {
  384. const context = { workspacePath: "/workspace", kind: "local" as const };
  385. const f = await fixture({}, { webRemoteControlLastEnabledContext: context });
  386. f.manager.syncAvailableWorkspaces(1, [context]);
  387. const stale = Promise.withResolvers<{ userId: string; jwt: string }>();
  388. f.readLogin
  389. .mockResolvedValueOnce({ userId: "user", jwt: "jwt" })
  390. .mockReturnValueOnce(stale.promise);
  391. const started = f.start().catch((error: unknown) => error);
  392. await vi.waitFor(() => expect(f.readLogin).toHaveBeenCalledTimes(2));
  393. f.setLogin({ userId: "other-user", jwt: "other" });
  394. const notification = f.manager.notifyAuthStateChanged(1, { state: "signed-in" });
  395. await vi.waitFor(() => expect(f.readLogin).toHaveBeenCalledTimes(3));
  396. stale.resolve({ userId: "user", jwt: "jwt" });
  397. await notification;
  398. expect(await started).toBeInstanceOf(Error);
  399. expect(f.manager.getStatus(1).status).toBe("running");
  400. expect(f.settings.webRemoteControlRelayV2Device?.userId).toBe("other-user");
  401. expect(f.relay.httpCalls.every((call) => call.userId === "other-user")).toBe(true);
  402. });
  403. it("懒注册、迁移V1并持久化身份,返回无密钥V4二维码且再次启动复用SID", async () => {
  404. const f = await fixture();
  405. expect(f.relay.httpCalls).toEqual([]);
  406. const result = await f.start();
  407. expect(f.settings.webRemoteControlRelayV2Device).toEqual({
  408. deviceSid: result.sessionId,
  409. userId: "user",
  410. endpointOrigin: f.relay.httpUrl,
  411. });
  412. expect(f.settings.webRemoteControlExternalRelayDevice).toBeUndefined();
  413. expect(f.credentials.size).toBe(0);
  414. const url = new URL(result.qrUrl);
  415. expect(url.pathname).toBe("/remote/v4");
  416. expect(Object.fromEntries(url.searchParams)).toEqual({
  417. app_version: "3.13.0",
  418. sid: result.sessionId,
  419. mid: "desktop-mid",
  420. name: "Desktop name",
  421. });
  422. expect(f.manager.getStatus(1)).toMatchObject({ status: "running", mobileConnected: false });
  423. const again = await f.start();
  424. expect(again.sessionId).toBe(result.sessionId);
  425. expect(f.relay.httpCalls.filter((call) => call.path === "/api/v1/remote/device")).toHaveLength(
  426. 1,
  427. );
  428. });
  429. it("无JWT明确失败,不注册不连接", async () => {
  430. const f = await fixture();
  431. f.setLogin(undefined);
  432. await expect(f.start()).rejects.toMatchObject({ reason: "auth-required" });
  433. expect(f.relay.httpCalls).toEqual([]);
  434. expect(f.relay.messages).toEqual([]);
  435. expect(f.manager.getStatus(1)).toMatchObject({ status: "auth-required" });
  436. });
  437. it("冷启动无JWT等待,登录通知只在workspace同步后恢复且重复通知不重连", async () => {
  438. const context = { workspacePath: "/workspace", kind: "local" as const };
  439. const f = await fixture({}, { webRemoteControlLastEnabledContext: context });
  440. f.setLogin(undefined);
  441. expect(await f.manager.restorePreviouslyEnabled(1, [context])).toBe(false);
  442. expect(f.manager.getStatus(1).status).toBe("auth-required");
  443. expect(f.relay.httpCalls).toEqual([]);
  444. expect(f.relay.messages).toEqual([]);
  445. f.setLogin({ jwt: "jwt", userId: "user" });
  446. await f.manager.notifyAuthStateChanged(1, { state: "signed-in" });
  447. expect(f.manager.getStatus(1).status).toBe("running");
  448. await f.manager.notifyAuthStateChanged(1, { state: "signed-in" });
  449. expect(f.relay.httpCalls.filter((call) => call.path.endsWith("/token"))).toHaveLength(1);
  450. });
  451. it("登录先于workspace同步时等待,登出停止且保留目标,重新登录可恢复", async () => {
  452. const context = { workspacePath: "/workspace", workspaceIdentity: "ssh://host/repo" };
  453. const f = await fixture({}, { webRemoteControlLastEnabledContext: context });
  454. await f.manager.notifyAuthStateChanged(1, { state: "signed-in" });
  455. expect(f.relay.httpCalls).toEqual([]);
  456. expect(
  457. await f.manager.restorePreviouslyEnabled(1, [{ ...context, remoteSessionId: "new-session" }]),
  458. ).toBe(true);
  459. f.setLogin(undefined);
  460. await f.manager.notifyAuthStateChanged(1, { state: "signed-out" });
  461. expect(f.manager.getStatus(1)).toEqual({ status: "auth-required" });
  462. expect(f.settings.webRemoteControlLastEnabledContext).toMatchObject(context);
  463. f.setLogin({ jwt: "jwt", userId: "user" });
  464. await f.manager.notifyAuthStateChanged(1, { state: "signed-in" });
  465. expect(f.manager.getStatus(1)).toMatchObject({
  466. status: "running",
  467. remoteSessionId: "new-session",
  468. });
  469. await f.manager.stop(1);
  470. await f.manager.notifyAuthStateChanged(1, { state: "signed-in" });
  471. expect(f.manager.getStatus(1).status).toBe("idle");
  472. expect(f.settings.webRemoteControlLastEnabledContext).toBeUndefined();
  473. });
  474. it("伪登录通知不能绕过JWT门禁", async () => {
  475. const f = await fixture(
  476. {},
  477. { webRemoteControlLastEnabledContext: { workspacePath: "/workspace" } },
  478. );
  479. f.setLogin(undefined);
  480. f.manager.syncAvailableWorkspaces(1, [{ workspacePath: "/workspace", kind: "local" }]);
  481. await f.manager.notifyAuthStateChanged(1, { state: "signed-in" });
  482. expect(f.manager.getStatus(1).status).toBe("auth-required");
  483. expect(f.relay.httpCalls).toEqual([]);
  484. expect(f.relay.messages).toEqual([]);
  485. });
  486. it("401等待登录通知,workspace重复同步不能用失效JWT再次注册", async () => {
  487. const context = { workspacePath: "/workspace", kind: "local" as const };
  488. const f = await fixture(
  489. { onHttp: () => ({ status: 401 }) },
  490. { webRemoteControlLastEnabledContext: context },
  491. );
  492. await expect(f.start()).rejects.toMatchObject({ reason: "auth-required" });
  493. expect(f.manager.getStatus(1).status).toBe("auth-required");
  494. const calls = f.relay.httpCalls.length;
  495. expect(await f.manager.restorePreviouslyEnabled(1, [context])).toBe(false);
  496. expect(f.relay.httpCalls).toHaveLength(calls);
  497. });
  498. it("登出撤销等待中的启动和迟到登录通知,不创建host或连接", async () => {
  499. const f = await fixture(
  500. {},
  501. { webRemoteControlLastEnabledContext: { workspacePath: "/workspace" } },
  502. );
  503. const pendingLogin = Promise.withResolvers<{ jwt: string; userId: string }>();
  504. f.readLogin.mockReturnValueOnce(pendingLogin.promise);
  505. const pendingStart = f.start().catch((error: unknown) => error);
  506. await vi.waitFor(() => expect(f.readLogin).toHaveBeenCalledOnce());
  507. f.setLogin(undefined);
  508. await f.manager.notifyAuthStateChanged(1, { state: "signed-out" });
  509. pendingLogin.resolve({ jwt: "jwt", userId: "user" });
  510. expect(await pendingStart).toBeInstanceOf(Error);
  511. const lateLogin = Promise.withResolvers<{ jwt: string; userId: string }>();
  512. f.readLogin.mockReturnValueOnce(lateLogin.promise);
  513. const notification = f.manager.notifyAuthStateChanged(1, { state: "signed-in" });
  514. await f.manager.notifyAuthStateChanged(1, { state: "signed-out" });
  515. lateLogin.resolve({ jwt: "jwt", userId: "user" });
  516. await notification;
  517. expect(f.manager.getStatus(1).status).toBe("auth-required");
  518. expect(f.relay.httpCalls).toEqual([]);
  519. expect(f.relay.messages).toEqual([]);
  520. expect(f.attachWorkspaceHost).not.toHaveBeenCalled();
  521. expect(f.settings.webRemoteControlLastEnabledContext).toEqual({ workspacePath: "/workspace" });
  522. });
  523. it("手动停止及关闭窗口使正在读取的启动恢复失效", async () => {
  524. const context = { workspacePath: "/workspace" };
  525. const f = await fixture({}, { webRemoteControlLastEnabledContext: context });
  526. const load = Promise.withResolvers<typeof context>();
  527. f.loadEnabled.mockReturnValueOnce(load.promise);
  528. const restore = f.manager.restorePreviouslyEnabled(1, [context]);
  529. await f.manager.stop(1);
  530. load.resolve(context);
  531. expect(await restore).toBe(false);
  532. expect(f.relay.httpCalls).toEqual([]);
  533. expect(f.attachWorkspaceHost).not.toHaveBeenCalled();
  534. });
  535. it("混合工作区完整同步保留本地目标,读取存储期间关闭目标不恢复旧快照", async () => {
  536. const local = { workspacePath: "/workspace", kind: "local" as const, label: "Local" };
  537. const remote = {
  538. workspacePath: "/remote",
  539. workspaceIdentity: "ssh://host/remote",
  540. remoteSessionId: "remote-1",
  541. kind: "remote" as const,
  542. label: "Remote",
  543. };
  544. const f = await fixture({}, { webRemoteControlLastEnabledContext: local });
  545. f.setLogin(undefined);
  546. await f.manager.restorePreviouslyEnabled(1, [local, remote]);
  547. f.setLogin({ jwt: "jwt", userId: "user" });
  548. await f.manager.notifyAuthStateChanged(1, { state: "signed-in" });
  549. expect(f.manager.getStatus(1)).toMatchObject({
  550. status: "running",
  551. workspacePath: "/workspace",
  552. });
  553. await f.manager.notifyAuthStateChanged(1, { state: "signed-out" });
  554. const pending = Promise.withResolvers<typeof local>();
  555. f.loadEnabled.mockReturnValueOnce(pending.promise);
  556. const login = f.manager.notifyAuthStateChanged(1, { state: "signed-in" });
  557. await vi.waitFor(() => expect(f.loadEnabled).toHaveBeenCalledTimes(3));
  558. f.manager.syncAvailableWorkspaces(1, [remote]);
  559. pending.resolve(local);
  560. await login;
  561. expect(f.manager.getStatus(1).status).toBe("idle");
  562. });
  563. it("远程恢复等待当前remoteSessionId,不为离线占位tab启动relay", async () => {
  564. const context = { workspacePath: "/remote", workspaceIdentity: "ssh://host/remote" };
  565. const f = await fixture({}, { webRemoteControlLastEnabledContext: context });
  566. expect(await f.manager.restorePreviouslyEnabled(1, [context])).toBe(false);
  567. expect(f.relay.httpCalls).toEqual([]);
  568. expect(f.attachWorkspaceHost).not.toHaveBeenCalled();
  569. });
  570. it("换账号重注册,旧记录删除无权限仍可启动", async () => {
  571. const f = await fixture();
  572. const first = await f.start();
  573. f.setLogin({ userId: "other-user", jwt: "other" });
  574. const next = await f.start();
  575. expect(next.sessionId).not.toBe(first.sessionId);
  576. expect(f.settings.webRemoteControlRelayV2Device?.userId).toBe("other-user");
  577. expect(
  578. f.relay.httpCalls.some(
  579. (call) => call.path.endsWith("/delete") && call.userId === "other-user",
  580. ),
  581. ).toBe(true);
  582. });
  583. it("换endpoint重新注册,不向旧域发送新域JWT", async () => {
  584. const f = await fixture();
  585. const first = await f.start();
  586. const other = await createFakeRelayV2({ users: { jwt: "user" } });
  587. cleanups.push(() => other.close());
  588. f.setEndpoint(other.httpUrl);
  589. const next = await f.start();
  590. expect(next.sessionId).not.toBe(first.sessionId);
  591. expect(f.settings.webRemoteControlRelayV2Device?.endpointOrigin).toBe(other.httpUrl);
  592. expect(f.relay.httpCalls.some((call) => call.path.endsWith("/delete"))).toBe(false);
  593. });
  594. it("auth_init AUTH_FAILED关闭旧socket并重新注册一次", async () => {
  595. let failed = false;
  596. const f = await fixture({
  597. onMessage: ({ message }) => {
  598. if (!failed && (message as { type: string }).type === "auth_init") {
  599. failed = true;
  600. return { error: "AUTH_FAILED" };
  601. }
  602. },
  603. });
  604. await f.start();
  605. expect(f.relay.httpCalls.filter((call) => call.path === "/api/v1/remote/device")).toHaveLength(
  606. 2,
  607. );
  608. expect(f.manager.getStatus(1)).toMatchObject({ status: "running" });
  609. });
  610. it("token401停止并保留auth-required与上次启用意图", async () => {
  611. let deny = false;
  612. const f = await fixture({
  613. onHttp: (call) => (deny && call.path.endsWith("/token") ? { status: 401 } : undefined),
  614. });
  615. await f.start();
  616. deny = true;
  617. f.relay.disconnect({ role: "device" });
  618. await vi.waitFor(
  619. () =>
  620. expect(f.manager.getStatus(1)).toMatchObject({
  621. status: "auth-required",
  622. }),
  623. { timeout: 4000 },
  624. );
  625. expect(f.settings.webRemoteControlLastEnabledContext).toEqual({ workspacePath: "/workspace" });
  626. expect(f.settings.webRemoteControlRelayV2Device).toBeDefined();
  627. });
  628. it("KICKED有界恢复最终对外返回session-conflict", async () => {
  629. const f = await fixture();
  630. await f.start();
  631. f.relay.sendError({ role: "device" }, "KICKED");
  632. await vi.waitFor(() => expect(f.relay.messages.length).toBe(2), { timeout: 6500 });
  633. f.relay.sendError({ role: "device" }, "KICKED");
  634. await vi.waitFor(() =>
  635. expect(f.manager.getStatus(1)).toMatchObject({
  636. status: "error",
  637. failure: { reason: "session-conflict" },
  638. }),
  639. );
  640. });
  641. it("AUTH_FAILED重新注册遇到5xx后退避重试注册,不复用已失效SID", async () => {
  642. let firstSid: string | undefined;
  643. let registrations = 0;
  644. const f = await fixture({
  645. onMessage: ({ message }) => {
  646. const wire = message as { type: string; device_sid: string };
  647. if (wire.type !== "auth_init") return;
  648. firstSid ??= wire.device_sid;
  649. if (wire.device_sid === firstSid) return { error: "AUTH_FAILED" };
  650. },
  651. onHttp: (call) => {
  652. if (call.path === "/api/v1/remote/device" && ++registrations === 2) return { status: 503 };
  653. },
  654. });
  655. const result = await f.start();
  656. expect(result.sessionId).not.toBe(firstSid);
  657. expect(registrations).toBe(3);
  658. });
  659. it.each(["/device", "/token"])("%s首个启动调用超时后后台恢复仍保存启用意图", async (path) => {
  660. let failing = true;
  661. const f = await fixture({
  662. onHttp: (call) => (call.path.endsWith(path) && failing ? { status: 503 } : undefined),
  663. });
  664. vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });
  665. const first = f.start().catch((error: Error) => error);
  666. await delay(60);
  667. await vi.advanceTimersByTimeAsync(30000);
  668. expect(await first).toBeInstanceOf(Error);
  669. failing = false;
  670. await delay(40);
  671. await vi.advanceTimersByTimeAsync(30000);
  672. await delay(80);
  673. expect(f.manager.getStatus(1).status).toBe("running");
  674. expect(f.settings.webRemoteControlLastEnabledContext).toEqual({ workspacePath: "/workspace" });
  675. });
  676. it("token401终止状态不能被远程workspace关闭通知覆盖", async () => {
  677. const f = await fixture({
  678. onHttp: (call) => (call.path.endsWith("/token") ? { status: 401 } : undefined),
  679. });
  680. await expect(
  681. f.start({ workspacePath: "/workspace", remoteSessionId: "remote-1" }),
  682. ).rejects.toMatchObject({ reason: "auth-required" });
  683. f.manager.failRemoteSession("remote-1", "closed", { reason: "workspace-closed" });
  684. expect(f.manager.getStatus(1)).toMatchObject({
  685. status: "auth-required",
  686. });
  687. });
  688. });