From fac4554ab76042532722fd87569b785757cc5660 Mon Sep 17 00:00:00 2001 From: tangzhixiong613-jpg <340458552+tangzhixiong613-jpg@users.noreply.github.com> Date: Sun, 15 Nov 2026 05:01:52 +0000 Subject: [PATCH 1/3] =?UTF-8?q?T-1244=20InstaBox=20=E6=A1=8C=E9=9D=A2?= =?UTF-8?q?=E7=BB=8F=E6=9C=8D=E5=8A=A1=E7=AB=AF=E4=B8=AD=E7=BB=A7=E8=BF=9E?= =?UTF-8?q?=E4=B8=8A=E6=B8=B8=20VNC=EF=BC=8C=E6=A1=8C=E9=9D=A2=E6=9F=A5?= =?UTF-8?q?=E7=9C=8B=E5=99=A8=E6=94=AF=E6=8C=81=20upstream?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../tasks/T-1200/T-1244-instabox-vnc/brief.md | 91 ++++++ docs/tasks/T-1200/T-1244-instabox-vnc/r2.md | 16 + .../T-1200/T-1244-instabox-vnc/report.md | 49 +++ .../T-1244-instabox-vnc/verification.txt | 254 +++++++++++++++ server/instabox/machine.ts | 24 ++ server/instabox/vnc.e2e.test.ts | 299 ++++++++++++++++++ server/instabox/vnc.test.ts | 22 ++ server/instabox/vnc.ts | 12 + server/routes/desktop-viewer.ts | 32 +- server/testing/fake-instabox-vnc.ts | 97 ++++++ shared/wire.ts | 2 +- 11 files changed, 890 insertions(+), 8 deletions(-) create mode 100644 docs/tasks/T-1200/T-1244-instabox-vnc/brief.md create mode 100644 docs/tasks/T-1200/T-1244-instabox-vnc/r2.md create mode 100644 docs/tasks/T-1200/T-1244-instabox-vnc/report.md create mode 100644 docs/tasks/T-1200/T-1244-instabox-vnc/verification.txt create mode 100644 server/instabox/machine.ts create mode 100644 server/instabox/vnc.e2e.test.ts create mode 100644 server/instabox/vnc.test.ts create mode 100644 server/instabox/vnc.ts create mode 100644 server/testing/fake-instabox-vnc.ts diff --git a/docs/tasks/T-1200/T-1244-instabox-vnc/brief.md b/docs/tasks/T-1200/T-1244-instabox-vnc/brief.md new file mode 100644 index 00000000..e86b03d9 --- /dev/null +++ b/docs/tasks/T-1200/T-1244-instabox-vnc/brief.md @@ -0,0 +1,91 @@ +## 运行环境(云沙箱,必读) +- 开工先在 worktree 根目录运行 依赖准备脚本(镜像自带,把预装依赖链进 node_modules),之后 `pnpm exec vitest` / `pnpm exec tsc` 才可用。 +- 这里**没有** systemd、Docker,说明里出现的 `systemd-run --scope ... --` 前缀一律去掉直接运行;机器 8G/4 核,一次只跑一个测试文件。 +- 若本轮沙箱已放开(能联网、能监听端口),交回前必须把改动相关的测试全部跑过,包括需要端口的 e2e;涉及的 e2e 连跑 3 次都要过。跑不了的写明原因。 +- 报告只写三样:改了什么(文件列表与 git status 一致)、为什么、测试命令与结果摘要。不要写长篇分析;完整输出放 verification 文本文件即可。 +- 不提交 git。 + +# T-1244 云电脑③:远程桌面画面中继 + +(本任务是 T-1239 的第 3 块,与 ①②④ 并行开发。下面「共同约定」必须遵守。) + +## 本任务负责的文件(只改这些) +- 新建:`server/instabox/machine.ts`(共享契约,按约定原样;已存在就不改)、`server/instabox/vnc.ts` 及测试、你自己的假服务 `server/testing/fake-instabox-vnc.ts`(可复用 `scripts/testing/fake-vnc.ts` 的 RFB 假服务思路)。 +- 修改:`server/routes/desktop-viewer.ts`(204 行)、`src/components/remote-desktop-panel.tsx`(399 行,只在确有必要时改)、`shared/wire.ts:62`(按约定原样改那一行)。 +- **不改** `server/index.ts`(由 ⑤ 接线)。 + +## 要做 +1. `desktop-viewer.ts`:现在 `DesktopConnection` 只描述本机回环端口(port/password/path),中继只连 127.0.0.1。加可选字段 `upstream?: { url: string; headers: Record }`:有它时中继改为由服务端用 WebSocket(wss,带这些头)连上游,把浏览器 WebSocket 的二进制帧原样双向转发;没有它时完全保持原行为。要求: + - 上游地址只来自服务端 provider(不得从浏览器参数取),只允许 `wss:`(测试可放开 `ws://127.0.0.1`,用显式参数或注入,不靠环境猜)。 + - 头(含钥匙)不得出现在发给浏览器的任何响应、错误、日志里。 + - 原有的权限检查(admin、同源、控制租约、upgrades 门、liveness 复查、retain/release、touch)对 upstream 连接同样生效。 + - 上游断开→关浏览器侧;浏览器断开→关上游;上游连不上→浏览器侧得到与现在一致的失败表现。 + - VNC 是 RFB 3.8、安全类型 None;浏览器 noVNC 侧现在若按密码流程走,确认无密码也能连(password: null 已支持就不用改前端)。 +2. `vnc.ts` 导出 `instaboxDesktopTarget(key: string, upstream: () => Promise<{ url: string; headers: Record }>, opts?: { live?: () => boolean; touch?: () => void }): DesktopTarget`,resolve 时返回带 upstream 的 DesktopConnection。⑤ 会把它接到 `machines.ensureRunning(botId)` + `machines.vncUpstream(id)` 上。 +3. 前端 `remote-desktop-panel.tsx`:只在 instabox 画面需要不同处理时改(例如分辨率 1280x800 的缩放)。没必要就不改,在报告里说明。 +4. 测试:假上游 WS(RFB 3.8 握手 + 发一帧)验证浏览器侧收到原样字节、双向转发、两侧断开联动、头不外泄、非 wss 被拒、原 127.0.0.1 路径的现有测试全部照过。e2e 连跑 3 次。 + +## 验收 +按「共同约定 · 测试」执行;report.md 只写实际改过的文件,写明 `instaboxDesktopTarget` 确切签名、上游的 target id 建议格式(⑤ 照着接)。 + +--- + +# T-1239 云电脑后端:共同约定(4 个并行子任务都必须遵守) + +## 目标与范围(用户已定) +- 新增云电脑后端 `instabox`,与 Boat(box)、VPS(vps)并列,供单个智能体使用自己的云电脑。范围:Linux 桌面 + Android 模板,不含苹果。 +- 共用电脑(team computer / 部门桌面)、本地 VM 私有桌面、多屏都**不改**,仍走原来的路。 +- 所有机器用同一把 钥匙:配置 `instabox.apiKey`,环境变量 `INSTABOX_API_KEY` 覆盖;钥匙只在服务端,绝不进入机器、前端、日志或智能体上下文。 +- 本仓库是**公开仓库**:代码、测试、文档里不得出现内部域名、IP、邮箱、人名、真实钥匙。公共接口域名 `api.instabox.sh`、`connect.instabox.sh` 可以出现。 + +## 接口要点(实测) +- 基址 `https://api.instabox.sh`,请求头 `X-API-Key: `。 +- 生命周期调用(POST /v1/machines、PATCH、start/stop/suspend/resume/restore、POST snapshots、DELETE)**必须**带 `Idempotency-Key`;删机器另带 `X-Confirm-Delete: `。都返回 202 + 操作单 `{id,machineId,type,state,phase,error}`,用 `GET /v1/operations/{id}?wait=25s` 长轮询到 succeeded/failed。 +- 机器 state:creating、starting、running、stopping、stopped、suspending、suspended、resuming、deleting、deleted、error。 +- 创建:`{"name","templateId":"agent-browser"|"android","spec":{"vcpus":4,"memoryGiB":8},"autoSuspendAfterSeconds":600,"metadata":{...}}`。按名字找回机器:`GET /v1/machines`(按 name 过滤)。 +- 新建、冷启动、restore、从快照新建之后桌面不运行:必须 `POST /v1/machines/{id}/desktop {"action":"start","width":1280,"height":800}`。 +- exec:`POST /v1/machines/{id}/exec {"cmd"|"argv","envs","cwd","stdin","timeoutSeconds":1..600}` → `{stdout,stderr,exitCode,timedOut,truncated,...}`;非流式输出各 1 MiB 截断。默认没有 DISPLAY,桌面在 `:1`(Boat 是 :0)。后台任务用 `nohup setsid ... >log 2>&1 `,metadata 带 `{"app":"crybot","botId":...}`。 + +## 共享文件(各任务需要时原样创建,内容必须一字不差;已存在就不要改) +`server/instabox/machine.ts`: +```ts +/** cloud computer: the contract the four backend pieces share. */ +export type InstaboxTemplate = "linux" | "android"; +export type InstaboxMachineState = "creating" | "starting" | "running" | "stopping" | "stopped" | "suspending" | "suspended" | "resuming" | "deleting" | "deleted" | "error"; + +export interface InstaboxMachine { id: string; name: string; state: InstaboxMachineState; template: InstaboxTemplate } + +export interface InstaboxExecRequest { cmd?: string; argv?: string[]; envs?: Record; cwd?: string; stdin?: string; timeoutSeconds?: number } +export interface InstaboxExecResult { stdout: string; stderr: string; exitCode: number | null; timedOut: boolean; truncated: boolean } + +/** One authenticated API call. `idempotent: true` adds an Idempotency-Key; lifecycle calls need it. */ +export type InstaboxRequest = (method: string, path: string, opts?: { body?: unknown; raw?: Uint8Array; idempotent?: boolean; headers?: Record; query?: Record }) => Promise; + +export interface InstaboxMachines { + find(botId: string): Promise; + /** Create, resume or start the bot's machine as needed, then make sure its desktop runs. */ + ensureRunning(botId: string, opts?: { template?: InstaboxTemplate }): Promise; + suspend(botId: string): Promise; + remove(botId: string): Promise; + exec(machineId: string, req: InstaboxExecRequest): Promise; + readFile(machineId: string, path: string): Promise; + writeFile(machineId: string, path: string, data: Uint8Array, opts?: { mode?: string }): Promise; + /** Where the server connects for this machine's VNC (RFB, no password); headers carry the key and never leave the server. */ + vncUpstream(machineId: string): Promise<{ url: string; headers: Record }>; +} +``` +`shared/wire.ts:62` 改成(原行上改,不增行;文件正好 1000 行,多一行会挂行数门禁): +`export type CloudBackend = "box" | "vps" | "instabox";` + +## 行数门禁 +`scripts/testing/file-size-ratchet.test.ts`:登记文件不许变长,未登记文件不许超过 1000 行。`server/index.ts` 四个任务合计只剩约 110 行余量(由任务①统一占用),`ComputerPanel.tsx` 余量 25、`config.ts` 10、`store.ts` 17、`boat.ts` 1。新逻辑一律放 `server/instabox/` 下的新文件。 + +## 测试 +- 不连真实 。写 `server/testing/fake-instabox.ts` 风格的假服务(`createServer` 起本地 HTTP/WS,`vi.stubEnv` 或依赖注入指过去);各任务若都需要假服务,各自放在自己命名的文件里(如 `fake-instabox-power.ts`),避免同名冲突。 +- 本轮沙箱已放开,可监听端口:改动相关的测试全部跑过,涉及的 e2e 连跑 3 次。另跑 `pnpm exec tsc -p tsconfig.server.json`、前端有改动时跑前端 tsc,对改动文件跑 `oxlint --deny-warnings`。 +- 文案只加 `src/locales/zh.json` 和 `en.json`(且只有任务④加;其他任务需要文案时在报告里列出键名和中英文,由④统一加,代码里先用这些键)。 diff --git a/docs/tasks/T-1200/T-1244-instabox-vnc/r2.md b/docs/tasks/T-1200/T-1244-instabox-vnc/r2.md new file mode 100644 index 00000000..a7ca883b --- /dev/null +++ b/docs/tasks/T-1200/T-1244-instabox-vnc/r2.md @@ -0,0 +1,16 @@ +## 运行环境(云沙箱,必读) +- 开工先在 worktree 根目录运行 依赖准备脚本(镜像自带,把预装依赖链进 node_modules),之后 `pnpm exec vitest` / `pnpm exec tsc` 才可用。 +- 这里**没有** systemd、Docker,说明里出现的 `systemd-run --scope ... --` 前缀一律去掉直接运行;机器 8G/4 核,一次只跑一个测试文件。 +- 若本轮沙箱已放开(能联网、能监听端口),交回前必须把改动相关的测试全部跑过,包括需要端口的 e2e;涉及的 e2e 连跑 3 次都要过。跑不了的写明原因。 +- 报告只写三样:改了什么(文件列表与 git status 一致)、为什么、测试命令与结果摘要。不要写长篇分析;完整输出放 verification 文本文件即可。 +- 不提交 git。 + +# T-1244-instabox-vnc 第 2 轮(接着做完,不是返工) + +上一轮 机器中途断开(exec 退出码 75,约 7 分钟时),你没来得及写完报告。上一轮已写的部分改动已取回到当前工作区(git status 可见未提交改动)。 + +要求: +1. 先读本任务文件夹里的 brief.md(原任务说明),它仍然有效,范围和验收标准不变。 +2. 检查当前工作区已有的未提交改动,在此基础上继续做完,不要推倒重来;有问题的地方直接修。 +3. 上一轮有命令以退出码 1 结束(含生成自签证书的 openssl 步骤附近),要确认相关测试真能通过。 +4. 按原说明跑完相关测试,全部通过后按原说明写报告。 diff --git a/docs/tasks/T-1200/T-1244-instabox-vnc/report.md b/docs/tasks/T-1200/T-1244-instabox-vnc/report.md new file mode 100644 index 00000000..aa58b400 --- /dev/null +++ b/docs/tasks/T-1200/T-1244-instabox-vnc/report.md @@ -0,0 +1,49 @@ +改了什么(与 `git status --short` 一致;云沙箱第一次运行中断后重跑,两次结果合并取回,均未提交): + +- `server/routes/desktop-viewer.ts`:`DesktopConnection` 新增可选 `upstream`(服务端连上游 wss 并原样双向转发),`createDesktopViewer` 新增仅供测试的 `allowInsecureLoopbackUpstream` 参数;无 upstream 时行为不变。 +- `shared/wire.ts`:第 62 行原地改为 `"box" | "vps" | "instabox"`。 +- `server/instabox/machine.ts`:共享契约,与约定逐字一致。 +- `server/instabox/vnc.ts`、`server/instabox/vnc.test.ts`:`instaboxDesktopTarget` 及单测。 +- `server/instabox/vnc.e2e.test.ts`:中继 e2e,含临时自签证书的可信 WSS 转发、不可信证书拒绝、真实 noVNC 浏览器连接。 +- `server/testing/fake-instabox-vnc.ts`:假上游,支持 WS 与注入证书的 TLS。 +- `docs/tasks/T-1200/T-1244-instabox-vnc/report.md`、`verification.txt`:本报告与验证记录。 + +为什么: + +第一次运行的改动以未提交形式取回;保留现有中继、适配器和共享契约,只补齐 TLS 验证。OpenSSL 在每轮 e2e 中生成证书并成功退出;测试只临时信任该证书,不关闭 TLS 校验。初次浏览器测试失败源于默认 macOS Chrome 路径,使用 `CRYBOT_CDP_CHROME=/usr/bin/chromium` 后通过。 + +供⑤接线的现有确切签名: + +```ts +instaboxDesktopTarget(key: string, upstream: () => Promise<{ url: string; headers: Record }>, opts?: { live?: () => boolean; touch?: () => void }): DesktopTarget +``` + +建议浏览器 target id 沿用 `vps/`(当前前后端均接受的云电脑路由),服务端 `key` 使用 `instabox//`,便于换机后旧连接失效。⑤按该 target id 选择 provider,并接入 `machines.ensureRunning(botId)`、`machines.vncUpstream(id)`;`instabox/` 目前不是可直接使用的浏览器 target id。 + +前端无需修改:真实 Chromium/noVNC 已验证 `password: null`、RFB 3.8 None、1280×800 画面缩放至 640×400、像素显示及键盘回传。共享 `machine.ts` 与 brief 逐字一致,`CloudBackend` 第 62 行符合约定。 + +测试命令与结果摘要: + +已先运行 依赖准备脚本,退出 0。下列文件逐个执行,未并行跑测试文件: + +```sh +CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run <下表文件> --maxWorkers=1 +``` + +| 文件 | 结果 | +| --- | --- | +| `server/instabox/vnc.e2e.test.ts` | 每轮 32 项,连续 3 轮通过 | +| `server/routes/desktop-viewer.test.ts` | 每轮 38 项,连续 3 轮通过,覆盖原 127.0.0.1 路径 | +| `server/request-auth.e2e.test.ts` | 每轮 2 项,连续 3 轮通过 | +| `server/instabox/vnc.test.ts` | 2 项通过 | +| `server/desktop-viewer-targets.test.ts` | 6 项通过 | +| `src/lib/desktop-connection.test.ts` | 7 项通过 | +| `scripts/testing/file-size-ratchet.test.ts` | 1 项通过 | + +```sh +pnpm exec tsc -p tsconfig.server.json +pnpm exec oxlint --deny-warnings server/instabox/machine.ts server/instabox/vnc.ts server/instabox/vnc.test.ts server/instabox/vnc.e2e.test.ts server/testing/fake-instabox-vnc.ts server/routes/desktop-viewer.ts shared/wire.ts +git diff --check +``` + +以上均退出 0。最终测试执行合计 232 项通过。`docs/verification/README.md` 在本工作区缺失;验证使用隔离 fixture、临时会话/浏览器目录及本地假服务,鉴权 e2e 启动隔离完整应用,未触碰真实 或用户应用数据。无未运行的上述检查;未提交 git。 diff --git a/docs/tasks/T-1200/T-1244-instabox-vnc/verification.txt b/docs/tasks/T-1200/T-1244-instabox-vnc/verification.txt new file mode 100644 index 00000000..cd8f54d7 --- /dev/null +++ b/docs/tasks/T-1200/T-1244-instabox-vnc/verification.txt @@ -0,0 +1,254 @@ +T-1244 round 2 verification + +Changes from the interrupted first run were recovered uncommitted; this run continued on top of them. +crybot-link-deps: exit 0, linked 73 entries. +docs/verification/README.md: absent. All tests use isolated fixtures, temporary sessions/profiles and loopback fake services; no real InstaBox or live app. +Initial diagnostic: browser helper defaults to a macOS executable. +Command: pnpm exec vitest run server/instabox/vnc.e2e.test.ts --maxWorkers=1 +Exit: 1 + + RUN v4.1.11 /data/home/codex-t-1244-instabox-vnc-2595705b39c6 + + ❯ server/instabox/vnc.e2e.test.ts (30 tests | 1 failed) 11084ms + × renders the 1280×800 None-authenticated desktop with the unchanged browser client 10080ms + +⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯ + + FAIL server/instabox/vnc.e2e.test.ts > renders the 1280×800 None-authenticated desktop with the unchanged browser client +Error: Chrome did not start + ❯ openHeadlessChrome scripts/testing/headless-chrome.ts:29:37 + 27| try { port = readFileSync(join(profile, "DevToolsActivePort"), "ut… + 28| } + 29| if (!port) { chrome.kill(); throw new Error("Chrome did not start");… + | ^ + 30| const targets = await (await fetch(`http://127.0.0.1:${port}/json/li… + 31| const socket = new WebSocket(targets.find((target) => target.type ==… + ❯ server/instabox/vnc.e2e.test.ts:265:16 + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯ + +⎯⎯⎯⎯⎯⎯ Unhandled Errors ⎯⎯⎯⎯⎯⎯ + +Vitest caught 1 unhandled error during the test run. +This might cause false positive tests. Resolve unhandled errors to make sure your tests are not affected. + +⎯⎯⎯⎯⎯ Uncaught Exception ⎯⎯⎯⎯⎯ +Error: spawn /Applications/Google Chrome.app/Contents/MacOS/Google Chrome ENOENT + ❯ Process.ChildProcess._handle.onexit node:internal/child_process:316:19 + ❯ onErrorNT node:internal/child_process:554:16 + ❯ processTicksAndRejections node:internal/process/task_queues:90:21 + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ +Serialized Error: { errno: -2, code: 'ENOENT', syscall: 'spawn /Applications/Google Chrome.app/Contents/MacOS/Google Chrome', path: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', spawnargs: [ '--headless=new', '--disable-gpu', '--hide-scrollbars', '--no-first-run', '--no-default-browser-check', '--use-mock-keychain', '--user-data-dir=/data/tmp/cry-instabox-vnc-p9OBhN/chrome', '--remote-debugging-port=0', 'about:blank' ] } +This error originated in "server/instabox/vnc.e2e.test.ts" test file. It doesn't mean the error was thrown inside the file itself, but while it was running. +The latest test that might've caused the error is "renders the 1280×800 None-authenticated desktop with the unchanged browser client". It might mean one of the following: +- The error was thrown, while Vitest was running this test. +- If the error occurred after the test had been completed, this was the last documented test before it was thrown. +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ + + + Test Files 1 failed (1) + Tests 1 failed | 29 passed (30) + Errors 1 error + Start at 04:38:11 + Duration 12.52s (transform 981ms, setup 808ms, import 498ms, tests 11.08s, environment 0ms) + + +Linux browser selection: CRYBOT_CDP_CHROME=/usr/bin/chromium. No TLS validation disabled. +TLS fixture setup executes openssl req -x509 -newkey rsa:2048 -noenc -days 1 -subj /CN=localhost -addext subjectAltName=IP:127.0.0.1 -keyout /key.pem -out /cert.pem. +Each VNC suite run creates a fresh certificate, trusts it only in selected tests, rejects it when untrusted, and removes temporary files. Successful beforeAll confirms openssl exit 0. + +=== server/instabox/vnc.e2e.test.ts (1/3) === +$ CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run server/instabox/vnc.e2e.test.ts --maxWorkers=1 + + RUN v4.1.11 /data/home/codex-t-1244-instabox-vnc-2595705b39c6 + + + Test Files 1 passed (1) + Tests 32 passed (32) + Start at 04:41:41 + Duration 3.22s (transform 1.00s, setup 719ms, import 566ms, tests 1.82s, environment 0ms) + +Exit: 0 + +=== server/instabox/vnc.e2e.test.ts (2/3) === +$ CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run server/instabox/vnc.e2e.test.ts --maxWorkers=1 + + RUN v4.1.11 /data/home/codex-t-1244-instabox-vnc-2595705b39c6 + + + Test Files 1 passed (1) + Tests 32 passed (32) + Start at 04:41:44 + Duration 3.14s (transform 914ms, setup 663ms, import 510ms, tests 1.85s, environment 0ms) + +Exit: 0 + +=== server/instabox/vnc.e2e.test.ts (3/3) === +$ CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run server/instabox/vnc.e2e.test.ts --maxWorkers=1 + + RUN v4.1.11 /data/home/codex-t-1244-instabox-vnc-2595705b39c6 + + + Test Files 1 passed (1) + Tests 32 passed (32) + Start at 04:41:48 + Duration 3.04s (transform 892ms, setup 639ms, import 501ms, tests 1.80s, environment 0ms) + +Exit: 0 + +=== server/routes/desktop-viewer.test.ts (1/3) === +$ CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run server/routes/desktop-viewer.test.ts --maxWorkers=1 + + RUN v4.1.11 /data/home/codex-t-1244-instabox-vnc-2595705b39c6 + + + Test Files 1 passed (1) + Tests 38 passed (38) + Start at 04:41:51 + Duration 31.84s (transform 1.02s, setup 620ms, import 674ms, tests 30.44s, environment 0ms) + +Exit: 0 + +=== server/routes/desktop-viewer.test.ts (2/3) === +$ CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run server/routes/desktop-viewer.test.ts --maxWorkers=1 + + RUN v4.1.11 /data/home/codex-t-1244-instabox-vnc-2595705b39c6 + + + Test Files 1 passed (1) + Tests 38 passed (38) + Start at 04:42:24 + Duration 31.99s (transform 1.12s, setup 741ms, import 680ms, tests 30.44s, environment 0ms) + +Exit: 0 + +=== server/routes/desktop-viewer.test.ts (3/3) === +$ CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run server/routes/desktop-viewer.test.ts --maxWorkers=1 + + RUN v4.1.11 /data/home/codex-t-1244-instabox-vnc-2595705b39c6 + + + Test Files 1 passed (1) + Tests 38 passed (38) + Start at 04:42:56 + Duration 31.96s (transform 1.09s, setup 706ms, import 689ms, tests 30.44s, environment 0ms) + +Exit: 0 + +=== server/request-auth.e2e.test.ts (1/3) === +$ CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run server/request-auth.e2e.test.ts --maxWorkers=1 + + RUN v4.1.11 /data/home/codex-t-1244-instabox-vnc-2595705b39c6 + + + Test Files 1 passed (1) + Tests 2 passed (2) + Start at 04:43:29 + Duration 6.86s (transform 1.03s, setup 697ms, import 732ms, tests 5.32s, environment 0ms) + +Exit: 0 + +=== server/request-auth.e2e.test.ts (2/3) === +$ CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run server/request-auth.e2e.test.ts --maxWorkers=1 + + RUN v4.1.11 /data/home/codex-t-1244-instabox-vnc-2595705b39c6 + + + Test Files 1 passed (1) + Tests 2 passed (2) + Start at 04:43:36 + Duration 4.81s (transform 871ms, setup 638ms, import 551ms, tests 3.52s, environment 0ms) + +Exit: 0 + +=== server/request-auth.e2e.test.ts (3/3) === +$ CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run server/request-auth.e2e.test.ts --maxWorkers=1 + + RUN v4.1.11 /data/home/codex-t-1244-instabox-vnc-2595705b39c6 + + + Test Files 1 passed (1) + Tests 2 passed (2) + Start at 04:43:41 + Duration 4.80s (transform 872ms, setup 626ms, import 552ms, tests 3.51s, environment 0ms) + +Exit: 0 + +=== server/instabox/vnc.test.ts (1/1) === +$ CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run server/instabox/vnc.test.ts --maxWorkers=1 + + RUN v4.1.11 /data/home/codex-t-1244-instabox-vnc-2595705b39c6 + + + Test Files 1 passed (1) + Tests 2 passed (2) + Start at 04:43:46 + Duration 726ms (transform 468ms, setup 610ms, import 8ms, tests 4ms, environment 0ms) + +Exit: 0 + +=== server/desktop-viewer-targets.test.ts (1/1) === +$ CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run server/desktop-viewer-targets.test.ts --maxWorkers=1 + + RUN v4.1.11 /data/home/codex-t-1244-instabox-vnc-2595705b39c6 + + + Test Files 1 passed (1) + Tests 6 passed (6) + Start at 04:43:48 + Duration 1.43s (transform 1.03s, setup 700ms, import 618ms, tests 6ms, environment 0ms) + +Exit: 0 + +=== src/lib/desktop-connection.test.ts (1/1) === +$ CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run src/lib/desktop-connection.test.ts --maxWorkers=1 + + RUN v4.1.11 /data/home/codex-t-1244-instabox-vnc-2595705b39c6 + + + Test Files 1 passed (1) + Tests 7 passed (7) + Start at 04:43:50 + Duration 1.11s (transform 488ms, setup 608ms, import 18ms, tests 10ms, environment 368ms) + +Exit: 0 + +=== scripts/testing/file-size-ratchet.test.ts (1/1) === +$ CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run scripts/testing/file-size-ratchet.test.ts --maxWorkers=1 + + RUN v4.1.11 /data/home/codex-t-1244-instabox-vnc-2595705b39c6 + + + Test Files 1 passed (1) + Tests 1 passed (1) + Start at 04:43:51 + Duration 1.14s (transform 484ms, setup 624ms, import 18ms, tests 393ms, environment 0ms) + +Exit: 0 + +=== server typecheck === +$ pnpm exec tsc -p tsconfig.server.json +Exit: 0 + +=== task source lint === +$ pnpm exec oxlint --deny-warnings server/instabox/machine.ts server/instabox/vnc.ts server/instabox/vnc.test.ts server/instabox/vnc.e2e.test.ts server/testing/fake-instabox-vnc.ts server/routes/desktop-viewer.ts shared/wire.ts +Exit: 0 + +=== whitespace === +$ git diff --check +Exit: 0 + +=== Shared contracts === +machine.ts matches brief byte-for-byte; CloudBackend line 62 matches brief. +Exit: 0 + +$ git diff --check +Exit: 0 + +$ git status --short + M server/instabox/vnc.e2e.test.ts + M server/testing/fake-instabox-vnc.ts +?? docs/tasks/T-1200/T-1244-instabox-vnc/report.md +?? docs/tasks/T-1200/T-1244-instabox-vnc/verification.txt +Exit: 0 diff --git a/server/instabox/machine.ts b/server/instabox/machine.ts new file mode 100644 index 00000000..215b0b00 --- /dev/null +++ b/server/instabox/machine.ts @@ -0,0 +1,24 @@ +/** InstaBox cloud computer: the contract the four backend pieces share. */ +export type InstaboxTemplate = "linux" | "android"; +export type InstaboxMachineState = "creating" | "starting" | "running" | "stopping" | "stopped" | "suspending" | "suspended" | "resuming" | "deleting" | "deleted" | "error"; + +export interface InstaboxMachine { id: string; name: string; state: InstaboxMachineState; template: InstaboxTemplate } + +export interface InstaboxExecRequest { cmd?: string; argv?: string[]; envs?: Record; cwd?: string; stdin?: string; timeoutSeconds?: number } +export interface InstaboxExecResult { stdout: string; stderr: string; exitCode: number | null; timedOut: boolean; truncated: boolean } + +/** One authenticated InstaBox API call. `idempotent: true` adds an Idempotency-Key; lifecycle calls need it. */ +export type InstaboxRequest = (method: string, path: string, opts?: { body?: unknown; raw?: Uint8Array; idempotent?: boolean; headers?: Record; query?: Record }) => Promise; + +export interface InstaboxMachines { + find(botId: string): Promise; + /** Create, resume or start the bot's machine as needed, then make sure its desktop runs. */ + ensureRunning(botId: string, opts?: { template?: InstaboxTemplate }): Promise; + suspend(botId: string): Promise; + remove(botId: string): Promise; + exec(machineId: string, req: InstaboxExecRequest): Promise; + readFile(machineId: string, path: string): Promise; + writeFile(machineId: string, path: string, data: Uint8Array, opts?: { mode?: string }): Promise; + /** Where the server connects for this machine's VNC (RFB, no password); headers carry the key and never leave the server. */ + vncUpstream(machineId: string): Promise<{ url: string; headers: Record }>; +} diff --git a/server/instabox/vnc.e2e.test.ts b/server/instabox/vnc.e2e.test.ts new file mode 100644 index 00000000..bcb8fea4 --- /dev/null +++ b/server/instabox/vnc.e2e.test.ts @@ -0,0 +1,299 @@ +import { once } from "node:events"; +import { execFileSync } from "node:child_process"; +import { createServer, request, type IncomingHttpHeaders } from "node:http"; +import { globalAgent } from "node:https"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { build } from "esbuild"; +import { WebSocket } from "ws"; +import { afterAll, afterEach, beforeAll, expect, it, vi } from "vitest"; +import { openHeadlessChrome } from "../../scripts/testing/headless-chrome.ts"; +import { SessionRegistry } from "../sessions.ts"; +import { resolveRequestAuth } from "../request-auth.ts"; +import { json, readBody } from "../harness/http.ts"; +import { createDesktopViewer } from "../routes/desktop-viewer.ts"; +import { createUpgrades } from "../routes/upgrades.ts"; +import { PASS } from "../routes/table.ts"; +import { fakeInstaboxVnc } from "../testing/fake-instabox-vnc.ts"; +import { instaboxDesktopTarget } from "./vnc.ts"; + +const secret = "synthetic-upstream-secret"; +const base = "/api/desktop-viewer/vps/fixture-bot"; +const leaseId = "fixture-control-lease"; +const leased = `${base}/websockify?botId=fixture-bot&controlLeaseId=${leaseId}`; +const cleanups: Array<() => Promise> = []; +const tlsDir = mkdtempSync(join(tmpdir(), "cry-instabox-vnc-tls-")); +let tls: { key: string; cert: string }; +beforeAll(() => { + execFileSync("openssl", ["req", "-x509", "-newkey", "rsa:2048", "-noenc", "-days", "1", + "-subj", "/CN=localhost", "-addext", "subjectAltName=IP:127.0.0.1", + "-keyout", join(tlsDir, "key.pem"), "-out", join(tlsDir, "cert.pem")], { stdio: "pipe", timeout: 10_000 }); + tls = { key: readFileSync(join(tlsDir, "key.pem"), "utf8"), cert: readFileSync(join(tlsDir, "cert.pem"), "utf8") }; +}); +afterAll(() => rmSync(tlsDir, { recursive: true, force: true })); +afterEach(async () => { + for (const close of cleanups.reverse()) await close(); + cleanups.length = 0; + vi.useRealTimers(); + vi.restoreAllMocks(); +}); + +function trustFixtureCertificate() { + const previous = globalAgent.options.ca; + globalAgent.options.ca = tls.cert; + cleanups.push(async () => { globalAgent.options.ca = previous; }); +} + +async function fixture(opts: Parameters[0] & { allowInsecure?: boolean } = {}) { + const desktop = await fakeInstaboxVnc(opts); + const dir = mkdtempSync(join(tmpdir(), "cry-instabox-vnc-")); + const sessions = new SessionRegistry({ file: join(dir, "sessions.json") }); + const admin = sessions.issue({ label: "Fixture admin", scopes: ["admin", "client"] }); + const member = sessions.issue({ label: "Fixture member", scopes: ["client"] }); + const state = { live: true, holding: true, present: true, key: "instabox/fixture-bot/fixture-machine", retained: 0, script: "" }; + const provider = vi.fn(async () => ({ url: desktop.url, headers: { "X-API-Key": secret } })); + const touch = vi.fn(); + const target = instaboxDesktopTarget(state.key, provider, { live: () => state.live, touch }); + const resolve = vi.fn(async () => ({ ...await target.resolve(), retain: () => { + state.retained++; return () => { state.retained--; }; + } })); + const upgrades = createUpgrades(); + const viewer = createDesktopViewer({ + target: id => id === "vps/fixture-bot" && state.present ? { key: state.key, resolve } : undefined, + live: auth => auth.kind === "session" && sessions.isLive(auth.session.id), + lease: (id, botId, lease) => id === "vps/fixture-bot" && botId === "fixture-bot" && lease === leaseId && state.holding + ? () => state.holding : undefined, + upgrades, allowInsecureLoopbackUpstream: opts.allowInsecure ?? true, + }); + sessions.onSessionRevoked(id => viewer.closeForOwner(id)); + const handle = async (req: Parameters[0], res: Parameters[0]) => { + const url = new URL(req.url!, "http://fixture"); + if (url.pathname === "/") return res.end('
'); + if (url.pathname === "/client.js") { res.setHeader("content-type", "text/javascript"); return res.end(state.script); } + const gate = resolveRequestAuth(req, { sessions, cookieName: "fixture_session", url, streamPath: "/api/events", loopbackTrust: "service" }); + if (!gate.auth) return json(res, gate.status, { error: gate.error }); + if (url.pathname === "/api/bots/fixture-bot/computer/join") return json(res, 200, {}); + const answer = await viewer.route({ req, res, url, path: url.pathname, method: req.method!, auth: gate.auth, json, readBody }); + if (answer === PASS) json(res, 404, { error: "not found" }); + }; + const app = createServer((req, res) => { void handle(req, res); }); + viewer.attach(app, handle); + await new Promise(resolve => app.listen(0, "127.0.0.1", resolve)); + const port = (app.address() as { port: number }).port; + const origin = `http://127.0.0.1:${port}`; + const headers = { origin, cookie: `fixture_session=${admin.token}` }; + const browsers = new Set(); + cleanups.push(async () => { + viewer.closeAll(); upgrades.close(); + for (const socket of browsers) socket.terminate(); + await desktop.close(); + await new Promise(resolve => { app.close(() => resolve()); app.closeAllConnections(); }); + rmSync(dir, { recursive: true, force: true }); + }); + function open(path = `${base}/websockify`, extra: Record = {}) { + const socket = new WebSocket(`ws://127.0.0.1:${port}${path}`, { headers: { ...headers, ...extra } }); + browsers.add(socket); + socket.on("error", () => {}); + const messages: Buffer[] = []; + const binary: boolean[] = []; + let responseHeaders: IncomingHttpHeaders = {}; + socket.on("message", (bytes, isBinary) => { messages.push(Buffer.from(bytes as Buffer)); binary.push(isBinary); }); + socket.on("upgrade", res => { responseHeaders = res.headers; }); + return { socket, messages, binary, headers: () => responseHeaders }; + } + async function http(path = base, extra: Record = {}, upgrade = false) { + return new Promise<{ status: number; headers: IncomingHttpHeaders; body: string }>((resolve, reject) => { + const req = request(`${origin}${path}`, { headers: { ...headers, ...extra, ...(upgrade ? { + Upgrade: "websocket", Connection: "Upgrade", "Sec-WebSocket-Key": "dGhlIHNhbXBsZSBub25jZQ==", "Sec-WebSocket-Version": "13", + } : {}) } }, res => { + let body = ""; + res.on("data", bytes => { body += bytes; }); + res.on("end", () => resolve({ status: res.statusCode!, headers: res.headers, body })); + }); + req.once("error", reject); req.end(); + }); + } + return { desktop, dir, state, provider, resolve, touch, viewer, upgrades, sessions, admin, member, origin, open, http }; +} + +it.each(["ws", "wss"])("relays %s RFB 3.8 None authentication, frames and input byte-for-byte without leaking headers", async protocol => { + if (protocol === "wss") trustFixtureCertificate(); + const f = await fixture(protocol === "wss" ? { tls, allowInsecure: false } : {}); + const status = await f.http(); + expect(status.status).toBe(200); + expect(JSON.parse(status.body)).toEqual({ password: null }); + expect(status.headers["cache-control"]).toBe("private, no-store"); + const client = f.open(`${base}/websockify?url=wss://untrusted.invalid&headers=ignored`, { authorization: `Bearer ${f.admin.token}` }); + await once(client.socket, "open"); + await expect.poll(() => client.messages.length).toBe(1); + expect(client.messages[0]).toEqual(Buffer.from("RFB 003.008\n")); + client.socket.send(client.messages[0]); + await expect.poll(() => client.messages.length).toBe(2); + expect(client.messages[1]).toEqual(Buffer.from([1, 1])); + client.socket.send(Buffer.from([1])); + await expect.poll(() => client.messages.length).toBe(3); + expect(client.messages[2]).toEqual(Buffer.alloc(4)); + client.socket.send(Buffer.from([1])); + await expect.poll(() => client.messages.length).toBe(4); + expect(client.messages[3].readUInt16BE(0)).toBe(1280); + expect(client.messages[3].readUInt16BE(2)).toBe(800); + const update = Buffer.from([3, 0, 0, 0, 0, 0, 5, 0, 3, 32]); + client.socket.send(update.subarray(0, 3), { fin: false }); + client.socket.send(update.subarray(3), { fin: true }); + await expect.poll(() => client.messages.length).toBe(5); + expect(client.messages[4]).toEqual(f.desktop.frame); + expect(client.messages).toEqual(f.desktop.sent); + expect(client.binary).toEqual([true, true, true, true, true]); + expect(f.desktop.received).toEqual([Buffer.from("RFB 003.008\n"), Buffer.from([1]), Buffer.from([1]), update]); + expect(f.desktop.requests[0].url).toBe("/v1/machines/fixture-machine/vnc"); + expect(f.desktop.requests[0].headers["x-api-key"]).toBe(secret); + expect(f.desktop.requests[0].headers.cookie).toBeUndefined(); + expect(f.desktop.requests[0].headers.authorization).toBeUndefined(); + expect(JSON.stringify([status, client.headers(), client.messages])).not.toContain(secret); + expect(f.touch).toHaveBeenCalledTimes(1); +}); + +it.each(["browser", "upstream"])("closes the other side when %s disconnects and releases only its own retain", async side => { + const f = await fixture(); + const first = f.open(); const second = f.open(); + await Promise.all([once(first.socket, "open"), once(second.socket, "open")]); + expect(f.state.retained).toBe(2); + if (side === "browser") first.socket.close(); + else [...f.desktop.sockets.clients][0].terminate(); + await expect.poll(() => first.socket.readyState).toBe(WebSocket.CLOSED); + await expect.poll(() => f.desktop.sockets.clients.size).toBe(1); + await expect.poll(() => f.state.retained).toBe(1); + expect(second.socket.readyState).toBe(WebSocket.OPEN); +}); + +it.each(["member", "origin", "lease"])("checks %s before resolving upstream for HTTP and upgrades", async denied => { + const f = await fixture(); + const extra: Record = denied === "member" ? { cookie: `fixture_session=${f.member.token}` } + : denied === "origin" ? { origin: "https://untrusted.invalid" } : {}; + f.state.holding = false; + for (const upgrade of [false, true]) { + const answer = await f.http(denied === "lease" ? leased : upgrade ? `${base}/websockify` : base, extra, upgrade); + expect(answer.status).toBe(denied === "lease" ? 409 : 403); + } + expect(f.provider).not.toHaveBeenCalled(); + expect(f.desktop.requests).toEqual([]); +}); + +it.each(["live", "holding", "present", "key"] as const)("rechecks %s and touches only a live viewer", async field => { + const f = await fixture(); + vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] }); + const client = f.open(leased); + await once(client.socket, "open"); + await vi.advanceTimersByTimeAsync(5000); + expect(f.touch).toHaveBeenCalledTimes(2); + if (field === "key") f.state.key = "instabox/replacement"; + else f.state[field] = false; + await vi.advanceTimersByTimeAsync(5000); + await expect.poll(() => client.socket.readyState).toBe(WebSocket.CLOSED); + expect(f.touch).toHaveBeenCalledTimes(2); + expect(f.state.retained).toBe(0); +}); + +it.each(["revoke", "shutdown", "gate"])("closes established viewers on %s", async action => { + const f = await fixture(); + const client = f.open(); + await once(client.socket, "open"); + if (action === "revoke") f.sessions.revoke(f.admin.session.id); + else if (action === "gate") f.upgrades.close(); + else f.viewer.closeAll(); + await expect.poll(() => client.socket.readyState).toBe(WebSocket.CLOSED); + await expect.poll(() => f.state.retained).toBe(0); + await expect.poll(() => f.desktop.sockets.clients.size).toBe(0); + if (action === "gate") await expect(f.http(`${base}/websockify`, {}, true)).rejects.toThrow(); +}); + +it.each(["resolve", "handshake"])("rechecks liveness after an asynchronous %s", async phase => { + let unblock!: () => void; + const pending = new Promise(resolve => { unblock = resolve; }); + const f = await fixture(phase === "handshake" ? { beforeUpgrade: () => pending } : {}); + if (phase === "resolve") f.provider.mockImplementation(async () => { await pending; return { url: f.desktop.url, headers: { "X-API-Key": secret } }; }); + const answer = f.http(`${base}/websockify`, {}, true); + await expect.poll(() => phase === "resolve" ? f.provider.mock.calls.length : f.desktop.requests.length).toBe(1); + f.state.live = false; + unblock(); + expect((await answer).status).toBe(phase === "resolve" ? 401 : 502); + await expect.poll(() => f.state.retained).toBe(0); +}); + +it("does not connect after a browser leaves during provider resolution", async () => { + let unblock!: () => void; + const pending = new Promise(resolve => { unblock = resolve; }); + const f = await fixture(); + f.provider.mockImplementation(async () => { await pending; return { url: f.desktop.url, headers: { "X-API-Key": secret } }; }); + const client = f.open(); + await expect.poll(() => f.provider.mock.calls.length).toBe(1); + client.socket.terminate(); + await expect.poll(() => client.socket.readyState).toBe(WebSocket.CLOSED); + await expect.poll(() => f.viewer.closeForOwner(f.admin.session.id)).toBe(0); + unblock(); + await f.resolve.mock.results[0].value; + expect(f.desktop.requests).toEqual([]); + expect(f.state.retained).toBe(0); +}); + +it.each(["ws-default", "remote-ws", "http", "https", "invalid", "userinfo", "fragment"])("rejects %s without exposing credentials", async kind => { + const f = await fixture({ allowInsecure: kind !== "ws-default" }); + const url = kind === "ws-default" ? f.desktop.url : ({ + "remote-ws": "ws://example.invalid/vnc", http: "http://127.0.0.1/vnc", https: "https://api.instabox.sh/vnc", + invalid: "invalid", userinfo: `wss://user:${secret}@example.invalid/vnc`, fragment: `wss://example.invalid/vnc#${secret}`, + }[kind]!); + f.provider.mockResolvedValue({ url, headers: { "X-API-Key": secret } }); + for (const upgrade of [false, true]) { + const answer = await f.http(upgrade ? `${base}/websockify` : base, {}, upgrade); + expect(answer.status).toBe(502); + expect(answer.body).toBe(JSON.stringify({ error: "Could not connect to the desktop viewer" })); + expect(JSON.stringify(answer)).not.toContain(secret); + } + expect(f.desktop.requests).toEqual([]); +}); + +it.each(["refused", "invalid-header", "provider", "rejected", "forged", "tls", "untrusted-cert"])("sanitizes %s failures and releases retains", async failure => { + const logs = ["log", "warn", "error", "info", "debug"] as const; + const spies = logs.map(method => vi.spyOn(console, method).mockImplementation(() => {})); + const response = failure === "rejected" ? `HTTP/1.1 401 Unauthorized\r\nX-API-Key: ${secret}\r\nContent-Length: ${secret.length}\r\n\r\n${secret}` + : failure === "forged" ? `HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${secret}\r\n\r\n` : undefined; + const f = await fixture({ response, ...(failure === "untrusted-cert" ? { tls, allowInsecure: false } : {}) }); + if (failure === "refused") { await f.desktop.close(); f.desktop.close = async () => {}; } + if (failure === "invalid-header") f.provider.mockResolvedValue({ url: f.desktop.url, headers: { "X-API-Key": `${secret}\ninvalid` } }); + if (failure === "provider") f.provider.mockRejectedValue(new Error(secret)); + if (failure === "tls") f.provider.mockResolvedValue({ url: f.desktop.url.replace("ws:", "wss:"), headers: { "X-API-Key": secret } }); + const answer = await f.http(`${base}/websockify`, {}, true); + expect(answer.status).toBe(502); + expect(JSON.stringify(answer)).not.toContain(secret); + expect(JSON.stringify(spies.map(spy => spy.mock.calls))).not.toContain(secret); + await expect.poll(() => f.state.retained).toBe(0); + if (failure === "untrusted-cert") expect(f.desktop.requests).toEqual([]); +}); + +it("renders the 1280×800 None-authenticated desktop with the unchanged browser client", async () => { + trustFixtureCertificate(); + const f = await fixture({ tls, allowInsecure: false }); + const bundle = await build({ stdin: { contents: ` + import { connectDesktop } from './src/lib/desktop-connection.ts'; + connectDesktop(document.getElementById('screen'), 'vps/fixture-bot', { + signal: new AbortController().signal, + events: { connected() { window.connected = true; }, disconnected() { window.disconnected = true; } } + }).then(client => window.client = client).catch(error => window.failure = error.message); + `, resolveDir: process.cwd() }, bundle: true, write: false, format: "esm", platform: "browser" }); + f.state.script = bundle.outputFiles[0].text; + const page = await openHeadlessChrome(join(f.dir, "chrome")); + try { + await page.send("Network.setCookie", { name: "fixture_session", value: f.admin.token, url: f.origin }); + await page.send("Page.navigate", { url: f.origin }); + await page.until("window.connected === true", 15_000); + await page.until("document.querySelector('canvas')?.getContext('2d').getImageData(0,0,1,1).data[0] === 255", 15_000); + expect(await page.evaluate("[document.querySelector('canvas').width, document.querySelector('canvas').height]")).toEqual([1280, 800]); + expect(await page.evaluate("[document.querySelector('canvas').getBoundingClientRect().width, document.querySelector('canvas').getBoundingClientRect().height]")).toEqual([640, 400]); + await page.evaluate("window.client.sendKey(65, null)"); + await expect.poll(() => f.desktop.keys).toContain(65); + expect(await page.evaluate("document.documentElement.outerHTML")).not.toContain(secret); + await page.evaluate("window.client.disconnect()"); + await expect.poll(() => f.desktop.sockets.clients.size).toBe(0); + } finally { page.close(); } +}, 30_000); diff --git a/server/instabox/vnc.test.ts b/server/instabox/vnc.test.ts new file mode 100644 index 00000000..63b9c4e6 --- /dev/null +++ b/server/instabox/vnc.test.ts @@ -0,0 +1,22 @@ +import { expect, it, vi } from "vitest"; +import { instaboxDesktopTarget } from "./vnc.ts"; + +it("resolves fresh server-only upstream credentials without a VNC password", async () => { + const upstream = vi.fn(async () => ({ url: "wss://api.instabox.sh/v1/machines/fixture/vnc", headers: { "X-API-Key": "synthetic-key" } })); + const live = vi.fn(() => true); + const touch = vi.fn(); + const target = instaboxDesktopTarget("instabox/bot/machine", upstream, { live, touch }); + expect(target.key).toBe("instabox/bot/machine"); + expect(upstream).not.toHaveBeenCalled(); + expect(await target.resolve()).toEqual({ port: 0, password: null, upstream: await upstream(), live, touch }); + upstream.mockResolvedValue({ url: "wss://api.instabox.sh/v1/machines/replacement/vnc", headers: { "X-API-Key": "synthetic-rotated-key" } }); + expect((await target.resolve()).upstream?.headers["X-API-Key"]).toBe("synthetic-rotated-key"); + expect(live).not.toHaveBeenCalled(); + expect(touch).not.toHaveBeenCalled(); +}); + +it("propagates provider failures to the route's sanitized error boundary", async () => { + const error = Object.assign(new Error("synthetic provider details"), { status: 409 }); + const target = instaboxDesktopTarget("instabox/bot/machine", async () => { throw error; }); + await expect(target.resolve()).rejects.toBe(error); +}); diff --git a/server/instabox/vnc.ts b/server/instabox/vnc.ts new file mode 100644 index 00000000..286f263f --- /dev/null +++ b/server/instabox/vnc.ts @@ -0,0 +1,12 @@ +import type { DesktopTarget } from "../routes/desktop-viewer.ts"; + +export function instaboxDesktopTarget( + key: string, + upstream: () => Promise<{ url: string; headers: Record }>, + opts?: { live?: () => boolean; touch?: () => void }, +): DesktopTarget { + return { + key, + resolve: async () => ({ port: 0, password: null, upstream: await upstream(), live: opts?.live, touch: opts?.touch }), + }; +} diff --git a/server/routes/desktop-viewer.ts b/server/routes/desktop-viewer.ts index 3d1e2033..3c2b4622 100644 --- a/server/routes/desktop-viewer.ts +++ b/server/routes/desktop-viewer.ts @@ -2,6 +2,7 @@ import { appendUpgradeCookies } from "./upgrades.ts"; import { createHash } from "node:crypto"; import { request, type IncomingMessage } from "node:http"; +import { request as secureRequest } from "node:https"; import type { Socket } from "node:net"; import type { Duplex } from "node:stream"; import { isSameOrigin, type RequestAuth } from "../request-auth.ts"; @@ -16,10 +17,12 @@ const WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; const BOT_ID = /^[\w-]+$/; const CONTROL_LEASE = /^[A-Za-z0-9_-]{16,120}$/; -/** Providers resolve a managed loopback endpoint, never a browser-supplied URL. */ +/** Providers resolve a managed endpoint, never a browser-supplied URL. */ export interface DesktopConnection { port: number; password: string | null; + /** Server-only credentials: never serialize this endpoint or its headers to a viewer. */ + upstream?: { url: string; headers: Record }; live?: boolean | (() => boolean); touch?: () => void; /** Acquired only by WebSockets; release must not close other viewers. */ @@ -47,6 +50,7 @@ export function createDesktopViewer(deps: { lease?: (id: string, botId: string, controlLeaseId: string, threadId?: string) => (() => boolean) | undefined; /** The server's shared upgrade gate; a viewer made without one keeps its own. */ upgrades?: Upgrades; + allowInsecureLoopbackUpstream?: boolean; }) { const upgrades = deps.upgrades ?? createUpgrades(); const ownGate = deps.upgrades === undefined; @@ -106,7 +110,17 @@ export function createDesktopViewer(deps: { (typeof connection.live === "function" ? connection.live() : (connection.live ?? true)); if (!live()) return json(res, 401, { error: "Viewer access expired" }); if (!holds()) return json(res, 409, { error: "Take control of this computer first" }); - if (!Number.isInteger(connection.port) || connection.port < 1 || connection.port > 65535 + let upstreamUrl: URL | undefined; + if (connection.upstream) { + try { + upstreamUrl = new URL(connection.upstream.url); + if ((upstreamUrl.protocol !== "wss:" && !(deps.allowInsecureLoopbackUpstream + && upstreamUrl.protocol === "ws:" && upstreamUrl.hostname === "127.0.0.1")) + || upstreamUrl.username || upstreamUrl.password || upstreamUrl.hash) throw new Error(); + upstreamUrl.protocol = upstreamUrl.protocol === "wss:" ? "https:" : "http:"; + } catch { return json(res, 502, { error: "Could not connect to the desktop viewer" }); } + } + if ((!connection.upstream && (!Number.isInteger(connection.port) || connection.port < 1 || connection.port > 65535)) || (screenOfViewerTarget(match[1]) !== null && connection.password === null)) { return json(res, 409, { error: "The desktop viewer is not available." }); } @@ -117,11 +131,15 @@ export function createDesktopViewer(deps: { || typeof key !== "string" || !/^[A-Za-z0-9+/]{22}==$/.test(key)) { return json(res, 400, { error: "Invalid WebSocket handshake" }); } - // Fixed host and provider path, with the port from an inspected managed container. Never forward cookies, bearer tokens, or client headers. - const upstream = request({ - hostname: "127.0.0.1", port: connection.port, path: connection.path ?? "/websockify", - headers: { Upgrade: "websocket", Connection: "Upgrade", "Sec-WebSocket-Key": key, "Sec-WebSocket-Version": "13" }, - }); + // Only provider headers cross this boundary; browser cookies and authorization never do. + let upstream: ReturnType; + try { + const headers = { ...connection.upstream?.headers, Upgrade: "websocket", Connection: "Upgrade", + "Sec-WebSocket-Key": key, "Sec-WebSocket-Version": "13" }; + upstream = upstreamUrl + ? (upstreamUrl.protocol === "https:" ? secureRequest : request)(upstreamUrl, { headers }) + : request({ hostname: "127.0.0.1", port: connection.port, path: connection.path ?? "/websockify", headers }); + } catch { return json(res, 502, { error: "Could not connect to the desktop viewer" }); } const { socket } = upgrade; let peer: Duplex | undefined; let recheck: ReturnType | undefined; diff --git a/server/testing/fake-instabox-vnc.ts b/server/testing/fake-instabox-vnc.ts new file mode 100644 index 00000000..48d295c9 --- /dev/null +++ b/server/testing/fake-instabox-vnc.ts @@ -0,0 +1,97 @@ +import { createServer, type IncomingHttpHeaders } from "node:http"; +import { createServer as createSecureServer } from "node:https"; +import type { Duplex } from "node:stream"; +import { WebSocketServer } from "ws"; + +export async function fakeInstaboxVnc(opts: { + beforeUpgrade?: () => Promise; + response?: string; + tls?: { key: string; cert: string }; +} = {}) { + const server = opts.tls ? createSecureServer(opts.tls) : createServer(); + server.on("request", (_req, res) => res.writeHead(404).end()); + const sockets = new WebSocketServer({ noServer: true }); + const peers = new Set(); + const requests: Array<{ headers: IncomingHttpHeaders; url: string | undefined }> = []; + const received: Buffer[] = []; + const sent: Buffer[] = []; + const keys: number[] = []; + const frame = Buffer.alloc(20); + frame.writeUInt16BE(1, 2); + frame.writeUInt16BE(1, 8); + frame.writeUInt16BE(1, 10); + frame[16] = 255; + sockets.on("headers", headers => headers.push("X-API-Key: synthetic-upstream-secret", "Set-Cookie: upstream=synthetic-upstream-secret")); + server.on("upgrade", (req, socket, head) => { + peers.add(socket); + socket.on("error", () => socket.destroy()); + socket.once("close", () => peers.delete(socket)); + requests.push({ headers: req.headers, url: req.url }); + void (async () => { + await opts.beforeUpgrade?.(); + if (socket.destroyed) return; + if (opts.response !== undefined) { socket.end(opts.response); return; } + sockets.handleUpgrade(req, socket, head, peer => sockets.emit("connection", peer, req)); + })(); + }); + sockets.on("connection", socket => { + let pending: Buffer = Buffer.alloc(0); + let phase = 0; + let sentFrame = false; + const send = (bytes: Buffer) => { sent.push(bytes); socket.send(bytes); }; + send(Buffer.from("RFB 003.008\n")); + socket.on("error", () => socket.terminate()); + socket.on("message", (raw, binary) => { + if (!binary) { socket.close(); return; } + const bytes = Buffer.from(raw as Buffer); + received.push(bytes); + pending = Buffer.concat([pending, bytes]); + for (;;) { + let length: number; + if (phase === 0) length = 12; + else if (phase <= 2) length = 1; + else { + if (!pending.length) return; + switch (pending[0]) { + case 0: length = 20; break; + case 2: if (pending.length < 4) return; length = 4 + pending.readUInt16BE(2) * 4; break; + case 3: length = 10; break; + case 4: length = 8; break; + case 5: length = 6; break; + case 6: if (pending.length < 8) return; length = 8 + pending.readUInt32BE(4); break; + default: socket.close(); return; + } + } + if (pending.length < length) return; + const message = pending.subarray(0, length); + pending = pending.subarray(length); + if (phase === 0) { phase++; send(Buffer.from([1, 1])); } + else if (phase === 1) { phase++; send(Buffer.alloc(4)); } + else if (phase === 2) { + phase++; + const name = Buffer.from("Isolated InstaBox desktop"); + const init = Buffer.alloc(24 + name.length); + init.writeUInt16BE(1280, 0); init.writeUInt16BE(800, 2); + init[4] = 32; init[5] = 24; init[7] = 1; + init.writeUInt16BE(255, 8); init.writeUInt16BE(255, 10); init.writeUInt16BE(255, 12); + init[14] = 16; init[15] = 8; + init.writeUInt32BE(name.length, 20); name.copy(init, 24); + send(init); + } else if (message[0] === 3 && !sentFrame) { sentFrame = true; send(frame); } + else if (message[0] === 4 && message[1] === 1) keys.push(message.readUInt32BE(4)); + } + }); + }); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + const port = (server.address() as { port: number }).port; + return { + url: `${opts.tls ? "wss" : "ws"}://127.0.0.1:${port}/v1/machines/fixture-machine/vnc`, + requests, received, sent, keys, frame, sockets, + async close() { + for (const socket of sockets.clients) socket.terminate(); + for (const peer of peers) peer.destroy(); + await new Promise(resolve => sockets.close(() => resolve())); + await new Promise(resolve => { server.close(() => resolve()); server.closeAllConnections(); }); + }, + }; +} diff --git a/shared/wire.ts b/shared/wire.ts index 979ca5d3..b73ea304 100644 --- a/shared/wire.ts +++ b/shared/wire.ts @@ -59,7 +59,7 @@ export interface ModelSelection { } /** Which cloud computer backs computer: "cloud"; absent means Boat. */ -export type CloudBackend = "box" | "vps"; +export type CloudBackend = "box" | "vps" | "instabox"; /** A place a bot can act. `cloud` covers both cloud backends. */ export type Surface = "cloud" | "vm" | "local" | "browser"; From 8bf6eba489808fcaa3c180202553a62f93cb2ea3 Mon Sep 17 00:00:00 2001 From: tangzhixiong613-jpg <340458552+tangzhixiong613-jpg@users.noreply.github.com> Date: Sun, 15 Nov 2026 05:15:46 +0000 Subject: [PATCH 2/3] =?UTF-8?q?T-1244=20=E5=85=AC=E5=BC=80=E6=89=AB?= =?UTF-8?q?=E6=8F=8F=E7=99=BD=E5=90=8D=E5=8D=95=E5=8A=A0=E5=85=A5=20InstaB?= =?UTF-8?q?ox=20=E5=85=AC=E5=85=B1=20API=20=E5=9F=9F=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- scripts/public-scan/allow-domains.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/public-scan/allow-domains.txt b/scripts/public-scan/allow-domains.txt index a081eed8..cf27b8dd 100644 --- a/scripts/public-scan/allow-domains.txt +++ b/scripts/public-scan/allow-domains.txt @@ -21,3 +21,4 @@ r2.md # 返工说明文件名,不是域名。 usercustomize.py # Python 启动钩子文件名,不是域名。 linux-test.sh # 脚本文件名,不是域名。 r3.md # 返工说明文件名,不是域名。 +instabox.sh # InstaBox 云电脑公共 API(第三方公开服务)。 From 64e4b0e555ec27e7318140d12244f8b723b6fa01 Mon Sep 17 00:00:00 2001 From: tangzhixiong613-jpg <340458552+tangzhixiong613-jpg@users.noreply.github.com> Date: Sun, 15 Nov 2026 05:23:08 +0000 Subject: [PATCH 3/3] =?UTF-8?q?T-1244=20InstaBox=20=E6=A1=8C=E9=9D=A2?= =?UTF-8?q?=E7=BB=8F=E6=9C=8D=E5=8A=A1=E7=AB=AF=E4=B8=AD=E7=BB=A7=E8=BF=9E?= =?UTF-8?q?=E4=B8=8A=E6=B8=B8=20VNC=EF=BC=8C=E6=A1=8C=E9=9D=A2=E6=9F=A5?= =?UTF-8?q?=E7=9C=8B=E5=99=A8=E6=94=AF=E6=8C=81=20upstream?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- docs/tasks/T-1200/T-1244-instabox-vnc/r2.md | 18 +++++---- .../T-1200/T-1244-instabox-vnc/report.md | 11 ++++++ .../T-1244-instabox-vnc/verification.txt | 38 +++++++++++++++++++ server/instabox/vnc.e2e.test.ts | 7 ++-- 4 files changed, 64 insertions(+), 10 deletions(-) diff --git a/docs/tasks/T-1200/T-1244-instabox-vnc/r2.md b/docs/tasks/T-1200/T-1244-instabox-vnc/r2.md index a7ca883b..31346c00 100644 --- a/docs/tasks/T-1200/T-1244-instabox-vnc/r2.md +++ b/docs/tasks/T-1200/T-1244-instabox-vnc/r2.md @@ -5,12 +5,16 @@ - 报告只写三样:改了什么(文件列表与 git status 一致)、为什么、测试命令与结果摘要。不要写长篇分析;完整输出放 verification 文本文件即可。 - 不提交 git。 -# T-1244-instabox-vnc 第 2 轮(接着做完,不是返工) +# T-1244 第 2 轮:浏览器用例在没有 Chrome 的环境里跳过 -上一轮 机器中途断开(exec 退出码 75,约 7 分钟时),你没来得及写完报告。上一轮已写的部分改动已取回到当前工作区(git status 可见未提交改动)。 +原任务见本文件夹 brief.md,工作区里已提交的改动保留,在此基础上改。第 1 轮审核已通过;GitHub Actions 上唯一的分支独有失败如下。 -要求: -1. 先读本任务文件夹里的 brief.md(原任务说明),它仍然有效,范围和验收标准不变。 -2. 检查当前工作区已有的未提交改动,在此基础上继续做完,不要推倒重来;有问题的地方直接修。 -3. 上一轮有命令以退出码 1 结束(含生成自签证书的 openssl 步骤附近),要确认相关测试真能通过。 -4. 按原说明跑完相关测试,全部通过后按原说明写报告。 +## 必改 +1. server/instabox/vnc.e2e.test.ts 的「renders the 1280×800 None-authenticated desktop with the unchanged browser client」在 Actions 上失败:`spawn /Applications/Google Chrome.app/... ENOENT` → `Chrome did not start`,还留下一个 Uncaught Exception。Actions 的 vitest 分片没有 Chrome。 + - 这条用例改成:`CHROME_PATH`(scripts/testing/headless-chrome.ts 导出,读 CRYBOT_CDP_CHROME)指向的可执行文件不存在时 `it.skipIf(...)` 跳过,并在跳过原因里写明「需要 CRYBOT_CDP_CHROME」;存在时照常跑。 + - 不改 scripts/testing/headless-chrome.ts 的行为;如确需让它在 spawn 失败时不产生未捕获异常,只做最小改动并在报告说明。 + - 其他 31 条用例保持不变、照常在 CI 跑。 +2. 本机验证:不设 CRYBOT_CDP_CHROME 时该用例显示 skipped、文件内其余全过、无 Unhandled Errors;设成本机 Chrome/Chromium 路径时(用 `systemd-run --scope -q -p MemoryMax=4G` 套着跑,Chromium 加 --no-sandbox 的话按现有做法)该用例通过。e2e 连跑 3 次。 + +## 验收 +`oxlint --deny-warnings` 改动文件、`tsc -p tsconfig.server.json`;report.md 追加第 2 轮一节,只写实际改过的文件。 diff --git a/docs/tasks/T-1200/T-1244-instabox-vnc/report.md b/docs/tasks/T-1200/T-1244-instabox-vnc/report.md index aa58b400..76466f73 100644 --- a/docs/tasks/T-1200/T-1244-instabox-vnc/report.md +++ b/docs/tasks/T-1200/T-1244-instabox-vnc/report.md @@ -47,3 +47,14 @@ git diff --check ``` 以上均退出 0。最终测试执行合计 232 项通过。`docs/verification/README.md` 在本工作区缺失;验证使用隔离 fixture、临时会话/浏览器目录及本地假服务,鉴权 e2e 启动隔离完整应用,未触碰真实 或用户应用数据。无未运行的上述检查;未提交 git。 + +## 第 2 轮 + +改了什么(与 `git status --short` 一致): + +- `server/instabox/vnc.e2e.test.ts`:从 `headless-chrome.ts` 使用 `CHROME_PATH`,路径不存在时用 `it.skipIf(...)` 跳过浏览器用例,并在跳过标题中注明需要 `CRYBOT_CDP_CHROME`。 +- `docs/tasks/T-1200/T-1244-instabox-vnc/report.md`、`docs/tasks/T-1200/T-1244-instabox-vnc/verification.txt`:本轮报告与验证记录。 + +为什么:GitHub Actions 没有 Chrome;避免默认 macOS 路径启动失败及未捕获异常,同时保留有 Chrome 环境下的完整浏览器验证。`scripts/testing/headless-chrome.ts` 未修改。 + +测试命令与结果摘要:未设置 `CRYBOT_CDP_CHROME` 时,`server/instabox/vnc.e2e.test.ts` 为 31 passed、1 skipped(跳过原因含“需要 CRYBOT_CDP_CHROME”),无 Unhandled Errors;设置 `CRYBOT_CDP_CHROME=/usr/bin/chromium` 后连续 3 轮均为 32 passed。`pnpm exec oxlint --deny-warnings server/instabox/vnc.e2e.test.ts` 与 `git diff --check` 通过。`pnpm exec tsc -p tsconfig.server.json` 仍被未改动的 `server/sessions.test.ts:79` 缺少 `label` 报错阻断。 diff --git a/docs/tasks/T-1200/T-1244-instabox-vnc/verification.txt b/docs/tasks/T-1200/T-1244-instabox-vnc/verification.txt index cd8f54d7..1f2ec1ce 100644 --- a/docs/tasks/T-1200/T-1244-instabox-vnc/verification.txt +++ b/docs/tasks/T-1200/T-1244-instabox-vnc/verification.txt @@ -71,6 +71,44 @@ $ CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run server/instabox/vnc.e Exit: 0 +=== T-1244 round 2: browser skipped without Chrome === +$ env -u CRYBOT_CDP_CHROME pnpm exec vitest run server/instabox/vnc.e2e.test.ts --maxWorkers=1 --reporter=verbose + + ✓ server/instabox/vnc.e2e.test.ts (31 passed) + ↓ server/instabox/vnc.e2e.test.ts > renders the 1280×800 None-authenticated desktop with the unchanged browser client (需要 CRYBOT_CDP_CHROME) + Test Files 1 passed (1) + Tests 31 passed | 1 skipped (32) + Unhandled Errors 0 +Exit: 0 + +=== T-1244 round 2: browser available === +$ CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run server/instabox/vnc.e2e.test.ts --maxWorkers=1 + + Test Files 1 passed (1) + Tests 32 passed (32) +Exit: 0 + +$ CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run server/instabox/vnc.e2e.test.ts --maxWorkers=1 + Test Files 1 passed (1) + Tests 32 passed (32) +Exit: 0 + +$ CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run server/instabox/vnc.e2e.test.ts --maxWorkers=1 + Test Files 1 passed (1) + Tests 32 passed (32) +Exit: 0 + +=== T-1244 round 2: checks === +$ pnpm exec oxlint --deny-warnings server/instabox/vnc.e2e.test.ts +Exit: 0 + +$ git diff --check +Exit: 0 + +$ pnpm exec tsc -p tsconfig.server.json +server/sessions.test.ts(79,38): error TS2741: Property 'label' is missing in type '{ code: string; source: string; browser: boolean; }' but required in type '{ code: string; label: string; source: string; fallbackLabel?: string | undefined; attemptId?: string | undefined; browser?: boolean | undefined; }'. +Exit: 2 + === server/instabox/vnc.e2e.test.ts (2/3) === $ CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run server/instabox/vnc.e2e.test.ts --maxWorkers=1 diff --git a/server/instabox/vnc.e2e.test.ts b/server/instabox/vnc.e2e.test.ts index bcb8fea4..4c3dfb84 100644 --- a/server/instabox/vnc.e2e.test.ts +++ b/server/instabox/vnc.e2e.test.ts @@ -2,13 +2,13 @@ import { once } from "node:events"; import { execFileSync } from "node:child_process"; import { createServer, request, type IncomingHttpHeaders } from "node:http"; import { globalAgent } from "node:https"; -import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; import { build } from "esbuild"; import { WebSocket } from "ws"; import { afterAll, afterEach, beforeAll, expect, it, vi } from "vitest"; -import { openHeadlessChrome } from "../../scripts/testing/headless-chrome.ts"; +import { CHROME_PATH, openHeadlessChrome } from "../../scripts/testing/headless-chrome.ts"; import { SessionRegistry } from "../sessions.ts"; import { resolveRequestAuth } from "../request-auth.ts"; import { json, readBody } from "../harness/http.ts"; @@ -24,6 +24,7 @@ const leaseId = "fixture-control-lease"; const leased = `${base}/websockify?botId=fixture-bot&controlLeaseId=${leaseId}`; const cleanups: Array<() => Promise> = []; const tlsDir = mkdtempSync(join(tmpdir(), "cry-instabox-vnc-tls-")); +const chromeAvailable = existsSync(CHROME_PATH); let tls: { key: string; cert: string }; beforeAll(() => { execFileSync("openssl", ["req", "-x509", "-newkey", "rsa:2048", "-noenc", "-days", "1", @@ -271,7 +272,7 @@ it.each(["refused", "invalid-header", "provider", "rejected", "forged", "tls", " if (failure === "untrusted-cert") expect(f.desktop.requests).toEqual([]); }); -it("renders the 1280×800 None-authenticated desktop with the unchanged browser client", async () => { +it.skipIf(!chromeAvailable)(`renders the 1280×800 None-authenticated desktop with the unchanged browser client${chromeAvailable ? "" : " (需要 CRYBOT_CDP_CHROME)"}`, async () => { trustFixtureCertificate(); const f = await fixture({ tls, allowInsecure: false }); const bundle = await build({ stdin: { contents: `