webRemoteControlDeviceClient.test.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { describe, expect, it } from "vitest";
  2. import { createFakeRelayV2 } from "@zcode/shared/testing/fake-relay-v2";
  3. import { createWebRemoteControlDeviceClient } from "#src/web-remote-control/index.js";
  4. describe("设备列表 HTTP", () => {
  5. it("忽略响应信封、设备及 meta 的新增字段后返回设备列表", async () => {
  6. const devices = [
  7. {
  8. device_sid: "d_1",
  9. device_mid: "machine-1",
  10. created_at: 1_600_000_000,
  11. online: false,
  12. meta: {},
  13. },
  14. ];
  15. const list = createWebRemoteControlDeviceClient("https://relay.example", async () =>
  16. Response.json({
  17. code: 0,
  18. msg: "",
  19. data: devices.map((device) => ({
  20. ...device,
  21. capabilities: ["remote"],
  22. meta: { arch: "arm64" },
  23. })),
  24. logid: "request-1",
  25. server_version: "next",
  26. }),
  27. );
  28. await expect(list("jwt", new AbortController().signal)).resolves.toEqual(devices);
  29. });
  30. it("只返回当前 JWT 账号的设备;其他账号最近 SID 不能作为连接依据", async () => {
  31. const relay = await createFakeRelayV2({ users: { a: "alice", b: "bob" } });
  32. try {
  33. for (const jwt of ["a", "b"]) {
  34. await fetch(`${relay.httpUrl}/api/v1/remote/device`, {
  35. method: "POST",
  36. headers: { Authorization: `Bearer ${jwt}`, "Content-Type": "application/json" },
  37. body: JSON.stringify({ device_mid: `mid-${jwt}` }),
  38. });
  39. }
  40. const list = createWebRemoteControlDeviceClient(relay.httpUrl);
  41. const devices = await list("a", new AbortController().signal);
  42. expect(devices).toEqual([
  43. expect.objectContaining({ device_mid: "mid-a", online: false, meta: {} }),
  44. ]);
  45. expect(await list("b", new AbortController().signal)).toEqual([
  46. expect.objectContaining({ device_mid: "mid-b" }),
  47. ]);
  48. await expect(list("invalid", new AbortController().signal)).rejects.toMatchObject({
  49. reason: "auth-required",
  50. });
  51. } finally {
  52. await relay.close();
  53. }
  54. });
  55. it.each([
  56. [503, "unavailable"],
  57. [200, "not-json"],
  58. [200, JSON.stringify({ code: 1006, msg: "private server detail" })],
  59. [200, JSON.stringify({ code: 0, msg: "", data: [{ device_sid: "incomplete" }] })],
  60. ])("HTTP %s 或非法信封不当成空设备列表", async (status, body) => {
  61. const list = createWebRemoteControlDeviceClient(
  62. "https://relay.example",
  63. async () => new Response(body, { status }),
  64. );
  65. await expect(list("jwt", new AbortController().signal)).rejects.toMatchObject({
  66. reason: "relay-unavailable",
  67. message: "relay-unavailable",
  68. });
  69. });
  70. });