From e7f62ed9f1d8201936da6ffe4273f32f6d238fd1 Mon Sep 17 00:00:00 2001 From: William Frank Monroy Mamani Date: Sun, 22 Nov 2026 12:37:13 -0600 Subject: [PATCH 01/15] ci: run turno-browser and turno-core tests on windows-latest --- .github/workflows/ci.yml | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0524bf1c..c3500ac9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -44,6 +44,34 @@ jobs: TURNO_SKIP_E2E: "1" - run: node scripts/pack-check.mjs + windows: + # turno-browser and the turno-core parts it uses on Windows. turno-cli (mcpd, launchd) is + # not supported there, so only these two packages build and test here. + name: browser on windows (node ${{ matrix.node }}) + strategy: + fail-fast: false + matrix: + node: [22, 24] + runs-on: windows-latest + permissions: + contents: read # check out the code + env: + # The package scripts (rm -rf, chmod) are POSIX; pnpm runs them with Git Bash here. + npm_config_script_shell: C:\Program Files\Git\bin\bash.exe + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: ${{ matrix.node }} + cache: pnpm + - run: pnpm install --frozen-lockfile + - run: pnpm --filter turno-core --filter turno-browser run build + - run: pnpm --filter turno-core --filter turno-browser run typecheck + - run: pnpm --filter turno-core --filter turno-browser run test + pull-request: name: pull request rules if: github.event_name == 'pull_request' From 3c335eadc10b295dbc68a47f5ba2c7c85906cae7 Mon Sep 17 00:00:00 2001 From: William Frank Monroy Mamani Date: Sun, 22 Nov 2026 12:39:35 -0600 Subject: [PATCH 02/15] ci: run the browser tests on windows even when core tests fail --- .github/workflows/ci.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c3500ac9..133992fb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -70,7 +70,11 @@ jobs: - run: pnpm install --frozen-lockfile - run: pnpm --filter turno-core --filter turno-browser run build - run: pnpm --filter turno-core --filter turno-browser run typecheck - - run: pnpm --filter turno-core --filter turno-browser run test + # The secret store tests drive POSIX shell stand-ins for security and secret-tool; the + # Windows secret store comes with its own tests. + - run: pnpm --filter turno-core exec vitest run --exclude test/secrets.test.ts + - run: pnpm --filter turno-browser run test + if: ${{ !cancelled() }} pull-request: name: pull request rules From ec3275d33ff61a862167e840d9a55e23cdde40dc Mon Sep 17 00:00:00 2001 From: William Frank Monroy Mamani Date: Sun, 22 Nov 2026 12:42:56 -0600 Subject: [PATCH 03/15] feat(core): Windows paths, PATHEXT lookup, process table and tree kill --- packages/browser/test/helpers/build-dist.ts | 4 +- packages/browser/test/helpers/global-setup.ts | 10 +- packages/core/src/index.ts | 6 + packages/core/src/paths.ts | 146 +++++++++++++++--- packages/core/src/process.ts | 82 +++++++++- packages/core/test/completion.test.ts | 38 +++-- packages/core/test/helpers/global-setup.ts | 10 +- packages/core/test/paths.test.ts | 67 ++++++-- packages/core/test/process.test.ts | 31 +++- 9 files changed, 330 insertions(+), 64 deletions(-) diff --git a/packages/browser/test/helpers/build-dist.ts b/packages/browser/test/helpers/build-dist.ts index 49df8e0d..819755ed 100644 --- a/packages/browser/test/helpers/build-dist.ts +++ b/packages/browser/test/helpers/build-dist.ts @@ -11,5 +11,7 @@ import { fileURLToPath } from "node:url"; export default function setup(): void { const pkg = fileURLToPath(new URL("../..", import.meta.url)); - execFileSync(join(pkg, "node_modules", ".bin", "tsc"), ["-p", "tsconfig.build.json"], { cwd: pkg, stdio: "inherit" }); + // tsc's own script through node: node_modules/.bin/tsc is a shell script, which Windows cannot run. + const tsc = join(pkg, "node_modules", "typescript", "bin", "tsc"); + execFileSync(process.execPath, [tsc, "-p", "tsconfig.build.json"], { cwd: pkg, stdio: "inherit" }); } diff --git a/packages/browser/test/helpers/global-setup.ts b/packages/browser/test/helpers/global-setup.ts index bf0d9e20..1ca91e75 100644 --- a/packages/browser/test/helpers/global-setup.ts +++ b/packages/browser/test/helpers/global-setup.ts @@ -11,7 +11,7 @@ */ import { chmodSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { delimiter, join } from "node:path"; const KEEP = new Set([ "TURNO_SKIP_E2E", @@ -43,6 +43,12 @@ export default function setup(): () => void { process.env.XDG_STATE_HOME = join(home, ".local", "state"); process.env.XDG_DATA_HOME = join(home, ".local", "share"); process.env.XDG_CACHE_HOME = join(home, ".cache"); + // Windows reads these instead of HOME: the profile folder, and turno's and Playwright's defaults. + if (process.platform === "win32") { + process.env.USERPROFILE = home; + process.env.APPDATA = join(home, "AppData", "Roaming"); + process.env.LOCALAPPDATA = join(home, "AppData", "Local"); + } process.env.TURNO_NO_UPDATE_CHECK = "1"; // No test reaches the real secret store: stand-ins for `security` and `secret-tool` that refuse // come first on PATH. A real Keychain call can open a macOS dialog that blocks the whole @@ -57,7 +63,7 @@ export default function setup(): () => void { ); chmodSync(file, 0o755); } - process.env.PATH = `${guard}:${process.env.PATH ?? ""}`; + process.env.PATH = `${guard}${delimiter}${process.env.PATH ?? ""}`; return () => { const found = guardFindings(home); rmSync(root, { recursive: true, force: true }); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 62b1f5c9..9c38f549 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -10,9 +10,12 @@ export { type TurnoRoots, browserPaths, ensurePrivateDir, + envValue, findOnPath, isPrivatePath, + pathsFor, privateRoots, + replaceFileSync, resetPrivateDirCache, turnoRoots, writePrivateFile, @@ -30,11 +33,14 @@ export { export { type ProcInfo, type ProcTable, + killTree, parentIsInit, parseProcTable, + parseWindowsProcTable, pidAlive, readProcTable, signalProcess, + treeKillCommand, } from "./process.js"; export { type PressureLevel, diff --git a/packages/core/src/paths.ts b/packages/core/src/paths.ts index 4d50713a..473a3bdb 100644 --- a/packages/core/src/paths.ts +++ b/packages/core/src/paths.ts @@ -7,29 +7,72 @@ import { fstatSync, mkdirSync, openSync, + renameSync, statSync, writeSync, } from "node:fs"; import { homedir } from "node:os"; -import { delimiter, dirname, isAbsolute, join, normalize, relative, sep } from "node:path"; +import { dirname, isAbsolute, posix, relative, sep, win32 } from "node:path"; + +/** The path functions of a platform, so a result never depends on the OS the tests run on. */ +export function pathsFor(platform: NodeJS.Platform = process.platform): typeof posix { + return platform === "win32" ? win32 : posix; +} + +/** + * A variable of `env`. Windows names are case-insensitive, but a copy of `process.env` (an + * object spread) keeps the case Windows gave them: `Path`, `ProgramFiles`, `LocalAppData`. + */ +export function envValue( + env: NodeJS.ProcessEnv, + name: string, + platform: NodeJS.Platform = process.platform, +): string | undefined { + const value = env[name]; + if (value !== undefined || platform !== "win32") return value; + const upper = name.toUpperCase(); + const key = Object.keys(env).find((k) => k.toUpperCase() === upper); + return key === undefined ? undefined : env[key]; +} /** * turno's own roots, derived from HOME and the XDG variables so tests can run against a * sandbox home. turno-cli and turno-browser both build their paths on these, so the two * packages always agree on where turno keeps its files. Call it each time instead of caching: * tests change HOME. + * + * On Windows the defaults follow the platform instead of XDG: the config roams with the user + * (`%APPDATA%\turno`), state and data (Chrome profiles, large) stay on the machine + * (`%LOCALAPPDATA%\turno\state` and `\data`). An XDG variable that is set still wins there. */ export interface TurnoRoots { home: string; - /** `TURNO_CONFIG_DIR`, else `$XDG_CONFIG_HOME/turno` (default `~/.config/turno`). */ + /** `TURNO_CONFIG_DIR`, else `$XDG_CONFIG_HOME/turno` (default `~/.config/turno`, Windows `%APPDATA%\turno`). */ config: string; - /** `TURNO_STATE_DIR`, else `$XDG_STATE_HOME/turno` (default `~/.local/state/turno`). */ + /** `TURNO_STATE_DIR`, else `$XDG_STATE_HOME/turno` (default `~/.local/state/turno`, Windows `%LOCALAPPDATA%\turno\state`). */ state: string; - /** `TURNO_DATA_DIR`, else `$XDG_DATA_HOME/turno` (default `~/.local/share/turno`). */ + /** `TURNO_DATA_DIR`, else `$XDG_DATA_HOME/turno` (default `~/.local/share/turno`, Windows `%LOCALAPPDATA%\turno\data`). */ data: string; } -export function turnoRoots(env: NodeJS.ProcessEnv = process.env): TurnoRoots { +export function turnoRoots( + env: NodeJS.ProcessEnv = process.env, + platform: NodeJS.Platform = process.platform, +): TurnoRoots { + const get = (name: string) => envValue(env, name, platform) || undefined; + const { join } = pathsFor(platform); + if (platform === "win32") { + const home = get("HOME") || get("USERPROFILE") || homedir(); + const roaming = get("APPDATA") || join(home, "AppData", "Roaming"); + const local = get("LOCALAPPDATA") || join(home, "AppData", "Local"); + const xdg = (name: string) => (get(name) ? join(get(name)!, "turno") : undefined); + return { + home, + config: get("TURNO_CONFIG_DIR") || xdg("XDG_CONFIG_HOME") || join(roaming, "turno"), + state: get("TURNO_STATE_DIR") || xdg("XDG_STATE_HOME") || join(local, "turno", "state"), + data: get("TURNO_DATA_DIR") || xdg("XDG_DATA_HOME") || join(local, "turno", "data"), + }; + } const home = env.HOME || homedir(); return { home, @@ -40,11 +83,17 @@ export function turnoRoots(env: NodeJS.ProcessEnv = process.env): TurnoRoots { } /** Replace the home prefix with ~ for display. */ -export function tildify(p: string, env: NodeJS.ProcessEnv): string { +export function tildify(p: string, env: NodeJS.ProcessEnv, platform: NodeJS.Platform = process.platform): string { + const path = pathsFor(platform); + const sepChars = platform === "win32" ? /[\\/]+$/ : /\/+$/; // HOME may come with a trailing slash or doubled slashes (HOME=/Users/a/): compare normalized. - const home = normalize(turnoRoots(env).home).replace(/(.)\/+$/, "$1"); - const q = isAbsolute(p) ? normalize(p) : p; - return q === home ? "~" : home !== "/" && q.startsWith(`${home}/`) ? `~${q.slice(home.length)}` : p; + let home = path.normalize(turnoRoots(env, platform).home); + if (home !== path.parse(home).root) home = home.replace(sepChars, ""); + const q = path.isAbsolute(p) ? path.normalize(p) : p; + if (home === path.parse(home).root) return p; + const same = (a: string, b: string) => (platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b); + if (same(q, home)) return "~"; + return same(q.slice(0, home.length + 1), `${home}${path.sep}`) ? `~${q.slice(home.length)}` : p; } /** Where turno-browser keeps its files. */ @@ -62,8 +111,12 @@ export interface BrowserPaths { identityStateDir: string; } -export function browserPaths(env: NodeJS.ProcessEnv = process.env): BrowserPaths { - const { home, state, data } = turnoRoots(env); +export function browserPaths( + env: NodeJS.ProcessEnv = process.env, + platform: NodeJS.Platform = process.platform, +): BrowserPaths { + const { home, state, data } = turnoRoots(env, platform); + const { join } = pathsFor(platform); const browserDir = join(data, "browser"); return { home, @@ -159,25 +212,68 @@ export function resetPrivateDirCache(): void { lockedRoots.clear(); } -/** The first executable called `name` on the PATH of `env`, or undefined. */ -export function findOnPath(name: string, env: NodeJS.ProcessEnv): string | undefined { - if (name.includes("/")) { +/** The extensions Windows runs a bare command name with (PATHEXT), lower case. */ +function pathExts(env: NodeJS.ProcessEnv): string[] { + return (envValue(env, "PATHEXT", "win32") || ".COM;.EXE;.BAT;.CMD") + .split(";") + .filter((e) => e.startsWith(".")) + .map((e) => e.toLowerCase()); +} + +/** + * The first executable called `name` on the PATH of `env`, or undefined. On Windows a bare + * name is tried with each PATHEXT extension (`claude` finds `claude.cmd`), and any file + * counts, since Windows has no execute bit. + */ +export function findOnPath( + name: string, + env: NodeJS.ProcessEnv, + platform: NodeJS.Platform = process.platform, +): string | undefined { + const path = pathsFor(platform); + const windows = platform === "win32"; + const runnable = (file: string): boolean => { try { - accessSync(name, constants.X_OK); - return name; + if (!windows) accessSync(file, constants.X_OK); + return statSync(file).isFile(); } catch { - return undefined; + return false; } - } - for (const dir of (env.PATH ?? "").split(delimiter)) { + }; + const exts = windows ? pathExts(env) : []; + const forms = (file: string): string[] => + !windows || exts.includes(path.extname(file).toLowerCase()) ? [file] : exts.map((e) => `${file}${e}`); + if (name.includes("/") || (windows && name.includes("\\"))) return forms(name).find(runnable); + for (const dir of (envValue(env, "PATH", platform) ?? "").split(path.delimiter)) { if (!dir) continue; - const file = join(dir, name); + const found = forms(path.join(dir, name)).find(runnable); + if (found) return found; + } + return undefined; +} + +const RENAME_BUSY = new Set(["EPERM", "EACCES", "EBUSY"]); + +/** + * `renameSync(from, to)`, replacing `to`. Windows refuses to replace a file another program + * holds open for a moment (an antivirus scan, the search indexer, a reader without delete + * sharing) with EPERM, EACCES or EBUSY; the rename is tried again for up to `ms` there. + */ +export function replaceFileSync( + from: string, + to: string, + platform: NodeJS.Platform = process.platform, + ms = 2000, +): void { + const end = Date.now() + ms; + for (let wait = 10; ; wait = Math.min(wait * 2, 200)) { try { - accessSync(file, constants.X_OK); - if (statSync(file).isFile()) return file; - } catch { - /* next */ + renameSync(from, to); + return; + } catch (err) { + const code = (err as NodeJS.ErrnoException).code ?? ""; + if (platform !== "win32" || !RENAME_BUSY.has(code) || Date.now() >= end) throw err; + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, wait); } } - return undefined; } diff --git a/packages/core/src/process.ts b/packages/core/src/process.ts index ca3c4b46..c6fc61c3 100644 --- a/packages/core/src/process.ts +++ b/packages/core/src/process.ts @@ -2,8 +2,10 @@ import { execFileSync } from "node:child_process"; /** * Process helpers shared by turno-cli and turno-browser: whether a PID lives, a signal that - * never throws, and the process table with process groups (Chrome runs as the leader of its own - * group). + * never throws, the process table with process groups (Chrome runs as the leader of its own + * group), and how to end a whole process tree. Windows has no process groups and no signals + * (`process.kill` terminates at once there), so the table comes from PowerShell with each + * process as its own group, and a tree ends with `taskkill /T`. */ /** Whether a process is alive. EPERM means it exists but belongs to someone else. */ @@ -46,8 +48,46 @@ export function parseProcTable(stdout: string): ProcTable { return t; } -/** Every process with its full command line, or undefined when `ps` is not available. */ -export function readProcTable(): ProcTable | undefined { +/** + * PowerShell's `Win32_Process` lines, `\t\t`. There are no process + * groups on Windows: each process counts as the leader of its own. A process whose command line + * the user may not read (another user's, a system one) has an empty one. + */ +export function parseWindowsProcTable(stdout: string): ProcTable { + const t: ProcTable = new Map(); + for (const line of stdout.split(/\r?\n/)) { + const m = /^(\d+)\t(\d+)\t(.*)$/.exec(line); + if (!m) continue; + const pid = Number(m[1]); + t.set(pid, { pid, ppid: Number(m[2]), pgid: pid, command: m[3]!.trim() }); + } + return t; +} + +/** Lists every process as `parseWindowsProcTable` reads it, in UTF-8 whatever the console code page. */ +const WINDOWS_PROC_SCRIPT = + "[Console]::OutputEncoding = [Text.Encoding]::UTF8; " + + "Get-CimInstance Win32_Process | ForEach-Object { '{0}`t{1}`t{2}' -f $_.ProcessId, $_.ParentProcessId, $_.CommandLine }"; + +/** + * Every process with its full command line, or undefined when the table cannot be read (no + * `ps`; on Windows, no PowerShell). + */ +export function readProcTable(platform: NodeJS.Platform = process.platform): ProcTable | undefined { + if (platform === "win32") { + try { + const out = execFileSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_PROC_SCRIPT], { + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + windowsHide: true, + maxBuffer: 64 * 1024 * 1024, + timeout: 15_000, + }); + return parseWindowsProcTable(out); + } catch { + return undefined; + } + } try { const out = execFileSync("ps", ["-A", "-ww", "-o", "pid=,ppid=,pgid=,command="], { encoding: "utf8", @@ -62,6 +102,40 @@ export function readProcTable(): ProcTable | undefined { } } +/** + * The command that ends a process and every process it started: `taskkill /T` on Windows, which + * walks the tree by parent PID (with `/F` it does not ask first). Undefined on other systems, + * where a tree is a process group and gets a signal (`signalProcess(-pgid, ...)`). + */ +export function treeKillCommand( + pid: number, + force: boolean, + platform: NodeJS.Platform = process.platform, +): { file: string; args: string[] } | undefined { + if (platform !== "win32") return undefined; + return { file: "taskkill.exe", args: ["/PID", String(pid), "/T", ...(force ? ["/F"] : [])] }; +} + +/** + * Ends the tree of `pid`. On Windows through `treeKillCommand`: without `force`, taskkill asks + * the windows of the tree to close, as the close button does (a headless process has none and + * keeps running); false when taskkill failed (the process is already gone, or access was + * denied). Elsewhere `pid` must lead its process group, which gets SIGTERM, or SIGKILL with `force`. + */ +export function killTree(pid: number, force: boolean, platform: NodeJS.Platform = process.platform): boolean { + const cmd = treeKillCommand(pid, force, platform); + if (!cmd) { + signalProcess(-pid, force ? "SIGKILL" : "SIGTERM"); + return true; + } + try { + execFileSync(cmd.file, cmd.args, { stdio: "ignore", windowsHide: true, timeout: 15_000 }); + return true; + } catch { + return false; + } +} + /** A parent that means "nobody": init, launchd, a `systemd --user` subreaper, or none at all. */ export function parentIsInit(ppid: number, table: ProcTable): boolean { const parent = table.get(ppid); diff --git a/packages/core/test/completion.test.ts b/packages/core/test/completion.test.ts index 7c17d8fc..7685208c 100644 --- a/packages/core/test/completion.test.ts +++ b/packages/core/test/completion.test.ts @@ -29,21 +29,25 @@ describe("completion scripts", () => { expect(s.fish).toContain("complete -c turno-browser -f -a '(__turno_browser_complete)'"); }); - it("pass each word to the program on its own under bash, empty last word included", () => { - const bin = fakeProgram("demo-prog"); - const script = completionScripts("demo-prog").bash; - const r = spawnSync( - "bash", - [ - "--norc", - "-c", - `eval "$1"; COMP_WORDS=(demo-prog do "two words" ""); COMP_CWORD=3; _demo_prog; printf '%s\\n' "\${COMPREPLY[@]}"`, - "x", - script, - ], - { encoding: "utf8", env: { PATH: `${bin}:/usr/bin:/bin` } }, - ); - expect(r.stderr).toBe(""); - expect(r.stdout.trim().split("\n")).toEqual(["", "", "<>"]); - }); + // The fake program is a POSIX shell script. + it.skipIf(process.platform === "win32")( + "pass each word to the program on its own under bash, empty last word included", + () => { + const bin = fakeProgram("demo-prog"); + const script = completionScripts("demo-prog").bash; + const r = spawnSync( + "bash", + [ + "--norc", + "-c", + `eval "$1"; COMP_WORDS=(demo-prog do "two words" ""); COMP_CWORD=3; _demo_prog; printf '%s\\n' "\${COMPREPLY[@]}"`, + "x", + script, + ], + { encoding: "utf8", env: { PATH: `${bin}:/usr/bin:/bin` } }, + ); + expect(r.stderr).toBe(""); + expect(r.stdout.trim().split("\n")).toEqual(["", "", "<>"]); + }, + ); }); diff --git a/packages/core/test/helpers/global-setup.ts b/packages/core/test/helpers/global-setup.ts index 95aab8ae..48901f7a 100644 --- a/packages/core/test/helpers/global-setup.ts +++ b/packages/core/test/helpers/global-setup.ts @@ -9,7 +9,7 @@ */ import { chmodSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { delimiter, join } from "node:path"; const KEEP = new Set(["TURNO_SKIP_E2E", "TURNO_E2E_NETWORK", "TURNO_SKIP_CHROME"]); const LIVE = /^(TURNO_|CLAUDE|CODEX_|CURSOR_|ANTHROPIC_|XDG_)/; @@ -33,6 +33,12 @@ export default function setup(): () => void { process.env.XDG_STATE_HOME = join(home, ".local", "state"); process.env.XDG_DATA_HOME = join(home, ".local", "share"); process.env.XDG_CACHE_HOME = join(home, ".cache"); + // Windows reads these instead of HOME: the profile folder, and turno's and Playwright's defaults. + if (process.platform === "win32") { + process.env.USERPROFILE = home; + process.env.APPDATA = join(home, "AppData", "Roaming"); + process.env.LOCALAPPDATA = join(home, "AppData", "Local"); + } process.env.TURNO_NO_UPDATE_CHECK = "1"; // No test reaches the real secret store: stand-ins for `security` and `secret-tool` that refuse // come first on PATH. A real Keychain call can open a macOS dialog that blocks the whole @@ -47,7 +53,7 @@ export default function setup(): () => void { ); chmodSync(file, 0o755); } - process.env.PATH = `${guard}:${process.env.PATH ?? ""}`; + process.env.PATH = `${guard}${delimiter}${process.env.PATH ?? ""}`; return () => { const found = guardFindings(home); rmSync(root, { recursive: true, force: true }); diff --git a/packages/core/test/paths.test.ts b/packages/core/test/paths.test.ts index 775d52a2..799c864e 100644 --- a/packages/core/test/paths.test.ts +++ b/packages/core/test/paths.test.ts @@ -4,9 +4,11 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { browserPaths, ensurePrivateDir, + envValue, findOnPath, isPrivatePath, resetPrivateDirCache, + tildify, turnoRoots, writePrivateFile, } from "../src/paths.js"; @@ -21,27 +23,30 @@ afterEach(() => sb.cleanup()); describe("turno's roots", () => { it("follow HOME, then XDG, then the TURNO_* overrides", () => { - expect(turnoRoots({ HOME: "/h" })).toEqual({ + expect(turnoRoots({ HOME: "/h" }, "linux")).toEqual({ home: "/h", config: "/h/.config/turno", state: "/h/.local/state/turno", data: "/h/.local/share/turno", }); expect( - turnoRoots({ HOME: "/h", XDG_CONFIG_HOME: "/x/c", XDG_STATE_HOME: "/x/s", XDG_DATA_HOME: "/x/d" }), + turnoRoots({ HOME: "/h", XDG_CONFIG_HOME: "/x/c", XDG_STATE_HOME: "/x/s", XDG_DATA_HOME: "/x/d" }, "linux"), ).toMatchObject({ config: "/x/c/turno", state: "/x/s/turno", data: "/x/d/turno", }); expect( - turnoRoots({ - HOME: "/h", - XDG_DATA_HOME: "/x/d", - TURNO_DATA_DIR: "/t/d", - TURNO_STATE_DIR: "/t/s", - TURNO_CONFIG_DIR: "/t/c", - }), + turnoRoots( + { + HOME: "/h", + XDG_DATA_HOME: "/x/d", + TURNO_DATA_DIR: "/t/d", + TURNO_STATE_DIR: "/t/s", + TURNO_CONFIG_DIR: "/t/c", + }, + "linux", + ), ).toMatchObject({ config: "/t/c", state: "/t/s", @@ -50,7 +55,7 @@ describe("turno's roots", () => { }); it("place turno-browser's files under the data and state roots", () => { - expect(browserPaths({ HOME: "/h" })).toEqual({ + expect(browserPaths({ HOME: "/h" }, "linux")).toEqual({ home: "/h", state: "/h/.local/state/turno", data: "/h/.local/share/turno", @@ -60,10 +65,35 @@ describe("turno's roots", () => { identityStateDir: "/h/.local/state/turno/browser/identities", }); }); + + it("on Windows, keep the config in APPDATA and state and data in LOCALAPPDATA", () => { + const env = { USERPROFILE: "C:\\Users\\a", AppData: "C:\\Users\\a\\AppData\\Roaming", LOCALAPPDATA: "D:\\local" }; + expect(turnoRoots(env, "win32")).toEqual({ + home: "C:\\Users\\a", + config: "C:\\Users\\a\\AppData\\Roaming\\turno", + state: "D:\\local\\turno\\state", + data: "D:\\local\\turno\\data", + }); + expect(browserPaths(env, "win32").identitiesDir).toBe("D:\\local\\turno\\data\\browser\\identities"); + // Without the variables (a sandbox env), from the profile folder; set XDG and TURNO_* still win. + expect(turnoRoots({ HOME: "C:\\h", XDG_STATE_HOME: "C:\\x\\s", TURNO_DATA_DIR: "C:\\t\\d" }, "win32")).toEqual({ + home: "C:\\h", + config: "C:\\h\\AppData\\Roaming\\turno", + state: "C:\\x\\s\\turno", + data: "C:\\t\\d", + }); + expect(tildify("c:\\users\\a\\x\\y", env, "win32")).toBe("~\\x\\y"); + }); + + it("read Windows variables whatever their case", () => { + expect(envValue({ Path: "C:\\bin" }, "PATH", "win32")).toBe("C:\\bin"); + expect(envValue({ Path: "/bin" }, "PATH", "linux")).toBeUndefined(); + }); }); describe("private files", () => { - it("creates folders 0700 and files 0600 inside turno's roots only", () => { + // Windows has no POSIX modes; the user's profile folder is private to the user by its ACL. + it.skipIf(process.platform === "win32")("creates folders 0700 and files 0600 inside turno's roots only", () => { const file = join(turnoRoots(sb.env).state, "a", "b.json"); writePrivateFile(file, "{}", sb.env); expect(statSync(file).mode & 0o777).toBe(0o600); @@ -76,7 +106,8 @@ describe("private files", () => { }); describe("findOnPath", () => { - it("finds an executable on PATH and nothing else", () => { + // The execute bit decides here; Windows has none (next test). + it.skipIf(process.platform === "win32")("finds an executable on PATH and nothing else", () => { sb.write("bin/tool", "#!/bin/sh\n", 0o755); sb.write("bin/data", "x", 0o644); const env = { PATH: `${join(sb.home, "missing")}:${join(sb.home, "bin")}` }; @@ -84,4 +115,16 @@ describe("findOnPath", () => { expect(findOnPath("data", env)).toBeUndefined(); expect(findOnPath(join(sb.home, "bin", "tool"), {})).toBe(join(sb.home, "bin", "tool")); }); + + it.runIf(process.platform === "win32")( + "on Windows, finds a command through PATHEXT, as claude finds claude.cmd", + () => { + sb.write("bin/tool.cmd", "@echo off\r\n"); + sb.write("bin/data.txt", "x"); + const env = { Path: `${join(sb.home, "missing")};${join(sb.home, "bin")}`, PATHEXT: ".EXE;.CMD" }; + expect(findOnPath("tool", env, "win32")?.toLowerCase()).toBe(join(sb.home, "bin", "tool.cmd").toLowerCase()); + expect(findOnPath("tool.cmd", env, "win32")?.toLowerCase()).toBe(join(sb.home, "bin", "tool.cmd").toLowerCase()); + expect(findOnPath("data", env, "win32")).toBeUndefined(); + }, + ); }); diff --git a/packages/core/test/process.test.ts b/packages/core/test/process.test.ts index 5ff9e1b5..7358fa6f 100644 --- a/packages/core/test/process.test.ts +++ b/packages/core/test/process.test.ts @@ -1,6 +1,14 @@ import { spawn } from "node:child_process"; import { describe, expect, it } from "vitest"; -import { parentIsInit, parseProcTable, pidAlive, readProcTable, signalProcess } from "../src/process.js"; +import { + parentIsInit, + parseProcTable, + parseWindowsProcTable, + pidAlive, + readProcTable, + signalProcess, + treeKillCommand, +} from "../src/process.js"; describe("process helpers", () => { it("parses ps output with process groups and skips other lines", () => { @@ -14,6 +22,27 @@ describe("process helpers", () => { expect(parentIsInit(999, t)).toBe(true); }); + it("parses the Windows table, where every process leads its own group", () => { + const t = parseWindowsProcTable( + '4\t0\t\r\n900\t12\t"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe" --user-data-dir=C:\\p q\r\nnoise\r\n', + ); + expect([...t.keys()]).toEqual([4, 900]); + expect(t.get(900)).toEqual({ + pid: 900, + ppid: 12, + pgid: 900, + command: '"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe" --user-data-dir=C:\\p q', + }); + expect(t.get(4)?.command).toBe(""); + expect(parentIsInit(12, t)).toBe(true); + }); + + it("ends a tree with taskkill /T on Windows only", () => { + expect(treeKillCommand(900, true, "win32")).toEqual({ file: "taskkill.exe", args: ["/PID", "900", "/T", "/F"] }); + expect(treeKillCommand(900, false, "win32")?.args).toEqual(["/PID", "900", "/T"]); + expect(treeKillCommand(900, true, "darwin")).toBeUndefined(); + }); + it("reads this process from the real process table", () => { const t = readProcTable(); if (!t) return; // no ps here From 6d6f36802345f50f16ab893339e9fab8c5aab08b Mon Sep 17 00:00:00 2001 From: William Frank Monroy Mamani Date: Sun, 22 Nov 2026 13:01:29 -0600 Subject: [PATCH 04/15] feat(browser): run on Windows with named pipes, taskkill and the Windows browser locations Named pipes for the background and live servers, Chrome found through its lockfile and the PowerShell process table, process trees ended with taskkill, Chrome, Edge and Brave in their Windows folders, agents' .cmd shims run through cmd.exe with escaped arguments, and tests that run on windows-latest. --- packages/browser/src/agent-mcp.ts | 60 ++++++- packages/browser/src/background-state.ts | 45 ++++-- packages/browser/src/background.ts | 52 +++++-- packages/browser/src/browsers.ts | 76 +++++++-- packages/browser/src/cli/context.ts | 19 ++- packages/browser/src/cli/init.ts | 9 +- packages/browser/src/cli/setup.ts | 31 +++- packages/browser/src/client.ts | 42 ++++- packages/browser/src/destroy.ts | 26 +++- packages/browser/src/doctor.ts | 20 ++- packages/browser/src/engine-attach.ts | 9 +- packages/browser/src/engine-camoufox.ts | 2 +- packages/browser/src/flows.ts | 6 +- packages/browser/src/health.ts | 5 +- packages/browser/src/identities.ts | 22 ++- packages/browser/src/last-used.ts | 5 +- packages/browser/src/lifecycle.ts | 63 +++++++- packages/browser/src/live-server.ts | 23 ++- packages/browser/src/login.ts | 5 +- packages/browser/src/network-chrome.ts | 13 +- packages/browser/src/recordings.ts | 5 +- packages/browser/src/runtime-lock.ts | 17 +- packages/browser/src/session-export.ts | 5 +- packages/browser/src/settings.ts | 6 +- packages/browser/src/vault.ts | 6 +- packages/browser/test/argv.test.ts | 6 +- packages/browser/test/background.test.ts | 41 ++--- packages/browser/test/browser-tools.test.ts | 6 +- packages/browser/test/browsers.test.ts | 34 ++++ packages/browser/test/cli/bin.test.ts | 146 ++++++++++-------- .../browser/test/cli/do-background.test.ts | 6 +- packages/browser/test/cli/flows.test.ts | 10 +- packages/browser/test/cli/init.test.ts | 116 ++++++++++++-- packages/browser/test/cli/remove.test.ts | 11 +- packages/browser/test/cli/session.test.ts | 6 +- packages/browser/test/cli/status.test.ts | 4 +- packages/browser/test/doctor.test.ts | 8 +- packages/browser/test/engines.test.ts | 22 +-- packages/browser/test/flows.test.ts | 8 +- packages/browser/test/helpers/chrome.ts | 19 ++- .../browser/test/helpers/fake-secret-store.ts | 8 + packages/browser/test/helpers/global-setup.ts | 12 +- packages/browser/test/helpers/programs.ts | 35 +++++ packages/browser/test/helpers/sandbox.ts | 33 +++- packages/browser/test/last-used.test.ts | 6 +- packages/browser/test/lifecycle.test.ts | 49 ++++++ packages/browser/test/live-server.test.ts | 10 +- packages/browser/test/network.test.ts | 113 +++++++------- packages/browser/test/reputation.test.ts | 6 +- packages/browser/test/resources.test.ts | 7 +- packages/browser/test/runtime-lock.test.ts | 16 +- packages/browser/test/settings.test.ts | 6 +- packages/browser/test/vault.test.ts | 135 ++++++++-------- packages/core/src/paths.ts | 3 +- packages/core/src/process.ts | 2 +- packages/core/test/helpers/global-setup.ts | 12 +- packages/core/test/helpers/sandbox.ts | 20 +++ 57 files changed, 1076 insertions(+), 412 deletions(-) create mode 100644 packages/browser/test/helpers/programs.ts diff --git a/packages/browser/src/agent-mcp.ts b/packages/browser/src/agent-mcp.ts index b7dbb65e..d6d75212 100644 --- a/packages/browser/src/agent-mcp.ts +++ b/packages/browser/src/agent-mcp.ts @@ -1,7 +1,7 @@ import { spawn } from "node:child_process"; -import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; -import { basename, dirname, join } from "node:path"; -import { browserPaths, findOnPath } from "turno-core/paths"; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { browserPaths, envValue, findOnPath, replaceFileSync } from "turno-core/paths"; import { identityStateDir } from "./ids.js"; /** @@ -214,7 +214,7 @@ export function isTurnoEntry(e: McpEntry): boolean { if (/^turno-browser(\.exe)?$/i.test(e.command?.split(/[\\/]/).pop() ?? "") && e.args?.[0] === "mcp") return true; return words.some( (w) => - basename(w) === "turno-browser-mcp" || basename(w) === "turno" || /turno-browser[\\/].*bin[\\/]mcp\.js$/.test(w), + /(^|[\\/])(turno-browser-mcp|turno)(\.cmd|\.exe)?$/i.test(w) || /turno-browser[\\/].*bin[\\/]mcp\.js$/.test(w), ); } @@ -289,7 +289,7 @@ export function recordRegistration(id: string, env: NodeJS.ProcessEnv, reg: Regi mkdirSync(identityStateDir(id, env), { recursive: true, mode: 0o700 }); const tmp = `${file}.${process.pid}.tmp`; writeFileSync(tmp, `${JSON.stringify({ version: 1, registrations: [...kept, reg] }, null, 2)}\n`, { mode: 0o600 }); - renameSync(tmp, file); + replaceFileSync(tmp, file); } /** What an agent's own command printed and how it ended. */ @@ -302,6 +302,47 @@ interface ExecResult { /** Runs an agent's command with its output captured; tests replace it. */ export type ExecCommand = (command: string, args: readonly string[], env: NodeJS.ProcessEnv) => Promise; +/** cmd.exe's own characters, escaped with `^` (the rules cross-spawn uses). */ +const CMD_META = /([()\][%!^"`<>&|;, *?])/g; + +/** + * One argument of a line cmd.exe runs a batch file with: quoted for the program's own parser + * (backslashes before a quote doubled), then cmd's characters escaped twice, because cmd reads the + * line once and the batch file's `%*` a second time (npm's shims pass their arguments on that way). + */ +export function cmdArgument(arg: string): string { + const quoted = `"${arg.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, "$1$1")}"`; + return quoted.replace(CMD_META, "^$1").replace(CMD_META, "^$1"); +} + +/** How Node starts a program: the file, its arguments, and whether they go to it as written. */ +export interface SpawnPlan { + file: string; + args: string[]; + /** Node's `windowsVerbatimArguments`: the line is already quoted for cmd.exe. */ + verbatim: boolean; +} + +/** + * How to start `command` by name. On Windows an agent installed with npm is a `.cmd` shim + * (`claude.cmd`), which Node cannot start without a shell, and with `shell: true` it would pass + * the arguments unquoted: the shim found through PATH and PATHEXT runs through cmd.exe with each + * argument quoted and escaped. An `.exe` (or a name not found) starts as it is. + */ +export function spawnPlan( + command: string, + args: readonly string[], + env: NodeJS.ProcessEnv, + platform: NodeJS.Platform = process.platform, +): SpawnPlan { + if (platform !== "win32") return { file: command, args: [...args], verbatim: false }; + const found = findOnPath(command, env, "win32"); + if (!found || !/\.(cmd|bat)$/i.test(found)) return { file: found ?? command, args: [...args], verbatim: false }; + const line = [found.replace(CMD_META, "^$1"), ...args.map(cmdArgument)].join(" "); + const comspec = envValue(env, "ComSpec", "win32") || "cmd.exe"; + return { file: comspec, args: ["/d", "/s", "/c", `"${line}"`], verbatim: true }; +} + /** The default: spawn it, without a shell, for at most a minute. A missing program is code 127. */ export const execCommand: ExecCommand = (command, args, env) => new Promise((resolve) => { @@ -311,7 +352,14 @@ export const execCommand: ExecCommand = (command, args, env) => }; let child: ReturnType; try { - child = spawn(command, [...args], { env, stdio: ["ignore", "pipe", "pipe"], timeout: 60_000 }); + const plan = spawnPlan(command, args, env); + child = spawn(plan.file, plan.args, { + env, + stdio: ["ignore", "pipe", "pipe"], + timeout: 60_000, + windowsVerbatimArguments: plan.verbatim, + windowsHide: true, + }); } catch (err) { resolve({ code: 127, output: (err as Error).message }); return; diff --git a/packages/browser/src/background-state.ts b/packages/browser/src/background-state.ts index 8b140487..4d952c2d 100644 --- a/packages/browser/src/background-state.ts +++ b/packages/browser/src/background-state.ts @@ -1,17 +1,21 @@ +import { createHash } from "node:crypto"; import { readFileSync, rmSync } from "node:fs"; import { join } from "node:path"; import { pidAlive, readProcTable } from "turno-core/process"; import type { IdentityRef } from "./engine.js"; import { IdentityError, identityStateDir } from "./ids.js"; +import { stopCommand } from "./runtime-lock.js"; /** * Where the background server of an identity (`turno-browser-mcp --identity --background`) * says it runs, and the rule it keeps with the other servers of that identity. * * Everything lives in `/browser/identities//background/`, a folder only the user can - * enter (0700): `server.json` (pid, address, version, mode 600), the Unix socket `sock`, or on a - * system without one, `token` (the per-server bearer token of the loopback port, mode 600), and - * `server.log`, where a server started by the client module writes its output. + * enter (0700): `server.json` (pid, address, version, mode 600), the Unix socket `sock`, or when + * no socket can be used, `token` (the per-server bearer token of the loopback port, mode 600), + * and `server.log`, where a server started by the client module writes its output. On Windows + * the socket is a named pipe (`backgroundSocketPath`), which lives in the system's pipe + * namespace instead of the folder. * * The rule: while a background server runs, it is the one owner of the identity's browser. A * stdio server of the same identity refuses every call that would launch the browser, with a @@ -46,8 +50,25 @@ export function backgroundStatePath(id: string, env: NodeJS.ProcessEnv = process return join(backgroundDir(id, env), "server.json"); } -export function backgroundSocketPath(id: string, env: NodeJS.ProcessEnv = process.env): string { - return join(backgroundDir(id, env), "sock"); +/** True for a Windows named pipe path (`\\.\pipe\...`), which is not a file. */ +export function isPipePath(path: string): boolean { + return /^[\\/]{2}[.?][\\/]pipe[\\/]/i.test(path); +} + +/** + * Where the background server listens: the Unix socket `sock` in its private folder, or on + * Windows the named pipe `\\.\pipe\turno-browser--`. The hash is of the folder (in + * lower case, as Windows paths compare), so two users, or two TURNO_STATE_DIRs, never share a + * pipe. A pipe name may be up to 256 characters; an identity id is at most 64. + */ +export function backgroundSocketPath( + id: string, + env: NodeJS.ProcessEnv = process.env, + platform: NodeJS.Platform = process.platform, +): string { + if (platform !== "win32") return join(backgroundDir(id, env), "sock"); + const hash = createHash("sha256").update(backgroundDir(id, env).toLowerCase()).digest("hex").slice(0, 16); + return `\\\\.\\pipe\\turno-browser-${id}-${hash}`; } export function backgroundTokenPath(id: string, env: NodeJS.ProcessEnv = process.env): string { @@ -80,19 +101,23 @@ export function readBackgroundState(id: string, env: NodeJS.ProcessEnv = process /** * True while the state's process runs and, when the process table can be read, is a background - * server (a pid the system gave to another program after a kill is not one). + * server (a pid the system gave to another program after a kill is not one; not checked on + * Windows). */ -export function backgroundAlive(state: BackgroundState): boolean { +export function backgroundAlive(state: BackgroundState, platform: NodeJS.Platform = process.platform): boolean { if (state.pid === process.pid) return true; if (!pidAlive(state.pid)) return false; + // Windows reads command lines through PowerShell, about a second per call: too slow for a + // check that clients make in a loop, so a live pid is taken at its word there. + if (platform === "win32") return true; const command = readProcTable()?.get(state.pid)?.command; return command === undefined || command.includes("--background"); } -/** Removes what a background server that is gone left behind (state, socket, token). */ +/** Removes what a background server that is gone left behind (state, socket, token). A pipe goes with its server. */ export function removeBackgroundFiles(id: string, env: NodeJS.ProcessEnv = process.env): void { for (const file of [backgroundStatePath(id, env), backgroundSocketPath(id, env), backgroundTokenPath(id, env)]) - rmSync(file, { force: true }); + if (!isPipePath(file)) rmSync(file, { force: true }); } /** The running background server of the identity, undefined when none runs (a stale state is removed). */ @@ -116,7 +141,7 @@ function backgroundOwnsMessage(id: string, state: BackgroundState): string { return ( `browser identity "${id}" is served by its background server (pid ${state.pid}) since ${state.startedAt}, ` + `which owns the identity's browser while it runs. Stop it with \`turno-browser background stop ${id}\` ` + - `(or \`kill ${state.pid}\`; it closes its Chrome first)${idle}; ` + + `(or \`${stopCommand(state.pid)}\`; ${process.platform === "win32" ? "that ends its Chrome with it" : "it closes its Chrome first"})${idle}; ` + "then try again." ); } diff --git a/packages/browser/src/background.ts b/packages/browser/src/background.ts index 8b009caa..7a97fd60 100644 --- a/packages/browser/src/background.ts +++ b/packages/browser/src/background.ts @@ -1,5 +1,5 @@ import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto"; -import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { type IncomingMessage, type Server as HttpServer, type ServerResponse, createServer } from "node:http"; import type { AddressInfo } from "node:net"; import { fileURLToPath } from "node:url"; @@ -11,6 +11,7 @@ import { isJSONRPCRequest, isJSONRPCResultResponse, } from "@modelcontextprotocol/sdk/types.js"; +import { replaceFileSync } from "turno-core/paths"; import { pidAlive } from "turno-core/process"; import { type BackgroundState, @@ -19,6 +20,7 @@ import { backgroundSocketPath, backgroundStatePath, backgroundTokenPath, + isPipePath, readBackgroundState, } from "./background-state.js"; import type { IdentityRef } from "./engine.js"; @@ -34,10 +36,12 @@ import { parseDuration } from "./units.js"; * * It serves the identity over MCP streamable HTTP, for shell use without turno's gateway * (`client.ts` starts it, connects and calls tools). Only the user reaches it: a Unix socket in - * a folder only the user can enter, or, where a socket cannot be used (Windows, or a path longer - * than the system allows), a loopback port that asks for a random per-server bearer token kept - * in a file only the user can read. It writes `server.json` (pid, address, version) when it is - * ready and removes it when it exits. + * a folder only the user can enter; on Windows a named pipe, whose default security lets only + * its creator, administrators and the system write to it (everyone else may only read, and + * cannot send a request); or, where neither can be used (a socket path longer than the system + * allows, a pipe name another process took), a loopback port that asks for a random per-server + * bearer token kept in a file only the user can read. It writes `server.json` (pid, address, + * version) when it is ready and removes it when it exits. * * Every connection is one client session, and they all drive the identity's one browser * (`shareHost`), as mcpd's sessions share one stdio server: with `"sharing": "tabs"` each session @@ -47,7 +51,8 @@ import { parseDuration } from "./units.js"; * and processes: a client that sends its `Mcp-Session-Id` again keeps its session and its tab. * * It exits after `idleMs` without a request (default 15 minutes), on SIGTERM, SIGINT and SIGHUP, - * closing Chrome first. Coexistence with the stdio servers of the identity: `background-state.ts`. + * or on a `POST /shutdown` from its client (how `background stop` asks on Windows, which has no + * SIGTERM), closing Chrome first. Coexistence with the stdio servers of the identity: `background-state.ts`. */ /** Exits after this long without a request, unless the flag or TURNO_BROWSER_BACKGROUND_IDLE says otherwise. */ @@ -130,7 +135,7 @@ export interface BackgroundOptions { idleMs: number; /** The identity's sharing mode now (the flag, else identity.json, else "session"). */ sharing: () => SharingMode; - /** "auto" (default): a Unix socket where it can, else loopback with a token. */ + /** "auto" (default): a Unix socket (a named pipe on Windows) where it can, else loopback with a token. */ transport?: "auto" | "socket" | "tcp"; /** With `"sharing": "session"`, how long an idle session keeps the browser. */ leaseMs?: number; @@ -170,7 +175,7 @@ function writeState(file: string, state: BackgroundState, flag: "w" | "wx"): voi } const tmp = `${file}.${process.pid}.tmp`; writeFileSync(tmp, `${JSON.stringify(state)}\n`, { mode: 0o600 }); - renameSync(tmp, file); + replaceFileSync(tmp, file); } /** The private folder of the identity's background server, 0700 even when it existed. */ @@ -223,7 +228,7 @@ function claim(id: string, env: NodeJS.ProcessEnv, idleMs: number): BackgroundSt function socketUsable(path: string, transport: BackgroundOptions["transport"]): boolean { if (transport === "tcp") return false; - const fits = process.platform !== "win32" && Buffer.byteLength(path) <= MAX_SOCKET_PATH; + const fits = isPipePath(path) || Buffer.byteLength(path) <= MAX_SOCKET_PATH; if (transport === "socket" && !fits) throw new BackgroundError(`cannot use a Unix socket at ${path} on this system (path too long or no sockets)`); return fits; @@ -277,7 +282,7 @@ export async function serveBackground(host: Host, options: BackgroundOptions): P const stateFile = backgroundStatePath(id, env); const socketPath = backgroundSocketPath(id, env); const tokenFile = backgroundTokenPath(id, env); - const useSocket = (() => { + const useSocketAtFirst = (() => { try { return socketUsable(socketPath, options.transport); } catch (error) { @@ -285,7 +290,8 @@ export async function serveBackground(host: Host, options: BackgroundOptions): P throw error; } })(); - const token = useSocket ? undefined : randomBytes(32).toString("base64url"); + let useSocket = useSocketAtFirst; + let token = useSocket ? undefined : randomBytes(32).toString("base64url"); const shared: SharedHost = shareHost(host); const sessions = new Map(); @@ -302,7 +308,7 @@ export async function serveBackground(host: Host, options: BackgroundOptions): P const ours = () => readBackgroundState(id, env)?.pid === process.pid; const removeFiles = () => { if (!ours()) return; - rmSync(socketPath, { force: true }); + if (!isPipePath(socketPath)) rmSync(socketPath, { force: true }); rmSync(tokenFile, { force: true }); rmSync(stateFile, { force: true }); }; @@ -412,7 +418,13 @@ export async function serveBackground(host: Host, options: BackgroundOptions): P reply(res, 401, "unauthorized"); return; } - if (new URL(req.url ?? "/", "http://localhost").pathname !== "/mcp") { + const pathname = new URL(req.url ?? "/", "http://localhost").pathname; + if (pathname === "/shutdown" && req.method === "POST") { + res.writeHead(202).end(); + void close("stop requested by its client"); + return; + } + if (pathname !== "/mcp") { reply(res, 404, "not found"); return; } @@ -462,11 +474,21 @@ export async function serveBackground(host: Host, options: BackgroundOptions): P http.requestTimeout = 0; try { - if (useSocket) { + if (useSocket && isPipePath(socketPath)) { + try { + await listen(http, socketPath); + } catch (error) { + // Another process holds the pipe's name: in "auto", the loopback port instead. + if ((error as NodeJS.ErrnoException).code !== "EADDRINUSE" || options.transport === "socket") throw error; + useSocket = false; + token = randomBytes(32).toString("base64url"); + } + } else if (useSocket) { rmSync(socketPath, { force: true }); await listen(http, socketPath); chmodSync(socketPath, 0o600); - } else { + } + if (!useSocket) { await listen(http, { port: 0, host: "127.0.0.1" }); writeFileSync(tokenFile, `${token}\n`, { mode: 0o600 }); chmodSync(tokenFile, 0o600); diff --git a/packages/browser/src/browsers.ts b/packages/browser/src/browsers.ts index 6d65d806..ccad1eca 100644 --- a/packages/browser/src/browsers.ts +++ b/packages/browser/src/browsers.ts @@ -1,12 +1,12 @@ import { execFileSync } from "node:child_process"; -import { existsSync, readFileSync, statSync } from "node:fs"; +import { existsSync, readFileSync, readdirSync, statSync } from "node:fs"; import { createRequire } from "node:module"; -import { dirname, isAbsolute, join } from "node:path"; -import { browserPaths as paths } from "turno-core/paths"; +import { dirname, isAbsolute, join, win32 } from "node:path"; +import { envValue, browserPaths as paths } from "turno-core/paths"; /** * Which Chromium-based browser runs an identity (identity.json `browser`), where each one lives - * on macOS and Linux, and how Playwright launches it. + * on macOS, Linux and Windows, and how Playwright launches it. * * - `chrome` (the default): Google Chrome. * - `edge`: Microsoft Edge. @@ -21,8 +21,10 @@ import { browserPaths as paths } from "turno-core/paths"; * Every browser in the table was launched on a persistent profile through Playwright's pipe, * headed and headless, with the live view's screencast and the agent cursor (see the * browsers section of the identities doc). Arc and Dia are Chromium builds turno could not - * test, so they have no name here: they may work with a path. Windows paths are a later stage; - * a new browser or OS is one more entry in `BROWSERS`. + * test, so they have no name here: they may work with a path. On Windows each browser is looked + * for where its installer puts it: per machine under Program Files (64 and 32 bit), then per + * user under %LOCALAPPDATA%, which needs no admin rights. A new browser or OS is one more entry + * in `BROWSERS`. */ export const BROWSER_IDS = ["chrome", "edge", "brave", "chromium", "chrome-for-testing"] as const; @@ -31,7 +33,23 @@ export type BrowserId = (typeof BROWSER_IDS)[number]; /** identity.json `browser`: one of `BROWSER_IDS`, or the absolute path of a browser's executable. */ export type BrowserChoice = BrowserId | (string & {}); -type Os = "darwin" | "linux"; +type Os = "darwin" | "linux" | "win32"; + +/** The folders a Windows browser installs into, from the environment (with Windows' defaults). */ +interface WindowsDirs { + programFiles: string; + programFilesX86: string; + localAppData: string; +} + +function windowsDirs(env: NodeJS.ProcessEnv, home: string): WindowsDirs { + const get = (name: string) => envValue(env, name, "win32") || undefined; + return { + programFiles: get("ProgramFiles") || "C:\\Program Files", + programFilesX86: get("ProgramFiles(x86)") || "C:\\Program Files (x86)", + localAppData: get("LOCALAPPDATA") || win32.join(home, "AppData", "Local"), + }; +} interface BrowserSpec { id: BrowserId; @@ -41,10 +59,10 @@ interface BrowserSpec { * somewhere else (Chrome in ~/Applications) is launched by path instead. */ channel?: string; - /** Where Playwright's channel looks, per OS. */ + /** Where Playwright's channel looks, per OS. None on Windows, where the found path is launched as is. */ channelPaths?: Partial>; /** Where the browser lives, per OS: system folders first, then the user's own. */ - paths: Partial string[]>>; + paths: Partial string[]>>; } const macApp = (app: string, exe: string) => (home: string) => [ @@ -52,6 +70,12 @@ const macApp = (app: string, exe: string) => (home: string) => [ join(home, "Applications", `${app}.app`, "Contents", "MacOS", exe), ]; +/** A Windows install: Program Files, Program Files (x86), then the per-user one in %LOCALAPPDATA%. */ +const winApp = + (...rel: string[]) => + (_home: string, win: WindowsDirs) => + [win.programFiles, win.programFilesX86, win.localAppData].map((dir) => win32.join(dir, ...rel)); + const BROWSERS: readonly BrowserSpec[] = [ { id: "chrome", @@ -64,6 +88,7 @@ const BROWSERS: readonly BrowserSpec[] = [ paths: { darwin: macApp("Google Chrome", "Google Chrome"), linux: () => ["/opt/google/chrome/chrome", "/usr/bin/google-chrome", "/usr/bin/google-chrome-stable"], + win32: winApp("Google", "Chrome", "Application", "chrome.exe"), }, }, { @@ -77,6 +102,7 @@ const BROWSERS: readonly BrowserSpec[] = [ paths: { darwin: macApp("Microsoft Edge", "Microsoft Edge"), linux: () => ["/opt/microsoft/msedge/msedge", "/usr/bin/microsoft-edge", "/usr/bin/microsoft-edge-stable"], + win32: winApp("Microsoft", "Edge", "Application", "msedge.exe"), }, }, { @@ -85,6 +111,7 @@ const BROWSERS: readonly BrowserSpec[] = [ paths: { darwin: macApp("Brave Browser", "Brave Browser"), linux: () => ["/opt/brave.com/brave/brave", "/usr/bin/brave-browser", "/usr/bin/brave-browser-stable"], + win32: winApp("BraveSoftware", "Brave-Browser", "Application", "brave.exe"), }, }, { @@ -93,6 +120,7 @@ const BROWSERS: readonly BrowserSpec[] = [ paths: { darwin: macApp("Chromium", "Chromium"), linux: () => ["/usr/bin/chromium", "/usr/bin/chromium-browser", "/usr/lib/chromium/chromium"], + win32: winApp("Chromium", "Application", "chrome.exe"), }, }, { @@ -129,7 +157,10 @@ export interface DetectedBrowser { /** What detection reads from the machine; tests give a fake one. */ export interface BrowserProbe { exists(path: string): boolean; - /** The browser's version, from the app's Info.plist on macOS or `--version` elsewhere. */ + /** + * The browser's version: the app's Info.plist on macOS, the version folder next to the + * executable on Windows (`Application\\\\`), `--version` on Linux. + */ version(path: string, platform: NodeJS.Platform): string | undefined; /** True for a launcher that hands over to a snap (Ubuntu's chromium-browser). */ isSnap(path: string): boolean; @@ -145,8 +176,24 @@ export function versionFromPlist(xml: string): string | undefined { return /CFBundleShortVersionString<\/key>\s*([^<]+)<\/string>/.exec(xml)?.[1]?.trim(); } -function readVersion(path: string, platform: NodeJS.Platform): string | undefined { +/** The highest `...` among folder names: the version a Windows install keeps next to its exe. */ +export function versionFromFolders(names: string[]): string | undefined { + const versions = names.filter((n) => /^\d+\.\d+\.\d+\.\d+$/.test(n)); + const key = (v: string) => v.split(".").map(Number); + return versions + .sort((a, b) => { + const [x, y] = [key(a), key(b)]; + for (let i = 0; i < 4; i++) if (x[i] !== y[i]) return x[i]! - y[i]!; + return 0; + }) + .at(-1); +} + +/** The version of the browser at `path` (see `BrowserProbe.version`); never starts a Windows browser. */ +export function readVersion(path: string, platform: NodeJS.Platform = process.platform): string | undefined { try { + // A Windows browser has no --version on the console: it would open a window instead. + if (platform === "win32") return versionFromFolders(readdirSync(dirname(path))); if (platform === "darwin") { const plist = join(dirname(dirname(path)), "Info.plist"); if (existsSync(plist)) return versionFromPlist(readFileSync(plist, "utf8")); @@ -195,7 +242,7 @@ const MACHINE_PROBE: BrowserProbe = { }; function osOf(platform: NodeJS.Platform): Os | undefined { - return platform === "darwin" || platform === "linux" ? platform : undefined; + return platform === "darwin" || platform === "linux" || platform === "win32" ? platform : undefined; } /** The first install of one browser, or undefined. */ @@ -212,8 +259,9 @@ export function findBrowser( path = exe && probe.exists(exe) ? exe : undefined; } else { const os = osOf(platform); - const candidates = os ? (spec.paths[os]?.(paths(env).home) ?? []) : []; - path = candidates.find((p) => probe.exists(p) && !probe.isSnap(p)); + const home = paths(env, platform).home; + const candidates = os ? (spec.paths[os]?.(home, windowsDirs(env, home)) ?? []) : []; + path = candidates.find((p) => probe.exists(p) && (platform === "win32" || !probe.isSnap(p))); } if (!path) return undefined; const version = probe.version(path, platform); diff --git a/packages/browser/src/cli/context.ts b/packages/browser/src/cli/context.ts index b03f3a0b..4c7a2bfe 100644 --- a/packages/browser/src/cli/context.ts +++ b/packages/browser/src/cli/context.ts @@ -91,12 +91,25 @@ export function context(host: BrowserCliHost, deps: CliDeps): Ctx { return { host, names: host.names, deps, api: deps.api }; } -/** `open` on macOS, `xdg-open` elsewhere, detached so the command can exit. */ +/** + * What opens a link in the default browser: `open` on macOS, `xdg-open` on Linux, and on Windows + * the URL handler of the shell, called without cmd.exe so that `&` in a link stays a character. + */ +export function openUrlCommand( + url: string, + platform: NodeJS.Platform = process.platform, +): { command: string; args: string[] } { + if (platform === "darwin") return { command: "open", args: [url] }; + if (platform === "win32") return { command: "rundll32.exe", args: ["url.dll,FileProtocolHandler", url] }; + return { command: "xdg-open", args: [url] }; +} + +/** Opens the link with `openUrlCommand`, detached so the command can exit. */ export const openInBrowser: OpenUrl = async (url, io) => { if (!/^https?:\/\//.test(url)) throw new Error(`refusing to open ${JSON.stringify(url)}: only http(s) links`); - const command = process.platform === "darwin" ? "open" : "xdg-open"; + const { command, args } = openUrlCommand(url); await new Promise((resolve, reject) => { - const child = spawn(command, [url], { stdio: "ignore", env: io.env, detached: true }); + const child = spawn(command, args, { stdio: "ignore", env: io.env, detached: true, windowsHide: true }); child.on("error", reject); child.on("spawn", () => { child.unref(); diff --git a/packages/browser/src/cli/init.ts b/packages/browser/src/cli/init.ts index 0ff71fd4..dbeaa60e 100644 --- a/packages/browser/src/cli/init.ts +++ b/packages/browser/src/cli/init.ts @@ -16,7 +16,7 @@ import { str, } from "turno-core/cli"; import { findOnPath, tildify } from "turno-core/paths"; -import { AGENTS, agentReachable, execCommand, findEntry, recordRegistration } from "../agent-mcp.js"; +import { AGENTS, agentReachable, execCommand, findEntry, recordRegistration, spawnPlan } from "../agent-mcp.js"; import type { Ctx } from "./context.js"; import { describePolicy, readPolicyFile, rehearse } from "./identity.js"; import { loginSummary } from "./login-summary.js"; @@ -86,7 +86,12 @@ export type RunCommand = (command: string, args: readonly string[], io: Io) => P const runCommand: RunCommand = (command, args, io) => new Promise((resolve) => { - const child = spawn(command, [...args], { stdio: "inherit", env: io.env }); + const plan = spawnPlan(command, args, io.env); + const child = spawn(plan.file, plan.args, { + stdio: "inherit", + env: io.env, + windowsVerbatimArguments: plan.verbatim, + }); child.on("error", () => resolve(127)); child.on("exit", (code) => resolve(code ?? 1)); }); diff --git a/packages/browser/src/cli/setup.ts b/packages/browser/src/cli/setup.ts index 0ffe4dc9..f37d44aa 100644 --- a/packages/browser/src/cli/setup.ts +++ b/packages/browser/src/cli/setup.ts @@ -57,13 +57,18 @@ export interface SetupConfig { notes: string[]; } -/** One word for a shell line: as it is when it needs no quotes. */ -function shellWord(word: string): string { +/** + * One word for a shell line: as it is when it needs no quotes; else in single quotes for a POSIX + * shell, or on Windows in double quotes, which cmd.exe and PowerShell both read (a path there + * has no `"` in it). + */ +function shellWord(word: string, platform: NodeJS.Platform): string { + if (platform === "win32") return /^[\w@+=:,./\\-]+$/.test(word) ? word : `"${word.replace(/"/g, '\\"')}"`; return /^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`; } -export function shellLine(words: readonly string[]): string { - return words.map(shellWord).join(" "); +export function shellLine(words: readonly string[], platform: NodeJS.Platform = process.platform): string { + return words.map((w) => shellWord(w, platform)).join(" "); } function json(v: unknown): string { @@ -75,12 +80,22 @@ function json(v: unknown): string { * executable (a Node.js single executable application, with this package inside it) runs * itself as ` mcp`. Otherwise `turno-browser-mcp` when it is on the PATH, else this * install's full path (a `pnpm add` or a local checkout puts it nowhere on the PATH); `onPath` - * is false only then. + * is false only then. On Windows npm installs it as a `.cmd` shim, which an agent can start + * only through cmd.exe (`cmd /c`, as Claude Code's docs say for npx); off the PATH, Node runs + * the script itself. */ -export function mcpCommand(env: NodeJS.ProcessEnv): { command: string; args: string[]; onPath: boolean } { +export function mcpCommand( + env: NodeJS.ProcessEnv, + platform: NodeJS.Platform = process.platform, +): { command: string; args: string[]; onPath: boolean } { if (isSea()) return { command: process.execPath, args: ["mcp"], onPath: true }; - if (findOnPath("turno-browser-mcp", env)) return { command: "turno-browser-mcp", args: [], onPath: true }; - return { command: fileURLToPath(new URL("../bin/mcp.js", import.meta.url)), args: [], onPath: false }; + const onPath = Boolean(findOnPath("turno-browser-mcp", env, platform)); + const script = fileURLToPath(new URL("../bin/mcp.js", import.meta.url)); + if (platform === "win32") + return onPath + ? { command: "cmd", args: ["/c", "turno-browser-mcp"], onPath } + : { command: process.execPath, args: [script], onPath }; + return onPath ? { command: "turno-browser-mcp", args: [], onPath } : { command: script, args: [], onPath }; } /** The config of `agent` for identity `id`, run as `command` with `lead` before `--identity`. */ diff --git a/packages/browser/src/client.ts b/packages/browser/src/client.ts index 25429990..a5c1ac26 100644 --- a/packages/browser/src/client.ts +++ b/packages/browser/src/client.ts @@ -146,7 +146,8 @@ export async function startBackground(id: string, options: StartBackgroundOption const child = spawn( process.execPath, [options.bin ?? defaultBin(), "--identity", id, "--background", ...(options.args ?? [])], - { detached: true, stdio: ["ignore", fd, fd], env, cwd: dir }, + // windowsHide: on Windows a detached child gets a console window of its own otherwise. + { detached: true, stdio: ["ignore", fd, fd], env, cwd: dir, windowsHide: true }, ); child.once("exit", (code, signal) => { exited = code ?? (signal ? -1 : null); @@ -186,21 +187,46 @@ export async function startBackground(id: string, options: StartBackgroundOption } /** - * Stops the identity's background server (SIGTERM: it closes its sessions and Chrome, then - * exits). Resolves true when one ran, false when none did. + * Asks the server to stop over its own transport (`POST /shutdown`). Windows has no SIGTERM: + * `process.kill` there ends the process at once, before it closes Chrome. + */ +async function requestShutdown(state: BackgroundState): Promise { + try { + const signal = AbortSignal.timeout(5000); + const res = + state.transport === "socket" + ? await socketFetch(state.socket!)("http://localhost/shutdown", { method: "POST", signal }) + : await fetch(`http://127.0.0.1:${state.port}/shutdown`, { + method: "POST", + signal, + headers: { Authorization: `Bearer ${readFileSync(state.tokenFile!, "utf8").trim()}` }, + }); + await res.body?.cancel(); + return res.status === 202; + } catch { + return false; + } +} + +/** + * Stops the identity's background server (SIGTERM, on Windows a `POST /shutdown`: it closes its + * sessions and Chrome, then exits). Resolves true when one ran, false when none did. */ export async function stopBackground( id: string, - options: BackgroundClientOptions & { timeoutMs?: number } = {}, + options: BackgroundClientOptions & { timeoutMs?: number; platform?: NodeJS.Platform } = {}, ): Promise { assertIdentityId(id); const env = envOf(options); const state = liveBackground(id, env); if (!state) return false; - try { - process.kill(state.pid, "SIGTERM"); - } catch { - /* exited meanwhile */ + const asked = (options.platform ?? process.platform) === "win32" && state.transport && (await requestShutdown(state)); + if (!asked) { + try { + process.kill(state.pid, "SIGTERM"); + } catch { + /* exited meanwhile */ + } } const deadline = Date.now() + (options.timeoutMs ?? 10_000); while (pidAlive(state.pid) && Date.now() < deadline) await sleep(50); diff --git a/packages/browser/src/destroy.ts b/packages/browser/src/destroy.ts index 03dd7cea..82ee49b4 100644 --- a/packages/browser/src/destroy.ts +++ b/packages/browser/src/destroy.ts @@ -2,7 +2,7 @@ import { execFileSync } from "node:child_process"; import { existsSync, readFileSync, readdirSync, rmSync } from "node:fs"; import { join } from "node:path"; import { browserPaths, turnoRoots } from "turno-core/paths"; -import { type ProcTable, pidAlive, readProcTable, signalProcess } from "turno-core/process"; +import { type ProcTable, killTree, pidAlive, readProcTable, signalProcess } from "turno-core/process"; import { type SecretStore, secretStore } from "turno-core/secrets"; import { AGENTS, @@ -22,7 +22,7 @@ import { flowsDir } from "./flows.js"; import { identityDir, identityStateDir, isValidIdentityId } from "./ids.js"; import { findProfileChrome, stopChrome, usesProfile } from "./lifecycle.js"; import { names } from "./names.js"; -import { readRuntimeLock, runtimeLockAlive } from "./runtime-lock.js"; +import { readRuntimeLock, runtimeLockAlive, stopCommand } from "./runtime-lock.js"; import { exportFiles } from "./session-export.js"; import { identitySettingsPath } from "./settings.js"; import { vaultItem, vaultPath } from "./vault.js"; @@ -241,8 +241,13 @@ function identityServers(table: ProcTable | undefined, id: string, env: NodeJS.P const out: number[] = []; for (const p of table.values()) { if (p.pid === process.pid) continue; - const words = p.command.split(/\s+/); - if (!words.some((w) => /(^|\/)turno-browser-mcp$/.test(w) || /turno-browser\/dist\/bin\/mcp\.js$/.test(w))) + // Windows separates with backslashes and quotes a path with a space in it. + const words = p.command.split(/\s+/).map((w) => w.replace(/^"|"$/g, "")); + if ( + !words.some( + (w) => /(^|[\\/])turno-browser-mcp(\.cmd)?$/i.test(w) || /turno-browser[\\/]dist[\\/]bin[\\/]mcp\.js$/.test(w), + ) + ) continue; const at = words.indexOf("--identity"); const given = at >= 0 ? words[at + 1] : words.find((w) => w.startsWith("--identity="))?.slice(11); @@ -404,9 +409,14 @@ async function stopProcess(id: string, item: RemovalItem, env: NodeJS.ProcessEnv if (chrome && (await stopChrome(chrome, { graceMs })) === "survived") throw new Error(`pid ${pid} did not stop`); return; } - signalProcess(pid, "SIGTERM"); - if (await waitGone(pid, graceMs)) return; - signalProcess(pid, "SIGKILL"); + if (process.platform === "win32") { + // No SIGTERM on Windows: end the server with its tree, its Chrome included. + killTree(pid, true, "win32"); + } else { + signalProcess(pid, "SIGTERM"); + if (await waitGone(pid, graceMs)) return; + signalProcess(pid, "SIGKILL"); + } if (!(await waitGone(pid, 5000))) throw new Error(`pid ${pid} did not stop`); } @@ -513,7 +523,7 @@ export async function runRemoval(plan: RemovalPlan, options: RemovalOptions): Pr what: "a process of the identity", pid: p.pid, reason: "still running", - command: `kill ${p.pid}`, + command: stopCommand(p.pid), }); return { deleted: verified, failed, left, kept, complete: failed.length === 0 && left.length === 0 }; } diff --git a/packages/browser/src/doctor.ts b/packages/browser/src/doctor.ts index d4723a48..59865d79 100644 --- a/packages/browser/src/doctor.ts +++ b/packages/browser/src/doctor.ts @@ -216,6 +216,12 @@ function systemChecks(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): Doctor manual: "run the browser through mcpd, or pass --headless when you start turno-browser-mcp here", }); } + } else if (platform === "win32") { + out.push({ + area: "system", + level: "info", + text: "Windows: Chrome opens in your desktop session, and the background server listens on a named pipe only your user can open", + }); } else if (platform === "linux") { if (env.DISPLAY || env.WAYLAND_DISPLAY) out.push({ @@ -667,7 +673,7 @@ async function networkRows(id: string, env: NodeJS.ProcessEnv, opts: DoctorOptio area, level: "fail", text: "the proxy credentials are in the secret store, and this machine has none", - manual: "install libsecret (secret-tool), or use a proxy without a password", + manual: `${noStoreHint(opts.platform ?? process.platform)}, or use a proxy without a password`, }); return out; } @@ -686,6 +692,13 @@ async function networkRows(id: string, env: NodeJS.ProcessEnv, opts: DoctorOptio return out; } +/** What gives this machine a secret store: libsecret on Linux; on Windows turno-browser has none yet. */ +function noStoreHint(platform: NodeJS.Platform): string { + return platform === "win32" + ? "turno-browser has no secret store on Windows yet: run this identity from macOS or Linux" + : "install libsecret (secret-tool)"; +} + /** Whether the secret store has an item for each credential of the vault: lookups only, never a value. */ async function vaultRows(id: string, env: NodeJS.ProcessEnv, opts: DoctorOptions): Promise { const sites = vaultSummary(id, env)?.sites ?? []; @@ -698,7 +711,7 @@ async function vaultRows(id: string, env: NodeJS.ProcessEnv, opts: DoctorOptions area, level: "fail", text: `the vault has ${sites.length} credential${sites.length === 1 ? "" : "s"} in the secret store, and this machine has none`, - manual: "install libsecret (secret-tool), then add them again with turno browser vault add", + manual: `${noStoreHint(opts.platform ?? process.platform)}, then add them again with turno browser vault add`, }, ]; const missing: string[] = []; @@ -832,8 +845,7 @@ async function collect( level: "fail", text: "Google Chrome not found, and no other Chromium-based browser (Edge, Brave, Chromium, Chrome for Testing)", fix: "turno browser install-browser", - manual: - "turno browser install-browser downloads Chrome for Testing into your user cache with no admin password; or install Google Chrome (https://www.google.com/chrome/)", + manual: `turno browser install-browser downloads Chrome for Testing into your user cache with no admin password; or install Google Chrome (https://www.google.com/chrome/)${platform === "win32" ? ", or with winget for your user alone: winget install --id Google.Chrome.EXE --scope user" : ""}`, }); // The test launch uses Chrome, or the first other browser when Chrome is missing. const first = others[0]; diff --git a/packages/browser/src/engine-attach.ts b/packages/browser/src/engine-attach.ts index 9e163d90..4224b4c6 100644 --- a/packages/browser/src/engine-attach.ts +++ b/packages/browser/src/engine-attach.ts @@ -2,7 +2,7 @@ import { readFileSync } from "node:fs"; import { isAbsolute, join } from "node:path"; import { setTimeout as delay } from "node:timers/promises"; import type { Browser, Page } from "patchright-core"; -import { browserPaths as paths } from "turno-core/paths"; +import { envValue, browserPaths as paths } from "turno-core/paths"; import type { Engine, LaunchedBrowser } from "./engine.js"; import { IdleTimer, idleMs } from "./idle-timer.js"; import { playwright, upstream } from "./upstream.js"; @@ -74,7 +74,12 @@ export function defaultChromeUserDataDir( const home = paths(env).home; if (platform === "darwin") return join(home, "Library", "Application Support", "Google", "Chrome"); if (platform === "win32") - return join(env.LOCALAPPDATA ?? join(home, "AppData", "Local"), "Google", "Chrome", "User Data"); + return join( + envValue(env, "LOCALAPPDATA", "win32") || join(home, "AppData", "Local"), + "Google", + "Chrome", + "User Data", + ); return join(env.XDG_CONFIG_HOME || join(home, ".config"), "google-chrome"); } diff --git a/packages/browser/src/engine-camoufox.ts b/packages/browser/src/engine-camoufox.ts index 96a18d46..653b2bd9 100644 --- a/packages/browser/src/engine-camoufox.ts +++ b/packages/browser/src/engine-camoufox.ts @@ -61,7 +61,7 @@ export function camoufoxRefusal(tool: string): string | undefined { /** How to install Camoufox, for errors and `turno browser doctor`. */ export function camoufoxInstallHint(platform: NodeJS.Platform = process.platform): string { if (platform === "win32") - return "pip install -U camoufox, then camoufox fetch (turno-browser does not run on Windows; use WSL)"; + return "pip install -U camoufox, then camoufox fetch, then set TURNO_CAMOUFOX_PATH to the camoufox.exe it downloaded"; return "pip install -U camoufox && camoufox fetch (then set TURNO_CAMOUFOX_PATH if turno does not find it)"; } diff --git a/packages/browser/src/flows.ts b/packages/browser/src/flows.ts index 13cc1c68..0dc4aeb7 100644 --- a/packages/browser/src/flows.ts +++ b/packages/browser/src/flows.ts @@ -1,6 +1,6 @@ -import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; import { join } from "node:path"; -import { browserPaths as paths } from "turno-core/paths"; +import { browserPaths as paths, replaceFileSync } from "turno-core/paths"; import { assertIdentityId } from "./ids.js"; /** @@ -268,7 +268,7 @@ export function writeFlow(id: string, flow: Flow, env: NodeJS.ProcessEnv = proce mkdirSync(flowsDir(id, env), { recursive: true, mode: 0o700 }); const tmp = `${path}.${process.pid}.tmp`; writeFileSync(tmp, `${JSON.stringify(flow, null, 2)}\n`, { mode: 0o600 }); - renameSync(tmp, path); + replaceFileSync(tmp, path); return path; } diff --git a/packages/browser/src/health.ts b/packages/browser/src/health.ts index d01c22ea..a8eb0e89 100644 --- a/packages/browser/src/health.ts +++ b/packages/browser/src/health.ts @@ -1,5 +1,6 @@ -import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; +import { replaceFileSync } from "turno-core/paths"; import { identityStateDir } from "./ids.js"; import type { HealthCheck } from "./settings.js"; import { names } from "./names.js"; @@ -55,7 +56,7 @@ export function writeHealth(id: string, env: NodeJS.ProcessEnv, record: HealthRe mkdirSync(identityStateDir(id, env), { recursive: true, mode: 0o700 }); const tmp = `${file}.${process.pid}.tmp`; writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 }); - renameSync(tmp, file); + replaceFileSync(tmp, file); } /** Forget the last result (after a login), so the next launch checks again. */ diff --git a/packages/browser/src/identities.ts b/packages/browser/src/identities.ts index d633b21e..3c7048fa 100644 --- a/packages/browser/src/identities.ts +++ b/packages/browser/src/identities.ts @@ -1,4 +1,4 @@ -import { existsSync, mkdirSync, readdirSync, readlinkSync, rmSync, statSync } from "node:fs"; +import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readlinkSync, rmSync, statSync } from "node:fs"; import { join } from "node:path"; import { browserPaths as paths } from "turno-core/paths"; import { pidAlive } from "turno-core/process"; @@ -107,9 +107,27 @@ export function inUseBy(id: string, env: NodeJS.ProcessEnv = process.env): strin return lock && runtimeLockAlive(lock) ? inUseMessage(id, lock) : undefined; } +/** + * True while a Chrome holds the profile on Windows: it keeps `lockfile` open without sharing it + * and deletes it when it exits (the check Playwright makes before a launch there). + */ +export function windowsProfileLocked(userDataDir: string): boolean { + try { + closeSync(openSync(join(userDataDir, "lockfile"), "r+")); + return false; + } catch (err) { + return (err as NodeJS.ErrnoException).code !== "ENOENT"; + } +} + /** True when a live process holds the identity's runtime lock or its Chrome profile. */ -export function isInUse(id: string, env: NodeJS.ProcessEnv = process.env): boolean { +export function isInUse( + id: string, + env: NodeJS.ProcessEnv = process.env, + platform: NodeJS.Platform = process.platform, +): boolean { if (inUseBy(id, env)) return true; + if (platform === "win32") return windowsProfileLocked(identityDir(id, env)); let target: string; try { target = readlinkSync(join(identityDir(id, env), "SingletonLock")); diff --git a/packages/browser/src/last-used.ts b/packages/browser/src/last-used.ts index 0ae90c4e..92784ea6 100644 --- a/packages/browser/src/last-used.ts +++ b/packages/browser/src/last-used.ts @@ -1,5 +1,6 @@ -import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; +import { replaceFileSync } from "turno-core/paths"; import { identityStateDir } from "./ids.js"; /** @@ -30,7 +31,7 @@ export function touchLastUsed(id: string, env: NodeJS.ProcessEnv = process.env, mkdirSync(identityStateDir(id, env), { recursive: true, mode: 0o700 }); const tmp = `${file}.${process.pid}.tmp`; writeFileSync(tmp, `${JSON.stringify({ at: now.toISOString() })}\n`, { mode: 0o600 }); - renameSync(tmp, file); + replaceFileSync(tmp, file); } catch { /* a hint only */ } diff --git a/packages/browser/src/lifecycle.ts b/packages/browser/src/lifecycle.ts index d49ac080..e39f4bfe 100644 --- a/packages/browser/src/lifecycle.ts +++ b/packages/browser/src/lifecycle.ts @@ -2,12 +2,13 @@ import { readlinkSync, realpathSync } from "node:fs"; import { join } from "node:path"; import { type ProcTable, + killTree, parentIsInit, pidAlive as processAlive, readProcTable, signalProcess as sendSignal, } from "turno-core/process"; -import { parseSingletonLock } from "./identities.js"; +import { parseSingletonLock, windowsProfileLocked } from "./identities.js"; /** * The life of the Chrome behind one profile. @@ -24,11 +25,19 @@ import { parseSingletonLock } from "./identities.js"; * signal arrives the program closes the browser gracefully, and if that has not finished in * time Chrome gets SIGTERM and then the whole group SIGKILL, inside the 4 seconds the MCP SDK * gives a server before it kills it. + * + * Windows has neither process groups nor a PID in the profile lock: Chrome holds `lockfile` in + * the profile open (and deletes it when it exits), the process table comes from PowerShell, and + * a Chrome is ended with its helpers by `taskkill /T`, which is never graceful for a headless + * one. Node's own `process.kill` there terminates at once, whatever the signal. */ export { type ProcTable, parseProcTable } from "turno-core/process"; -/** The PID in the profile's `SingletonLock` (`-`), if there is one. */ +/** + * The PID in the profile's `SingletonLock` (`-`), if there is one. Windows' lock names + * no PID, so there it is always undefined. + */ export function readLockPid(userDataDir: string): number | undefined { try { return parseSingletonLock(readlinkSync(join(userDataDir, "SingletonLock"))); @@ -53,7 +62,8 @@ export function usesProfile(command: string, userDataDir: string): boolean { const flag = `--user-data-dir=${dir}`; for (let i = command.indexOf(flag); i >= 0; i = command.indexOf(flag, i + 1)) { const end = i + flag.length; - if (end === command.length || command[end] === " ") return true; + // Windows quotes an argument with a space in it: "--user-data-dir=C:\Users\a b\p". + if (end === command.length || command[end] === " " || command[end] === '"') return true; } } return false; @@ -86,6 +96,24 @@ export interface FindOptions { alive?: Alive; /** The PID that counts as "self" (default: this process). */ selfPid?: number; + platform?: NodeJS.Platform; + /** Windows: whether a Chrome holds the profile's `lockfile` (default: `windowsProfileLocked`). */ + locked?: (userDataDir: string) => boolean; +} + +/** + * Windows: the browser process for this profile from the process table, while a Chrome holds + * the profile's lockfile. A parent that is not in the table has exited: the Chrome is an orphan. + */ +function findWindowsProfileChrome(userDataDir: string, opts: FindOptions): ProfileChrome | undefined { + if (!(opts.locked ?? windowsProfileLocked)(userDataDir)) return undefined; + const table = opts.table ?? (opts.readTable ?? (() => readProcTable("win32")))(); + if (!table) return undefined; + const self = opts.selfPid ?? process.pid; + const leader = [...table.values()].find((p) => usesProfile(p.command, userDataDir) && isBrowserProcess(p.command)); + if (!leader) return undefined; + const owner: ChromeOwner = leader.ppid === self ? "self" : parentIsInit(leader.ppid, table) ? "orphan" : "other"; + return { pid: leader.pid, pgid: leader.pid, leaderAlive: true, owner }; } /** @@ -94,6 +122,7 @@ export interface FindOptions { * lock points at some other program (a reused PID). */ export function findProfileChrome(userDataDir: string, opts: FindOptions = {}): ProfileChrome | undefined { + if ((opts.platform ?? process.platform) === "win32") return findWindowsProfileChrome(userDataDir, opts); const pid = readLockPid(userDataDir); if (pid === undefined) return undefined; const alive = opts.alive ?? processAlive; @@ -130,6 +159,9 @@ export interface StopOptions { killMs?: number; signal?: Signal; alive?: Alive; + platform?: NodeJS.Platform; + /** Windows: ends a process tree (default: turno-core's `killTree`). */ + killTree?: (pid: number, force: boolean) => void; } async function waitUntil(cond: () => boolean, ms: number): Promise { @@ -153,6 +185,16 @@ export async function stopChrome( ): Promise<"exited" | "killed" | "survived"> { const signal = opts.signal ?? sendSignal; const alive = opts.alive ?? processAlive; + if ((opts.platform ?? process.platform) === "win32") { + // No signal to ask for a clean exit: close the windows of the tree (a headed Chrome saves + // and quits), then end the tree. + const kill = opts.killTree ?? ((pid: number, force: boolean) => void killTree(pid, force, "win32")); + const gone = () => !alive(target.pid); + kill(target.pid, false); + if (await waitUntil(gone, opts.graceMs ?? 3000)) return "exited"; + kill(target.pid, true); + return (await waitUntil(gone, opts.killMs ?? KILL_WAIT_MS)) ? "killed" : "survived"; + } const leadsGroup = target.pgid === target.pid; const handle = leadsGroup ? -target.pid : target.pid; const gone = () => !alive(handle); @@ -177,6 +219,7 @@ export async function sweepOrphan(userDataDir: string, opts: FindOptions & StopO } export interface ShutdownOptions { + platform?: NodeJS.Platform; /** Time the program gets to close the browser gracefully before Chrome gets SIGTERM. */ graceMs?: number; /** Time Chrome gets after SIGTERM before this process exits and its group gets SIGKILL. */ @@ -196,8 +239,9 @@ export interface ShutdownOptions { export function installShutdownGuard(userDataDir: string, opts: ShutdownOptions = {}): void { const graceMs = opts.graceMs ?? 1500; const termMs = opts.termMs ?? 1000; + const windows = (opts.platform ?? process.platform) === "win32"; const ours = () => { - const c = findProfileChrome(userDataDir); + const c = findProfileChrome(userDataDir, windows ? { platform: "win32" } : {}); return c && c.owner !== "other" ? c : undefined; }; let started = false; @@ -206,7 +250,8 @@ export function installShutdownGuard(userDataDir: string, opts: ShutdownOptions started = true; setTimeout(() => { const c = ours(); - if (c?.leaderAlive) sendSignal(c.pid, "SIGTERM"); + // Windows has no SIGTERM to give Chrome: the exit handler ends its tree. + if (c?.leaderAlive && !windows) sendSignal(c.pid, "SIGTERM"); setTimeout(() => process.exit(0), termMs).unref(); }, graceMs).unref(); }; @@ -215,10 +260,14 @@ export function installShutdownGuard(userDataDir: string, opts: ShutdownOptions process.on("SIGINT", begin); process.on("SIGHUP", () => { begin(); - process.kill(process.pid, "SIGTERM"); + // On Windows (the console window closed) process.kill would end this process at once. + if (windows) process.emit("SIGTERM", "SIGTERM"); + else process.kill(process.pid, "SIGTERM"); }); process.on("exit", () => { const c = ours(); - if (c) sendSignal(c.pgid === c.pid ? -c.pid : c.pid, "SIGKILL"); + if (!c) return; + if (windows) killTree(c.pid, true, "win32"); + else sendSignal(c.pgid === c.pid ? -c.pid : c.pid, "SIGKILL"); }); } diff --git a/packages/browser/src/live-server.ts b/packages/browser/src/live-server.ts index eec6838d..997df823 100644 --- a/packages/browser/src/live-server.ts +++ b/packages/browser/src/live-server.ts @@ -1,9 +1,10 @@ import { randomBytes, timingSafeEqual } from "node:crypto"; -import { chmodSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { type IncomingMessage, type Server, type ServerResponse, createServer } from "node:http"; import type { AddressInfo } from "node:net"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; +import { replaceFileSync } from "turno-core/paths"; import type { BrowserContext, CDPSession, Page } from "patchright-core"; import type { IdentityRef } from "./engine.js"; import { type LiveFile, type LivePolicy, PauseGate, type PauseHold, type TabState, liveFilePath } from "./live.js"; @@ -23,8 +24,10 @@ import { type BrowserWatch, titleOf } from "./watch.js"; * and for two minutes. Every request must name the server by its loopback Host (DNS * rebinding), and every POST must come from the view's own origin with its header. * - `turno browser live|pause|resume` talk to the server over a Unix socket in a private - * folder (mode 700, socket 600): the file system is the access check there. Where to find - * both is in `/browser/identities//live.json`, without any secret. + * folder (mode 700, socket 600): the file system is the access check there. On Windows it is + * a named pipe with a random name, which by default only its creator, administrators and the + * system can write to. Where to find both is in `/browser/identities//live.json`, + * without any secret. * - The picture is a CDP screencast of one tab (the one the agent used last, or the one the * user picked), taken only while a view is open. A frame of a page that holds a vault or * sensitive value (the vault guard: a `browser_login` fill, a password typed) is never sent; @@ -192,6 +195,7 @@ export class LiveServer implements BrowserWatch { private unix: Server | undefined; private port = 0; private socketDir: string | undefined; + private pipe: string | undefined; private started = ""; private queued = false; private heartbeat: NodeJS.Timeout | undefined; @@ -219,7 +223,7 @@ export class LiveServer implements BrowserWatch { /** The control socket path (tests). */ get socket(): string | undefined { - return this.socketDir && join(this.socketDir, "control.sock"); + return this.pipe ?? (this.socketDir && join(this.socketDir, "control.sock")); } private get cookieName(): string { @@ -235,12 +239,15 @@ export class LiveServer implements BrowserWatch { } private async listenAll(): Promise { - this.socketDir = mkdtempSync(join(tmpdir(), "turno-live-")); - chmodSync(this.socketDir, 0o700); + if (process.platform === "win32") this.pipe = `\\\\.\\pipe\\turno-live-${randomBytes(12).toString("hex")}`; + else { + this.socketDir = mkdtempSync(join(tmpdir(), "turno-live-")); + chmodSync(this.socketDir, 0o700); + } const socket = this.socket!; this.unix = createServer((req, res) => void this.handle(req, res, true)); await listen(this.unix, socket); - chmodSync(socket, 0o600); + if (!this.pipe) chmodSync(socket, 0o600); this.tcp = createServer((req, res) => void this.handle(req, res, false)); await listen(this.tcp, 0, "127.0.0.1"); this.port = (this.tcp.address() as AddressInfo).port; @@ -253,7 +260,7 @@ export class LiveServer implements BrowserWatch { const data: LiveFile = { version: 1, pid: process.pid, socket, port: this.port, started: this.started }; const tmp = `${file}.${process.pid}.tmp`; writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 }); - renameSync(tmp, file); + replaceFileSync(tmp, file); process.once("exit", this.onExit); this.heartbeat = setInterval(() => { for (const v of this.viewers) v.write(": ping\n\n"); diff --git a/packages/browser/src/login.ts b/packages/browser/src/login.ts index 24ad9300..c9e5e3e0 100644 --- a/packages/browser/src/login.ts +++ b/packages/browser/src/login.ts @@ -1,5 +1,6 @@ -import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; +import { replaceFileSync } from "turno-core/paths"; import { identityBrowserLaunch } from "./browsers.js"; import { clearHealth } from "./health.js"; import { identityStateDir } from "./ids.js"; @@ -58,7 +59,7 @@ function writeLoginRecord(id: string, env: NodeJS.ProcessEnv, record: LoginRecor mkdirSync(identityStateDir(id, env), { recursive: true, mode: 0o700 }); const tmp = `${file}.${process.pid}.tmp`; writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 }); - renameSync(tmp, file); + replaceFileSync(tmp, file); } /** The host of a page the person opened, without "www."; undefined for blank and internal pages. */ diff --git a/packages/browser/src/network-chrome.ts b/packages/browser/src/network-chrome.ts index 93411e64..dfa73198 100644 --- a/packages/browser/src/network-chrome.ts +++ b/packages/browser/src/network-chrome.ts @@ -1,9 +1,8 @@ -import { execFileSync } from "node:child_process"; import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import type { BrowserContext, Page } from "patchright-core"; import { PRIVATE_DIR_MODE, PRIVATE_FILE_MODE, browserPaths as paths } from "turno-core/paths"; -import { findBrowser } from "./browsers.js"; +import { findBrowser, readVersion } from "./browsers.js"; import { findChrome } from "./doctor.js"; import { CHROME_PROXY_ARGS, @@ -132,15 +131,7 @@ const hasArg = (args: readonly string[], flag: string) => args.some((a) => a === /** The installed Chrome's version, for the user agent string a headless Chrome needs. */ function chromeVersion(config: McpConfig, env: NodeJS.ProcessEnv): string | undefined { const exe = config.browser.launchOptions.executablePath; - if (typeof exe === "string") { - try { - return /(\d+\.\d+\.\d+\.\d+)/.exec( - execFileSync(exe, ["--version"], { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"] }), - )?.[1]; - } catch { - return undefined; - } - } + if (typeof exe === "string") return readVersion(exe); const channel = config.browser.launchOptions.channel ?? "chrome"; if (channel === "chrome-for-testing") return findBrowser("chrome-for-testing", env)?.version; return channel === "chrome" ? findChrome(env)?.version : undefined; diff --git a/packages/browser/src/recordings.ts b/packages/browser/src/recordings.ts index 5f050add..cb155faf 100644 --- a/packages/browser/src/recordings.ts +++ b/packages/browser/src/recordings.ts @@ -1,8 +1,9 @@ import { spawn } from "node:child_process"; -import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; import { createRequire } from "node:module"; import { dirname, join } from "node:path"; import { inflateRawSync } from "node:zlib"; +import { replaceFileSync } from "turno-core/paths"; import type { BrowserContext, Page } from "patchright-core"; import type { IdentityRef } from "./engine.js"; import { identityStateDir } from "./ids.js"; @@ -360,7 +361,7 @@ export class Recording { const file = join(this.dir, INDEX); const tmp = `${file}.${process.pid}.tmp`; writeFileSync(tmp, `${JSON.stringify(this.index, null, 2)}\n`, { mode: 0o600 }); - renameSync(tmp, file); + replaceFileSync(tmp, file); } catch { /* best effort: a full disk must not break a tool call */ } diff --git a/packages/browser/src/runtime-lock.ts b/packages/browser/src/runtime-lock.ts index 4609d0d9..0788df6c 100644 --- a/packages/browser/src/runtime-lock.ts +++ b/packages/browser/src/runtime-lock.ts @@ -1,5 +1,6 @@ -import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; +import { replaceFileSync } from "turno-core/paths"; import { pidAlive } from "turno-core/process"; import { IdentityError, identityStateDir } from "./ids.js"; import { names } from "./names.js"; @@ -83,8 +84,16 @@ export function runtimeLockAlive(lock: RuntimeLock): boolean { return pidAlive(lock.nodePid); } +/** + * The command that stops a turno-browser-mcp, for messages: `kill ` (SIGTERM: it closes its + * Chrome first), or on Windows, which has no SIGTERM, `taskkill` of its tree (its Chrome with it). + */ +export function stopCommand(pid: number, platform: NodeJS.Platform = process.platform): string { + return platform === "win32" ? `taskkill /PID ${pid} /T /F` : `kill ${pid}`; +} + /** Who holds the identity and how to get it back, for errors and `turno browser doctor`. */ -export function inUseMessage(id: string, lock: RuntimeLock): string { +export function inUseMessage(id: string, lock: RuntimeLock, platform: NodeJS.Platform = process.platform): string { const pids = `pid ${lock.nodePid}${lock.chromePid ? `, Chrome pid ${lock.chromePid}` : ""}`; if (lock.holder === "login") { return `browser identity "${id}" is in use by ${names().browser} login (${pids}) since ${lock.startedAt}. Close that Chrome window to finish the login, then try again.`; @@ -95,14 +104,14 @@ export function inUseMessage(id: string, lock: RuntimeLock): string { return ( `browser identity "${id}" is in use by turno-browser-mcp (${pids}) since ${lock.startedAt}. ` + "One identity drives one Chrome at a time: wait for that session to end (mcpd stops the server after its lease or idle time), " + - `or stop it now with \`kill ${lock.nodePid}\`, which closes its Chrome first.` + `or stop it now with \`${stopCommand(lock.nodePid, platform)}\`, ${platform === "win32" ? "which ends its Chrome with it" : "which closes its Chrome first"}.` ); } function writeAtomic(file: string, lock: RuntimeLock): void { const tmp = `${file}.${process.pid}.tmp`; writeFileSync(tmp, `${JSON.stringify(lock)}\n`, { mode: 0o600 }); - renameSync(tmp, file); + replaceFileSync(tmp, file); } /** Locks this process holds, released on exit (sync: an exit handler cannot wait). */ diff --git a/packages/browser/src/session-export.ts b/packages/browser/src/session-export.ts index a696710b..e1452b5b 100644 --- a/packages/browser/src/session-export.ts +++ b/packages/browser/src/session-export.ts @@ -1,5 +1,6 @@ -import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; +import { replaceFileSync } from "turno-core/paths"; import type { BrowserContext } from "patchright-core"; import { identityBrowserLaunch } from "./browsers.js"; import { clearHealth } from "./health.js"; @@ -281,7 +282,7 @@ export function recordExportFile(id: string, file: string, env: NodeJS.ProcessEn mkdirSync(identityStateDir(id, env), { recursive: true, mode: 0o700 }); const tmp = `${record}.${process.pid}.tmp`; writeFileSync(tmp, `${JSON.stringify({ version: 1, files }, null, 2)}\n`, { mode: 0o600 }); - renameSync(tmp, record); + replaceFileSync(tmp, record); } /** diff --git a/packages/browser/src/settings.ts b/packages/browser/src/settings.ts index 77cbaaab..21b52599 100644 --- a/packages/browser/src/settings.ts +++ b/packages/browser/src/settings.ts @@ -1,6 +1,6 @@ -import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; -import { browserPaths as paths } from "turno-core/paths"; +import { browserPaths as paths, replaceFileSync } from "turno-core/paths"; import { type ActSettings, type CaptchaSettings, actProblems, captchaProblems } from "./opt-in-settings.js"; import { parseAttachTarget } from "./engine-attach.js"; import { IdentityError, assertIdentityId } from "./ids.js"; @@ -714,7 +714,7 @@ export function writeIdentitySettings( mkdirSync(dirname(path), { recursive: true, mode: 0o700 }); const tmp = `${path}.${process.pid}.tmp`; writeFileSync(tmp, `${JSON.stringify(ordered, null, 2)}\n`, { mode: 0o600 }); - renameSync(tmp, path); + replaceFileSync(tmp, path); return ordered; } diff --git a/packages/browser/src/vault.ts b/packages/browser/src/vault.ts index 5a00d30e..979d83d3 100644 --- a/packages/browser/src/vault.ts +++ b/packages/browser/src/vault.ts @@ -1,6 +1,6 @@ -import { readFileSync, renameSync, rmSync, statSync } from "node:fs"; +import { readFileSync, rmSync, statSync } from "node:fs"; import { join } from "node:path"; -import { browserPaths, writePrivateFile } from "turno-core/paths"; +import { browserPaths, writePrivateFile, replaceFileSync } from "turno-core/paths"; import { type SecretStore, requireSecretStore } from "turno-core/secrets"; import { IdentityError, assertIdentityId, identityDir } from "./ids.js"; import { type TotpParams, parseTotpSecret } from "./totp.js"; @@ -149,7 +149,7 @@ function writeIndex(id: string, index: VaultIndex, env: NodeJS.ProcessEnv): void ); const tmp = `${file}.${process.pid}.tmp`; writePrivateFile(tmp, `${JSON.stringify({ version: 1, submit: index.submit, sites }, null, 2)}\n`, env); - renameSync(tmp, file); + replaceFileSync(tmp, file); } function storeOf(options: VaultOptions): SecretStore { diff --git a/packages/browser/test/argv.test.ts b/packages/browser/test/argv.test.ts index 5e053c30..ce135cff 100644 --- a/packages/browser/test/argv.test.ts +++ b/packages/browser/test/argv.test.ts @@ -18,9 +18,9 @@ describe("buildArgv", () => { "--browser", "chrome", "--user-data-dir", - "/tmp/turno-browser-test/profile", + join("/tmp/turno-browser-test", "profile"), "--config", - "/tmp/turno-browser-test/mcp-config.json", + join("/tmp/turno-browser-test", "mcp-config.json"), ]); expect(b.tempDir).toBe("/tmp/turno-browser-test"); expect(b.identity).toBeUndefined(); @@ -99,7 +99,7 @@ describe("buildArgv", () => { "--browser", "chrome", "--config", - "/tmp/turno-browser-test/mcp-config.json", + join("/tmp/turno-browser-test", "mcp-config.json"), ]); expect(b.userDataDir).toBeUndefined(); expect(b.tempDir).toBe("/tmp/turno-browser-test"); diff --git a/packages/browser/test/background.test.ts b/packages/browser/test/background.test.ts index 3e01042e..58ae2272 100644 --- a/packages/browser/test/background.test.ts +++ b/packages/browser/test/background.test.ts @@ -1,14 +1,5 @@ import { type ChildProcess, spawn } from "node:child_process"; -import { - existsSync, - mkdirSync, - mkdtempSync, - readFileSync, - realpathSync, - rmSync, - statSync, - writeFileSync, -} from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; @@ -26,6 +17,7 @@ import { backgroundStatePath, backgroundTokenPath, readBackgroundState, + isPipePath, } from "../src/background-state.js"; import { BackgroundError, @@ -43,7 +35,7 @@ import { upstream } from "../src/upstream.js"; import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { alive, waitFor } from "./helpers/chrome.js"; -import { type Sandbox, sandbox } from "./helpers/sandbox.js"; +import { type Sandbox, sandbox, expectMode } from "./helpers/sandbox.js"; /** * The background server of an identity (`--background`) and its client: in process with a fake @@ -82,10 +74,6 @@ function textOf(res: unknown): string { return ((res as { content: { text?: string }[] }).content ?? []).map((c) => c.text ?? "").join("\n"); } -function mode(file: string): number { - return statSync(file).mode & 0o777; -} - /** A test tool that reports the client session the host gave the call. */ function sessionTool(wait?: () => Promise): TurnoTool { const z = turnoZod(); @@ -202,9 +190,9 @@ describe("the background server in process", () => { expect(server.state).toMatchObject({ v: 1, pid: process.pid, identity: ID, transport: "socket" }); expect(server.state.socket).toBe(backgroundSocketPath(ID, env)); expect(readBackgroundState(ID, env)).toEqual(server.state); - expect(mode(backgroundDir(ID, env))).toBe(0o700); - expect(mode(backgroundStatePath(ID, env))).toBe(0o600); - expect(mode(backgroundSocketPath(ID, env))).toBe(0o600); + expectMode(backgroundDir(ID, env), 0o700); + expectMode(backgroundStatePath(ID, env), 0o600); + expectMode(backgroundSocketPath(ID, env), 0o600); expect(existsSync(backgroundTokenPath(ID, env))).toBe(false); const s = await openBackgroundSession(ID, { env, start: false }); @@ -328,7 +316,7 @@ describe("the background server in process", () => { it("on loopback, asks for the token in a 0600 file and checks the Host header", async () => { const server = await startInProcess({ transport: "tcp" }); expect(server.state).toMatchObject({ transport: "tcp", tokenFile: backgroundTokenPath(ID, env) }); - expect(mode(backgroundTokenPath(ID, env))).toBe(0o600); + expectMode(backgroundTokenPath(ID, env), 0o600); const token = readFileSync(backgroundTokenPath(ID, env), "utf8").trim(); expect(token.length).toBeGreaterThanOrEqual(40); expect(JSON.stringify(readBackgroundState(ID, env))).not.toContain(token); @@ -450,7 +438,7 @@ describe("the background server as a program, through the client", () => { expect(first.state).toMatchObject({ identity: ID, transport: "socket" }); expect(first.state.pid).not.toBe(process.pid); expect(alive(first.state.pid)).toBe(true); - expect(mode(backgroundLogPath(ID, env))).toBe(0o600); + expectMode(backgroundLogPath(ID, env), 0o600); const second = await startBackground(ID, { env, bin }); expect(second).toEqual({ state: first.state, started: false }); @@ -544,3 +532,16 @@ describe("the background server as a program, through the client", () => { expect(err).toContain("--background needs --identity "); }); }); + +describe("where the background server listens on Windows", () => { + it("is a named pipe per identity and state folder, never a file", () => { + const env = { USERPROFILE: "C:\\Users\\a", LOCALAPPDATA: "C:\\Users\\a\\AppData\\Local" }; + const pipe = backgroundSocketPath("work", env, "win32"); + expect(pipe).toMatch(/^\\\\\.\\pipe\\turno-browser-work-[0-9a-f]{16}$/); + expect(isPipePath(pipe)).toBe(true); + expect(backgroundSocketPath("work", env, "win32")).toBe(pipe); + expect(backgroundSocketPath("work", { ...env, TURNO_STATE_DIR: "D:\\turno" }, "win32")).not.toBe(pipe); + expect(backgroundSocketPath("home", env, "win32")).not.toBe(pipe.replace("-work-", "-home-")); + expect(isPipePath(backgroundSocketPath("work", { HOME: "/home/a" }, "linux"))).toBe(false); + }); +}); diff --git a/packages/browser/test/browser-tools.test.ts b/packages/browser/test/browser-tools.test.ts index 67148121..6c748871 100644 --- a/packages/browser/test/browser-tools.test.ts +++ b/packages/browser/test/browser-tools.test.ts @@ -1,6 +1,6 @@ import { writeFileSync } from "node:fs"; import { type Server, createServer } from "node:http"; -import { readdirSync, statSync } from "node:fs"; +import { readdirSync } from "node:fs"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; @@ -10,7 +10,7 @@ import { POPUP_GRACE_MS } from "../src/governor.js"; import { identityStateDir } from "../src/ids.js"; import { writeIdentitySettings } from "../src/settings.js"; import { chromeUnavailable, stopSandboxProcesses } from "./helpers/chrome.js"; -import { type Sandbox, sandbox } from "./helpers/sandbox.js"; +import { type Sandbox, sandbox, expectMode } from "./helpers/sandbox.js"; /** * The browser tools against a real Google Chrome, through the built server: the tab @@ -390,7 +390,7 @@ describe.skipIf(reason !== undefined)( expect(n("/static/app.css")).toBe(1); const dir = join(identityStateDir("res-a", sb.env), "resource-cache"); expect(readdirSync(dir).some((f) => f.endsWith(".json"))).toBe(true); - expect(statSync(dir).mode & 0o777).toBe(0o700); + expectMode(dir, 0o700); // Never across identities, and nothing blocked without a block setting. writeIdentitySettings("res-b", { cache: {} }, sb.env); diff --git a/packages/browser/test/browsers.test.ts b/packages/browser/test/browsers.test.ts index bf1d9cb0..1478576a 100644 --- a/packages/browser/test/browsers.test.ts +++ b/packages/browser/test/browsers.test.ts @@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { type BrowserProbe, browserSwitchProblem, + versionFromFolders, detectBrowsers, profileLastVersion, resolveBrowser, @@ -66,6 +67,39 @@ describe("detection", () => { ]); expect(detectBrowsers(sb.env, "win32", probe)).toEqual([]); }); + + it("finds Windows browsers in Program Files, Program Files (x86) and the per-user LOCALAPPDATA", () => { + const env = { + USERPROFILE: "C:\\Users\\a", + ProgramFiles: "C:\\Program Files", + "ProgramFiles(x86)": "C:\\Program Files (x86)", + LOCALAPPDATA: "C:\\Users\\a\\AppData\\Local", + }; + const chrome = "C:\\Users\\a\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"; + const edge = "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe"; + const brave = "C:\\Program Files\\BraveSoftware\\Brave-Browser\\Application\\brave.exe"; + const probe = machine({ [chrome]: "157.0.8103.79", [edge]: "158.0.4370.33", [brave]: "157.1.99.57" }); + expect(detectBrowsers(env, "win32", probe).map((b) => [b.id, b.path])).toEqual([ + ["chrome", chrome], + ["edge", edge], + ["brave", brave], + ]); + // Without the variables, Windows' default folders. + expect(detectBrowsers({ USERPROFILE: "C:\\Users\\a" }, "win32", probe).map((b) => b.id)).toEqual([ + "chrome", + "edge", + "brave", + ]); + // Launched by path: Playwright's channel lookup on Windows has its own order. + expect(resolveBrowser("chrome", { env, platform: "win32", probe }).launch).toEqual({ executablePath: chrome }); + }); + + it("reads a Windows browser's version from the folder next to its executable", () => { + expect(versionFromFolders(["chrome.exe", "157.0.8103.79", "157.0.8103.114", "SetupMetrics"])).toBe( + "157.0.8103.114", + ); + expect(versionFromFolders(["chrome.exe"])).toBeUndefined(); + }); }); describe("how a browser is launched", () => { diff --git a/packages/browser/test/cli/bin.test.ts b/packages/browser/test/cli/bin.test.ts index 5f094cc6..b737a771 100644 --- a/packages/browser/test/cli/bin.test.ts +++ b/packages/browser/test/cli/bin.test.ts @@ -1,10 +1,11 @@ import { spawnSync } from "node:child_process"; -import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; -import { dirname, join } from "node:path"; +import { existsSync, readFileSync, readdirSync } from "node:fs"; +import { dirname, join, sep } from "node:path"; import { fileURLToPath } from "node:url"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; -import { type FakeSecretStore, fakeSecretStore } from "../helpers/fake-secret-store.js"; +import { type FakeSecretStore, fakeSecretStore, noFakeSecretStore } from "../helpers/fake-secret-store.js"; import { type Sandbox, sandbox } from "../helpers/sandbox.js"; +import { fakeProgram, pathWith, slashes } from "../helpers/programs.js"; /** * The `turno-browser` program, run from dist/ in a throwaway HOME: the identity commands without @@ -39,12 +40,14 @@ function runWith(args: string[], extra: NodeJS.ProcessEnv, input = "") { return { code: r.status, out: r.stdout, err: r.stderr }; } +/** How an agent starts turno-browser-mcp found on the PATH: through cmd.exe on Windows, where npm installs a `.cmd`. */ +const MCP = process.platform === "win32" ? ["cmd", "/c", "turno-browser-mcp"] : ["turno-browser-mcp"]; + /** A PATH where turno-browser-mcp is found: a stand-in in the sandbox. */ function onPath(): NodeJS.ProcessEnv { const dir = join(sb.home, "mcpbin"); - mkdirSync(dir, { recursive: true }); - writeFileSync(join(dir, "turno-browser-mcp"), "#!/bin/sh\nexit 0\n", { mode: 0o755 }); - return { PATH: `${dir}:${sb.env.PATH ?? ""}` }; + fakeProgram(dir, "turno-browser-mcp"); + return { PATH: pathWith(sb.env.PATH, dir) }; } /** Every file under `dir`, for "writes nothing". */ @@ -52,7 +55,7 @@ function files(dir: string): string[] { return readdirSync(dir, { recursive: true, withFileTypes: true }) .filter((e) => e.isFile()) .map((e) => join(e.parentPath, e.name)) - .filter((f) => !f.includes("/mcpbin/")) + .filter((f) => !f.includes(`${sep}mcpbin${sep}`)) .sort(); } @@ -76,7 +79,7 @@ describe("turno-browser", () => { it("adds an identity and prints how to connect an agent instead of an mcp.toml block", () => { const r = run(["add", "school", "--languages", "es-MX,es,en"]); expect(r.code).toBe(0); - expect(r.out).toMatch(/identity "school" ready at ~\/\.local\/share\/turno\/browser\/identities\/school/); + expect(slashes(r.out)).toMatch(/identity "school" ready at ~\/\.local\/share\/turno\/browser\/identities\/school/); expect(r.out).toContain("turno-browser setup claude-code --identity school"); expect(r.out).toContain("turno-browser-mcp --identity school"); expect(r.out).toContain("turno-browser login school"); @@ -91,7 +94,12 @@ describe("turno-browser", () => { expect(text.code).toBe(0); expect(text.out).toMatch(/^school +not in use/m); expect(JSON.parse(run(["list", "--json"]).out)).toEqual([ - { schemaVersion: 1, id: "school", inUse: false, dir: "~/.local/share/turno/browser/identities/school" }, + { + schemaVersion: 1, + id: "school", + inUse: false, + dir: join("~", ".local", "share", "turno", "browser", "identities", "school"), + }, ]); }); @@ -117,7 +125,7 @@ describe("turno-browser", () => { ); }); - it("lists a vault without its values", () => { + it.skipIf(noFakeSecretStore)("lists a vault without its values", () => { run(["add", "school"]); const add = run( ["vault", "add", "school", "mail", "--url", "https://mail.example.com", "--username", "alice@example.com"], @@ -181,7 +189,7 @@ describe("turno-browser", () => { [ 'Run this once to give Claude Code the browser identity "school":', "", - "claude mcp add --scope user browser-school -- turno-browser-mcp --identity school", + `claude mcp add --scope user browser-school -- ${MCP.join(" ")} --identity school`, "", "--scope user adds it to every project; leave it out to add it to the current folder only.", "Start a new agent session to load it. Sign in to your sites once with turno-browser login school.", @@ -189,15 +197,16 @@ describe("turno-browser", () => { ].join("\n"), ); const codex = runWith(["setup", "codex"], onPath()); + const stdio = { command: MCP[0], args: [...MCP.slice(1), "--identity", "school"] }; expect(codex.out).toContain( - '[mcp_servers.browser-school]\ncommand = "turno-browser-mcp"\nargs = ["--identity", "school"]\n', + `[mcp_servers.browser-school]\ncommand = "${stdio.command}"\nargs = ${JSON.stringify(stdio.args).replace(/","/g, '", "')}\n`, ); - expect(codex.out).toContain("Or run: codex mcp add browser-school -- turno-browser-mcp --identity school"); + expect(codex.out).toContain(`Or run: codex mcp add browser-school -- ${MCP.join(" ")} --identity school`); for (const [agent, entry] of [ - ["cursor", { type: "stdio", command: "turno-browser-mcp", args: ["--identity", "school"] }], - ["copilot", { type: "local", command: "turno-browser-mcp", args: ["--identity", "school"], tools: ["*"] }], - ["gemini", { command: "turno-browser-mcp", args: ["--identity", "school"] }], - ["json", { command: "turno-browser-mcp", args: ["--identity", "school"] }], + ["cursor", { type: "stdio", ...stdio }], + ["copilot", { type: "local", ...stdio, tools: ["*"] }], + ["gemini", stdio], + ["json", stdio], ] as const) { const r = runWith(["setup", agent, "--json"], onPath()); expect(r.code).toBe(0); @@ -205,12 +214,16 @@ describe("turno-browser", () => { expect(out.server).toBe("browser-school"); expect(JSON.parse(out.config)).toEqual({ mcpServers: { "browser-school": entry } }); } - // Not on the PATH: the full path of this install's server. - const full = runWith(["setup", "json", "--json"], { PATH: dirname(process.execPath) }); - expect(JSON.parse(full.out)).toMatchObject({ - command: fileURLToPath(new URL("../../dist/bin/mcp.js", import.meta.url)), - notes: expect.arrayContaining([expect.stringMatching(/not on the PATH/)]), - }); + // Not on the PATH: the full path of this install's server (run by Node on Windows). + const full = JSON.parse(runWith(["setup", "json", "--json"], { PATH: dirname(process.execPath) }).out); + const script = fileURLToPath(new URL("../../dist/bin/mcp.js", import.meta.url)); + expect([full.command, ...full.args]).toEqual([ + ...(process.platform === "win32" ? [process.execPath] : []), + script, + "--identity", + "school", + ]); + expect(full.notes).toEqual(expect.arrayContaining([expect.stringMatching(/not on the PATH/)])); expect(files(sb.home)).toEqual(before); }); @@ -228,40 +241,43 @@ describe("turno-browser", () => { expect(run(["setup", "codex", "--identity", "nobody"])).toMatchObject({ code: 2 }); }); - it("stores, checks, lists and removes the secrets identity.json names, never printing them", () => { - run(["add", "school"]); - run([ - "set", - "school", - "--proxy-server", - "http://proxy.example.com:8080", - "--proxy-username", - "alice", - "--proxy-password", - "keychain:school-proxy", - ]); - const missing = run(["secret", "list"]); - expect(missing.code).toBe(1); - expect(missing.out).toMatch( - /^MISSING {2}keychain:school-proxy {2}\(school\) {2}turno-browser secret set school-proxy$/m, - ); - const set = run(["secret", "set", "school-proxy"], "correct-horse-battery"); - expect(set).toMatchObject({ code: 0, out: "stored keychain:school-proxy\n" }); - expect(store.read("school-proxy")).toBe("correct-horse-battery"); - expect(run(["secret", "has", "school-proxy"]).code).toBe(0); - const list = run(["secret", "list", "--json"]); - expect(list.code).toBe(0); - expect(JSON.parse(list.out)).toEqual([ - { schemaVersion: 1, item: "school-proxy", stored: true, identities: ["school"] }, - ]); - expect(list.out + set.out).not.toContain("correct-horse"); - expect(run(["secret", "remove", "school-proxy"])).toMatchObject({ - code: 0, - out: "removed keychain:school-proxy\n", - }); - expect(run(["secret", "has", "school-proxy"]).code).toBe(1); - expect(run(["secret", "set", "empty"], "").code).toBe(2); - }); + it.skipIf(noFakeSecretStore)( + "stores, checks, lists and removes the secrets identity.json names, never printing them", + () => { + run(["add", "school"]); + run([ + "set", + "school", + "--proxy-server", + "http://proxy.example.com:8080", + "--proxy-username", + "alice", + "--proxy-password", + "keychain:school-proxy", + ]); + const missing = run(["secret", "list"]); + expect(missing.code).toBe(1); + expect(missing.out).toMatch( + /^MISSING {2}keychain:school-proxy {2}\(school\) {2}turno-browser secret set school-proxy$/m, + ); + const set = run(["secret", "set", "school-proxy"], "correct-horse-battery"); + expect(set).toMatchObject({ code: 0, out: "stored keychain:school-proxy\n" }); + expect(store.read("school-proxy")).toBe("correct-horse-battery"); + expect(run(["secret", "has", "school-proxy"]).code).toBe(0); + const list = run(["secret", "list", "--json"]); + expect(list.code).toBe(0); + expect(JSON.parse(list.out)).toEqual([ + { schemaVersion: 1, item: "school-proxy", stored: true, identities: ["school"] }, + ]); + expect(list.out + set.out).not.toContain("correct-horse"); + expect(run(["secret", "remove", "school-proxy"])).toMatchObject({ + code: 0, + out: "removed keychain:school-proxy\n", + }); + expect(run(["secret", "has", "school-proxy"]).code).toBe(1); + expect(run(["secret", "set", "empty"], "").code).toBe(2); + }, + ); it("reports usage errors with exit 2, as text or JSON", () => { expect(run(["add"])).toMatchObject({ @@ -283,13 +299,12 @@ describe("turno-browser", () => { */ function fakeClaude(): { log: string; config: () => Record } { const dir = join(sb.home, "agentbin"); - mkdirSync(dir, { recursive: true }); const log = join(sb.home, "claude.log"); const config = join(sb.home, ".claude.json"); - writeFileSync( - join(dir, "claude"), - `#!${process.execPath} -const fs = require("node:fs"); + fakeProgram( + dir, + "claude", + `const fs = require("node:fs"); const args = process.argv.slice(2); fs.appendFileSync(${JSON.stringify(log)}, JSON.stringify(args) + "\\n"); const file = ${JSON.stringify(config)}; @@ -300,7 +315,6 @@ else if (args[1] === "remove") { if (!c.mcpServers[name]) { console.error("not f fs.writeFileSync(file, JSON.stringify(c)); console.log(args[1] + " " + name); `, - { mode: 0o755 }, ); return { log, @@ -311,13 +325,15 @@ console.log(args[1] + " " + name); describe("onboarding and offboarding without a terminal", () => { it("init --yes --json registers the agent, remove --yes --json takes everything out again", () => { const claude = fakeClaude(); - const env = { PATH: `${join(sb.home, "agentbin")}:${onPath().PATH}` }; + const env = { PATH: pathWith(onPath().PATH, join(sb.home, "agentbin")) }; const first = runWith(["init", "--identity", "school", "--agent", "claude-code", "--yes", "--json"], env); expect(first.code).toBe(0); const report = JSON.parse(first.out); expect(report.mcp).toMatchObject({ status: "added", exitCode: 0, output: "add browser-school" }); expect(claude.config()).toEqual({ - mcpServers: { "browser-school": { type: "stdio", command: "turno-browser-mcp", args: ["--identity", "school"] } }, + mcpServers: { + "browser-school": { type: "stdio", command: MCP[0], args: [...MCP.slice(1), "--identity", "school"] }, + }, }); const again = runWith(["init", "--identity", "school", "--agent", "claude-code", "--yes", "--json"], env); expect(JSON.parse(again.out).mcp.status).toBe("already"); diff --git a/packages/browser/test/cli/do-background.test.ts b/packages/browser/test/cli/do-background.test.ts index ee30cdf6..e3a91381 100644 --- a/packages/browser/test/cli/do-background.test.ts +++ b/packages/browser/test/cli/do-background.test.ts @@ -1,11 +1,11 @@ -import { existsSync, readFileSync, statSync } from "node:fs"; +import { existsSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { parseFlags } from "turno-core/cli"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import type { BackgroundState } from "../../src/background-state.js"; import type { BackgroundSession, OpenSessionOptions } from "../../src/client.js"; import { type BackgroundDoDeps, backgroundTransport } from "../../src/cli/do-background.js"; -import { type Sandbox, sandbox } from "../helpers/sandbox.js"; +import { type Sandbox, sandbox, expectMode } from "../helpers/sandbox.js"; import { fakeIo } from "./helpers.js"; /** @@ -110,7 +110,7 @@ describe("the background transport of do", () => { expect(f.opened[0]!.session).toBeUndefined(); const saved = JSON.parse(readFileSync(savedFile(), "utf8")); expect(saved).toMatchObject({ v: 1, identity: "school", serverPid: 4242, sessionId: "s1", name: "default" }); - expect(statSync(savedFile()).mode & 0o777).toBe(0o600); + expectMode(savedFile(), 0o600); const second = await backgroundTransport(f.deps).target("school", p(), io); expect(second.describe(io).open).toBe(true); diff --git a/packages/browser/test/cli/flows.test.ts b/packages/browser/test/cli/flows.test.ts index 380344a2..ccedc87f 100644 --- a/packages/browser/test/cli/flows.test.ts +++ b/packages/browser/test/cli/flows.test.ts @@ -6,6 +6,7 @@ import type { VaultInput } from "../../src/cli/context.js"; import * as flowCmd from "../../src/cli/flows.js"; import { type Sandbox, sandbox } from "../helpers/sandbox.js"; import { cli, ctx, fakeIo, real } from "./helpers.js"; +import { slashes } from "../helpers/programs.js"; /** * `record|flows|replay|traces`. The real turno-browser from the workspace runs @@ -70,7 +71,7 @@ describe("turno-browser record and set --record-*", () => { expect((await browser(["add", "school"])).code).toBe("0"); const none = await browser(["record", "school"]); expect(none.out).toMatch(/records\s+nothing \(the agent can still record a flow with browser_record\)/); - expect(none.out).toMatch(/flows\s+~\/\.local\/share\/turno\/browser\/flows\/school/); + expect(slashes(none.out)).toMatch(/flows\s+~\/\.local\/share\/turno\/browser\/flows\/school/); const on = await browser(["record", "school", "--flows", "--traces", "--max-size", "50MB"]); expect(on.code).toBe("0"); @@ -123,7 +124,12 @@ describe("turno-browser flows", () => { expect(list.out).toMatch(/\* sensitive: no value is saved/); const json = JSON.parse((await browser(["flows", "school", "--json"])).out); expect(json).toMatchObject([ - { name: "sign-in", steps: 4, auto: false, file: "~/.local/share/turno/browser/flows/school/sign-in.json" }, + { + name: "sign-in", + steps: 4, + auto: false, + file: join("~", ".local", "share", "turno", "browser", "flows", "school", "sign-in.json"), + }, ]); const show = await browser(["flows", "school", "sign-in"]); expect(show.out).toMatch(/1\. browser_navigate https:\/\/example\.com\/login/); diff --git a/packages/browser/test/cli/init.test.ts b/packages/browser/test/cli/init.test.ts index c4b30e49..342ee977 100644 --- a/packages/browser/test/cli/init.test.ts +++ b/packages/browser/test/cli/init.test.ts @@ -1,17 +1,19 @@ -import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import type { Io } from "turno-core/cli"; -import { readRegistrations } from "../../src/agent-mcp.js"; +import { cmdArgument, execCommand, readRegistrations, spawnPlan } from "../../src/agent-mcp.js"; import type { BrowserFunctions } from "../../src/api.js"; import { localTime } from "../../src/cli/identity.js"; import { detectAgents, init, shellWords } from "../../src/cli/init.js"; import { loginSummary } from "../../src/cli/login-summary.js"; import { errorHint } from "../../src/cli/do.js"; import { formatIdle } from "../../src/cli/do-background.js"; -import { unknownAgent } from "../../src/cli/setup.js"; +import { mcpCommand, shellLine, unknownAgent } from "../../src/cli/setup.js"; +import { openUrlCommand } from "../../src/cli/context.js"; import { siteOf, welcomePage } from "../../src/login.js"; +import { fakeProgram, pathWith } from "../helpers/programs.js"; import { ctx, fakeAgentCli, fakeIo, real } from "./helpers.js"; /** A sandbox: turno's folders, a HOME, and a PATH with only the agents a test puts there. */ @@ -27,11 +29,7 @@ function sandbox() { TURNO_DATA_DIR: join(root, "data"), }; mkdirSync(env.HOME!); - const agent = (name: string) => { - const file = join(bin, name); - writeFileSync(file, "#!/bin/sh\nexit 0\n"); - chmodSync(file, 0o755); - }; + const agent = (name: string) => fakeProgram(bin, name); return { root, env, agent, done: () => rmSync(root, { recursive: true, force: true }) }; } @@ -201,7 +199,7 @@ describe("turno-browser init without a terminal", () => { status: "added", agent: "claude-code", server: "browser-school", - file: "~/.claude.json", + file: join("~", ".claude.json"), exitCode: 0, output: "add browser-school", }, @@ -210,7 +208,7 @@ describe("turno-browser init without a terminal", () => { expect(first.mcp.run.slice(-2)).toEqual(["--identity", "school"]); expect(first.next.join("\n")).toContain("turno-browser login school"); expect(agent.calls).toHaveLength(1); - expect(agent.config().mcpServers["browser-school"]!.args).toEqual(["--identity", "school"]); + expect(agent.config().mcpServers["browser-school"]!.args.slice(-2)).toEqual(["--identity", "school"]); expect(readRegistrations("school", sb.env)).toMatchObject([ { agent: "claude-code", server: "browser-school", file: join(sb.env.HOME!, ".claude.json") }, ]); @@ -265,8 +263,8 @@ describe("turno-browser init without a terminal", () => { const io = fakeIo(sb.env); expect(await init(ctx(api), ["--identity", "school", "--agent", "cursor", "--yes", "--json"], io)).toBe(0); const r = report(io); - expect(r.mcp).toMatchObject({ status: "manual", register: null, file: "~/.cursor/mcp.json" }); - expect(JSON.parse(r.mcp.config).mcpServers["browser-school"].args).toEqual(["--identity", "school"]); + expect(r.mcp).toMatchObject({ status: "manual", register: null, file: join("~", ".cursor", "mcp.json") }); + expect(JSON.parse(r.mcp.config).mcpServers["browser-school"].args.slice(-2)).toEqual(["--identity", "school"]); }); it("--json --dry-run creates nothing and says what it would run", async () => { @@ -350,3 +348,97 @@ describe("the words of the first steps", () => { expect(localTime("2026-11-20T05:46:30.169Z")).toMatch(/^2026-11-(19|20) \d\d:\d\d$/); }); }); + +describe("running an agent's command on Windows", () => { + const tricky = ["a b", 'say "hi"', "100%", "x&y|z", "^caret", "trail\\", 'back\\"slash', "(paren)", "!bang", ""]; + + it("quotes each argument for the program and escapes cmd.exe's characters twice", () => { + expect(cmdArgument("x&y")).toBe('^^^"x^^^&y^^^"'); + expect(cmdArgument('a"b\\')).toBe('^^^"a\\^^^"b\\\\^^^"'); + }); + + it("runs a .cmd shim through cmd.exe and an .exe as it is", () => { + const dir = mkdtempSync(join(tmpdir(), "turno-spawn-")); + try { + writeFileSync(join(dir, "claude.cmd"), ""); + const env = { Path: dir, PATHEXT: ".EXE;.CMD", ComSpec: "C:\\Windows\\system32\\cmd.exe" }; + expect(spawnPlan("claude", ["mcp", "list"], { ...env, Path: "" }, "win32")).toEqual({ + file: "claude", + args: ["mcp", "list"], + verbatim: false, + }); + expect(spawnPlan("claude", ["mcp"], env, "darwin")).toEqual({ file: "claude", args: ["mcp"], verbatim: false }); + if (process.platform !== "win32") return; + const plan = spawnPlan("claude", ["mcp", "x&y"], env, "win32"); + expect(plan.file).toBe("C:\\Windows\\system32\\cmd.exe"); + expect(plan.args.slice(0, 3)).toEqual(["/d", "/s", "/c"]); + expect(plan.verbatim).toBe(true); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + // A real cmd.exe and a real npm-style shim: each argument arrives as it was given. + it.runIf(process.platform === "win32")("passes every argument through an npm-style shim unchanged", async () => { + const dir = mkdtempSync(join(tmpdir(), "turno-spawn-")); + try { + fakeProgram(join(dir, "bin"), "echoargs", "process.stdout.write(JSON.stringify(process.argv.slice(2)));"); + const env = { ...process.env, PATH: pathWith(process.env.PATH, join(dir, "bin")) }; + const r = await execCommand("echoargs", tricky, env); + expect(r.code).toBe(0); + expect(JSON.parse(r.output)).toEqual(tricky); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); + +describe("how an agent starts turno-browser-mcp", () => { + it("by name when it is on the PATH, through cmd /c on Windows; else by its full path, run by Node on Windows", () => { + const empty = { PATH: "" }; + expect(mcpCommand(empty, "linux")).toMatchObject({ prefix: [], onPath: false }); + expect(mcpCommand(empty, "linux").command).toMatch(/[\\/]bin[\\/]mcp\.js$/); + const win = mcpCommand(empty, "win32"); + expect(win.command).toBe(process.execPath); + expect(win.prefix[0]).toMatch(/[\\/]bin[\\/]mcp\.js$/); + const dir = mkdtempSync(join(tmpdir(), "turno-mcp-")); + try { + fakeProgram(dir, "turno-browser-mcp"); + const env = { PATH: pathWith(undefined, dir) }; + expect(mcpCommand(env)).toEqual( + process.platform === "win32" + ? { command: "cmd", prefix: ["/c", "turno-browser-mcp"], onPath: true } + : { command: "turno-browser-mcp", prefix: [], onPath: true }, + ); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("prints a line cmd.exe and PowerShell read on Windows, and a POSIX one elsewhere", () => { + const words = [ + "claude", + "mcp", + "add", + "--", + "C:\\Program Files\\nodejs\\node.exe", + "C:\\x\\mcp.js", + "--identity", + "a", + ]; + expect(shellLine(words, "win32")).toBe( + 'claude mcp add -- "C:\\Program Files\\nodejs\\node.exe" C:\\x\\mcp.js --identity a', + ); + expect(shellLine(["claude", "/x y/mcp.js"], "linux")).toBe("claude '/x y/mcp.js'"); + }); + + it("opens a link without cmd.exe on Windows, so & stays part of it", () => { + const url = "https://example.com/?a=1&b=2"; + expect(openUrlCommand(url, "win32")).toEqual({ + command: "rundll32.exe", + args: ["url.dll,FileProtocolHandler", url], + }); + expect(openUrlCommand(url, "darwin")).toEqual({ command: "open", args: [url] }); + expect(openUrlCommand(url, "linux")).toEqual({ command: "xdg-open", args: [url] }); + }); +}); diff --git a/packages/browser/test/cli/remove.test.ts b/packages/browser/test/cli/remove.test.ts index 7ca9c766..949a1ec9 100644 --- a/packages/browser/test/cli/remove.test.ts +++ b/packages/browser/test/cli/remove.test.ts @@ -12,9 +12,10 @@ import { runtimeLockPath } from "../../src/runtime-lock.js"; import { recordExportFile } from "../../src/session-export.js"; import { identitySettingsPath } from "../../src/settings.js"; import { vaultPath } from "../../src/vault.js"; -import { type FakeSecretStore, fakeSecretStore } from "../helpers/fake-secret-store.js"; +import { type FakeSecretStore, fakeSecretStore, noFakeSecretStore } from "../helpers/fake-secret-store.js"; import { type Sandbox, sandbox } from "../helpers/sandbox.js"; import { cli, fakeAgentCli, fakeIo, real } from "./helpers.js"; +import { fakeProgram, pathWith } from "../helpers/programs.js"; /** * `turno-browser remove`: everything an identity left, removed and checked. The secret store is @@ -41,9 +42,8 @@ afterEach(() => { /** A program on the sandbox PATH that exits 0: an agent that is installed. */ function installed(name: string): void { const dir = join(sb.home, "agentbin"); - mkdirSync(dir, { recursive: true }); - writeFileSync(join(dir, name), "#!/bin/sh\nexit 0\n", { mode: 0o755 }); - if (!sb.env.PATH!.includes(dir)) sb.env.PATH = `${dir}:${sb.env.PATH}`; + fakeProgram(dir, name); + if (!sb.env.PATH!.includes(dir)) sb.env.PATH = pathWith(sb.env.PATH, dir); } /** The identity "school" with a vault, a proxy secret, an export and an agent that has it. */ @@ -101,7 +101,8 @@ function claudeHas(id: string, env: NodeJS.ProcessEnv = sb.env): void { const json = (io: { lines: string[] }) => JSON.parse(io.lines.join("\n")); -describe("turno-browser remove", () => { +// Every case removes vault credentials from the secret store. +describe.skipIf(noFakeSecretStore)("turno-browser remove", () => { it("without a terminal needs --yes and deletes nothing; an unknown identity is refused", async () => { await expect(cli(api).run("remove", ["nope", "--yes"], fakeIo(sb.env))).rejects.toThrow(/does not exist/); await school(); diff --git a/packages/browser/test/cli/session.test.ts b/packages/browser/test/cli/session.test.ts index 66ca3d23..5d5a14e1 100644 --- a/packages/browser/test/cli/session.test.ts +++ b/packages/browser/test/cli/session.test.ts @@ -1,11 +1,11 @@ -import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import type { BrowserFunctions as BrowserApi } from "../../src/api.js"; import type { CliDeps, VaultInput } from "../../src/cli/context.js"; import * as session from "../../src/cli/session.js"; import { parseExpiry } from "../../src/cli/session.js"; -import { type Sandbox, sandbox } from "../helpers/sandbox.js"; +import { type Sandbox, sandbox, expectMode } from "../helpers/sandbox.js"; import { ctx, fakeIo } from "./helpers.js"; let sb: Sandbox; @@ -83,7 +83,7 @@ describe("export", () => { expect(await exportSession(fakeModule(calls), ["work", "--out", out, "--expires", "2d"], io, input())).toBe(0); expect(calls.exported[0]!.options.passphrase === PASS).toBe(true); expect(calls.exported[0]!.options.expiresInMs).toBe(2 * 24 * 3600_000); - expect(statSync(out).mode & 0o777).toBe(0o600); + expectMode(out, 0o600); expect(readFileSync(out, "utf8")).toContain("turno-browser-session"); const text = [...io.lines, ...io.errors].join("\n"); expect(text).toMatch(/3 cookies, storage of 2 sites/); diff --git a/packages/browser/test/cli/status.test.ts b/packages/browser/test/cli/status.test.ts index f6207188..044aa29f 100644 --- a/packages/browser/test/cli/status.test.ts +++ b/packages/browser/test/cli/status.test.ts @@ -61,7 +61,7 @@ describe("turno-browser status", () => { expect(r.identities.map((i: { id: string }) => i.id)).toEqual(["school", "work"]); expect(r.identities[0]).toMatchObject({ id: "school", - profile: "~/" + identityDir("school", sb.env).slice(sb.home.length + 1), + profile: join("~", identityDir("school", sb.env).slice(sb.home.length + 1)), settings: { timezone: "America/Monterrey", languages: ["es-MX", "en"], @@ -75,7 +75,7 @@ describe("turno-browser status", () => { signedIn: { at: "2026-11-19T15:00:00.000Z", sites: ["canvas.example.edu"] }, cookieHosts: ["canvas.example.edu"], lastUsed: "2026-11-20T18:00:00.000Z", - agents: [{ agent: "claude-code", server: "browser-school", file: "~/.claude.json" }], + agents: [{ agent: "claude-code", server: "browser-school", file: join("~", ".claude.json") }], }); expect(r.identities[1].settings.resources).toBe("normal"); expect(r.identities[1]).toMatchObject({ id: "work", signedIn: null, cookieHosts: [], lastUsed: null, agents: [] }); diff --git a/packages/browser/test/doctor.test.ts b/packages/browser/test/doctor.test.ts index a4c5e1ee..f5097a8e 100644 --- a/packages/browser/test/doctor.test.ts +++ b/packages/browser/test/doctor.test.ts @@ -14,6 +14,7 @@ import { acquireRuntimeLock, runtimeLockPath } from "../src/runtime-lock.js"; import { identitySettingsPath, systemTimezone } from "../src/settings.js"; import { vaultAdd, vaultItem } from "../src/vault.js"; import { type Sandbox, sandbox } from "./helpers/sandbox.js"; +import { fakeProgram, pathWith, slashes } from "./helpers/programs.js"; /** * `turno browser doctor`: Chrome and its version, the desktop session, a smoke launch on a @@ -49,7 +50,7 @@ async function doctor(over: Parameters[0] = {}) { } const find = (checks: DoctorCheck[], area: string, text: RegExp) => - checks.find((c) => c.area === area && text.test(c.text)); + checks.find((c) => c.area === area && text.test(slashes(c.text))); describe("browser doctor: Chrome and the system", () => { it("reports Chrome with its version and a smoke launch on a temporary profile", async () => { @@ -500,9 +501,8 @@ describe("browser doctor: the agents that have each identity", () => { }), ); const bin = join(sb.home, "bin"); - mkdirSync(bin); - writeFileSync(join(bin, "turno-browser-mcp"), "#!/bin/sh\n", { mode: 0o755 }); - const env = { ...sb.env, PATH: `${bin}:${sb.env.PATH}` }; + fakeProgram(bin, "turno-browser-mcp"); + const env = { ...sb.env, PATH: pathWith(sb.env.PATH, bin) }; const { checks } = await doctor({ env, agents: browserEntries(env) }); expect(find(checks, "identity school", /^Claude Code has it \(browser-school in ~\/\.claude\.json\)$/)?.level).toBe( "ok", diff --git a/packages/browser/test/engines.test.ts b/packages/browser/test/engines.test.ts index d34827b9..1b529d9b 100644 --- a/packages/browser/test/engines.test.ts +++ b/packages/browser/test/engines.test.ts @@ -125,15 +125,19 @@ describe("Lightpanda discovery and read mode", () => { return file; } - it("finds lightpanda on PATH, or at TURNO_LIGHTPANDA_PATH, with its version", () => { - const onPath = fakeLightpanda("bin"); - expect(findLightpanda({ ...sb.env, PATH: join(sb.home, "bin") })).toEqual({ - path: onPath, - version: "1.1.0-nightly.1+test", - }); - const configured = fakeLightpanda("opt"); - expect(findLightpanda({ ...sb.env, PATH: "", TURNO_LIGHTPANDA_PATH: configured })?.path).toBe(configured); - }); + // The fake Lightpanda is a shell script (and Lightpanda has no Windows build). + it.skipIf(process.platform === "win32")( + "finds lightpanda on PATH, or at TURNO_LIGHTPANDA_PATH, with its version", + () => { + const onPath = fakeLightpanda("bin"); + expect(findLightpanda({ ...sb.env, PATH: join(sb.home, "bin") })).toEqual({ + path: onPath, + version: "1.1.0-nightly.1+test", + }); + const configured = fakeLightpanda("opt"); + expect(findLightpanda({ ...sb.env, PATH: "", TURNO_LIGHTPANDA_PATH: configured })?.path).toBe(configured); + }, + ); it("finds nothing when it is missing or the configured path is relative", () => { expect(findLightpanda({ ...sb.env, PATH: join(sb.home, "empty") })).toBeUndefined(); diff --git a/packages/browser/test/flows.test.ts b/packages/browser/test/flows.test.ts index 19856819..c1ea092f 100644 --- a/packages/browser/test/flows.test.ts +++ b/packages/browser/test/flows.test.ts @@ -1,4 +1,4 @@ -import { existsSync, statSync, utimesSync, writeFileSync } from "node:fs"; +import { existsSync, utimesSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { @@ -16,7 +16,7 @@ import { writeFlow, } from "../src/flows.js"; import { addIdentity, removeIdentity } from "../src/identities.js"; -import { type Sandbox, sandbox } from "./helpers/sandbox.js"; +import { type Sandbox, sandbox, expectMode } from "./helpers/sandbox.js"; /** Flow files: format, parameters, storage per identity. */ @@ -63,8 +63,8 @@ describe("flow files", () => { it("live per identity under the data folder, mode 600, and read back as written", () => { const file = writeFlow("work", flow("sign-in"), sb.env); expect(file).toBe(join(sb.home, ".local", "share", "turno", "browser", "flows", "work", "sign-in.json")); - expect(statSync(file).mode & 0o777).toBe(0o600); - expect(statSync(flowsDir("work", sb.env)).mode & 0o777).toBe(0o700); + expectMode(file, 0o600); + expectMode(flowsDir("work", sb.env), 0o700); expect(readFlow("work", "sign-in", sb.env)).toEqual(flow("sign-in")); }); diff --git a/packages/browser/test/helpers/chrome.ts b/packages/browser/test/helpers/chrome.ts index 768ed3b7..7f3b6b47 100644 --- a/packages/browser/test/helpers/chrome.ts +++ b/packages/browser/test/helpers/chrome.ts @@ -3,6 +3,7 @@ import { existsSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; +import { readProcTable } from "turno-core/process"; /** Shared by the tests that start a real Google Chrome (chrome-lifecycle, browser-tools). */ @@ -11,13 +12,16 @@ const pkg = fileURLToPath(new URL("../..", import.meta.url)); const CHROME_PATHS: Partial> = { darwin: ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"], linux: ["/opt/google/chrome/chrome"], + win32: [process.env.ProgramFiles, process.env["ProgramFiles(x86)"], process.env.LOCALAPPDATA] + .filter((d) => d !== undefined) + .map((d) => join(d, "Google", "Chrome", "Application", "chrome.exe")), }; /** Why these tests cannot run here, or undefined when a real Chrome starts. */ export function chromeUnavailable(): string | undefined { if (process.env.TURNO_SKIP_CHROME === "1") return "TURNO_SKIP_CHROME=1"; const candidates = CHROME_PATHS[process.platform]; - if (!candidates) return `no process groups to test on ${process.platform}`; + if (!candidates) return `no Chrome location known on ${process.platform}`; const exe = candidates.find((p) => existsSync(p)); if (!exe) return `Google Chrome is not installed (looked for ${candidates.join(", ")})`; // Start it once, headless, from a throwaway HOME, so a Chrome that is present but cannot run @@ -31,7 +35,10 @@ export function chromeUnavailable(): string | undefined { try { const core = join(pkg, "node_modules", "patchright-core"); execFileSync(process.execPath, ["-e", probe, core], { - env: { PATH: process.env.PATH, HOME: home }, + env: + process.platform === "win32" + ? { ...process.env, HOME: home, USERPROFILE: home, LOCALAPPDATA: home, APPDATA: home } + : { PATH: process.env.PATH, HOME: home }, stdio: ["ignore", "ignore", "pipe"], timeout: 40_000, }); @@ -86,6 +93,12 @@ export async function waitFor(cond: () => boolean, ms: number): Promise /** Processes whose command line names the sandbox (only the Chromes these tests started). */ export function sandboxProcesses(home: string): { pid: number; ppid: number; pgid: number }[] { + if (process.platform === "win32") { + // PowerShell's table: no process groups there, each process is its own. + return [...(readProcTable("win32")?.values() ?? [])] + .filter((p) => p.command.includes(home)) + .map(({ pid, ppid, pgid }) => ({ pid, ppid, pgid })); + } const out = execFileSync("ps", ["-A", "-ww", "-o", "pid=,ppid=,pgid=,command="], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024, @@ -108,7 +121,7 @@ export function sandboxProcesses(home: string): { pid: number; ppid: number; pgi export async function stopSandboxProcesses(home: string, ms = 10_000): Promise { const left = () => sandboxProcesses(home).filter((p) => alive(p.pid)); for (const p of left()) { - for (const sig of ["SIGCONT", "SIGKILL"] as const) { + for (const sig of process.platform === "win32" ? (["SIGKILL"] as const) : (["SIGCONT", "SIGKILL"] as const)) { try { process.kill(p.pid, sig); } catch { diff --git a/packages/browser/test/helpers/fake-secret-store.ts b/packages/browser/test/helpers/fake-secret-store.ts index 97aa3bb5..a2b981f3 100644 --- a/packages/browser/test/helpers/fake-secret-store.ts +++ b/packages/browser/test/helpers/fake-secret-store.ts @@ -7,6 +7,14 @@ import type { Sandbox } from "./sandbox.js"; * first on the sandbox PATH. Items live under `/fake-secrets/`, never in a real * Keychain. `failWrites(true)` makes every store fail, like a locked Keychain. */ +/** + * Why a test that stores a secret cannot run here: the stand-ins replace the macOS and Linux + * commands, and turno-core has no Windows secret store yet, so turno-browser there says "no + * secret store" (which other tests cover). Undefined where the stand-ins work. + */ +export const noFakeSecretStore: string | undefined = + process.platform === "win32" ? "no secret store on Windows yet" : undefined; + export interface FakeSecretStore { dir: string; read(service: string): string | undefined; diff --git a/packages/browser/test/helpers/global-setup.ts b/packages/browser/test/helpers/global-setup.ts index 1ca91e75..205885d9 100644 --- a/packages/browser/test/helpers/global-setup.ts +++ b/packages/browser/test/helpers/global-setup.ts @@ -11,7 +11,7 @@ */ import { chmodSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { delimiter, join } from "node:path"; +import { delimiter, join, sep } from "node:path"; const KEEP = new Set([ "TURNO_SKIP_E2E", @@ -24,10 +24,16 @@ const KEEP = new Set([ ]); const LIVE = /^(TURNO_|CLAUDE|CODEX_|CURSOR_|ANTHROPIC_|XDG_)/; +/** The folders the setup itself makes on Windows (above), not counted while they stay empty. */ +const SETUP_DIRS = new Set(["AppData", join("AppData", "Local"), join("AppData", "Roaming")]); + /** Paths written under the guard HOME, relative to it. */ export function guardFindings(home: string): string[] { try { - return readdirSync(home, { recursive: true }).map(String).sort(); + const found = readdirSync(home, { recursive: true }).map(String).sort(); + return found.filter( + (p) => !SETUP_DIRS.has(p) || found.some((q) => q !== p && q.startsWith(`${p}${sep}`) && !SETUP_DIRS.has(q)), + ); } catch { return []; } @@ -44,10 +50,12 @@ export default function setup(): () => void { process.env.XDG_DATA_HOME = join(home, ".local", "share"); process.env.XDG_CACHE_HOME = join(home, ".cache"); // Windows reads these instead of HOME: the profile folder, and turno's and Playwright's defaults. + // PowerShell and Chrome create them when they are missing, so they are made here and not counted. if (process.platform === "win32") { process.env.USERPROFILE = home; process.env.APPDATA = join(home, "AppData", "Roaming"); process.env.LOCALAPPDATA = join(home, "AppData", "Local"); + for (const dir of [process.env.APPDATA, process.env.LOCALAPPDATA]) mkdirSync(dir, { recursive: true }); } process.env.TURNO_NO_UPDATE_CHECK = "1"; // No test reaches the real secret store: stand-ins for `security` and `secret-tool` that refuse diff --git a/packages/browser/test/helpers/programs.ts b/packages/browser/test/helpers/programs.ts new file mode 100644 index 00000000..384b5298 --- /dev/null +++ b/packages/browser/test/helpers/programs.ts @@ -0,0 +1,35 @@ +import { chmodSync, mkdirSync, writeFileSync } from "node:fs"; +import { delimiter, join } from "node:path"; + +/** + * A stand-in program `name` in `dir`, in the form the system runs it: on macOS and Linux a script + * with a shebang; on Windows a `.cmd` shim next to a `.js` file, as npm installs an agent there + * (`claude.cmd`). `js` is the JavaScript it runs (its arguments in `process.argv.slice(2)`); + * without it, the program exits 0. Returns the path a PATH lookup finds. + */ +export function fakeProgram(dir: string, name: string, js?: string): string { + mkdirSync(dir, { recursive: true }); + if (process.platform === "win32") { + const shim = join(dir, `${name}.cmd`); + if (js === undefined) writeFileSync(shim, "@exit /b 0\r\n"); + else { + writeFileSync(join(dir, `${name}.js`), js); + writeFileSync(shim, `@"${process.execPath}" "%~dp0${name}.js" %*\r\n`); + } + return shim; + } + const file = join(dir, name); + writeFileSync(file, js === undefined ? "#!/bin/sh\nexit 0\n" : `#!${process.execPath}\n${js}`); + chmodSync(file, 0o755); + return file; +} + +/** `dirs` in front of `path`, joined the way the system's PATH is. */ +export function pathWith(path: string | undefined, ...dirs: string[]): string { + return [...dirs, ...(path ? [path] : [])].join(delimiter); +} + +/** Output with Windows' separators turned into `/`, so one expectation reads paths on every OS. */ +export function slashes(text: string): string { + return process.platform === "win32" ? text.replaceAll("\\", "/") : text; +} diff --git a/packages/browser/test/helpers/sandbox.ts b/packages/browser/test/helpers/sandbox.ts index ecc9ecce..6fe9887c 100644 --- a/packages/browser/test/helpers/sandbox.ts +++ b/packages/browser/test/helpers/sandbox.ts @@ -1,6 +1,7 @@ -import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; +import { expect } from "vitest"; /** A throwaway HOME with the env turno reads. Never touches the real home. */ export interface Sandbox { @@ -10,12 +11,32 @@ export interface Sandbox { cleanup(): void; } +/** + * Windows: what programs there need to start (SystemRoot, PATHEXT, the temp folder, where + * browsers are installed), the profile folders inside the sandbox, and turno's folders in the + * XDG layout, so a test reads the same relative paths on every OS. The Windows defaults + * (APPDATA, LOCALAPPDATA) have their own unit test in turno-core. + */ +function windowsEnv(home: string): NodeJS.ProcessEnv { + const keep = ["SystemRoot", "windir", "ComSpec", "PATHEXT", "TEMP", "TMP", "ProgramFiles", "ProgramFiles(x86)"]; + return { + ...Object.fromEntries(keep.map((k) => [k, process.env[k]])), + USERPROFILE: home, + APPDATA: join(home, "AppData", "Roaming"), + LOCALAPPDATA: join(home, "AppData", "Local"), + XDG_CONFIG_HOME: join(home, ".config"), + XDG_STATE_HOME: join(home, ".local", "state"), + XDG_DATA_HOME: join(home, ".local", "share"), + }; +} + export function sandbox(): Sandbox { const home = realpathSync(mkdtempSync(join(tmpdir(), "turno-test-"))); const env: NodeJS.ProcessEnv = { PATH: process.env.PATH, HOME: home, TMPDIR: process.env.TMPDIR, + ...(process.platform === "win32" ? windowsEnv(home) : {}), }; return { home, @@ -31,3 +52,13 @@ export function sandbox(): Sandbox { }, }; } + +/** + * Expects `path` to have exactly the permission bits `mode`. Windows has no POSIX modes (the + * user's profile folder keeps turno's files private there by its access list), so it checks + * nothing on Windows. + */ +export function expectMode(path: string, mode: number): void { + if (process.platform === "win32") return; + expect(statSync(path).mode & 0o777).toBe(mode); +} diff --git a/packages/browser/test/last-used.test.ts b/packages/browser/test/last-used.test.ts index 81e77ab4..8557b43e 100644 --- a/packages/browser/test/last-used.test.ts +++ b/packages/browser/test/last-used.test.ts @@ -1,10 +1,10 @@ -import { readFileSync, statSync, writeFileSync } from "node:fs"; +import { readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { PassThrough } from "node:stream"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { identityStateDir } from "../src/ids.js"; import { readLastUsed, touchLastUsed, watchStdinCalls } from "../src/last-used.js"; -import { type Sandbox, sandbox } from "./helpers/sandbox.js"; +import { type Sandbox, sandbox, expectMode } from "./helpers/sandbox.js"; /** When an identity last served a tool call: written at most once a minute, read by `status`. */ @@ -22,7 +22,7 @@ describe("last used", () => { touchLastUsed("school", sb.env, T); expect(readLastUsed("school", sb.env)).toBe(T.toISOString()); const file = join(identityStateDir("school", sb.env), "last-used.json"); - expect(statSync(file).mode & 0o777).toBe(0o600); + expectMode(file, 0o600); expect(JSON.parse(readFileSync(file, "utf8"))).toEqual({ at: T.toISOString() }); // A file it cannot parse reads as never; a write it cannot make (the state folder is a file) is ignored. writeFileSync(file, "{not json"); diff --git a/packages/browser/test/lifecycle.test.ts b/packages/browser/test/lifecycle.test.ts index 62a68bed..779065b4 100644 --- a/packages/browser/test/lifecycle.test.ts +++ b/packages/browser/test/lifecycle.test.ts @@ -255,3 +255,52 @@ describe("sweepOrphan", () => { expect(await sweepOrphan(dir)).toEqual({ action: "none" }); }); }); + +describe("on Windows", () => { + const WIN_CHROME = '"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"'; + const profile = "C:\\Users\\a\\AppData\\Local\\turno\\data\\browser\\identities\\work"; + const winTable = (rows: [number, number, string][]): ProcTable => + new Map(rows.map(([pid, ppid, command]) => [pid, { pid, ppid, pgid: pid, command }])); + const opts = (t: ProcTable, locked = true) => ({ + platform: "win32" as const, + table: t, + locked: () => locked, + selfPid: 7, + }); + + it("matches a profile Windows quoted for its space", () => { + expect(usesProfile(`${WIN_CHROME} "--user-data-dir=C:\\Users\\a b\\p" --no-first-run`, "C:\\Users\\a b\\p")).toBe( + true, + ); + expect(usesProfile(`${WIN_CHROME} "--user-data-dir=C:\\Users\\a b\\p-2"`, "C:\\Users\\a b\\p")).toBe(false); + }); + + it("finds the browser process by its command line while Chrome holds the lockfile, an orphan when its parent left", () => { + const t = winTable([ + [900, 4444, `${WIN_CHROME} --user-data-dir=${profile} --remote-debugging-pipe`], + [901, 900, `${WIN_CHROME} --type=renderer --user-data-dir=${profile}`], + ]); + expect(findProfileChrome(profile, opts(t))).toEqual({ pid: 900, pgid: 900, leaderAlive: true, owner: "orphan" }); + expect(findProfileChrome(profile, opts(t, false))).toBeUndefined(); + t.set(4444, { pid: 4444, ppid: 1, pgid: 4444, command: "node.exe mcp.js" }); + expect(findProfileChrome(profile, opts(t))?.owner).toBe("other"); + t.get(900)!.ppid = 7; + expect(findProfileChrome(profile, opts(t))?.owner).toBe("self"); + }); + + it("closes the tree's windows, then ends the tree with taskkill", async () => { + const calls: [number, boolean][] = []; + let alive = true; + const target = { pid: 900, pgid: 900, leaderAlive: true, owner: "orphan" as const }; + const kill = (pid: number, force: boolean) => { + calls.push([pid, force]); + if (force) alive = false; + }; + const run = { platform: "win32" as const, killTree: kill, alive: () => alive, graceMs: 50, killMs: 50 }; + expect(await stopChrome(target, run)).toBe("killed"); + expect(calls).toEqual([ + [900, false], + [900, true], + ]); + }); +}); diff --git a/packages/browser/test/live-server.test.ts b/packages/browser/test/live-server.test.ts index 756039f9..e0586643 100644 --- a/packages/browser/test/live-server.test.ts +++ b/packages/browser/test/live-server.test.ts @@ -1,4 +1,4 @@ -import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; import { request } from "node:http"; import { dirname } from "node:path"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; @@ -13,7 +13,7 @@ import { LiveServer } from "../src/live-server.js"; import { Redactor, VaultGuard } from "../src/redact.js"; import { writeIdentitySettings } from "../src/settings.js"; import { upstream } from "../src/upstream.js"; -import { type Sandbox, sandbox } from "./helpers/sandbox.js"; +import { type Sandbox, sandbox, expectMode } from "./helpers/sandbox.js"; /** * The live view server without a browser: where it listens, who it answers, the one-time link, @@ -90,9 +90,9 @@ describe("the live view server", () => { const data = JSON.parse(readFileSync(file, "utf8")) as Record; expect(Object.keys(data).sort()).toEqual(["pid", "port", "socket", "started", "version"]); expect(data.pid).toBe(process.pid); - expect(statSync(file).mode & 0o777).toBe(0o600); - expect(statSync(server.socket!).mode & 0o777).toBe(0o600); - expect(statSync(dirname(server.socket!)).mode & 0o777).toBe(0o700); + expectMode(file, 0o600); + expectMode(server.socket!, 0o600); + expectMode(dirname(server.socket!), 0o700); const status = await liveStatus("work", sb.env); expect(status).toMatchObject({ identity: "work", paused: null, browser: false, wait: 5_000, waiting: 0 }); expect(status?.view).toEqual({ available: true, headless: true }); diff --git a/packages/browser/test/network.test.ts b/packages/browser/test/network.test.ts index 8de0cfb8..7ed3babe 100644 --- a/packages/browser/test/network.test.ts +++ b/packages/browser/test/network.test.ts @@ -24,7 +24,7 @@ import { } from "../src/network.js"; import { type IdentitySettings, readIdentitySettings, writeIdentitySettings } from "../src/settings.js"; import type { McpConfig } from "../src/upstream.js"; -import { type FakeSecretStore, fakeSecretStore } from "./helpers/fake-secret-store.js"; +import { type FakeSecretStore, fakeSecretStore, noFakeSecretStore } from "./helpers/fake-secret-store.js"; import { type Sandbox, sandbox } from "./helpers/sandbox.js"; /** @@ -144,7 +144,7 @@ describe("identity.json userAgent and proxy (format 11)", () => { }); describe("the proxy credentials", () => { - it("come from the secret store, and every form of them joins the redactor", async () => { + it.skipIf(noFakeSecretStore)("come from the secret store, and every form of them joins the redactor", async () => { store.write("proxy-pass", PASSWORD); store.write("proxy-user", "alice-zone-1"); const hidden: [string, string][] = []; @@ -160,7 +160,7 @@ describe("the proxy credentials", () => { expect(hidden.map(([v]) => v).includes(basic)).toBe(true); }); - it("fails with the item's name, never a value, when the store lacks it", async () => { + it.skipIf(noFakeSecretStore)("fails with the item's name, never a value, when the store lacks it", async () => { const error = await resolveProxy( { server: "http://127.0.0.1:3128", username: "alice", password: "keychain:missing-item" }, sb.env, @@ -297,27 +297,31 @@ describe("the camoufox engine without a browser", () => { ); }); - it("finds Camoufox at TURNO_CAMOUFOX_PATH or in its installer's cache, and never downloads it", () => { - expect(findCamoufox(sb.env, "darwin")).toBeUndefined(); - const app = join( - camoufoxCacheDir(sb.env, "darwin"), - "browsers", - "official", - "152.0", - "Camoufox.app", - "Contents", - "MacOS", - ); - mkdirSync(app, { recursive: true }); - writeFileSync(join(app, "camoufox"), "#!/bin/sh\necho 'Camoufox 152.0'\n"); - chmodSync(join(app, "camoufox"), 0o755); - expect(findCamoufox(sb.env, "darwin")).toEqual({ path: join(app, "camoufox"), version: "Camoufox 152.0" }); - expect(findCamoufox({ ...sb.env, TURNO_CAMOUFOX_PATH: "relative/camoufox" }, "darwin")).toBeUndefined(); - expect(findCamoufox({ ...sb.env, TURNO_CAMOUFOX_PATH: join(app, "camoufox") }, "linux")?.path).toBe( - join(app, "camoufox"), - ); - expect(camoufoxCacheDir({ ...sb.env, XDG_CACHE_HOME: "/x/cache" }, "linux")).toBe("/x/cache/camoufox"); - }); + // The fake Camoufox is a shell script. + it.skipIf(process.platform === "win32")( + "finds Camoufox at TURNO_CAMOUFOX_PATH or in its installer's cache, and never downloads it", + () => { + expect(findCamoufox(sb.env, "darwin")).toBeUndefined(); + const app = join( + camoufoxCacheDir(sb.env, "darwin"), + "browsers", + "official", + "152.0", + "Camoufox.app", + "Contents", + "MacOS", + ); + mkdirSync(app, { recursive: true }); + writeFileSync(join(app, "camoufox"), "#!/bin/sh\necho 'Camoufox 152.0'\n"); + chmodSync(join(app, "camoufox"), 0o755); + expect(findCamoufox(sb.env, "darwin")).toEqual({ path: join(app, "camoufox"), version: "Camoufox 152.0" }); + expect(findCamoufox({ ...sb.env, TURNO_CAMOUFOX_PATH: "relative/camoufox" }, "darwin")).toBeUndefined(); + expect(findCamoufox({ ...sb.env, TURNO_CAMOUFOX_PATH: join(app, "camoufox") }, "linux")?.path).toBe( + join(app, "camoufox"), + ); + expect(camoufoxCacheDir({ ...sb.env, XDG_CACHE_HOME: "/x/cache" }, "linux")).toBe("/x/cache/camoufox"); + }, + ); it("needs stock playwright-core of patchright-core's minor version", () => { const dir = join(sb.home, "pw"); @@ -409,34 +413,37 @@ describe("combinations refused before anything starts", () => { }); describe("turno browser doctor", () => { - it("says whether the secret store holds the proxy credentials, without reading them", async () => { - addIdentity("px", sb.env); - writeIdentitySettings( - "px", - { proxy: { server: "http://proxy.example.com:8080", username: "alice", password: "keychain:px-pass" } }, - sb.env, - ); - const run = () => - runDoctor({ - env: sb.env, - launch: false, - chrome: () => ({ path: "/chrome", version: "157.0.0.1" }), - lightpanda: () => undefined, - camoufox: () => undefined, - playwrightCore: () => undefined, - procTable: () => new Map(), - }); - const missing = (await run()).checks.filter((c) => c.area === "identity px"); - expect( - missing.find((c) => /proxy http:\/\/proxy\.example\.com:8080: the proxy's operator sees/.test(c.text))?.level, - ).toBe("info"); - const fail = missing.find((c) => c.text.startsWith("proxy credentials")); - expect(fail).toMatchObject({ level: "fail", fix: "turno-browser secret set px-pass" }); - store.write("px-pass", PASSWORD); - const present = (await run()).checks.filter((c) => c.area === "identity px"); - expect(present.find((c) => c.text.startsWith("proxy credentials"))?.level).toBe("ok"); - expect(JSON.stringify(present)).not.toContain(PASSWORD); - }); + it.skipIf(noFakeSecretStore)( + "says whether the secret store holds the proxy credentials, without reading them", + async () => { + addIdentity("px", sb.env); + writeIdentitySettings( + "px", + { proxy: { server: "http://proxy.example.com:8080", username: "alice", password: "keychain:px-pass" } }, + sb.env, + ); + const run = () => + runDoctor({ + env: sb.env, + launch: false, + chrome: () => ({ path: "/chrome", version: "157.0.0.1" }), + lightpanda: () => undefined, + camoufox: () => undefined, + playwrightCore: () => undefined, + procTable: () => new Map(), + }); + const missing = (await run()).checks.filter((c) => c.area === "identity px"); + expect( + missing.find((c) => /proxy http:\/\/proxy\.example\.com:8080: the proxy's operator sees/.test(c.text))?.level, + ).toBe("info"); + const fail = missing.find((c) => c.text.startsWith("proxy credentials")); + expect(fail).toMatchObject({ level: "fail", fix: "turno-browser secret set px-pass" }); + store.write("px-pass", PASSWORD); + const present = (await run()).checks.filter((c) => c.area === "identity px"); + expect(present.find((c) => c.text.startsWith("proxy credentials"))?.level).toBe("ok"); + expect(JSON.stringify(present)).not.toContain(PASSWORD); + }, + ); it("fails on a missing Camoufox or playwright-core only when an identity uses the engine", async () => { const run = () => @@ -479,6 +486,8 @@ describe("the chrome engine's network launch options", () => { const exe = join(sb.home, "chrome"); writeFileSync(exe, "#!/bin/sh\necho 'Google Chrome 157.0.8103.79'\n"); chmodSync(exe, 0o755); + // Where Windows keeps the version: a folder next to the executable. + mkdirSync(join(sb.home, "157.0.8103.79")); // The metadata this Chrome reports, as a first headless launch would have read and kept it. const metadata = { brands: [{ brand: "Google Chrome", version: "157" }], diff --git a/packages/browser/test/reputation.test.ts b/packages/browser/test/reputation.test.ts index 12678d2c..e0a63008 100644 --- a/packages/browser/test/reputation.test.ts +++ b/packages/browser/test/reputation.test.ts @@ -1,5 +1,5 @@ import { EventEmitter } from "node:events"; -import { readFileSync, statSync, writeFileSync } from "node:fs"; +import { readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { addIdentity } from "../src/identities.js"; @@ -11,7 +11,7 @@ import { summarizeChallenges, watchChallenges, } from "../src/reputation.js"; -import { type Sandbox, sandbox } from "./helpers/sandbox.js"; +import { type Sandbox, sandbox, expectMode } from "./helpers/sandbox.js"; /** * The reputation log: one JSON line per challenge a page of an identity showed (captcha, @@ -33,7 +33,7 @@ describe("reputation log", () => { recordChallenge("school", sb.env, { site: "mail.example.com", kind: "verify", markers: ["verify it's you"] }, NOW); const file = reputationPath("school", sb.env); expect(file).toBe(join(sb.home, ".local", "state", "turno", "browser", "identities", "school", "reputation.jsonl")); - expect(statSync(file).mode & 0o777).toBe(0o600); + expectMode(file, 0o600); expect( readFileSync(file, "utf8") .trim() diff --git a/packages/browser/test/resources.test.ts b/packages/browser/test/resources.test.ts index 7003da20..79c12c22 100644 --- a/packages/browser/test/resources.test.ts +++ b/packages/browser/test/resources.test.ts @@ -1,8 +1,9 @@ -import { mkdtempSync, readdirSync, rmSync, statSync } from "node:fs"; +import { mkdtempSync, readdirSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { ResourceCache, blocker, freshness, storable } from "../src/resources.js"; +import { expectMode } from "./helpers/sandbox.js"; describe("blocker", () => { const block = blocker({ @@ -81,8 +82,8 @@ describe("ResourceCache", () => { let now = 1_000; const cache = new ResourceCache(dir, 1024 ** 2 * 10, () => now); expect(await cache.put(meta("https://a.example/1.png", 5_000), Buffer.from("one"))).toBe(true); - expect(statSync(dir).mode & 0o777).toBe(0o700); - for (const f of readdirSync(dir)) expect(statSync(join(dir, f)).mode & 0o777).toBe(0o600); + expectMode(dir, 0o700); + for (const f of readdirSync(dir)) expectMode(join(dir, f), 0o600); expect((await cache.get("https://a.example/1.png", undefined))?.body.toString()).toBe("one"); const again = new ResourceCache(dir, 1024 ** 2 * 10, () => now); diff --git a/packages/browser/test/runtime-lock.test.ts b/packages/browser/test/runtime-lock.test.ts index 6d0e708f..be92b7b5 100644 --- a/packages/browser/test/runtime-lock.test.ts +++ b/packages/browser/test/runtime-lock.test.ts @@ -1,5 +1,5 @@ import { spawn } from "node:child_process"; -import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { addIdentity, isInUse, inUseBy } from "../src/identities.js"; @@ -10,8 +10,9 @@ import { readRuntimeLock, runtimeLockAlive, runtimeLockPath, + stopCommand, } from "../src/runtime-lock.js"; -import { type Sandbox, sandbox } from "./helpers/sandbox.js"; +import { type Sandbox, sandbox, expectMode } from "./helpers/sandbox.js"; /** * The runtime lock: who drives an identity's Chrome right now ({ nodePid, chromePid, pgid, @@ -39,7 +40,7 @@ describe("runtime lock", () => { const held = acquireRuntimeLock("school", sb.env, { holder: "mcp", now: T0 }); const file = runtimeLockPath("school", sb.env); expect(file).toBe(join(sb.home, ".local", "state", "turno", "browser", "identities", "school", "lock.json")); - expect(statSync(file).mode & 0o777).toBe(0o600); + expectMode(file, 0o600); expect(readRuntimeLock("school", sb.env)).toEqual({ nodePid: process.pid, holder: "mcp", @@ -146,3 +147,12 @@ describe("runtime lock", () => { expect(isInUse("school", sb.env)).toBe(false); }); }); + +describe("how a message says to stop the holder", () => { + it("is kill elsewhere, and taskkill of the tree on Windows, which has no SIGTERM", () => { + expect(stopCommand(123, "darwin")).toBe("kill 123"); + expect(stopCommand(123, "win32")).toBe("taskkill /PID 123 /T /F"); + const lock = { nodePid: 123, holder: "mcp" as const, startedAt: "2026-11-22T00:00:00.000Z" }; + expect(inUseMessage("work", lock, "win32")).toContain("`taskkill /PID 123 /T /F`, which ends its Chrome with it"); + }); +}); diff --git a/packages/browser/test/settings.test.ts b/packages/browser/test/settings.test.ts index 3a67efd5..554954c1 100644 --- a/packages/browser/test/settings.test.ts +++ b/packages/browser/test/settings.test.ts @@ -1,4 +1,4 @@ -import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { addIdentity, identityDir, removeIdentity } from "../src/identities.js"; @@ -11,7 +11,7 @@ import { readIdentitySettings, writeIdentitySettings, } from "../src/settings.js"; -import { type Sandbox, sandbox } from "./helpers/sandbox.js"; +import { type Sandbox, sandbox, expectMode } from "./helpers/sandbox.js"; /** * identity.json: the settings that stay fixed for one browser identity (timezone, languages, @@ -64,7 +64,7 @@ describe("writeIdentitySettings", () => { }); const file = identitySettingsPath("school", sb.env); expect(JSON.parse(readFileSync(file, "utf8"))).toEqual(s); - expect(statSync(file).mode & 0o777).toBe(0o600); + expectMode(file, 0o600); expect(readIdentitySettings("school", sb.env)).toEqual(s); }); diff --git a/packages/browser/test/vault.test.ts b/packages/browser/test/vault.test.ts index 75189dbe..71c136fe 100644 --- a/packages/browser/test/vault.test.ts +++ b/packages/browser/test/vault.test.ts @@ -1,4 +1,4 @@ -import { readFileSync, rmSync, statSync } from "node:fs"; +import { readFileSync, rmSync } from "node:fs"; import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { secretStore } from "turno-core/secrets"; @@ -19,8 +19,8 @@ import { vaultSetSubmit, vaultSite, } from "../src/vault.js"; -import { type FakeSecretStore, fakeSecretStore } from "./helpers/fake-secret-store.js"; -import { type Sandbox, sandbox } from "./helpers/sandbox.js"; +import { type FakeSecretStore, fakeSecretStore, noFakeSecretStore } from "./helpers/fake-secret-store.js"; +import { type Sandbox, sandbox, expectMode } from "./helpers/sandbox.js"; let sb: Sandbox; let fake: FakeSecretStore; @@ -36,33 +36,36 @@ const TOTP_SECRET = "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP"; const opts = () => ({ env: sb.env, store: secretStore(sb.env, "darwin")! }); describe("the credential vault", () => { - it("keeps the values in the secret store and only names and origins in the index", async () => { - const site = await vaultAdd( - "work", - "github", - { - urls: ["https://github.com/login", "https://github.com/session"], - username: "alice@example.com", - password: PASSWORD, - totp: TOTP_SECRET, - }, - opts(), - ); - expect(site).toMatchObject({ site: "github", origins: ["https://github.com"], totp: true }); - const index = readFileSync(vaultPath("work", sb.env), "utf8"); - expect(index).not.toContain("alice"); - expect(index).not.toContain("battery"); - expect(index).not.toContain(TOTP_SECRET); - expect(statSync(vaultPath("work", sb.env)).mode & 0o777).toBe(0o600); - expect(fake.services()).toEqual([vaultItem("work", "github")]); - expect(fake.read(vaultItem("work", "github"))).not.toContain("\n"); - const cred = await readCredential("work", "github", opts()); - expect(cred.username === "alice@example.com" && cred.password === PASSWORD).toBe(true); - expect(cred.totp).toMatchObject({ algorithm: "SHA1", digits: 6, period: 30 }); - expect(totp(cred.totp!, 0)).toMatch(/^\d{6}$/); - }); + it.skipIf(noFakeSecretStore)( + "keeps the values in the secret store and only names and origins in the index", + async () => { + const site = await vaultAdd( + "work", + "github", + { + urls: ["https://github.com/login", "https://github.com/session"], + username: "alice@example.com", + password: PASSWORD, + totp: TOTP_SECRET, + }, + opts(), + ); + expect(site).toMatchObject({ site: "github", origins: ["https://github.com"], totp: true }); + const index = readFileSync(vaultPath("work", sb.env), "utf8"); + expect(index).not.toContain("alice"); + expect(index).not.toContain("battery"); + expect(index).not.toContain(TOTP_SECRET); + expectMode(vaultPath("work", sb.env), 0o600); + expect(fake.services()).toEqual([vaultItem("work", "github")]); + expect(fake.read(vaultItem("work", "github"))).not.toContain("\n"); + const cred = await readCredential("work", "github", opts()); + expect(cred.username === "alice@example.com" && cred.password === PASSWORD).toBe(true); + expect(cred.totp).toMatchObject({ algorithm: "SHA1", digits: 6, period: 30 }); + expect(totp(cred.totp!, 0)).toMatch(/^\d{6}$/); + }, + ); - it("lists sites without reading a value, and says when an item went missing", async () => { + it.skipIf(noFakeSecretStore)("lists sites without reading a value, and says when an item went missing", async () => { await vaultAdd( "work", "github", @@ -87,40 +90,46 @@ describe("the credential vault", () => { await expect(readCredential("work", "mail", opts())).rejects.toThrow(/missing from the secret store/); }); - it("replaces a site's credentials by deleting the item first, keeping its creation date", async () => { - const first = await vaultAdd( - "work", - "github", - { urls: ["https://github.com"], username: "alice", password: "first-pass" }, - { ...opts(), now: new Date("2026-01-01T00:00:00Z") }, - ); - const second = await vaultAdd( - "work", - "github", - { urls: ["https://github.com"], username: "alice", password: "second-pass" }, - { ...opts(), now: new Date("2026-02-01T00:00:00Z") }, - ); - expect(second.created).toBe(first.created); - expect(second.updated).toBe("2026-02-01T00:00:00.000Z"); - expect((await readCredential("work", "github", opts())).password === "second-pass").toBe(true); - }); + it.skipIf(noFakeSecretStore)( + "replaces a site's credentials by deleting the item first, keeping its creation date", + async () => { + const first = await vaultAdd( + "work", + "github", + { urls: ["https://github.com"], username: "alice", password: "first-pass" }, + { ...opts(), now: new Date("2026-01-01T00:00:00Z") }, + ); + const second = await vaultAdd( + "work", + "github", + { urls: ["https://github.com"], username: "alice", password: "second-pass" }, + { ...opts(), now: new Date("2026-02-01T00:00:00Z") }, + ); + expect(second.created).toBe(first.created); + expect(second.updated).toBe("2026-02-01T00:00:00.000Z"); + expect((await readCredential("work", "github", opts())).password === "second-pass").toBe(true); + }, + ); - it("removes one site, then everything, and refuses to remove an identity that still has credentials", async () => { - await vaultAdd("work", "github", { urls: ["https://github.com"], username: "alice", password: PASSWORD }, opts()); - await vaultAdd( - "work", - "mail", - { urls: ["https://mail.example.com"], username: "alice", password: PASSWORD }, - opts(), - ); - expect(await vaultRemove("work", "github", opts())).toBe(true); - expect(await vaultRemove("work", "github", opts())).toBe(false); - expect(vaultHasSites("work", sb.env)).toBe(true); - expect(() => removeIdentity("work", sb.env)).toThrow(/still has vault credentials/); - expect(await vaultClear("work", opts())).toBe(1); - expect(fake.services()).toEqual([]); - removeIdentity("work", sb.env); - }); + it.skipIf(noFakeSecretStore)( + "removes one site, then everything, and refuses to remove an identity that still has credentials", + async () => { + await vaultAdd("work", "github", { urls: ["https://github.com"], username: "alice", password: PASSWORD }, opts()); + await vaultAdd( + "work", + "mail", + { urls: ["https://mail.example.com"], username: "alice", password: PASSWORD }, + opts(), + ); + expect(await vaultRemove("work", "github", opts())).toBe(true); + expect(await vaultRemove("work", "github", opts())).toBe(false); + expect(vaultHasSites("work", sb.env)).toBe(true); + expect(() => removeIdentity("work", sb.env)).toThrow(/still has vault credentials/); + expect(await vaultClear("work", opts())).toBe(1); + expect(fake.services()).toEqual([]); + removeIdentity("work", sb.env); + }, + ); it("binds credentials to https origins (http only on this machine)", async () => { expect(vaultOrigin("https://github.com/login?x=1")).toBe("https://github.com"); @@ -156,7 +165,7 @@ describe("the credential vault", () => { expect(fake.services()).toEqual([]); }); - it("records the submit policy per identity", async () => { + it.skipIf(noFakeSecretStore)("records the submit policy per identity", async () => { expect(vaultSetSubmit("work", "auto", { env: sb.env })).toBe("auto"); await vaultAdd("work", "github", { urls: ["https://github.com"], username: "alice", password: PASSWORD }, opts()); expect(vaultSite("work", "github", sb.env)?.submit).toBe("auto"); diff --git a/packages/core/src/paths.ts b/packages/core/src/paths.ts index 473a3bdb..4ead3996 100644 --- a/packages/core/src/paths.ts +++ b/packages/core/src/paths.ts @@ -62,7 +62,8 @@ export function turnoRoots( const get = (name: string) => envValue(env, name, platform) || undefined; const { join } = pathsFor(platform); if (platform === "win32") { - const home = get("HOME") || get("USERPROFILE") || homedir(); + // USERPROFILE first, as Node's os.homedir() and the agents read it; Git Bash may set HOME too. + const home = get("USERPROFILE") || get("HOME") || homedir(); const roaming = get("APPDATA") || join(home, "AppData", "Roaming"); const local = get("LOCALAPPDATA") || join(home, "AppData", "Local"); const xdg = (name: string) => (get(name) ? join(get(name)!, "turno") : undefined); diff --git a/packages/core/src/process.ts b/packages/core/src/process.ts index c6fc61c3..3e93c379 100644 --- a/packages/core/src/process.ts +++ b/packages/core/src/process.ts @@ -67,7 +67,7 @@ export function parseWindowsProcTable(stdout: string): ProcTable { /** Lists every process as `parseWindowsProcTable` reads it, in UTF-8 whatever the console code page. */ const WINDOWS_PROC_SCRIPT = "[Console]::OutputEncoding = [Text.Encoding]::UTF8; " + - "Get-CimInstance Win32_Process | ForEach-Object { '{0}`t{1}`t{2}' -f $_.ProcessId, $_.ParentProcessId, $_.CommandLine }"; + "Get-CimInstance Win32_Process | ForEach-Object { ($_.ProcessId, $_.ParentProcessId, $_.CommandLine) -join [char]9 }"; /** * Every process with its full command line, or undefined when the table cannot be read (no diff --git a/packages/core/test/helpers/global-setup.ts b/packages/core/test/helpers/global-setup.ts index 48901f7a..993912cf 100644 --- a/packages/core/test/helpers/global-setup.ts +++ b/packages/core/test/helpers/global-setup.ts @@ -9,15 +9,21 @@ */ import { chmodSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { delimiter, join } from "node:path"; +import { delimiter, join, sep } from "node:path"; const KEEP = new Set(["TURNO_SKIP_E2E", "TURNO_E2E_NETWORK", "TURNO_SKIP_CHROME"]); const LIVE = /^(TURNO_|CLAUDE|CODEX_|CURSOR_|ANTHROPIC_|XDG_)/; +/** The folders the setup itself makes on Windows (above), not counted while they stay empty. */ +const SETUP_DIRS = new Set(["AppData", join("AppData", "Local"), join("AppData", "Roaming")]); + /** Paths written under the guard HOME, relative to it. */ export function guardFindings(home: string): string[] { try { - return readdirSync(home, { recursive: true }).map(String).sort(); + const found = readdirSync(home, { recursive: true }).map(String).sort(); + return found.filter( + (p) => !SETUP_DIRS.has(p) || found.some((q) => q !== p && q.startsWith(`${p}${sep}`) && !SETUP_DIRS.has(q)), + ); } catch { return []; } @@ -34,10 +40,12 @@ export default function setup(): () => void { process.env.XDG_DATA_HOME = join(home, ".local", "share"); process.env.XDG_CACHE_HOME = join(home, ".cache"); // Windows reads these instead of HOME: the profile folder, and turno's and Playwright's defaults. + // PowerShell and Chrome create them when they are missing, so they are made here and not counted. if (process.platform === "win32") { process.env.USERPROFILE = home; process.env.APPDATA = join(home, "AppData", "Roaming"); process.env.LOCALAPPDATA = join(home, "AppData", "Local"); + for (const dir of [process.env.APPDATA, process.env.LOCALAPPDATA]) mkdirSync(dir, { recursive: true }); } process.env.TURNO_NO_UPDATE_CHECK = "1"; // No test reaches the real secret store: stand-ins for `security` and `secret-tool` that refuse diff --git a/packages/core/test/helpers/sandbox.ts b/packages/core/test/helpers/sandbox.ts index ecc9ecce..f06a41c3 100644 --- a/packages/core/test/helpers/sandbox.ts +++ b/packages/core/test/helpers/sandbox.ts @@ -10,12 +10,32 @@ export interface Sandbox { cleanup(): void; } +/** + * Windows: what programs there need to start (SystemRoot, PATHEXT, the temp folder, where + * browsers are installed), the profile folders inside the sandbox, and turno's folders in the + * XDG layout, so a test reads the same relative paths on every OS. The Windows defaults + * (APPDATA, LOCALAPPDATA) have their own unit test in turno-core. + */ +function windowsEnv(home: string): NodeJS.ProcessEnv { + const keep = ["SystemRoot", "windir", "ComSpec", "PATHEXT", "TEMP", "TMP", "ProgramFiles", "ProgramFiles(x86)"]; + return { + ...Object.fromEntries(keep.map((k) => [k, process.env[k]])), + USERPROFILE: home, + APPDATA: join(home, "AppData", "Roaming"), + LOCALAPPDATA: join(home, "AppData", "Local"), + XDG_CONFIG_HOME: join(home, ".config"), + XDG_STATE_HOME: join(home, ".local", "state"), + XDG_DATA_HOME: join(home, ".local", "share"), + }; +} + export function sandbox(): Sandbox { const home = realpathSync(mkdtempSync(join(tmpdir(), "turno-test-"))); const env: NodeJS.ProcessEnv = { PATH: process.env.PATH, HOME: home, TMPDIR: process.env.TMPDIR, + ...(process.platform === "win32" ? windowsEnv(home) : {}), }; return { home, From ccb7782320df6f08e3761ec73b12064c1e4d0358 Mon Sep 17 00:00:00 2001 From: William Frank Monroy Mamani Date: Sun, 22 Nov 2026 13:10:22 -0600 Subject: [PATCH 05/15] fix(browser): Windows session owners, doctor hints and docs for Windows Session owners know cmd, PowerShell and Git Bash on Windows; doctor's secret store and Chrome install hints name what works there; the docs say how to install turno-browser on Windows, where its data lives and what was checked; CI installs the packed packages with npm on windows-latest. --- .changeset/feat-browser-windows.md | 8 +++ .github/workflows/ci.yml | 51 ++++++++++++++++++- README.md | 4 +- apps/docs/content/docs/(docs)/faq.mdx | 2 +- .../docs/(docs)/get-started/install.mdx | 2 +- apps/docs/content/docs/(docs)/index.mdx | 2 +- .../docs/content/docs/browser/get-started.mdx | 15 ++++++ apps/docs/content/docs/browser/identities.mdx | 23 +++++++-- .../browser-proxy-no-secret-store.mdx | 2 +- .../browser-vault-no-secret-store.mdx | 2 +- apps/docs/reference/doctor-checks.mjs | 4 +- apps/docs/scripts/lib/doctor-findings.mjs | 3 ++ packages/browser/README.md | 2 + packages/browser/src/doctor.ts | 19 ++++--- packages/browser/test/background.test.ts | 10 ++-- packages/browser/test/cli/bin.test.ts | 5 +- packages/browser/test/health.test.ts | 3 +- packages/browser/test/identities.test.ts | 3 +- packages/browser/test/lifecycle.test.ts | 7 +-- packages/browser/test/runtime-lock.test.ts | 2 +- packages/core/src/cli/session.ts | 11 +++- packages/turno/test/cli-browser-do.test.ts | 10 ++++ 22 files changed, 153 insertions(+), 37 deletions(-) create mode 100644 .changeset/feat-browser-windows.md diff --git a/.changeset/feat-browser-windows.md b/.changeset/feat-browser-windows.md new file mode 100644 index 00000000..ae432808 --- /dev/null +++ b/.changeset/feat-browser-windows.md @@ -0,0 +1,8 @@ +--- +"turno-browser": minor +"turno-core": minor +--- + +turno-browser runs on Windows 10 and 11 (x64): `npm install --global turno-browser`, no admin rights. It finds Google Chrome, Microsoft Edge and Brave in `Program Files`, `Program Files (x86)` and `%LOCALAPPDATA%`, and `install-browser` puts Chrome for Testing in `%LOCALAPPDATA%\ms-playwright`. Identities live in `%LOCALAPPDATA%\turno\data`, settings in `%APPDATA%\turno` and runtime state in `%LOCALAPPDATA%\turno\state`; the `TURNO_*_DIR` and `XDG_*` variables still move them. The background server and the live view listen on named pipes (`\\.\pipe\turno-browser--`) instead of socket files. A Chrome left running is found through its profile's lock and the process table, and ended with its helpers by `taskkill /T`; messages say `taskkill /PID /T /F` where they said `kill `. `setup` and `init` register the server as `cmd /c turno-browser-mcp --identity `, and `init --yes` runs an agent's `.cmd` command through `cmd.exe` with each argument quoted. Not on Windows yet: proxy passwords and the vault (no secret store there), and Lightpanda. + +turno-core: the turno folders follow Windows' conventions (`%APPDATA%`, `%LOCALAPPDATA%`), `findOnPath` reads `PATHEXT`, a file replaced while another process reads it is retried instead of failing, and `killTree` ends a process tree on every platform. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 133992fb..f173f412 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -73,8 +73,57 @@ jobs: # The secret store tests drive POSIX shell stand-ins for security and secret-tool; the # Windows secret store comes with its own tests. - run: pnpm --filter turno-core exec vitest run --exclude test/secrets.test.ts - - run: pnpm --filter turno-browser run test + - name: Time the process table (diagnostic) + shell: pwsh + run: | + foreach ($i in 1..3) { (Measure-Command { powershell.exe -NoProfile -NonInteractive -Command "Get-CimInstance Win32_Process | Out-Null" }).TotalSeconds } + - run: pnpm --filter turno-browser exec vitest run --reporter=verbose + if: ${{ !cancelled() }} + # What a person gets from npm: the packed packages installed with npm (its .cmd shims), + # then install-browser and a smoke launch of Chrome through doctor, in a scratch turno folder. + - name: Install the packed packages with npm and run them if: ${{ !cancelled() }} + shell: pwsh + run: | + $ErrorActionPreference = "Stop" + $pack = Join-Path $env:RUNNER_TEMP "pack" + $app = Join-Path $env:RUNNER_TEMP "app" + New-Item -ItemType Directory -Force $pack, $app | Out-Null + foreach ($pkg in "core", "browser") { + Push-Location "packages/$pkg"; pnpm pack --pack-destination $pack; Pop-Location + if ($LASTEXITCODE) { exit 1 } + } + $core = (Get-ChildItem $pack -Filter "turno-core-*.tgz").FullName + $browser = (Get-ChildItem $pack -Filter "turno-browser-*.tgz").FullName + @{ private = $true; dependencies = @{ "turno-browser" = "file:$browser" }; overrides = @{ "turno-core" = "file:$core" } } | + ConvertTo-Json | Set-Content (Join-Path $app "package.json") + Set-Location $app + npm install --no-audit --no-fund + if ($LASTEXITCODE) { exit 1 } + $env:TURNO_CONFIG_DIR = Join-Path $env:RUNNER_TEMP "turno\config" + $env:TURNO_STATE_DIR = Join-Path $env:RUNNER_TEMP "turno\state" + $env:TURNO_DATA_DIR = Join-Path $env:RUNNER_TEMP "turno\data" + $env:Path = "$app\node_modules\.bin;$env:Path" + cmd /c "turno-browser --version" + if ($LASTEXITCODE) { exit 1 } + cmd /c "turno-browser add smoke" + if ($LASTEXITCODE) { exit 1 } + cmd /c "turno-browser setup claude-code --identity smoke" + # Chrome for Testing goes to %LOCALAPPDATA%\ms-playwright: no admin rights needed. + cmd /c "turno-browser install-browser" + if ($LASTEXITCODE) { exit 1 } + $doctor = cmd /c "turno-browser doctor --json" | Out-String + Write-Output $doctor + $checks = $doctor | ConvertFrom-Json + $checks = $checks.checks + if (-not ($checks | Where-Object { $_.status -eq "ok" -and $_.text -like "smoke launch:*" })) { + Write-Error "doctor did not start and close Chrome" + } + if (-not ($checks | Where-Object { $_.status -eq "ok" -and $_.text -like "Chrome for Testing *" })) { + Write-Error "doctor did not find the Chrome for Testing install-browser downloaded" + } + cmd /c "turno-browser remove smoke --yes" + if ($LASTEXITCODE) { exit 1 } pull-request: name: pull request rules diff --git a/README.md b/README.md index 8a1aaa9f..8364c8f8 100644 --- a/README.md +++ b/README.md @@ -212,7 +212,9 @@ way. Only MCP tool calls go through `mcpd`, on `127.0.0.1`, with a bearer token and requests with an `Origin` header are rejected so web pages cannot reach it. **Linux? Windows?** Linux works too: secrets go to the Secret Service (`secret-tool`), mcpd runs -as a `systemd --user` unit, and links open with `xdg-open`. Windows is not supported. +as a `systemd --user` unit, and links open with `xdg-open`. turno itself does not run on Windows, +but turno-browser does, on its own: `npm install --global turno-browser` (see +[Get started](https://turno.wimo.dev/docs/browser/get-started#on-windows)). **Can scripts and agents run turno?** Yes. turno asks only when a person is at a terminal: with `--no-input` (or `TURNO_NO_INPUT=1`), when stdin is not a terminal, and inside a Claude Code, diff --git a/apps/docs/content/docs/(docs)/faq.mdx b/apps/docs/content/docs/(docs)/faq.mdx index e4546e61..16db19ba 100644 --- a/apps/docs/content/docs/(docs)/faq.mdx +++ b/apps/docs/content/docs/(docs)/faq.mdx @@ -19,7 +19,7 @@ No. It launches the agent and gets out of the way. Only MCP tool calls go throug ## Linux? Windows? -Linux works too: secrets go to the Secret Service (`secret-tool`), mcpd runs as a `systemd --user` unit, and links open with `xdg-open`. Windows is not supported. +Linux works too: secrets go to the Secret Service (`secret-tool`), mcpd runs as a `systemd --user` unit, and links open with `xdg-open`. turno itself does not run on Windows, but turno-browser does, on its own: see [Get started](/docs/browser/get-started#on-windows). ## Can scripts and agents run turno? diff --git a/apps/docs/content/docs/(docs)/get-started/install.mdx b/apps/docs/content/docs/(docs)/get-started/install.mdx index 7c46e666..bfacb593 100644 --- a/apps/docs/content/docs/(docs)/get-started/install.mdx +++ b/apps/docs/content/docs/(docs)/get-started/install.mdx @@ -7,7 +7,7 @@ This page installs the `turno` command and shows how to update and remove it. ## Requirements -- macOS or Linux. Windows is not supported. +- macOS or Linux. turno does not run on Windows; turno-browser does, on its own ([Get started](/docs/browser/get-started#on-windows)). - Node 22.11 or newer. - At least one of the agents turno works with: Claude Code, Codex CLI, GitHub Copilot CLI or Cursor CLI. diff --git a/apps/docs/content/docs/(docs)/index.mdx b/apps/docs/content/docs/(docs)/index.mdx index 0204d916..664fd799 100644 --- a/apps/docs/content/docs/(docs)/index.mdx +++ b/apps/docs/content/docs/(docs)/index.mdx @@ -63,7 +63,7 @@ Machine ──────────────────────── turno is for the case where you run many sessions of several agents with more than one account. If you only need one of those pieces, other tools do it well: see the [comparison](/docs/comparison). -It runs on macOS and Linux with Node 22.11 or newer. Windows is not supported. Nothing leaves your machine: no account, no telemetry, no proxy for model traffic. +It runs on macOS and Linux with Node 22.11 or newer. On Windows only turno-browser runs, on its own ([Get started](/docs/browser/get-started#on-windows)). Nothing leaves your machine: no account, no telemetry, no proxy for model traffic. The intended use is separate work and personal accounts. turno runs each vendor's own, unmodified CLI, and each account stays bound by its vendor's terms. Do not use it to get around usage limits or safeguards. See [Vendor terms](/docs/security#vendor-terms). diff --git a/apps/docs/content/docs/browser/get-started.mdx b/apps/docs/content/docs/browser/get-started.mdx index cfb244fc..24f5a55b 100644 --- a/apps/docs/content/docs/browser/get-started.mdx +++ b/apps/docs/content/docs/browser/get-started.mdx @@ -13,6 +13,21 @@ npm install --global turno-browser This installs two commands: `turno-browser`, which manages identities, and `turno-browser-mcp`, the MCP server an agent runs for one identity. +### On Windows + +turno-browser runs on Windows 10 and 11 (x64) too. Install it the same way, from PowerShell or the Command Prompt, with no admin rights: + +```powershell +npm install --global turno-browser +``` + +- **Browsers.** It finds Google Chrome, Microsoft Edge and Brave in `Program Files`, `Program Files (x86)` and, for an install for your user alone, `%LOCALAPPDATA%`. With none of them, `turno-browser install-browser` puts Chrome for Testing in `%LOCALAPPDATA%\ms-playwright`, and `winget install --id Google.Chrome.EXE --scope user` installs Chrome for your user alone. +- **Your data.** Identities and their profiles go to `%LOCALAPPDATA%\turno\data\browser`, settings to `%APPDATA%\turno` and runtime state to `%LOCALAPPDATA%\turno\state`. `TURNO_CONFIG_DIR`, `TURNO_STATE_DIR` and `TURNO_DATA_DIR`, or the `XDG_*` variables, move them as on Linux. [Identities](/docs/browser/identities#on-windows) has the details. +- **Agents.** npm installs `turno-browser-mcp` as a `.cmd` file, which a program can start only through `cmd.exe`, so `setup` and `init` register it as `cmd /c turno-browser-mcp --identity `. +- **Not on Windows yet:** proxy passwords and the [vault](/docs/browser/vault) (turno-browser has no secret store there), and Lightpanda, which has no Windows build. Camoufox runs when `TURNO_CAMOUFOX_PATH` names its `camoufox.exe`. turno itself (`turno-cli`) does not install on Windows: npm refuses it. + +What was checked: the test suite, including the tests that start a real Google Chrome, on GitHub's `windows-latest` runner with Node 22 and 24, and an npm install of the packages followed by `install-browser` and `doctor`'s test launch. Edge and Brave are detected there but were not launched, and nobody has tried it by hand on a Windows 10 or 11 desktop or on ARM64 yet. + ## Install without Node On a machine without Node or npm, use the standalone executable: one file that holds turno-browser and the Node.js runtime it needs. It still drives the Chrome, Edge or Brave installed on the machine, or the Chrome for Testing that `turno-browser install-browser` puts in your user cache. The GitHub release of each turno-browser version, tagged `turno-browser@` on the [releases page](https://github.com/wimo-dev/turno/releases), has one archive per platform and a `SHA256SUMS` file: diff --git a/apps/docs/content/docs/browser/identities.mdx b/apps/docs/content/docs/browser/identities.mdx index 3d58ab54..27a761e8 100644 --- a/apps/docs/content/docs/browser/identities.mdx +++ b/apps/docs/content/docs/browser/identities.mdx @@ -17,7 +17,19 @@ turno-browser login school turno-browser list ``` -Identities live under `~/.local/share/turno/browser/`. They hold live cookies of the sites you signed into: treat that folder as credentials. +Identities live under `~/.local/share/turno/browser/` (on Windows, `%LOCALAPPDATA%\turno\data\browser\`). They hold live cookies of the sites you signed into: treat that folder as credentials. + +### On Windows + +| What | Where | +|---|---| +| Identities, profiles, flows, recordings | `%LOCALAPPDATA%\turno\data\browser` | +| Settings | `%APPDATA%\turno` | +| Runtime locks, background server state, logs | `%LOCALAPPDATA%\turno\state` | + +`TURNO_DATA_DIR`, `TURNO_CONFIG_DIR` and `TURNO_STATE_DIR` (or `XDG_DATA_HOME`, `XDG_CONFIG_HOME` and `XDG_STATE_HOME`) move them as on macOS and Linux. + +The background server listens on a named pipe, `\\.\pipe\turno-browser--`, instead of a socket file. By default Windows lets only your user, the administrators and the system account write to a pipe like it, so nobody else can send it a request. The hash comes from the state folder, so two turno folders never share a pipe. When another program already holds that name, the server listens on `127.0.0.1` instead, with a bearer token kept in your state folder. Windows has no signals, so `background stop` asks the server to stop over its own pipe, and a holder that does not answer is ended with `taskkill /PID /T /F`, which ends its Chrome with it. ## Settings that do not change @@ -84,7 +96,10 @@ turno-browser doctor tools, the [live view](/docs/browser/live-view)'s picture and the [agent cursor](/docs/browser/agent-cursor) worked, with cookies kept from one start to the next. Arc and Dia are Chromium builds turno has not tested: give their path if you want to try one. On Linux turno looks in the packages' usual -places (`/opt/google/chrome`, `/opt/microsoft/msedge`, `/opt/brave.com/brave`, `/usr/bin`). +places (`/opt/google/chrome`, `/opt/microsoft/msedge`, `/opt/brave.com/brave`, `/usr/bin`). On +Windows it looks in `Program Files`, `Program Files (x86)` and `%LOCALAPPDATA%` (where a browser +installed for your user alone goes), and reads the version from the folder next to the browser +instead of starting it. When Google Chrome is not installed, `add` and `init` pick the first browser they find and write it to `identity.json`, so the profile never changes browser by itself. A server's own `--browser` @@ -99,8 +114,8 @@ turno-browser set school --browser chrome-for-testing `install-browser` downloads Chrome for Testing, the Chrome build Google publishes for automation, with the installer of the Playwright build turno-browser uses: about 190 MB into your user cache -(`~/Library/Caches/ms-playwright` on macOS, `~/.cache/ms-playwright` on Linux, or -`PLAYWRIGHT_BROWSERS_PATH`). It needs no admin password and changes nothing outside that folder. +(`~/Library/Caches/ms-playwright` on macOS, `~/.cache/ms-playwright` on Linux, +`%LOCALAPPDATA%\ms-playwright` on Windows, or `PLAYWRIGHT_BROWSERS_PATH`). It needs no admin password and changes nothing outside that folder. Its limits: it does not update itself (run the command again after you update turno-browser), it can be a version behind Chrome, and Google publishes it for testing, not as an everyday browser. Google's sign-in page loaded in it as in Chrome and Brave when turno tried it. diff --git a/apps/docs/content/docs/troubleshooting/browser-proxy-no-secret-store.mdx b/apps/docs/content/docs/troubleshooting/browser-proxy-no-secret-store.mdx index 9500a2c4..4242e973 100644 --- a/apps/docs/content/docs/troubleshooting/browser-proxy-no-secret-store.mdx +++ b/apps/docs/content/docs/troubleshooting/browser-proxy-no-secret-store.mdx @@ -26,7 +26,7 @@ Install libsecret (secret-tool), or use a proxy without a password. No single command fixes this one, so doctor names the manual step. -Install libsecret (secret-tool) on Linux, or use a proxy without a password. +Install libsecret (secret-tool) on Linux, or use a proxy without a password. On Windows turno-browser has no secret store yet, so only a proxy without a password works there. Then run `turno browser doctor` again to see the row turn into `ok`. diff --git a/apps/docs/content/docs/troubleshooting/browser-vault-no-secret-store.mdx b/apps/docs/content/docs/troubleshooting/browser-vault-no-secret-store.mdx index d34f0819..045b50d1 100644 --- a/apps/docs/content/docs/troubleshooting/browser-vault-no-secret-store.mdx +++ b/apps/docs/content/docs/troubleshooting/browser-vault-no-secret-store.mdx @@ -26,7 +26,7 @@ Install libsecret (secret-tool), then add them again with turno browser vault ad No single command fixes this one, so doctor names the manual step. -Install libsecret (secret-tool) on Linux, then add the credentials again with turno browser vault add. +Install libsecret (secret-tool) on Linux, then add the credentials again with turno browser vault add. On Windows turno-browser has no secret store yet, so the vault does not work there. Then run `turno browser doctor` again to see the row turn into `ok`. diff --git a/apps/docs/reference/doctor-checks.mjs b/apps/docs/reference/doctor-checks.mjs index 270717be..f15c8fc7 100644 --- a/apps/docs/reference/doctor-checks.mjs +++ b/apps/docs/reference/doctor-checks.mjs @@ -496,7 +496,7 @@ export const DOCTOR_CHECKS = [ match: "the proxy credentials are in the secret store, and this machine has none", title: "No secret store for the proxy credentials", why: "An identity's proxy signs in with a keychain: reference, and this machine has neither the macOS Keychain tool nor secret-tool (libsecret), so turno cannot read the password and the browser does not start.", - fix: "Install libsecret (secret-tool) on Linux, or use a proxy without a password.", + fix: "Install libsecret (secret-tool) on Linux, or use a proxy without a password. On Windows turno-browser has no secret store yet, so only a proxy without a password works there.", }, { id: "browser-proxy-secret-missing", @@ -511,7 +511,7 @@ export const DOCTOR_CHECKS = [ match: "credential in the secret store, and this machine has none", title: "No secret store for the vault", why: "The identity's vault keeps each site's credentials in the secret store, and this machine has neither the macOS Keychain tool nor secret-tool (libsecret), so browser_login cannot sign in anywhere.", - fix: "Install libsecret (secret-tool) on Linux, then add the credentials again with turno browser vault add.", + fix: "Install libsecret (secret-tool) on Linux, then add the credentials again with turno browser vault add. On Windows turno-browser has no secret store yet, so the vault does not work there.", }, { id: "browser-vault-store-no-answer", diff --git a/apps/docs/scripts/lib/doctor-findings.mjs b/apps/docs/scripts/lib/doctor-findings.mjs index aeb73ddc..51861a47 100644 --- a/apps/docs/scripts/lib/doctor-findings.mjs +++ b/apps/docs/scripts/lib/doctor-findings.mjs @@ -28,6 +28,9 @@ function render(node, sf) { return out; } if (ts.isParenthesizedExpression(node)) return render(node.expression, sf); + // A platform branch (`platform === "win32" ? windows : general`): the page shows the general + // side, and its fix text covers the other. + if (ts.isConditionalExpression(node) && node.condition.getText(sf).includes('"win32"')) return render(node.whenFalse, sf); return undefined; } diff --git a/packages/browser/README.md b/packages/browser/README.md index 01993d5a..294c15b4 100644 --- a/packages/browser/README.md +++ b/packages/browser/README.md @@ -14,6 +14,8 @@ npm install --global turno-browser turno-browser init ``` +It runs on macOS, Linux and Windows 10 and 11 (x64). + `init` asks a name for the identity, opens Chrome so you sign in by hand once, and gives the identity to your agent. Each step is also a command of its own: `turno-browser add`, `login` and `setup`. diff --git a/packages/browser/src/doctor.ts b/packages/browser/src/doctor.ts index 59865d79..49d2db98 100644 --- a/packages/browser/src/doctor.ts +++ b/packages/browser/src/doctor.ts @@ -220,7 +220,7 @@ function systemChecks(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): Doctor out.push({ area: "system", level: "info", - text: "Windows: Chrome opens in your desktop session, and the background server listens on a named pipe only your user can open", + text: "Windows: Chrome opens in your desktop session, and the background server listens on a named pipe only your user can send requests to", }); } else if (platform === "linux") { if (env.DISPLAY || env.WAYLAND_DISPLAY) @@ -673,7 +673,10 @@ async function networkRows(id: string, env: NodeJS.ProcessEnv, opts: DoctorOptio area, level: "fail", text: "the proxy credentials are in the secret store, and this machine has none", - manual: `${noStoreHint(opts.platform ?? process.platform)}, or use a proxy without a password`, + manual: + (opts.platform ?? process.platform) === "win32" + ? "turno-browser has no secret store on Windows yet: use a proxy without a password" + : "install libsecret (secret-tool), or use a proxy without a password", }); return out; } @@ -692,13 +695,6 @@ async function networkRows(id: string, env: NodeJS.ProcessEnv, opts: DoctorOptio return out; } -/** What gives this machine a secret store: libsecret on Linux; on Windows turno-browser has none yet. */ -function noStoreHint(platform: NodeJS.Platform): string { - return platform === "win32" - ? "turno-browser has no secret store on Windows yet: run this identity from macOS or Linux" - : "install libsecret (secret-tool)"; -} - /** Whether the secret store has an item for each credential of the vault: lookups only, never a value. */ async function vaultRows(id: string, env: NodeJS.ProcessEnv, opts: DoctorOptions): Promise { const sites = vaultSummary(id, env)?.sites ?? []; @@ -711,7 +707,10 @@ async function vaultRows(id: string, env: NodeJS.ProcessEnv, opts: DoctorOptions area, level: "fail", text: `the vault has ${sites.length} credential${sites.length === 1 ? "" : "s"} in the secret store, and this machine has none`, - manual: `${noStoreHint(opts.platform ?? process.platform)}, then add them again with turno browser vault add`, + manual: + (opts.platform ?? process.platform) === "win32" + ? "turno-browser has no secret store on Windows yet: run this identity's vault from macOS or Linux" + : "install libsecret (secret-tool), then add them again with turno browser vault add", }, ]; const missing: string[] = []; diff --git a/packages/browser/test/background.test.ts b/packages/browser/test/background.test.ts index 58ae2272..82947176 100644 --- a/packages/browser/test/background.test.ts +++ b/packages/browser/test/background.test.ts @@ -28,7 +28,7 @@ import { } from "../src/client.js"; import type { Engine, LaunchRequest } from "../src/engine.js"; import { createHost, serve } from "../src/host.js"; -import { runtimeLockPath } from "../src/runtime-lock.js"; +import { runtimeLockPath, stopCommand } from "../src/runtime-lock.js"; import type { SharingMode } from "../src/sharing.js"; import { type TurnoTool, turnoZod } from "../src/tools.js"; import { upstream } from "../src/upstream.js"; @@ -419,10 +419,12 @@ describe("the background server in process", () => { socket: backgroundSocketPath(ID, env), }), ); - writeFileSync(backgroundSocketPath(ID, env), ""); + // A socket file stays behind a killed server; Windows removes a pipe with its process. + const staleSocket = () => process.platform !== "win32" && writeFileSync(backgroundSocketPath(ID, env), ""); + staleSocket(); expect(backgroundStatus(ID, { env })).toBeUndefined(); expect(existsSync(backgroundStatePath(ID, env))).toBe(false); - writeFileSync(backgroundSocketPath(ID, env), ""); + staleSocket(); const server = await startInProcess(); expect(server.state.pid).toBe(process.pid); const s = await openBackgroundSession(ID, { env, start: false }); @@ -472,7 +474,7 @@ describe("the background server as a program, through the client", () => { const res = await client.callTool({ name: "browser_snapshot", arguments: {} }); expect(res.isError).toBe(true); expect(textOf(res)).toContain( - `browser identity "${ID}" is served by its background server (pid ${state.pid}) since ${state.startedAt}, which owns the identity's browser while it runs. Stop it with \`turno-browser background stop ${ID}\` (or \`kill ${state.pid}\`; it closes its Chrome first), or wait: it exits after 15m without a request; then try again.`, + `browser identity "${ID}" is served by its background server (pid ${state.pid}) since ${state.startedAt}, which owns the identity's browser while it runs. Stop it with \`turno-browser background stop ${ID}\` (or \`${stopCommand(state.pid)}\`; ${process.platform === "win32" ? "that ends its Chrome with it" : "it closes its Chrome first"}), or wait: it exits after 15m without a request; then try again.`, ); expect(engine.launches).toEqual([]); // A tool that needs no browser still answers. diff --git a/packages/browser/test/cli/bin.test.ts b/packages/browser/test/cli/bin.test.ts index b737a771..725d2961 100644 --- a/packages/browser/test/cli/bin.test.ts +++ b/packages/browser/test/cli/bin.test.ts @@ -37,7 +37,8 @@ function runWith(args: string[], extra: NodeJS.ProcessEnv, input = "") { input, timeout: 30_000, }); - return { code: r.status, out: r.stdout, err: r.stderr }; + // A run that timed out has no exit code: its error says so. + return { code: r.status, out: r.stdout, err: r.error ? `${r.stderr}${r.error.message}` : r.stderr }; } /** How an agent starts turno-browser-mcp found on the PATH: through cmd.exe on Windows, where npm installs a `.cmd`. */ @@ -344,7 +345,7 @@ describe("onboarding and offboarding without a terminal", () => { expect(refused.err).toContain("pass --yes"); const removed = runWith(["remove", "school", "--yes", "--json"], env); - expect(removed.code).toBe(0); + expect(removed.code, removed.err).toBe(0); const r = JSON.parse(removed.out); expect(r).toMatchObject({ complete: true, failed: [], left: [] }); expect(r.deleted.map((d: { kind: string }) => d.kind)).toContain("mcp"); diff --git a/packages/browser/test/health.test.ts b/packages/browser/test/health.test.ts index 684e2e02..fd9ad6e6 100644 --- a/packages/browser/test/health.test.ts +++ b/packages/browser/test/health.test.ts @@ -9,6 +9,7 @@ import { writeHealth, } from "../src/health.js"; import { type Sandbox, sandbox } from "./helpers/sandbox.js"; +import { slashes } from "./helpers/programs.js"; /** * Session health: a URL plus a text or selector that only a signed-in page shows. The check @@ -113,7 +114,7 @@ describe("health record", () => { it("is stored per identity and cleared after a login", () => { expect(readHealth("school", sb.env)).toBeUndefined(); writeHealth("school", sb.env, { status: "needs_auth", url: check.url, checkedAt: NOW.toISOString(), detail: "x" }); - expect(healthPath("school", sb.env)).toMatch(/state\/turno\/browser\/identities\/school\/health\.json$/); + expect(slashes(healthPath("school", sb.env))).toMatch(/state\/turno\/browser\/identities\/school\/health\.json$/); expect(readHealth("school", sb.env)).toMatchObject({ status: "needs_auth" }); clearHealth("school", sb.env); expect(readHealth("school", sb.env)).toBeUndefined(); diff --git a/packages/browser/test/identities.test.ts b/packages/browser/test/identities.test.ts index 077e4825..2418c42f 100644 --- a/packages/browser/test/identities.test.ts +++ b/packages/browser/test/identities.test.ts @@ -57,7 +57,8 @@ describe("in use detection", () => { expect(parseSingletonLock("garbage")).toBeUndefined(); }); - it("is in use when the lock points to a live PID", () => { + // SingletonLock is POSIX; on Windows Chrome holds a lockfile no Node process can hold the same way. + it.skipIf(process.platform === "win32")("is in use when the lock points to a live PID", () => { const { dir } = addIdentity("work", sb.env); expect(isInUse("work", sb.env)).toBe(false); symlinkSync(`${hostname()}-${process.pid}`, join(dir, "SingletonLock")); diff --git a/packages/browser/test/lifecycle.test.ts b/packages/browser/test/lifecycle.test.ts index 779065b4..0e262ab0 100644 --- a/packages/browser/test/lifecycle.test.ts +++ b/packages/browser/test/lifecycle.test.ts @@ -64,7 +64,8 @@ describe("process table", () => { }); }); -describe("findProfileChrome", () => { +// SingletonLock and process groups are POSIX; the Windows branch has its own tests at the end. +describe.skipIf(process.platform === "win32")("findProfileChrome", () => { const alive = () => true; it("finds nothing without a lock or when the lock points at another program", () => { @@ -148,7 +149,7 @@ describe("findProfileChrome", () => { }); }); -describe("stopChrome", () => { +describe.skipIf(process.platform === "win32")("stopChrome", () => { function fakeProcs(dieOn: NodeJS.Signals | "never") { const sent: [number, NodeJS.Signals][] = []; let dead = false; @@ -219,7 +220,7 @@ describe("stopChrome", () => { }); }); -describe("sweepOrphan", () => { +describe.skipIf(process.platform === "win32")("sweepOrphan", () => { it("leaves a Chrome that another live process owns", async () => { lock(500); const t = table([ diff --git a/packages/browser/test/runtime-lock.test.ts b/packages/browser/test/runtime-lock.test.ts index be92b7b5..4768e702 100644 --- a/packages/browser/test/runtime-lock.test.ts +++ b/packages/browser/test/runtime-lock.test.ts @@ -78,7 +78,7 @@ describe("runtime lock", () => { expect(message).toContain( `browser identity "school" is in use by turno-browser-mcp (pid ${other.pid}, Chrome pid 777) since ${T0.toISOString()}`, ); - expect(message).toContain(`kill ${other.pid}`); + expect(message).toContain(stopCommand(other.pid!)); expect(JSON.parse(readFileSync(file, "utf8")).nodePid).toBe(other.pid); } finally { other.kill(); diff --git a/packages/core/src/cli/session.ts b/packages/core/src/cli/session.ts index f7856195..efc5f39d 100644 --- a/packages/core/src/cli/session.ts +++ b/packages/core/src/cli/session.ts @@ -19,15 +19,20 @@ export interface Owner { } const SHELLS = new Set(["sh", "bash", "zsh", "dash", "fish", "ksh", "mksh", "ash", "csh", "tcsh"]); +/** Windows' shells: `cmd /c` (an npm `.cmd` shim, a command an agent runs) and PowerShell's `-Command`. */ +const WINDOWS_SHELLS = new Set(["cmd", "powershell", "pwsh"]); const WRAPPERS = new Set(["env", "timeout", "gtimeout", "nice", "nohup", "stdbuf", "time", "xargs"]); const RUNNERS = /^(pnpm|pnpx|npm|npx|yarn|bunx|corepack)(\.c?js)?$|^(npm|npx)-cli\.js$/; +/** The words of a command line; a Windows path with a space comes in double quotes. */ function words(command: string): string[] { - return command.trim().split(/\s+/); + return [...command.trim().matchAll(/"([^"]*)"|(\S+)/g)].map((m) => m[1] ?? m[2]!); } +/** A program's name: no folder (either separator), no login dash, and on Windows no `.exe`, in lower case. */ function program(word: string | undefined): string { - return basename(word ?? "").replace(/^-/, ""); + const name = basename((word ?? "").replace(/\\/g, "/")).replace(/^-/, ""); + return /\.exe$/i.test(name) ? name.slice(0, -4).toLowerCase() : name; } /** @@ -40,6 +45,8 @@ export function passesOn(command: string): boolean { const [first, ...rest] = words(command); const name = program(first); if (SHELLS.has(name)) return rest.some((w) => /^-[a-zA-Z]*c[a-zA-Z]*$/.test(w)); + if (WINDOWS_SHELLS.has(name.toLowerCase())) + return rest.some((w) => /^\/c$/i.test(w) || /^-(c|command|encodedcommand|ec)$/i.test(w)); if (WRAPPERS.has(name)) return true; if (RUNNERS.test(name)) return true; if (name === "node" || name === "bun") return RUNNERS.test(program(rest[0])); diff --git a/packages/turno/test/cli-browser-do.test.ts b/packages/turno/test/cli-browser-do.test.ts index 3948afc5..e4326585 100644 --- a/packages/turno/test/cli-browser-do.test.ts +++ b/packages/turno/test/cli-browser-do.test.ts @@ -7,6 +7,7 @@ import { browserCommand, defaultDeps } from "../src/cli/commands/browser.js"; import type { DoDeps } from "../src/cli/commands/browser-do.js"; import { identityServer, + ownerName, passesOn, sessionName, sessionOwner, @@ -102,6 +103,15 @@ describe("the session owner", () => { expect(passesOn("node /opt/agent/cli.js")).toBe(false); }); + it("knows Windows' shells, quoted paths and .exe names", () => { + expect(passesOn('C:\\WINDOWS\\system32\\cmd.exe /d /s /c "turno-browser do x snapshot"')).toBe(true); + expect(passesOn('"C:\\Program Files\\PowerShell\\7\\pwsh.exe" -NoProfile -Command turno-browser do x')).toBe(true); + expect(passesOn('"C:\\Program Files\\Git\\usr\\bin\\bash.exe" -c "turno-browser do x"')).toBe(true); + expect(passesOn('"C:\\Program Files\\PowerShell\\7\\pwsh.exe"')).toBe(false); + expect(passesOn("C:\\WINDOWS\\system32\\cmd.exe")).toBe(false); + expect(ownerName({ pid: 7, command: '"C:\\Program Files\\nodejs\\node.exe" "C:\\agent\\cli.js"' })).toBe("cli"); + }); + it("is the agent above its per-command shells, or the terminal's shell", () => { const table = parseProcTable( [ From d4f86b18dd0debf3f3445c6e87888d97ce70ade6 Mon Sep 17 00:00:00 2001 From: William Frank Monroy Mamani Date: Sun, 22 Nov 2026 13:18:10 -0600 Subject: [PATCH 06/15] fix: pack on Windows, and let the test guard allow PowerShell's caches --- .github/workflows/ci.yml | 23 +++++++++++++++---- .../docs/content/docs/browser/get-started.mdx | 2 +- packages/browser/test/helpers/global-setup.ts | 17 ++++++++++---- packages/core/test/helpers/global-setup.ts | 17 ++++++++++---- scripts/shrinkwrap.mjs | 7 ++++-- 5 files changed, 49 insertions(+), 17 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f173f412..6fc3b1f2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -70,13 +70,28 @@ jobs: - run: pnpm install --frozen-lockfile - run: pnpm --filter turno-core --filter turno-browser run build - run: pnpm --filter turno-core --filter turno-browser run typecheck + - name: Diagnostics (temporary) + continue-on-error: true + shell: pwsh + run: | + $q = "Get-CimInstance Win32_Process | Out-Null" + foreach ($i in 1..2) { "normal: " + (Measure-Command { powershell.exe -NoProfile -NonInteractive -Command $q }).TotalSeconds } + $fresh = Join-Path $env:RUNNER_TEMP "fresh" + New-Item -ItemType Directory -Force $fresh | Out-Null + $old = $env:LOCALAPPDATA + $env:LOCALAPPDATA = $fresh + foreach ($i in 1..2) { "fresh LOCALAPPDATA: " + (Measure-Command { powershell.exe -NoProfile -NonInteractive -Command $q }).TotalSeconds } + $env:LOCALAPPDATA = $old + Set-Location packages/browser + $probe = "const { chromium } = require(process.argv[1]); chromium.launch({ channel: 'chrome', headless: true, timeout: 30000 }).then((b) => { console.log('started', b.version()); return b.close(); }).catch((e) => { console.error(e.message); process.exit(1); });" + "probe, normal env:"; node -e $probe (Resolve-Path node_modules/patchright-core) + $home2 = Join-Path $env:RUNNER_TEMP "home2" + New-Item -ItemType Directory -Force $home2 | Out-Null + $env:USERPROFILE = $home2; $env:LOCALAPPDATA = $home2; $env:APPDATA = $home2; $env:HOME = $home2 + "probe, redirected home:"; node -e $probe (Resolve-Path node_modules/patchright-core) # The secret store tests drive POSIX shell stand-ins for security and secret-tool; the # Windows secret store comes with its own tests. - run: pnpm --filter turno-core exec vitest run --exclude test/secrets.test.ts - - name: Time the process table (diagnostic) - shell: pwsh - run: | - foreach ($i in 1..3) { (Measure-Command { powershell.exe -NoProfile -NonInteractive -Command "Get-CimInstance Win32_Process | Out-Null" }).TotalSeconds } - run: pnpm --filter turno-browser exec vitest run --reporter=verbose if: ${{ !cancelled() }} # What a person gets from npm: the packed packages installed with npm (its .cmd shims), diff --git a/apps/docs/content/docs/browser/get-started.mdx b/apps/docs/content/docs/browser/get-started.mdx index 24f5a55b..87822408 100644 --- a/apps/docs/content/docs/browser/get-started.mdx +++ b/apps/docs/content/docs/browser/get-started.mdx @@ -24,7 +24,7 @@ npm install --global turno-browser - **Browsers.** It finds Google Chrome, Microsoft Edge and Brave in `Program Files`, `Program Files (x86)` and, for an install for your user alone, `%LOCALAPPDATA%`. With none of them, `turno-browser install-browser` puts Chrome for Testing in `%LOCALAPPDATA%\ms-playwright`, and `winget install --id Google.Chrome.EXE --scope user` installs Chrome for your user alone. - **Your data.** Identities and their profiles go to `%LOCALAPPDATA%\turno\data\browser`, settings to `%APPDATA%\turno` and runtime state to `%LOCALAPPDATA%\turno\state`. `TURNO_CONFIG_DIR`, `TURNO_STATE_DIR` and `TURNO_DATA_DIR`, or the `XDG_*` variables, move them as on Linux. [Identities](/docs/browser/identities#on-windows) has the details. - **Agents.** npm installs `turno-browser-mcp` as a `.cmd` file, which a program can start only through `cmd.exe`, so `setup` and `init` register it as `cmd /c turno-browser-mcp --identity `. -- **Not on Windows yet:** proxy passwords and the [vault](/docs/browser/vault) (turno-browser has no secret store there), and Lightpanda, which has no Windows build. Camoufox runs when `TURNO_CAMOUFOX_PATH` names its `camoufox.exe`. turno itself (`turno-cli`) does not install on Windows: npm refuses it. +- **Not on Windows yet:** proxy passwords and the [vault](/docs/browser/vault) (turno-browser has no secret store there), and Lightpanda, which has no Windows build. Camoufox was not tried there: `TURNO_CAMOUFOX_PATH` can name its `camoufox.exe`. turno itself (`turno-cli`) does not install on Windows: npm refuses it. What was checked: the test suite, including the tests that start a real Google Chrome, on GitHub's `windows-latest` runner with Node 22 and 24, and an npm install of the packages followed by `install-browser` and `doctor`'s test launch. Edge and Brave are detected there but were not launched, and nobody has tried it by hand on a Windows 10 or 11 desktop or on ARM64 yet. diff --git a/packages/browser/test/helpers/global-setup.ts b/packages/browser/test/helpers/global-setup.ts index 205885d9..23badd94 100644 --- a/packages/browser/test/helpers/global-setup.ts +++ b/packages/browser/test/helpers/global-setup.ts @@ -24,16 +24,23 @@ const KEEP = new Set([ ]); const LIVE = /^(TURNO_|CLAUDE|CODEX_|CURSOR_|ANTHROPIC_|XDG_)/; -/** The folders the setup itself makes on Windows (above), not counted while they stay empty. */ +/** + * What may appear under the guard HOME on Windows: the folders the setup itself makes (above), + * and PowerShell's own caches, which every powershell.exe (the process table) writes under + * LOCALAPPDATA. + */ const SETUP_DIRS = new Set(["AppData", join("AppData", "Local"), join("AppData", "Roaming")]); +const POWERSHELL = join("AppData", "Local", "Microsoft", "Windows", "PowerShell"); +const allowed = (p: string) => + SETUP_DIRS.has(p) || POWERSHELL === p || POWERSHELL.startsWith(`${p}${sep}`) || p.startsWith(`${POWERSHELL}${sep}`); /** Paths written under the guard HOME, relative to it. */ export function guardFindings(home: string): string[] { try { - const found = readdirSync(home, { recursive: true }).map(String).sort(); - return found.filter( - (p) => !SETUP_DIRS.has(p) || found.some((q) => q !== p && q.startsWith(`${p}${sep}`) && !SETUP_DIRS.has(q)), - ); + return readdirSync(home, { recursive: true }) + .map(String) + .sort() + .filter((p) => !allowed(p)); } catch { return []; } diff --git a/packages/core/test/helpers/global-setup.ts b/packages/core/test/helpers/global-setup.ts index 993912cf..ce6dfa0e 100644 --- a/packages/core/test/helpers/global-setup.ts +++ b/packages/core/test/helpers/global-setup.ts @@ -14,16 +14,23 @@ import { delimiter, join, sep } from "node:path"; const KEEP = new Set(["TURNO_SKIP_E2E", "TURNO_E2E_NETWORK", "TURNO_SKIP_CHROME"]); const LIVE = /^(TURNO_|CLAUDE|CODEX_|CURSOR_|ANTHROPIC_|XDG_)/; -/** The folders the setup itself makes on Windows (above), not counted while they stay empty. */ +/** + * What may appear under the guard HOME on Windows: the folders the setup itself makes (above), + * and PowerShell's own caches, which every powershell.exe (the process table) writes under + * LOCALAPPDATA. + */ const SETUP_DIRS = new Set(["AppData", join("AppData", "Local"), join("AppData", "Roaming")]); +const POWERSHELL = join("AppData", "Local", "Microsoft", "Windows", "PowerShell"); +const allowed = (p: string) => + SETUP_DIRS.has(p) || POWERSHELL === p || POWERSHELL.startsWith(`${p}${sep}`) || p.startsWith(`${POWERSHELL}${sep}`); /** Paths written under the guard HOME, relative to it. */ export function guardFindings(home: string): string[] { try { - const found = readdirSync(home, { recursive: true }).map(String).sort(); - return found.filter( - (p) => !SETUP_DIRS.has(p) || found.some((q) => q !== p && q.startsWith(`${p}${sep}`) && !SETUP_DIRS.has(q)), - ); + return readdirSync(home, { recursive: true }) + .map(String) + .sort() + .filter((p) => !allowed(p)); } catch { return []; } diff --git a/scripts/shrinkwrap.mjs b/scripts/shrinkwrap.mjs index d9628135..cb3bc6b8 100644 --- a/scripts/shrinkwrap.mjs +++ b/scripts/shrinkwrap.mjs @@ -77,6 +77,9 @@ export function publishedManifest(manifest, versions) { return out; } +/** A folder with `/` between its parts, as on Windows it has `\`; the same length, so indexes carry over. */ +const slashes = (dir) => dir.replaceAll("\\", "/"); + /** Declared edges of a manifest: name -> { spec, optional }. Dev dependencies never count. */ function edgesOf(manifest) { const out = new Map(); @@ -96,7 +99,7 @@ function edgesOf(manifest) { function locate(dir, name, isRoot) { const candidates = [join(dir, "node_modules", name)]; if (!isRoot) { - const i = dir.lastIndexOf("/node_modules/"); + const i = slashes(dir).lastIndexOf("/node_modules/"); if (i >= 0) candidates.push(join(dir.slice(0, i), "node_modules", name)); } for (const c of candidates) { @@ -134,7 +137,7 @@ export function collectGraph(pkgDir, versions = workspaceVersions(pkgDir)) { edges.set(name, key); if (!nodes.has(key)) { // A sibling of the workspace is linked from its own folder, never from a node_modules. - const workspace = !at.includes("/node_modules/") && versions.get(m.name) === m.version; + const workspace = !slashes(at).includes("/node_modules/") && versions.get(m.name) === m.version; const node = { key, name: m.name, version: m.version, dir: at, manifest: m, edges: new Map(), workspace }; nodes.set(key, node); node.edges = resolveEdges(at, m, false, key); From 6099ad6fbe43fafbc751dbc2e9d5baf0893cf20f Mon Sep 17 00:00:00 2001 From: William Frank Monroy Mamani Date: Sun, 22 Nov 2026 13:24:53 -0600 Subject: [PATCH 07/15] fix: read pnpm-lock.yaml with CRLF line endings when packing on Windows --- .github/workflows/ci.yml | 26 ++++++++++++++------------ scripts/shrinkwrap.mjs | 3 ++- 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6fc3b1f2..a0dac853 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -74,21 +74,23 @@ jobs: continue-on-error: true shell: pwsh run: | - $q = "Get-CimInstance Win32_Process | Out-Null" - foreach ($i in 1..2) { "normal: " + (Measure-Command { powershell.exe -NoProfile -NonInteractive -Command $q }).TotalSeconds } - $fresh = Join-Path $env:RUNNER_TEMP "fresh" - New-Item -ItemType Directory -Force $fresh | Out-Null - $old = $env:LOCALAPPDATA - $env:LOCALAPPDATA = $fresh - foreach ($i in 1..2) { "fresh LOCALAPPDATA: " + (Measure-Command { powershell.exe -NoProfile -NonInteractive -Command $q }).TotalSeconds } - $env:LOCALAPPDATA = $old Set-Location packages/browser - $probe = "const { chromium } = require(process.argv[1]); chromium.launch({ channel: 'chrome', headless: true, timeout: 30000 }).then((b) => { console.log('started', b.version()); return b.close(); }).catch((e) => { console.error(e.message); process.exit(1); });" - "probe, normal env:"; node -e $probe (Resolve-Path node_modules/patchright-core) + $core = Resolve-Path node_modules/patchright-core + $probe = "const { chromium } = require(process.argv[1]); chromium.launch({ channel: 'chrome', headless: true, timeout: 30000 }).then((b) => { console.log('started'); return b.close(); }).catch((e) => { console.error(e.message.split('\n')[0]); process.exit(1); });" $home2 = Join-Path $env:RUNNER_TEMP "home2" New-Item -ItemType Directory -Force $home2 | Out-Null - $env:USERPROFILE = $home2; $env:LOCALAPPDATA = $home2; $env:APPDATA = $home2; $env:HOME = $home2 - "probe, redirected home:"; node -e $probe (Resolve-Path node_modules/patchright-core) + foreach ($v in "USERPROFILE", "LOCALAPPDATA", "APPDATA", "HOME") { + $old = [Environment]::GetEnvironmentVariable($v) + [Environment]::SetEnvironmentVariable($v, $home2) + "probe with only $v redirected:"; node -e $probe $core + [Environment]::SetEnvironmentVariable($v, $old) + } + $env:TURNO_CONFIG_DIR = Join-Path $env:RUNNER_TEMP "t\c"; $env:TURNO_STATE_DIR = Join-Path $env:RUNNER_TEMP "t\s"; $env:TURNO_DATA_DIR = Join-Path $env:RUNNER_TEMP "t\d" + $env:TURNO_NO_INPUT = "1" + "add: " + (Measure-Command { node dist/cli/main.js add school | Out-Host }).TotalSeconds + "do session: " + (Measure-Command { node dist/cli/main.js do school session | Out-Host }).TotalSeconds + "do end: " + (Measure-Command { node dist/cli/main.js do school end | Out-Host }).TotalSeconds + "remove: " + (Measure-Command { node dist/cli/main.js remove school --yes --json | Out-Host }).TotalSeconds # The secret store tests drive POSIX shell stand-ins for security and secret-tool; the # Windows secret store comes with its own tests. - run: pnpm --filter turno-core exec vitest run --exclude test/secrets.test.ts diff --git a/scripts/shrinkwrap.mjs b/scripts/shrinkwrap.mjs index cb3bc6b8..bf3d7bd4 100644 --- a/scripts/shrinkwrap.mjs +++ b/scripts/shrinkwrap.mjs @@ -23,7 +23,8 @@ const keyOf = (name, version) => `${name}@${version}`; export function lockIntegrity(text) { const out = new Map(); const re = /^ {2}'?((?:@[^@'\s/]+\/)?[^@'\s/]+@[^'\s:]+)'?:\n {4}resolution: \{integrity: ([^,}\s]+)/gm; - for (const m of text.matchAll(re)) out.set(m[1], m[2]); + // A Windows checkout can turn the lockfile's line endings into CRLF. + for (const m of text.replaceAll("\r\n", "\n").matchAll(re)) out.set(m[1], m[2]); return out; } From 1666b52dc52d5052bca4082b854bcdb56f10e863 Mon Sep 17 00:00:00 2001 From: William Frank Monroy Mamani Date: Sun, 22 Nov 2026 13:50:49 -0600 Subject: [PATCH 08/15] fix(browser): Chrome on Windows gets the account's USERPROFILE, and fold the Windows secret store job in --- .changeset/feat-browser-windows.md | 2 +- .github/workflows/ci.yml | 65 ++++++++----------- .../docs/content/docs/browser/get-started.mdx | 3 +- .../browser-proxy-no-secret-store.mdx | 2 +- .../browser-vault-no-secret-store.mdx | 2 +- apps/docs/reference/doctor-checks.mjs | 4 +- apps/docs/scripts/lib/doctor-findings.mjs | 3 - packages/browser/src/doctor.ts | 20 +++--- packages/browser/src/engine.ts | 3 + packages/browser/src/network-chrome.ts | 3 +- packages/browser/src/settings.ts | 14 +++- packages/browser/test/helpers/chrome.ts | 7 +- .../browser/test/helpers/fake-secret-store.ts | 6 +- packages/core/src/process.ts | 20 ++++-- 14 files changed, 80 insertions(+), 74 deletions(-) diff --git a/.changeset/feat-browser-windows.md b/.changeset/feat-browser-windows.md index ae432808..6967837a 100644 --- a/.changeset/feat-browser-windows.md +++ b/.changeset/feat-browser-windows.md @@ -3,6 +3,6 @@ "turno-core": minor --- -turno-browser runs on Windows 10 and 11 (x64): `npm install --global turno-browser`, no admin rights. It finds Google Chrome, Microsoft Edge and Brave in `Program Files`, `Program Files (x86)` and `%LOCALAPPDATA%`, and `install-browser` puts Chrome for Testing in `%LOCALAPPDATA%\ms-playwright`. Identities live in `%LOCALAPPDATA%\turno\data`, settings in `%APPDATA%\turno` and runtime state in `%LOCALAPPDATA%\turno\state`; the `TURNO_*_DIR` and `XDG_*` variables still move them. The background server and the live view listen on named pipes (`\\.\pipe\turno-browser--`) instead of socket files. A Chrome left running is found through its profile's lock and the process table, and ended with its helpers by `taskkill /T`; messages say `taskkill /PID /T /F` where they said `kill `. `setup` and `init` register the server as `cmd /c turno-browser-mcp --identity `, and `init --yes` runs an agent's `.cmd` command through `cmd.exe` with each argument quoted. Not on Windows yet: proxy passwords and the vault (no secret store there), and Lightpanda. +turno-browser runs on Windows 10 and 11 (x64): `npm install --global turno-browser`, no admin rights. It finds Google Chrome, Microsoft Edge and Brave in `Program Files`, `Program Files (x86)` and `%LOCALAPPDATA%`, and `install-browser` puts Chrome for Testing in `%LOCALAPPDATA%\ms-playwright`. Identities live in `%LOCALAPPDATA%\turno\data`, settings in `%APPDATA%\turno` and runtime state in `%LOCALAPPDATA%\turno\state`; the `TURNO_*_DIR` and `XDG_*` variables still move them. The background server and the live view listen on named pipes (`\\.\pipe\turno-browser--`) instead of socket files. A Chrome left running is found through its profile's lock and the process table, and ended with its helpers by `taskkill /T`; messages say `taskkill /PID /T /F` where they said `kill `. `setup` and `init` register the server as `cmd /c turno-browser-mcp --identity `, and `init --yes` runs an agent's `.cmd` command through `cmd.exe` with each argument quoted. The vault and `keychain:` secrets use turno-core's Windows secret store (DPAPI files). Lightpanda has no Windows build. turno-core: the turno folders follow Windows' conventions (`%APPDATA%`, `%LOCALAPPDATA%`), `findOnPath` reads `PATHEXT`, a file replaced while another process reads it is retried instead of failing, and `killTree` ends a process tree on every platform. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a0dac853..faa7eb1b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -74,26 +74,34 @@ jobs: continue-on-error: true shell: pwsh run: | - Set-Location packages/browser - $core = Resolve-Path node_modules/patchright-core - $probe = "const { chromium } = require(process.argv[1]); chromium.launch({ channel: 'chrome', headless: true, timeout: 30000 }).then((b) => { console.log('started'); return b.close(); }).catch((e) => { console.error(e.message.split('\n')[0]); process.exit(1); });" - $home2 = Join-Path $env:RUNNER_TEMP "home2" - New-Item -ItemType Directory -Force $home2 | Out-Null - foreach ($v in "USERPROFILE", "LOCALAPPDATA", "APPDATA", "HOME") { - $old = [Environment]::GetEnvironmentVariable($v) - [Environment]::SetEnvironmentVariable($v, $home2) - "probe with only $v redirected:"; node -e $probe $core - [Environment]::SetEnvironmentVariable($v, $old) + $js = @' + const { spawnSync } = require("node:child_process"); + const { mkdtempSync } = require("node:fs"); + const { tmpdir } = require("node:os"); + const { join } = require("node:path"); + const e = process.env; + const home = mkdtempSync(join(tmpdir(), "ps-")); + const keep = ["SystemRoot", "windir", "ComSpec", "PATHEXT", "TEMP", "TMP", "ProgramFiles", "ProgramFiles(x86)", "PATH"]; + const base = Object.fromEntries(keep.map((k) => [k, e[k]])); + const sandbox = { ...base, HOME: home, USERPROFILE: home, APPDATA: join(home, "r"), LOCALAPPDATA: join(home, "l") }; + const variants = { + full: e, + sandbox, + "sandbox + real USERPROFILE": { ...sandbox, USERPROFILE: e.USERPROFILE }, + "sandbox + real LOCALAPPDATA": { ...sandbox, LOCALAPPDATA: e.LOCALAPPDATA }, + "sandbox + PSModulePath": { ...sandbox, PSModulePath: e.PSModulePath }, + "sandbox + SystemDrive, ProgramData": { ...sandbox, SystemDrive: e.SystemDrive, ProgramData: e.ProgramData }, + "full - USERPROFILE": { ...e, USERPROFILE: home }, + }; + for (const [name, env] of Object.entries(variants)) { + const t = Date.now(); + const r = spawnSync(join(e.SystemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), ["-NoProfile", "-NonInteractive", "-Command", "(Get-CimInstance Win32_Process).Count"], { env, encoding: "utf8", timeout: 25000, windowsHide: true }); + console.log(`${name}: ${((Date.now() - t) / 1000).toFixed(1)}s status=${r.status} out=${(r.stdout || "").trim()} err=${(r.stderr || "").trim().split("\n")[0]} ${r.error ? r.error.code : ""}`); } - $env:TURNO_CONFIG_DIR = Join-Path $env:RUNNER_TEMP "t\c"; $env:TURNO_STATE_DIR = Join-Path $env:RUNNER_TEMP "t\s"; $env:TURNO_DATA_DIR = Join-Path $env:RUNNER_TEMP "t\d" - $env:TURNO_NO_INPUT = "1" - "add: " + (Measure-Command { node dist/cli/main.js add school | Out-Host }).TotalSeconds - "do session: " + (Measure-Command { node dist/cli/main.js do school session | Out-Host }).TotalSeconds - "do end: " + (Measure-Command { node dist/cli/main.js do school end | Out-Host }).TotalSeconds - "remove: " + (Measure-Command { node dist/cli/main.js remove school --yes --json | Out-Host }).TotalSeconds - # The secret store tests drive POSIX shell stand-ins for security and secret-tool; the - # Windows secret store comes with its own tests. - - run: pnpm --filter turno-core exec vitest run --exclude test/secrets.test.ts + '@ + node -e $js + # The core suite, the Windows secret store's DPAPI round trip included. + - run: pnpm --filter turno-core run test - run: pnpm --filter turno-browser exec vitest run --reporter=verbose if: ${{ !cancelled() }} # What a person gets from npm: the packed packages installed with npm (its .cmd shims), @@ -175,22 +183,3 @@ jobs: with: fail-on-severity: moderate deny-licenses: GPL-2.0-only, GPL-2.0-or-later, GPL-3.0-only, GPL-3.0-or-later, AGPL-3.0-only, AGPL-3.0-or-later, SSPL-1.0 - - windows-secrets: - # The Windows secret store (DPAPI through Windows PowerShell) with a real round trip in a - # temporary folder. Only these tests run here; the rest of the suite is not ported to Windows. - name: secret store on windows - runs-on: windows-latest - permissions: - contents: read # check out the code - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version: 24 - cache: pnpm - - run: pnpm install --frozen-lockfile - - run: pnpm --filter turno-core exec vitest run test/secrets.test.ts --reporter verbose diff --git a/apps/docs/content/docs/browser/get-started.mdx b/apps/docs/content/docs/browser/get-started.mdx index 87822408..0b8c913f 100644 --- a/apps/docs/content/docs/browser/get-started.mdx +++ b/apps/docs/content/docs/browser/get-started.mdx @@ -24,7 +24,8 @@ npm install --global turno-browser - **Browsers.** It finds Google Chrome, Microsoft Edge and Brave in `Program Files`, `Program Files (x86)` and, for an install for your user alone, `%LOCALAPPDATA%`. With none of them, `turno-browser install-browser` puts Chrome for Testing in `%LOCALAPPDATA%\ms-playwright`, and `winget install --id Google.Chrome.EXE --scope user` installs Chrome for your user alone. - **Your data.** Identities and their profiles go to `%LOCALAPPDATA%\turno\data\browser`, settings to `%APPDATA%\turno` and runtime state to `%LOCALAPPDATA%\turno\state`. `TURNO_CONFIG_DIR`, `TURNO_STATE_DIR` and `TURNO_DATA_DIR`, or the `XDG_*` variables, move them as on Linux. [Identities](/docs/browser/identities#on-windows) has the details. - **Agents.** npm installs `turno-browser-mcp` as a `.cmd` file, which a program can start only through `cmd.exe`, so `setup` and `init` register it as `cmd /c turno-browser-mcp --identity `. -- **Not on Windows yet:** proxy passwords and the [vault](/docs/browser/vault) (turno-browser has no secret store there), and Lightpanda, which has no Windows build. Camoufox was not tried there: `TURNO_CAMOUFOX_PATH` can name its `camoufox.exe`. turno itself (`turno-cli`) does not install on Windows: npm refuses it. +- **Secrets.** The [vault](/docs/browser/vault#on-windows) and `keychain:` secrets live in files encrypted with DPAPI for your Windows user. +- **Not on Windows:** Lightpanda, which has no Windows build. Camoufox was not tried there: `TURNO_CAMOUFOX_PATH` can name its `camoufox.exe`. turno itself (`turno-cli`) does not install on Windows: npm refuses it. What was checked: the test suite, including the tests that start a real Google Chrome, on GitHub's `windows-latest` runner with Node 22 and 24, and an npm install of the packages followed by `install-browser` and `doctor`'s test launch. Edge and Brave are detected there but were not launched, and nobody has tried it by hand on a Windows 10 or 11 desktop or on ARM64 yet. diff --git a/apps/docs/content/docs/troubleshooting/browser-proxy-no-secret-store.mdx b/apps/docs/content/docs/troubleshooting/browser-proxy-no-secret-store.mdx index 4242e973..9500a2c4 100644 --- a/apps/docs/content/docs/troubleshooting/browser-proxy-no-secret-store.mdx +++ b/apps/docs/content/docs/troubleshooting/browser-proxy-no-secret-store.mdx @@ -26,7 +26,7 @@ Install libsecret (secret-tool), or use a proxy without a password. No single command fixes this one, so doctor names the manual step. -Install libsecret (secret-tool) on Linux, or use a proxy without a password. On Windows turno-browser has no secret store yet, so only a proxy without a password works there. +Install libsecret (secret-tool) on Linux, or use a proxy without a password. Then run `turno browser doctor` again to see the row turn into `ok`. diff --git a/apps/docs/content/docs/troubleshooting/browser-vault-no-secret-store.mdx b/apps/docs/content/docs/troubleshooting/browser-vault-no-secret-store.mdx index 045b50d1..d34f0819 100644 --- a/apps/docs/content/docs/troubleshooting/browser-vault-no-secret-store.mdx +++ b/apps/docs/content/docs/troubleshooting/browser-vault-no-secret-store.mdx @@ -26,7 +26,7 @@ Install libsecret (secret-tool), then add them again with turno browser vault ad No single command fixes this one, so doctor names the manual step. -Install libsecret (secret-tool) on Linux, then add the credentials again with turno browser vault add. On Windows turno-browser has no secret store yet, so the vault does not work there. +Install libsecret (secret-tool) on Linux, then add the credentials again with turno browser vault add. Then run `turno browser doctor` again to see the row turn into `ok`. diff --git a/apps/docs/reference/doctor-checks.mjs b/apps/docs/reference/doctor-checks.mjs index f15c8fc7..270717be 100644 --- a/apps/docs/reference/doctor-checks.mjs +++ b/apps/docs/reference/doctor-checks.mjs @@ -496,7 +496,7 @@ export const DOCTOR_CHECKS = [ match: "the proxy credentials are in the secret store, and this machine has none", title: "No secret store for the proxy credentials", why: "An identity's proxy signs in with a keychain: reference, and this machine has neither the macOS Keychain tool nor secret-tool (libsecret), so turno cannot read the password and the browser does not start.", - fix: "Install libsecret (secret-tool) on Linux, or use a proxy without a password. On Windows turno-browser has no secret store yet, so only a proxy without a password works there.", + fix: "Install libsecret (secret-tool) on Linux, or use a proxy without a password.", }, { id: "browser-proxy-secret-missing", @@ -511,7 +511,7 @@ export const DOCTOR_CHECKS = [ match: "credential in the secret store, and this machine has none", title: "No secret store for the vault", why: "The identity's vault keeps each site's credentials in the secret store, and this machine has neither the macOS Keychain tool nor secret-tool (libsecret), so browser_login cannot sign in anywhere.", - fix: "Install libsecret (secret-tool) on Linux, then add the credentials again with turno browser vault add. On Windows turno-browser has no secret store yet, so the vault does not work there.", + fix: "Install libsecret (secret-tool) on Linux, then add the credentials again with turno browser vault add.", }, { id: "browser-vault-store-no-answer", diff --git a/apps/docs/scripts/lib/doctor-findings.mjs b/apps/docs/scripts/lib/doctor-findings.mjs index 51861a47..aeb73ddc 100644 --- a/apps/docs/scripts/lib/doctor-findings.mjs +++ b/apps/docs/scripts/lib/doctor-findings.mjs @@ -28,9 +28,6 @@ function render(node, sf) { return out; } if (ts.isParenthesizedExpression(node)) return render(node.expression, sf); - // A platform branch (`platform === "win32" ? windows : general`): the page shows the general - // side, and its fix text covers the other. - if (ts.isConditionalExpression(node) && node.condition.getText(sf).includes('"win32"')) return render(node.whenFalse, sf); return undefined; } diff --git a/packages/browser/src/doctor.ts b/packages/browser/src/doctor.ts index 49d2db98..af9b0015 100644 --- a/packages/browser/src/doctor.ts +++ b/packages/browser/src/doctor.ts @@ -41,7 +41,13 @@ import { findProfileChrome, sweepOrphan } from "./lifecycle.js"; import { totalMemory } from "./memory.js"; import { readChallenges, summarizeChallenges } from "./reputation.js"; import { inUseMessage, readRuntimeLock, runtimeLockAlive, runtimeLockPath } from "./runtime-lock.js"; -import { type IdentitySettings, acceptLanguages, checkIdentitySettings, systemTimezone } from "./settings.js"; +import { + type IdentitySettings, + acceptLanguages, + checkIdentitySettings, + chromeEnv, + systemTimezone, +} from "./settings.js"; import { names } from "./names.js"; import { AGENTS, @@ -184,7 +190,7 @@ async function smokeLaunch(env: NodeJS.ProcessEnv, launch: BrowserLaunch = { cha ...launch, headless: true, timeout: 30_000, - env: { ...env } as Record, + env: chromeEnv(env), }); try { const page = context.pages()[0] ?? (await context.newPage()); @@ -673,10 +679,7 @@ async function networkRows(id: string, env: NodeJS.ProcessEnv, opts: DoctorOptio area, level: "fail", text: "the proxy credentials are in the secret store, and this machine has none", - manual: - (opts.platform ?? process.platform) === "win32" - ? "turno-browser has no secret store on Windows yet: use a proxy without a password" - : "install libsecret (secret-tool), or use a proxy without a password", + manual: "install libsecret (secret-tool), or use a proxy without a password", }); return out; } @@ -707,10 +710,7 @@ async function vaultRows(id: string, env: NodeJS.ProcessEnv, opts: DoctorOptions area, level: "fail", text: `the vault has ${sites.length} credential${sites.length === 1 ? "" : "s"} in the secret store, and this machine has none`, - manual: - (opts.platform ?? process.platform) === "win32" - ? "turno-browser has no secret store on Windows yet: run this identity's vault from macOS or Linux" - : "install libsecret (secret-tool), then add them again with turno browser vault add", + manual: "install libsecret (secret-tool), then add them again with turno browser vault add", }, ]; const missing: string[] = []; diff --git a/packages/browser/src/engine.ts b/packages/browser/src/engine.ts index af82ea92..200fcd9e 100644 --- a/packages/browser/src/engine.ts +++ b/packages/browser/src/engine.ts @@ -17,6 +17,7 @@ import { readIdentitySettings, recordEngineClash, systemTimezone, + chromeEnv, } from "./settings.js"; import { type Tuning, launchTuning } from "./tuning.js"; import { IdleTimer, idleMs } from "./idle-timer.js"; @@ -224,6 +225,8 @@ const chromeEngine: Engine = { ...(network?.proxy ? { proxy: network.proxy } : {}), handleSIGINT: false, handleSIGTERM: false, + // Elsewhere Chrome gets this process's environment, as before. + ...(process.platform === "win32" ? { env: chromeEnv(process.env) } : {}), ignoreDefaultArgs: ignore === true ? true diff --git a/packages/browser/src/network-chrome.ts b/packages/browser/src/network-chrome.ts index dfa73198..cd4cf317 100644 --- a/packages/browser/src/network-chrome.ts +++ b/packages/browser/src/network-chrome.ts @@ -15,7 +15,7 @@ import { reducedUserAgent, resolveProxy, } from "./network.js"; -import { type IdentitySettings, acceptLanguages } from "./settings.js"; +import { type IdentitySettings, acceptLanguages, chromeEnv } from "./settings.js"; import type { McpConfig } from "./upstream.js"; /** @@ -105,6 +105,7 @@ async function realMetadata(config: McpConfig, env: NodeJS.ProcessEnv, version: : { channel: lo.channel ?? "chrome" }), headless: true, timeout: 20_000, + ...(process.platform === "win32" ? { env: chromeEnv(process.env) } : {}), }); let metadata: UserAgentMetadata; try { diff --git a/packages/browser/src/settings.ts b/packages/browser/src/settings.ts index 21b52599..259e708c 100644 --- a/packages/browser/src/settings.ts +++ b/packages/browser/src/settings.ts @@ -1,4 +1,5 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { userInfo } from "node:os"; import { dirname, join } from "node:path"; import { browserPaths as paths, replaceFileSync } from "turno-core/paths"; import { type ActSettings, type CaptchaSettings, actProblems, captchaProblems } from "./opt-in-settings.js"; @@ -329,11 +330,18 @@ export function keychainArgs(settings: Pick | unde /** * The environment for a Chrome this process launches for an identity: the caller's, so HOME - * and the XDG folders follow the identity's environment instead of this process's. + * and the XDG folders follow the identity's environment instead of this process's. On Windows + * USERPROFILE is the account's own profile folder: with another one Chrome refuses the DevTools + * pipe ("remote debugging requires a non-default data directory"), as seen on windows-latest. */ -export function chromeEnv(env: NodeJS.ProcessEnv): Record { +export function chromeEnv( + env: NodeJS.ProcessEnv, + platform: NodeJS.Platform = process.platform, +): Record { const out: Record = {}; - for (const [k, v] of Object.entries(env)) if (v !== undefined) out[k] = v; + for (const [k, v] of Object.entries(env)) + if (v !== undefined && !(platform === "win32" && k.toUpperCase() === "USERPROFILE")) out[k] = v; + if (platform === "win32") out.USERPROFILE = userInfo().homedir; return out; } diff --git a/packages/browser/test/helpers/chrome.ts b/packages/browser/test/helpers/chrome.ts index 7f3b6b47..dd2e676e 100644 --- a/packages/browser/test/helpers/chrome.ts +++ b/packages/browser/test/helpers/chrome.ts @@ -1,6 +1,6 @@ import { type ChildProcess, execFileSync, spawn } from "node:child_process"; import { existsSync, mkdtempSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { tmpdir, userInfo } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { readProcTable } from "turno-core/process"; @@ -37,7 +37,8 @@ export function chromeUnavailable(): string | undefined { execFileSync(process.execPath, ["-e", probe, core], { env: process.platform === "win32" - ? { ...process.env, HOME: home, USERPROFILE: home, LOCALAPPDATA: home, APPDATA: home } + ? // USERPROFILE stays the account's: Chrome refuses the DevTools pipe with another one. + { ...process.env, HOME: home, USERPROFILE: userInfo().homedir, LOCALAPPDATA: home, APPDATA: home } : { PATH: process.env.PATH, HOME: home }, stdio: ["ignore", "ignore", "pipe"], timeout: 40_000, @@ -69,7 +70,7 @@ export function spawnChrome(exe: string, userDataDir: string, args: string[], en "--no-default-browser-check", ...args, ], - { stdio: "ignore", env }, + { stdio: "ignore", env: process.platform === "win32" ? { ...env, USERPROFILE: userInfo().homedir } : env }, ); } diff --git a/packages/browser/test/helpers/fake-secret-store.ts b/packages/browser/test/helpers/fake-secret-store.ts index a2b981f3..d3c12960 100644 --- a/packages/browser/test/helpers/fake-secret-store.ts +++ b/packages/browser/test/helpers/fake-secret-store.ts @@ -9,11 +9,11 @@ import type { Sandbox } from "./sandbox.js"; */ /** * Why a test that stores a secret cannot run here: the stand-ins replace the macOS and Linux - * commands, and turno-core has no Windows secret store yet, so turno-browser there says "no - * secret store" (which other tests cover). Undefined where the stand-ins work. + * commands, and Windows' DPAPI store runs Windows PowerShell instead (turno-core tests it with + * a real round trip). Undefined where the stand-ins work. */ export const noFakeSecretStore: string | undefined = - process.platform === "win32" ? "no secret store on Windows yet" : undefined; + process.platform === "win32" ? "the stand-ins replace macOS and Linux commands" : undefined; export interface FakeSecretStore { dir: string; diff --git a/packages/core/src/process.ts b/packages/core/src/process.ts index 3e93c379..f36526ad 100644 --- a/packages/core/src/process.ts +++ b/packages/core/src/process.ts @@ -1,4 +1,5 @@ import { execFileSync } from "node:child_process"; +import { windowsPowerShell } from "./secrets.js"; /** * Process helpers shared by turno-cli and turno-browser: whether a PID lives, a signal that @@ -76,13 +77,18 @@ const WINDOWS_PROC_SCRIPT = export function readProcTable(platform: NodeJS.Platform = process.platform): ProcTable | undefined { if (platform === "win32") { try { - const out = execFileSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_PROC_SCRIPT], { - encoding: "utf8", - stdio: ["ignore", "pipe", "ignore"], - windowsHide: true, - maxBuffer: 64 * 1024 * 1024, - timeout: 15_000, - }); + // By its full path: the PATH an agent hands a server can leave System32 out. + const out = execFileSync( + windowsPowerShell(process.env), + ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_PROC_SCRIPT], + { + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + windowsHide: true, + maxBuffer: 64 * 1024 * 1024, + timeout: 15_000, + }, + ); return parseWindowsProcTable(out); } catch { return undefined; From 2893c4df2dc40d59663621f10f223b1441680097 Mon Sep 17 00:00:00 2001 From: William Frank Monroy Mamani Date: Sun, 22 Nov 2026 14:10:03 -0600 Subject: [PATCH 09/15] fix(core): give Windows PowerShell its modules folder, and run the real-Chrome tests on Windows --- packages/browser/src/doctor.ts | 4 +- packages/browser/test/act-chrome.test.ts | 168 +++++++------- packages/browser/test/attach.test.ts | 12 +- .../browser/test/background-chrome.test.ts | 3 +- .../browser/test/chrome-lifecycle.test.ts | 87 ++++---- packages/browser/test/helpers/chrome.ts | 5 + packages/browser/test/helpers/sandbox.ts | 3 +- .../browser/test/human-step-chrome.test.ts | 4 +- packages/browser/test/network-chrome.test.ts | 207 +++++++++--------- packages/browser/test/passkey-chrome.test.ts | 7 +- packages/browser/test/session-export.test.ts | 6 +- packages/core/src/process.ts | 3 +- packages/core/src/secrets.ts | 15 +- packages/core/test/process.test.ts | 12 + 14 files changed, 299 insertions(+), 237 deletions(-) diff --git a/packages/browser/src/doctor.ts b/packages/browser/src/doctor.ts index af9b0015..60d8ad41 100644 --- a/packages/browser/src/doctor.ts +++ b/packages/browser/src/doctor.ts @@ -673,7 +673,7 @@ async function networkRows(id: string, env: NodeJS.ProcessEnv, opts: DoctorOptio }); const refs = [proxy.username, proxy.password].filter((r): r is string => r?.startsWith("keychain:") === true); if (!refs.length) return out; - const store = opts.secrets ?? secretStore(env); + const store = opts.secrets ?? secretStore(env, opts.platform ?? process.platform); if (!store) { out.push({ area, @@ -703,7 +703,7 @@ async function vaultRows(id: string, env: NodeJS.ProcessEnv, opts: DoctorOptions const sites = vaultSummary(id, env)?.sites ?? []; if (!sites.length) return []; const area = `identity ${id}`; - const store = opts.secrets ?? secretStore(env); + const store = opts.secrets ?? secretStore(env, opts.platform ?? process.platform); if (!store) return [ { diff --git a/packages/browser/test/act-chrome.test.ts b/packages/browser/test/act-chrome.test.ts index e4a092ce..8908f1f5 100644 --- a/packages/browser/test/act-chrome.test.ts +++ b/packages/browser/test/act-chrome.test.ts @@ -11,7 +11,7 @@ import { addIdentity } from "../src/identities.js"; import { readSolves, reputationPath } from "../src/reputation.js"; import { writeIdentitySettings } from "../src/settings.js"; import { chromeUnavailable, stopSandboxProcesses } from "./helpers/chrome.js"; -import { type FakeSecretStore, fakeSecretStore } from "./helpers/fake-secret-store.js"; +import { type FakeSecretStore, fakeSecretStore, noFakeSecretStore } from "./helpers/fake-secret-store.js"; import { type Sandbox, sandbox } from "./helpers/sandbox.js"; /** @@ -255,88 +255,96 @@ describe.skipIf(reason !== undefined)( expect((await call(client, "browser_snapshot")).text).toContain("keys 3"); }, 90_000); - it("extracts data through a configured provider, its key read from the secret store and never shown", async () => { - const site = await web(() => - JSON.stringify({ - data: [ - { name: "Apple", price: "1 USD" }, - { name: "Pear", price: "2 USD" }, - ], - }), - ); - onTestFinished(() => site.close()); - store.write("act-model", MODEL_KEY); - addIdentity("reader", sb.env); - writeIdentitySettings( - "reader", - { - act: { - sampling: false, - provider: "chat-completions", - endpoint: `${site.url}/llm/v1`, - model: "fake-model", - key: "keychain:act-model", + it.skipIf(noFakeSecretStore)( + "extracts data through a configured provider, its key read from the secret store and never shown", + async () => { + const site = await web(() => + JSON.stringify({ + data: [ + { name: "Apple", price: "1 USD" }, + { name: "Pear", price: "2 USD" }, + ], + }), + ); + onTestFinished(() => site.close()); + store.write("act-model", MODEL_KEY); + addIdentity("reader", sb.env); + writeIdentitySettings( + "reader", + { + act: { + sampling: false, + provider: "chat-completions", + endpoint: `${site.url}/llm/v1`, + model: "fake-model", + key: "keychain:act-model", + }, }, - }, - sb.env, - ); - const client = await start("reader"); - await call(client, "browser_navigate", { url: `${site.url}/form` }); - const out = await call(client, "browser_extract", { instruction: "each fruit and its price" }); - expect(out.error, out.text).toBe(false); - expect(out.text).toMatch(/Model: chat-completions fake-model at 127\.0\.0\.1:\d+/); - expect(out.text).toContain('"name": "Pear"'); - expect(out.text).toMatch(/### Budget\nabout 940 of 50,000 tokens/); - expect(site.llm.auth.length).toBe(1); - expect(site.llm.auth[0] === `Bearer ${MODEL_KEY}`, "the provider got the stored key").toBe(true); - expect(out.text.includes(MODEL_KEY), "key in the result").toBe(false); - expect(site.llm.prompts[0]!.includes(PAGE_SECRET), "page secret in the prompt").toBe(false); - expect(site.llm.prompts[0]).toContain("Apple 1 USD"); - }, 90_000); + sb.env, + ); + const client = await start("reader"); + await call(client, "browser_navigate", { url: `${site.url}/form` }); + const out = await call(client, "browser_extract", { instruction: "each fruit and its price" }); + expect(out.error, out.text).toBe(false); + expect(out.text).toMatch(/Model: chat-completions fake-model at 127\.0\.0\.1:\d+/); + expect(out.text).toContain('"name": "Pear"'); + expect(out.text).toMatch(/### Budget\nabout 940 of 50,000 tokens/); + expect(site.llm.auth.length).toBe(1); + expect(site.llm.auth[0] === `Bearer ${MODEL_KEY}`, "the provider got the stored key").toBe(true); + expect(out.text.includes(MODEL_KEY), "key in the result").toBe(false); + expect(site.llm.prompts[0]!.includes(PAGE_SECRET), "page secret in the prompt").toBe(false); + expect(site.llm.prompts[0]).toContain("Apple 1 USD"); + }, + 90_000, + ); - it("solves a captcha widget through the configured solver, puts the token in the page and logs it", async () => { - const site = await web(() => ""); - onTestFinished(() => site.close()); - store.write("captcha-solver", SOLVER_KEY); - addIdentity("shop", sb.env); - writeIdentitySettings( - "shop", - { captcha: { provider: "task-api", endpoint: `${site.url}/solver`, key: "keychain:captcha-solver" } }, - sb.env, - ); - const client = await start("shop"); - expect((await client.listTools()).tools.map((t) => t.name)).toContain("browser_solve_captcha"); - await call(client, "browser_navigate", { url: `${site.url}/captcha` }); - const solved = await call(client, "browser_solve_captcha"); - expect(solved.error, solved.text).toBe(false); - expect(solved.text).toContain("Widget: reCAPTCHA v2"); - expect(solved.text).toContain("Token put into the page (1 response field); the widget's callback onToken ran."); - expect(solved.text.includes(SOLVER_KEY), "key in the result").toBe(false); + it.skipIf(noFakeSecretStore)( + "solves a captcha widget through the configured solver, puts the token in the page and logs it", + async () => { + const site = await web(() => ""); + onTestFinished(() => site.close()); + store.write("captcha-solver", SOLVER_KEY); + addIdentity("shop", sb.env); + writeIdentitySettings( + "shop", + { captcha: { provider: "task-api", endpoint: `${site.url}/solver`, key: "keychain:captcha-solver" } }, + sb.env, + ); + const client = await start("shop"); + expect((await client.listTools()).tools.map((t) => t.name)).toContain("browser_solve_captcha"); + await call(client, "browser_navigate", { url: `${site.url}/captcha` }); + const solved = await call(client, "browser_solve_captcha"); + expect(solved.error, solved.text).toBe(false); + expect(solved.text).toContain("Widget: reCAPTCHA v2"); + expect(solved.text).toContain("Token put into the page (1 response field); the widget's callback onToken ran."); + expect(solved.text.includes(SOLVER_KEY), "key in the result").toBe(false); - const value = await call(client, "browser_evaluate", { - function: "() => document.getElementById('g-recaptcha-response').value === '" + TOKEN + "' && document.title", - }); - expect(value.text).toContain(`solved ${TOKEN.length}`); - const task = site.solver.bodies[0] as { clientKey: string; task: Record }; - expect(task.clientKey === SOLVER_KEY, "the solver got the stored key").toBe(true); - expect(task.task).toEqual({ - type: "RecaptchaV2TaskProxyless", - websiteURL: `${site.url}/captcha`, - websiteKey: "test-site-key-123", - }); + const value = await call(client, "browser_evaluate", { + function: "() => document.getElementById('g-recaptcha-response').value === '" + TOKEN + "' && document.title", + }); + expect(value.text).toContain(`solved ${TOKEN.length}`); + const task = site.solver.bodies[0] as { clientKey: string; task: Record }; + expect(task.clientKey === SOLVER_KEY, "the solver got the stored key").toBe(true); + expect(task.task).toEqual({ + type: "RecaptchaV2TaskProxyless", + websiteURL: `${site.url}/captcha`, + websiteKey: "test-site-key-123", + }); - expect(readSolves("shop", sb.env)).toEqual([ - { - ts: expect.any(String), - site: "127.0.0.1", - kind: "solve", - widget: "recaptcha", - provider: "task-api", - ok: true, - }, - ]); - const log = readFileSync(reputationPath("shop", sb.env), "utf8"); - expect(log.includes(TOKEN) || log.includes(SOLVER_KEY), "token or key in the log").toBe(false); - }, 90_000); + expect(readSolves("shop", sb.env)).toEqual([ + { + ts: expect.any(String), + site: "127.0.0.1", + kind: "solve", + widget: "recaptcha", + provider: "task-api", + ok: true, + }, + ]); + const log = readFileSync(reputationPath("shop", sb.env), "utf8"); + expect(log.includes(TOKEN) || log.includes(SOLVER_KEY), "token or key in the log").toBe(false); + }, + 90_000, + ); }, ); diff --git a/packages/browser/test/attach.test.ts b/packages/browser/test/attach.test.ts index 4e298797..de0059cb 100644 --- a/packages/browser/test/attach.test.ts +++ b/packages/browser/test/attach.test.ts @@ -7,7 +7,14 @@ import type { Browser } from "patchright-core"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { resolveAttachEndpoint } from "../src/engine-attach.js"; import { playwright } from "../src/upstream.js"; -import { alive, chromeUnavailable, spawnChrome, stopSandboxProcesses, waitFor } from "./helpers/chrome.js"; +import { + alive, + chromeExecutable, + chromeUnavailable, + spawnChrome, + stopSandboxProcesses, + waitFor, +} from "./helpers/chrome.js"; import { type Sandbox, sandbox } from "./helpers/sandbox.js"; /** @@ -24,8 +31,7 @@ import { type Sandbox, sandbox } from "./helpers/sandbox.js"; const pkg = fileURLToPath(new URL("..", import.meta.url)); const bin = join(pkg, "dist", "bin", "mcp.js"); const reason = chromeUnavailable(); -const CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"; -const exe = process.platform === "darwin" ? CHROME : "/opt/google/chrome/chrome"; +const exe = chromeExecutable() ?? "chrome"; const USER_PAGE = "data:text/html,User tab

the user's own page

"; diff --git a/packages/browser/test/background-chrome.test.ts b/packages/browser/test/background-chrome.test.ts index b9161dc1..394f5121 100644 --- a/packages/browser/test/background-chrome.test.ts +++ b/packages/browser/test/background-chrome.test.ts @@ -1,5 +1,6 @@ import { spawnSync } from "node:child_process"; import { mkdtempSync, realpathSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; @@ -31,7 +32,7 @@ const stdio: StdioClientTransport[] = []; beforeEach(() => { sb = sandbox(); // A short state folder, so the Unix socket path fits. - stateRoot = realpathSync(mkdtempSync("/tmp/tb-")); + stateRoot = realpathSync(mkdtempSync(process.platform === "win32" ? join(tmpdir(), "tb-") : "/tmp/tb-")); env = { ...sb.env, TURNO_STATE_DIR: stateRoot }; }); diff --git a/packages/browser/test/chrome-lifecycle.test.ts b/packages/browser/test/chrome-lifecycle.test.ts index 5fc71cdf..6d40c40e 100644 --- a/packages/browser/test/chrome-lifecycle.test.ts +++ b/packages/browser/test/chrome-lifecycle.test.ts @@ -11,7 +11,7 @@ import { findBrowser } from "../src/browsers.js"; import { runDoctor } from "../src/doctor.js"; import { readHealth } from "../src/health.js"; import { createHost, serve } from "../src/host.js"; -import { readLockPid } from "../src/lifecycle.js"; +import { findProfileChrome, readLockPid } from "../src/lifecycle.js"; import { readChallenges } from "../src/reputation.js"; import { readRuntimeLock } from "../src/runtime-lock.js"; import { writeIdentitySettings } from "../src/settings.js"; @@ -107,9 +107,10 @@ function textOf(res: unknown): string { return ((res as { content: { text?: string }[] }).content ?? []).map((c) => c.text ?? "").join("\n"); } +/** The browser process on the identity's profile: its SingletonLock, or on Windows its lockfile and the process table. */ function chromePid(id: string): number { - const pid = readLockPid(profileDir(id)); - expect(pid, "Chrome holds the profile's SingletonLock").toBeDefined(); + const pid = process.platform === "win32" ? findProfileChrome(profileDir(id))?.pid : readLockPid(profileDir(id)); + expect(pid, "Chrome holds the profile").toBeDefined(); return pid!; } @@ -131,19 +132,24 @@ describe.skipIf(reason !== undefined)(reason ? `real Chrome (skipped: ${reason}) expect(await waitFor(() => !alive(second), 5_000), "Chrome closed with stdin").toBe(true); }, 60_000); - it("stops a Chrome that does not close in time when the server gets SIGTERM", async () => { - const r = await start("stuck"); - await navigate(r); - const pid = chromePid("stuck"); - // A Chrome that cannot answer: the graceful close upstream would wait 15 seconds for it. - process.kill(pid, "SIGSTOP"); - const t0 = Date.now(); - process.kill(r.pid, "SIGTERM"); - expect(await waitFor(() => !alive(r.pid) && !alive(pid), 10_000)).toBe(true); - // Within the 4 seconds mcpd gives a server between closing stdin and SIGKILL. - expect(Date.now() - t0).toBeLessThan(4_000); - expect(sandboxProcesses(sb.home)).toEqual([]); - }, 60_000); + // SIGSTOP freezes Chrome here; Windows has no way to stop a process like it. + it.skipIf(process.platform === "win32")( + "stops a Chrome that does not close in time when the server gets SIGTERM", + async () => { + const r = await start("stuck"); + await navigate(r); + const pid = chromePid("stuck"); + // A Chrome that cannot answer: the graceful close upstream would wait 15 seconds for it. + process.kill(pid, "SIGSTOP"); + const t0 = Date.now(); + process.kill(r.pid, "SIGTERM"); + expect(await waitFor(() => !alive(r.pid) && !alive(pid), 10_000)).toBe(true); + // Within the 4 seconds mcpd gives a server between closing stdin and SIGKILL. + expect(Date.now() - t0).toBeLessThan(4_000); + expect(sandboxProcesses(sb.home)).toEqual([]); + }, + 60_000, + ); it("does not let a server killed with SIGKILL block the next start", async () => { const r = await start("killed"); @@ -158,28 +164,33 @@ describe.skipIf(reason !== undefined)(reason ? `real Chrome (skipped: ${reason}) expect(chromePid("killed")).not.toBe(pid); }, 60_000); - it("sweeps an orphaned Chrome of the same identity on start", async () => { - const r = await start("orphan"); - await navigate(r); - const pid = chromePid("orphan"); - // Freeze Chrome so it cannot notice its pipe closing, then kill the server the way the - // MCP SDK does after its grace periods: Chrome is left running with no parent. - process.kill(pid, "SIGSTOP"); - process.kill(r.pid, "SIGKILL"); - expect(await waitFor(() => !alive(r.pid), 5_000)).toBe(true); - expect( - await waitFor(() => sandboxProcesses(sb.home).some((p) => p.pid === pid && p.ppid !== r.pid), 5_000), - "Chrome reparented", - ).toBe(true); - - const next = await start("orphan"); - await navigate(next); - // The old Chrome was signalled before the new one started; on a busy runner its exit can - // still be on its way. - expect(await waitFor(() => !alive(pid), 5_000)).toBe(true); - expect(sandboxProcesses(sb.home).filter((p) => p.pgid === pid)).toEqual([]); - expect(next.stderr()).toMatch(new RegExp(`closed a Chrome .*pid ${pid}`)); - }, 60_000); + // SIGSTOP freezes Chrome here; Windows has no way to stop a process like it. + it.skipIf(process.platform === "win32")( + "sweeps an orphaned Chrome of the same identity on start", + async () => { + const r = await start("orphan"); + await navigate(r); + const pid = chromePid("orphan"); + // Freeze Chrome so it cannot notice its pipe closing, then kill the server the way the + // MCP SDK does after its grace periods: Chrome is left running with no parent. + process.kill(pid, "SIGSTOP"); + process.kill(r.pid, "SIGKILL"); + expect(await waitFor(() => !alive(r.pid), 5_000)).toBe(true); + expect( + await waitFor(() => sandboxProcesses(sb.home).some((p) => p.pid === pid && p.ppid !== r.pid), 5_000), + "Chrome reparented", + ).toBe(true); + + const next = await start("orphan"); + await navigate(next); + // The old Chrome was signalled before the new one started; on a busy runner its exit can + // still be on its way. + expect(await waitFor(() => !alive(pid), 5_000)).toBe(true); + expect(sandboxProcesses(sb.home).filter((p) => p.pgid === pid)).toEqual([]); + expect(next.stderr()).toMatch(new RegExp(`closed a Chrome .*pid ${pid}`)); + }, + 60_000, + ); it("drives stock tools end to end through the host: navigate and snapshot a data: page", async () => { const r = await start("e2e"); diff --git a/packages/browser/test/helpers/chrome.ts b/packages/browser/test/helpers/chrome.ts index dd2e676e..b18e5599 100644 --- a/packages/browser/test/helpers/chrome.ts +++ b/packages/browser/test/helpers/chrome.ts @@ -17,6 +17,11 @@ const CHROME_PATHS: Partial> = { .map((d) => join(d, "Google", "Chrome", "Application", "chrome.exe")), }; +/** The installed Google Chrome these tests start by hand, if there is one. */ +export function chromeExecutable(): string | undefined { + return CHROME_PATHS[process.platform]?.find((p) => existsSync(p)); +} + /** Why these tests cannot run here, or undefined when a real Chrome starts. */ export function chromeUnavailable(): string | undefined { if (process.env.TURNO_SKIP_CHROME === "1") return "TURNO_SKIP_CHROME=1"; diff --git a/packages/browser/test/helpers/sandbox.ts b/packages/browser/test/helpers/sandbox.ts index 6fe9887c..db894c53 100644 --- a/packages/browser/test/helpers/sandbox.ts +++ b/packages/browser/test/helpers/sandbox.ts @@ -48,7 +48,8 @@ export function sandbox(): Sandbox { return file; }, cleanup() { - rmSync(home, { recursive: true, force: true }); + // Windows keeps a file busy for a moment after the Chrome that had it open exits. + rmSync(home, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }); }, }; } diff --git a/packages/browser/test/human-step-chrome.test.ts b/packages/browser/test/human-step-chrome.test.ts index 55f72e16..60c9332b 100644 --- a/packages/browser/test/human-step-chrome.test.ts +++ b/packages/browser/test/human-step-chrome.test.ts @@ -12,6 +12,7 @@ import { liveLink, liveStatus } from "../src/live-client.js"; import { SESSION_META_KEY } from "../src/session.js"; import { chromeUnavailable, stopSandboxProcesses } from "./helpers/chrome.js"; import { type Sandbox, sandbox } from "./helpers/sandbox.js"; +import { chromeEnv } from "../src/settings.js"; /** * The person step (`browser_request_human`) on a real Google Chrome, headless: @@ -72,8 +73,7 @@ describe.skipIf(reason)(`the person step's banner on a real Chrome${reason ? ` ( let home: Sandbox | undefined; beforeAll(async () => { home = sandbox(); - const env = Object.fromEntries(Object.entries(home.env).filter((e): e is [string, string] => e[1] !== undefined)); - browser = await chromium.launch({ channel: "chrome", headless: true, env }); + browser = await chromium.launch({ channel: "chrome", headless: true, env: chromeEnv(home.env) }); web = await site(); }); afterAll(async () => { diff --git a/packages/browser/test/network-chrome.test.ts b/packages/browser/test/network-chrome.test.ts index 623f6854..b4482cfe 100644 --- a/packages/browser/test/network-chrome.test.ts +++ b/packages/browser/test/network-chrome.test.ts @@ -12,7 +12,7 @@ import { liveStatus } from "../src/live-client.js"; import { listRecordings, recordingsDir, zipTexts } from "../src/recordings.js"; import { writeIdentitySettings } from "../src/settings.js"; import { chromeUnavailable, stopSandboxProcesses, waitFor } from "./helpers/chrome.js"; -import { type FakeSecretStore, fakeSecretStore } from "./helpers/fake-secret-store.js"; +import { type FakeSecretStore, fakeSecretStore, noFakeSecretStore } from "./helpers/fake-secret-store.js"; import { localProxy } from "./helpers/local-proxy.js"; import { type Sandbox, sandbox } from "./helpers/sandbox.js"; @@ -219,36 +219,39 @@ describe.skipIf(reason)("identity.json userAgent with a real Chrome", () => { }); describe.skipIf(reason)("identity.json proxy with a real Chrome and a local proxy", () => { - it("sends the traffic through the proxy with the password from the secret store, which no tool result shows", async () => { - const proxy = await localProxy("alice", PASSWORD, listen); - store.write("proxy-pass", PASSWORD); - addIdentity("px", sb.env); - writeIdentitySettings( - "px", - { proxy: { server: proxy.server, username: "alice", password: "keychain:proxy-pass" } }, - sb.env, - ); - const site = await probeSite(); - const client = await start("px"); - // http://127.0.0.1, not localhost: Playwright sends loopback through the proxy too, and a - // plain http:// request carries Proxy-Authorization, the case a header could leak in. - const target = site.url.replace("localhost", "127.0.0.1"); - const results = [await call(client, "browser_navigate", { url: target })]; - expect(results[0]!.error, results[0]!.text).toBe(false); - await site.until(2); - expect(proxy.seen.relayed).toContain("/probe"); - expect(proxy.seen.relayed).toContain("/worker.js"); - expect(proxy.seen.wrongCredentials).toBe(0); - results.push(await call(client, "browser_network_requests", { static: true })); - for (let i = 1; i <= 3; i++) results.push(await call(client, "browser_network_request", { index: i })); - results.push(await call(client, "browser_snapshot")); - results.push(await call(client, "browser_evaluate", { function: "() => document.title" })); - const basic = Buffer.from(`alice:${PASSWORD}`).toString("base64"); - for (const r of results) { - expect(r.text.includes(PASSWORD)).toBe(false); - expect(r.text.includes(basic)).toBe(false); - } - }); + it.skipIf(noFakeSecretStore)( + "sends the traffic through the proxy with the password from the secret store, which no tool result shows", + async () => { + const proxy = await localProxy("alice", PASSWORD, listen); + store.write("proxy-pass", PASSWORD); + addIdentity("px", sb.env); + writeIdentitySettings( + "px", + { proxy: { server: proxy.server, username: "alice", password: "keychain:proxy-pass" } }, + sb.env, + ); + const site = await probeSite(); + const client = await start("px"); + // http://127.0.0.1, not localhost: Playwright sends loopback through the proxy too, and a + // plain http:// request carries Proxy-Authorization, the case a header could leak in. + const target = site.url.replace("localhost", "127.0.0.1"); + const results = [await call(client, "browser_navigate", { url: target })]; + expect(results[0]!.error, results[0]!.text).toBe(false); + await site.until(2); + expect(proxy.seen.relayed).toContain("/probe"); + expect(proxy.seen.relayed).toContain("/worker.js"); + expect(proxy.seen.wrongCredentials).toBe(0); + results.push(await call(client, "browser_network_requests", { static: true })); + for (let i = 1; i <= 3; i++) results.push(await call(client, "browser_network_request", { index: i })); + results.push(await call(client, "browser_snapshot")); + results.push(await call(client, "browser_evaluate", { function: "() => document.title" })); + const basic = Buffer.from(`alice:${PASSWORD}`).toString("base64"); + for (const r of results) { + expect(r.text.includes(PASSWORD)).toBe(false); + expect(r.text.includes(basic)).toBe(false); + } + }, + ); it("refuses to start without the secret, naming the item and never a value", async () => { const proxy = await localProxy("alice", PASSWORD, listen); @@ -269,76 +272,82 @@ describe.skipIf(reason)("identity.json proxy with a real Chrome and a local prox expect(site.reports).toEqual([]); }); - it("records flows and screenshots behind a proxy with a password, and no recording holds it", async () => { - const proxy = await localProxy("alice", PASSWORD, listen); - store.write("proxy-pass", PASSWORD); - addIdentity("rec", sb.env); - writeIdentitySettings( - "rec", - { - proxy: { server: proxy.server, username: "alice", password: "keychain:proxy-pass" }, - record: { flows: true, screenshots: true }, - }, - sb.env, - ); - const site = await probeSite(); - const client = await start("rec"); - const target = site.url.replace("localhost", "127.0.0.1"); - expect((await call(client, "browser_navigate", { url: target })).error).toBe(false); - await site.until(2); - await call(client, "browser_navigate", { url: `${target}?again` }); - await call(client, "browser_close"); - expect(await waitFor(() => listRecordings("rec", sb.env)[0]?.ended !== undefined, 15_000)).toBe(true); - expect(proxy.seen.relayed).toContain("/probe"); - expect(listRecordings("rec", sb.env)[0]?.screenshots).toBeGreaterThan(0); - const recorded = allText(recordingsDir("rec", sb.env)); - const basic = Buffer.from(`alice:${PASSWORD}`).toString("base64"); - expect(recorded.includes(PASSWORD)).toBe(false); - expect(recorded.includes(basic)).toBe(false); - }); + it.skipIf(noFakeSecretStore)( + "records flows and screenshots behind a proxy with a password, and no recording holds it", + async () => { + const proxy = await localProxy("alice", PASSWORD, listen); + store.write("proxy-pass", PASSWORD); + addIdentity("rec", sb.env); + writeIdentitySettings( + "rec", + { + proxy: { server: proxy.server, username: "alice", password: "keychain:proxy-pass" }, + record: { flows: true, screenshots: true }, + }, + sb.env, + ); + const site = await probeSite(); + const client = await start("rec"); + const target = site.url.replace("localhost", "127.0.0.1"); + expect((await call(client, "browser_navigate", { url: target })).error).toBe(false); + await site.until(2); + await call(client, "browser_navigate", { url: `${target}?again` }); + await call(client, "browser_close"); + expect(await waitFor(() => listRecordings("rec", sb.env)[0]?.ended !== undefined, 15_000)).toBe(true); + expect(proxy.seen.relayed).toContain("/probe"); + expect(listRecordings("rec", sb.env)[0]?.screenshots).toBeGreaterThan(0); + const recorded = allText(recordingsDir("rec", sb.env)); + const basic = Buffer.from(`alice:${PASSWORD}`).toString("base64"); + expect(recorded.includes(PASSWORD)).toBe(false); + expect(recorded.includes(basic)).toBe(false); + }, + ); - it("keeps the proxy credentials out of the act model's prompt and the live view's tab list", async () => { - const proxy = await localProxy("alice", PASSWORD, listen); - store.write("proxy-pass", PASSWORD); - addIdentity("act", sb.env); - writeIdentitySettings( - "act", - { - proxy: { server: proxy.server, username: "alice", password: "keychain:proxy-pass" }, - act: {}, - live: { enabled: true }, - }, - sb.env, - ); - // A page that shows the credentials, as a page that echoed them would. - const basic = Buffer.from(`alice:${PASSWORD}`).toString("base64"); - const shown = PASSWORD.replace(/&/g, "&").replace(//g, ">"); - const port = await listen( - createServer((_req, res) => { - res.setHeader("content-type", "text/html"); - res.end(`echo ${shown}

alice:${shown}

${basic}

`); - }), - ); - const prompts: string[] = []; - const client = await start("act", (prompt) => { - prompts.push(prompt); - return JSON.stringify({ done: true, success: true, summary: "read the page" }); - }); - const nav = await call(client, "browser_navigate", { url: `http://127.0.0.1:${port}/echo` }); - expect(nav.error, nav.text).toBe(false); - expect(proxy.seen.relayed).toContain("/echo"); - const acted = await call(client, "browser_act", { instruction: "Read the page" }); - expect(acted.error, acted.text).toBe(false); - expect(prompts.length).toBeGreaterThan(0); - const status = JSON.stringify(await liveStatus("act", sb.env)); - expect(status).toContain("/echo"); - for (const text of [...prompts, acted.text, nav.text, status]) { - expect(text.includes(PASSWORD)).toBe(false); - expect(text.includes(basic)).toBe(false); - } - }); + it.skipIf(noFakeSecretStore)( + "keeps the proxy credentials out of the act model's prompt and the live view's tab list", + async () => { + const proxy = await localProxy("alice", PASSWORD, listen); + store.write("proxy-pass", PASSWORD); + addIdentity("act", sb.env); + writeIdentitySettings( + "act", + { + proxy: { server: proxy.server, username: "alice", password: "keychain:proxy-pass" }, + act: {}, + live: { enabled: true }, + }, + sb.env, + ); + // A page that shows the credentials, as a page that echoed them would. + const basic = Buffer.from(`alice:${PASSWORD}`).toString("base64"); + const shown = PASSWORD.replace(/&/g, "&").replace(//g, ">"); + const port = await listen( + createServer((_req, res) => { + res.setHeader("content-type", "text/html"); + res.end(`echo ${shown}

alice:${shown}

${basic}

`); + }), + ); + const prompts: string[] = []; + const client = await start("act", (prompt) => { + prompts.push(prompt); + return JSON.stringify({ done: true, success: true, summary: "read the page" }); + }); + const nav = await call(client, "browser_navigate", { url: `http://127.0.0.1:${port}/echo` }); + expect(nav.error, nav.text).toBe(false); + expect(proxy.seen.relayed).toContain("/echo"); + const acted = await call(client, "browser_act", { instruction: "Read the page" }); + expect(acted.error, acted.text).toBe(false); + expect(prompts.length).toBeGreaterThan(0); + const status = JSON.stringify(await liveStatus("act", sb.env)); + expect(status).toContain("/echo"); + for (const text of [...prompts, acted.text, nav.text, status]) { + expect(text.includes(PASSWORD)).toBe(false); + expect(text.includes(basic)).toBe(false); + } + }, + ); - it("works with userAgent coherent, humanize and tab sharing on one identity", async () => { + it.skipIf(noFakeSecretStore)("works with userAgent coherent, humanize and tab sharing on one identity", async () => { const proxy = await localProxy("alice", PASSWORD, listen); store.write("proxy-pass", PASSWORD); addIdentity("all", sb.env); diff --git a/packages/browser/test/passkey-chrome.test.ts b/packages/browser/test/passkey-chrome.test.ts index f62ba1eb..79fa4338 100644 --- a/packages/browser/test/passkey-chrome.test.ts +++ b/packages/browser/test/passkey-chrome.test.ts @@ -8,7 +8,7 @@ import type { Browser, CDPSession, Page } from "patchright-core"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { resolveAttachEndpoint } from "../src/engine-attach.js"; import { playwright } from "../src/upstream.js"; -import { chromeUnavailable, spawnChrome, stopSandboxProcesses, waitFor } from "./helpers/chrome.js"; +import { chromeExecutable, chromeUnavailable, spawnChrome, stopSandboxProcesses, waitFor } from "./helpers/chrome.js"; import { type Sandbox, sandbox } from "./helpers/sandbox.js"; /** @@ -27,10 +27,7 @@ import { type Sandbox, sandbox } from "./helpers/sandbox.js"; const pkg = fileURLToPath(new URL("..", import.meta.url)); const bin = join(pkg, "dist", "bin", "mcp.js"); const reason = chromeUnavailable(); -const exe = - process.platform === "darwin" - ? "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" - : "/opt/google/chrome/chrome"; +const exe = chromeExecutable() ?? "chrome"; const PAGE = `Sign in diff --git a/packages/browser/test/session-export.test.ts b/packages/browser/test/session-export.test.ts index aa889df5..55864291 100644 --- a/packages/browser/test/session-export.test.ts +++ b/packages/browser/test/session-export.test.ts @@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, onTestFinished } from "vit import { addIdentity, identityExists } from "../src/identities.js"; import { seal } from "../src/sealed.js"; import { exportSession, importSession, profileOrigins, readSessionExport } from "../src/session-export.js"; -import { keychainArgs, readIdentitySettings, writeIdentitySettings } from "../src/settings.js"; +import { chromeEnv, keychainArgs, readIdentitySettings, writeIdentitySettings } from "../src/settings.js"; import { vaultAdd } from "../src/vault.js"; import { chromeUnavailable, stopSandboxProcesses } from "./helpers/chrome.js"; import { fakeSecretStore } from "./helpers/fake-secret-store.js"; @@ -158,7 +158,7 @@ describe.skipIf(reason !== undefined)( const ctx = await chromium.launchPersistentContext(identityDir("source", sb.env), { channel: "chrome", headless: true, - env: sb.env as Record, + env: chromeEnv(sb.env), }); const page = await ctx.newPage(); await page.goto(`${web.url}/set`); @@ -186,7 +186,7 @@ describe.skipIf(reason !== undefined)( const ctx2 = await chromium.launchPersistentContext(identityDir("copy", sb.env), { channel: "chrome", headless: true, - env: sb.env as Record, + env: chromeEnv(sb.env), }); const cookies = await ctx2.cookies(web.url); expect(cookies.find((c) => c.name === "sid")?.value === "cookie-value-42").toBe(true); diff --git a/packages/core/src/process.ts b/packages/core/src/process.ts index f36526ad..a9fdc44c 100644 --- a/packages/core/src/process.ts +++ b/packages/core/src/process.ts @@ -1,5 +1,5 @@ import { execFileSync } from "node:child_process"; -import { windowsPowerShell } from "./secrets.js"; +import { windowsPowerShell, windowsPowerShellEnv } from "./secrets.js"; /** * Process helpers shared by turno-cli and turno-browser: whether a PID lives, a signal that @@ -85,6 +85,7 @@ export function readProcTable(platform: NodeJS.Platform = process.platform): Pro encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], windowsHide: true, + env: windowsPowerShellEnv(process.env), maxBuffer: 64 * 1024 * 1024, timeout: 15_000, }, diff --git a/packages/core/src/secrets.ts b/packages/core/src/secrets.ts index 425abf8b..08173923 100644 --- a/packages/core/src/secrets.ts +++ b/packages/core/src/secrets.ts @@ -271,10 +271,21 @@ export function dpapiInput(service: string, data: Buffer): Buffer { /** Runs one DPAPI call: (operation, stdin) to the process result. Tests pass a stand-in. */ export type DpapiRunner = (op: DpapiOp, input: Buffer) => Promise; +/** + * The environment Windows PowerShell gets: the caller's, with what it needs when the caller + * trimmed it (an agent hands its MCP servers a few variables). SystemRoot it cannot start + * without; without PSModulePath it searches for its modules for 20 seconds and more + * (measured on windows-latest), so it gets the folder of the modules that come with Windows. + */ +export function windowsPowerShellEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { + const root = env.SystemRoot || env.SYSTEMROOT || process.env.SystemRoot || "C:\\Windows"; + const modules = env.PSModulePath || env.PSMODULEPATH || `${root}\\System32\\WindowsPowerShell\\v1.0\\Modules`; + return { ...env, SystemRoot: root, PSModulePath: modules }; +} + function powershellRunner(env: NodeJS.ProcessEnv): DpapiRunner { const bin = windowsPowerShell(env); - // PowerShell needs SystemRoot even when the caller passes a trimmed environment. - const childEnv = { ...env, SystemRoot: env.SystemRoot || env.SYSTEMROOT || process.env.SystemRoot }; + const childEnv = windowsPowerShellEnv(env); return (op, input) => exec(bin, dpapiArgs(op), childEnv, input, 30_000); } diff --git a/packages/core/test/process.test.ts b/packages/core/test/process.test.ts index 7358fa6f..15499d6f 100644 --- a/packages/core/test/process.test.ts +++ b/packages/core/test/process.test.ts @@ -9,6 +9,7 @@ import { signalProcess, treeKillCommand, } from "../src/process.js"; +import { windowsPowerShellEnv } from "../src/secrets.js"; describe("process helpers", () => { it("parses ps output with process groups and skips other lines", () => { @@ -60,3 +61,14 @@ describe("process helpers", () => { expect(() => signalProcess(pid, "SIGTERM")).not.toThrow(); }); }); + +describe("Windows PowerShell's environment", () => { + it("fills in SystemRoot and the modules folder a trimmed environment leaves out, and keeps the caller's", () => { + expect(windowsPowerShellEnv({ SystemRoot: "D:\\Win", PATH: "x" })).toEqual({ + SystemRoot: "D:\\Win", + PSModulePath: "D:\\Win\\System32\\WindowsPowerShell\\v1.0\\Modules", + PATH: "x", + }); + expect(windowsPowerShellEnv({ SystemRoot: "D:\\Win", PSModulePath: "E:\\m" }).PSModulePath).toBe("E:\\m"); + }); +}); From b4ddaa0450c633dc3889f136367d3a5d0208e28c Mon Sep 17 00:00:00 2001 From: William Frank Monroy Mamani Date: Sun, 22 Nov 2026 14:11:39 -0600 Subject: [PATCH 10/15] fix(browser): keep the standalone executable's agent command next to the Windows one --- apps/docs/content/docs/browser/get-started.mdx | 2 +- packages/browser/test/cli/init.test.ts | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/apps/docs/content/docs/browser/get-started.mdx b/apps/docs/content/docs/browser/get-started.mdx index 0b8c913f..883cf2b0 100644 --- a/apps/docs/content/docs/browser/get-started.mdx +++ b/apps/docs/content/docs/browser/get-started.mdx @@ -40,7 +40,7 @@ On a machine without Node or npm, use the standalone executable: one file that h | Linux, x64 | `turno-browser-linux-x64.zip` | | Windows, x64 (experimental) | `turno-browser-win-x64.zip` | -Windows is experimental: turno-browser does not support Windows yet, so that executable is published for testing and may not work. +The Windows executable is experimental: the npm install is what CI tests on Windows (see [On Windows](#on-windows)), while the release workflow only checks that this executable starts and answers an MCP request. Each archive holds the executable (`turno-browser`, or `turno-browser.exe`) and its license files. The one executable is both programs: `turno-browser ` is the CLI, and `turno-browser mcp` is the MCP server that `turno-browser-mcp` is in the npm package. diff --git a/packages/browser/test/cli/init.test.ts b/packages/browser/test/cli/init.test.ts index 342ee977..52e72a38 100644 --- a/packages/browser/test/cli/init.test.ts +++ b/packages/browser/test/cli/init.test.ts @@ -396,19 +396,19 @@ describe("running an agent's command on Windows", () => { describe("how an agent starts turno-browser-mcp", () => { it("by name when it is on the PATH, through cmd /c on Windows; else by its full path, run by Node on Windows", () => { const empty = { PATH: "" }; - expect(mcpCommand(empty, "linux")).toMatchObject({ prefix: [], onPath: false }); + expect(mcpCommand(empty, "linux")).toMatchObject({ args: [], onPath: false }); expect(mcpCommand(empty, "linux").command).toMatch(/[\\/]bin[\\/]mcp\.js$/); const win = mcpCommand(empty, "win32"); expect(win.command).toBe(process.execPath); - expect(win.prefix[0]).toMatch(/[\\/]bin[\\/]mcp\.js$/); + expect(win.args[0]).toMatch(/[\\/]bin[\\/]mcp\.js$/); const dir = mkdtempSync(join(tmpdir(), "turno-mcp-")); try { fakeProgram(dir, "turno-browser-mcp"); const env = { PATH: pathWith(undefined, dir) }; expect(mcpCommand(env)).toEqual( process.platform === "win32" - ? { command: "cmd", prefix: ["/c", "turno-browser-mcp"], onPath: true } - : { command: "turno-browser-mcp", prefix: [], onPath: true }, + ? { command: "cmd", args: ["/c", "turno-browser-mcp"], onPath: true } + : { command: "turno-browser-mcp", args: [], onPath: true }, ); } finally { rmSync(dir, { recursive: true, force: true }); From 1ad098af8c2f143850f8916eff195727b907a056 Mon Sep 17 00:00:00 2001 From: William Frank Monroy Mamani Date: Sun, 22 Nov 2026 14:28:38 -0600 Subject: [PATCH 11/15] fix(browser): record Chrome's pid on Windows, and run the secret store tests there on DPAPI --- .github/workflows/ci.yml | 41 ++-- packages/browser/src/engine.ts | 12 +- packages/browser/src/lifecycle.ts | 11 + packages/browser/src/login.ts | 4 +- packages/browser/src/session-export.ts | 4 +- packages/browser/test/act-chrome.test.ts | 168 +++++++------- .../browser/test/background-chrome.test.ts | 10 +- packages/browser/test/chrome-features.test.ts | 5 +- .../browser/test/chrome-lifecycle.test.ts | 7 +- packages/browser/test/cli/bin.test.ts | 75 +++---- packages/browser/test/cli/remove.test.ts | 4 +- .../browser/test/helpers/fake-secret-store.ts | 73 +++++- packages/browser/test/network-chrome.test.ts | 207 +++++++++--------- packages/browser/test/network.test.ts | 65 +++--- packages/browser/test/vault.test.ts | 131 ++++++----- 15 files changed, 433 insertions(+), 384 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index faa7eb1b..62a5085c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -70,39 +70,46 @@ jobs: - run: pnpm install --frozen-lockfile - run: pnpm --filter turno-core --filter turno-browser run build - run: pnpm --filter turno-core --filter turno-browser run typecheck - - name: Diagnostics (temporary) + - name: Trace the CLI's child processes (temporary) continue-on-error: true shell: pwsh run: | + $trace = @' + const cp = require("node:child_process"); + for (const k of ["spawn", "spawnSync", "execFile", "execFileSync"]) { + const f = cp[k]; + cp[k] = function (...a) { + const t = Date.now(); + const r = f.apply(this, a); + const log = () => process.stderr.write(`[trace ${process.pid}] ${k} ${String(a[0]).slice(-60)} ${JSON.stringify(Array.isArray(a[1]) ? a[1].slice(0, 3) : "").slice(0, 100)} ${Date.now() - t}ms\n`); + if (r && typeof r.on === "function") r.on("exit", log); else log(); + return r; + }; + } + require("node:module").syncBuiltinESMExports(); + '@ + Set-Content -Path "$env:RUNNER_TEMP\trace.cjs" -Value $trace $js = @' const { spawnSync } = require("node:child_process"); const { mkdtempSync } = require("node:fs"); const { tmpdir } = require("node:os"); const { join } = require("node:path"); const e = process.env; - const home = mkdtempSync(join(tmpdir(), "ps-")); + const home = mkdtempSync(join(tmpdir(), "tr-")); const keep = ["SystemRoot", "windir", "ComSpec", "PATHEXT", "TEMP", "TMP", "ProgramFiles", "ProgramFiles(x86)", "PATH"]; - const base = Object.fromEntries(keep.map((k) => [k, e[k]])); - const sandbox = { ...base, HOME: home, USERPROFILE: home, APPDATA: join(home, "r"), LOCALAPPDATA: join(home, "l") }; - const variants = { - full: e, - sandbox, - "sandbox + real USERPROFILE": { ...sandbox, USERPROFILE: e.USERPROFILE }, - "sandbox + real LOCALAPPDATA": { ...sandbox, LOCALAPPDATA: e.LOCALAPPDATA }, - "sandbox + PSModulePath": { ...sandbox, PSModulePath: e.PSModulePath }, - "sandbox + SystemDrive, ProgramData": { ...sandbox, SystemDrive: e.SystemDrive, ProgramData: e.ProgramData }, - "full - USERPROFILE": { ...e, USERPROFILE: home }, - }; - for (const [name, env] of Object.entries(variants)) { + const env = { ...Object.fromEntries(keep.map((k) => [k, e[k]])), HOME: home, USERPROFILE: home, APPDATA: join(home, "AppData", "Roaming"), LOCALAPPDATA: join(home, "AppData", "Local"), XDG_CONFIG_HOME: join(home, ".config"), XDG_STATE_HOME: join(home, ".local", "state"), XDG_DATA_HOME: join(home, ".local", "share"), TURNO_NO_INPUT: "1", NODE_OPTIONS: `--require ${join(e.RUNNER_TEMP, "trace.cjs")}` }; + const cli = join("packages", "browser", "dist", "cli", "main.js"); + for (const args of [["add", "school"], ["doctor", "--no-launch", "--json"], ["do", "school", "session"], ["do", "school", "end"]]) { const t = Date.now(); - const r = spawnSync(join(e.SystemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), ["-NoProfile", "-NonInteractive", "-Command", "(Get-CimInstance Win32_Process).Count"], { env, encoding: "utf8", timeout: 25000, windowsHide: true }); - console.log(`${name}: ${((Date.now() - t) / 1000).toFixed(1)}s status=${r.status} out=${(r.stdout || "").trim()} err=${(r.stderr || "").trim().split("\n")[0]} ${r.error ? r.error.code : ""}`); + const r = spawnSync(process.execPath, [cli, ...args], { env, encoding: "utf8", timeout: 60000 }); + console.log(`== ${args.join(" ")}: ${Date.now() - t}ms status=${r.status} ${r.error ? r.error.code : ""}`); + console.log((r.stderr || "").split("\n").filter((l) => l.startsWith("[trace")).join("\n")); } '@ node -e $js # The core suite, the Windows secret store's DPAPI round trip included. - run: pnpm --filter turno-core run test - - run: pnpm --filter turno-browser exec vitest run --reporter=verbose + - run: pnpm --filter turno-browser run test if: ${{ !cancelled() }} # What a person gets from npm: the packed packages installed with npm (its .cmd shims), # then install-browser and a smoke launch of Chrome through doctor, in a scratch turno folder. diff --git a/packages/browser/src/engine.ts b/packages/browser/src/engine.ts index 200fcd9e..f60e9ad6 100644 --- a/packages/browser/src/engine.ts +++ b/packages/browser/src/engine.ts @@ -4,7 +4,7 @@ import { storagePartitioningArgs } from "./chrome-features.js"; import { type AttachTarget, createAttachEngine, parseAttachTarget } from "./engine-attach.js"; import { createCamoufoxEngine } from "./engine-camoufox.js"; import { createLightpandaEngine } from "./engine-lightpanda.js"; -import { findProfileChrome, readLockPid } from "./lifecycle.js"; +import { findProfileChrome, startedChromePid } from "./lifecycle.js"; import { chromeNetwork, pinUserAgent, verifyCoherence } from "./network-chrome.js"; import { networkEngineClash } from "./network.js"; import { policyEngineClash } from "./policy.js"; @@ -267,10 +267,16 @@ const chromeEngine: Engine = { browser.once("disconnected", () => timer.dispose()); idleTimer = timer; } - const pid = readLockPid(userDataDir); + const pid = startedChromePid(userDataDir); if (held) { // Playwright starts Chrome as the leader of its own process group; ps confirms it. - const pgid = pid !== undefined ? (findProfileChrome(userDataDir)?.pgid ?? pid) : undefined; + // Windows has no process groups: the pid stands for the tree taskkill ends. + const pgid = + pid !== undefined + ? process.platform === "win32" + ? pid + : (findProfileChrome(userDataDir)?.pgid ?? pid) + : undefined; held.update({ ...(pid !== undefined ? { chromePid: pid } : {}), ...(pgid !== undefined ? { pgid } : {}) }); browser.once("disconnected", () => held.release()); } diff --git a/packages/browser/src/lifecycle.ts b/packages/browser/src/lifecycle.ts index e39f4bfe..1d52eaa1 100644 --- a/packages/browser/src/lifecycle.ts +++ b/packages/browser/src/lifecycle.ts @@ -143,6 +143,17 @@ export function findProfileChrome(userDataDir: string, opts: FindOptions = {}): return { pid, pgid: pid, leaderAlive: false, owner: orphaned ? "orphan" : "other" }; } +/** + * The pid of the Chrome just started on `userDataDir`: what its SingletonLock names, or on + * Windows, where Chrome writes no such lock, the browser process the process table shows. + */ +export function startedChromePid( + userDataDir: string, + platform: NodeJS.Platform = process.platform, +): number | undefined { + return platform === "win32" ? findProfileChrome(userDataDir, { platform })?.pid : readLockPid(userDataDir); +} + /** * How long `stopChrome` waits for the group to go after SIGKILL. A SIGKILL is delivered at * once, but the group is gone only when the kernel has torn down every member and init (or a diff --git a/packages/browser/src/login.ts b/packages/browser/src/login.ts index c9e5e3e0..02b4b540 100644 --- a/packages/browser/src/login.ts +++ b/packages/browser/src/login.ts @@ -5,7 +5,7 @@ import { identityBrowserLaunch } from "./browsers.js"; import { clearHealth } from "./health.js"; import { identityStateDir } from "./ids.js"; import { IdentityError, identityDir, inUseBy, isInUse } from "./identities.js"; -import { readLockPid } from "./lifecycle.js"; +import { startedChromePid } from "./lifecycle.js"; import { CHROME_PROXY_ARGS, resolveProxy } from "./network.js"; import { acquireRuntimeLock } from "./runtime-lock.js"; import { chromeEnv, keychainArgs, launchSettings, readIdentitySettings, systemTimezone } from "./settings.js"; @@ -147,7 +147,7 @@ export async function loginIdentity(id: string, options: LoginOptions = {}): Pro env: chromeEnv(env), }); const sites = new Set(); - const pid = readLockPid(dir); + const pid = startedChromePid(dir); if (pid !== undefined) held.update({ chromePid: pid, pgid: pid }); const closed = new Promise((resolve) => ctx.on("close", () => resolve())); // On macOS Chrome keeps running with no windows, so treat "last page closed" as done. diff --git a/packages/browser/src/session-export.ts b/packages/browser/src/session-export.ts index e1452b5b..8e6adca3 100644 --- a/packages/browser/src/session-export.ts +++ b/packages/browser/src/session-export.ts @@ -14,7 +14,7 @@ import { isInUse, } from "./identities.js"; import { identityStateDir } from "./ids.js"; -import { readLockPid } from "./lifecycle.js"; +import { startedChromePid } from "./lifecycle.js"; import { acquireRuntimeLock } from "./runtime-lock.js"; import { SEALED_FORMAT, SealError, seal, unseal } from "./sealed.js"; import { names } from "./names.js"; @@ -84,7 +84,7 @@ async function withProfile( // Chrome gets the caller's environment (HOME, XDG dirs), not this process's. env: chromeEnv(env), }); - const pid = readLockPid(dir); + const pid = startedChromePid(dir); if (pid !== undefined) held.update({ chromePid: pid, pgid: pid }); try { return await use(ctx); diff --git a/packages/browser/test/act-chrome.test.ts b/packages/browser/test/act-chrome.test.ts index 8908f1f5..e4a092ce 100644 --- a/packages/browser/test/act-chrome.test.ts +++ b/packages/browser/test/act-chrome.test.ts @@ -11,7 +11,7 @@ import { addIdentity } from "../src/identities.js"; import { readSolves, reputationPath } from "../src/reputation.js"; import { writeIdentitySettings } from "../src/settings.js"; import { chromeUnavailable, stopSandboxProcesses } from "./helpers/chrome.js"; -import { type FakeSecretStore, fakeSecretStore, noFakeSecretStore } from "./helpers/fake-secret-store.js"; +import { type FakeSecretStore, fakeSecretStore } from "./helpers/fake-secret-store.js"; import { type Sandbox, sandbox } from "./helpers/sandbox.js"; /** @@ -255,96 +255,88 @@ describe.skipIf(reason !== undefined)( expect((await call(client, "browser_snapshot")).text).toContain("keys 3"); }, 90_000); - it.skipIf(noFakeSecretStore)( - "extracts data through a configured provider, its key read from the secret store and never shown", - async () => { - const site = await web(() => - JSON.stringify({ - data: [ - { name: "Apple", price: "1 USD" }, - { name: "Pear", price: "2 USD" }, - ], - }), - ); - onTestFinished(() => site.close()); - store.write("act-model", MODEL_KEY); - addIdentity("reader", sb.env); - writeIdentitySettings( - "reader", - { - act: { - sampling: false, - provider: "chat-completions", - endpoint: `${site.url}/llm/v1`, - model: "fake-model", - key: "keychain:act-model", - }, + it("extracts data through a configured provider, its key read from the secret store and never shown", async () => { + const site = await web(() => + JSON.stringify({ + data: [ + { name: "Apple", price: "1 USD" }, + { name: "Pear", price: "2 USD" }, + ], + }), + ); + onTestFinished(() => site.close()); + store.write("act-model", MODEL_KEY); + addIdentity("reader", sb.env); + writeIdentitySettings( + "reader", + { + act: { + sampling: false, + provider: "chat-completions", + endpoint: `${site.url}/llm/v1`, + model: "fake-model", + key: "keychain:act-model", }, - sb.env, - ); - const client = await start("reader"); - await call(client, "browser_navigate", { url: `${site.url}/form` }); - const out = await call(client, "browser_extract", { instruction: "each fruit and its price" }); - expect(out.error, out.text).toBe(false); - expect(out.text).toMatch(/Model: chat-completions fake-model at 127\.0\.0\.1:\d+/); - expect(out.text).toContain('"name": "Pear"'); - expect(out.text).toMatch(/### Budget\nabout 940 of 50,000 tokens/); - expect(site.llm.auth.length).toBe(1); - expect(site.llm.auth[0] === `Bearer ${MODEL_KEY}`, "the provider got the stored key").toBe(true); - expect(out.text.includes(MODEL_KEY), "key in the result").toBe(false); - expect(site.llm.prompts[0]!.includes(PAGE_SECRET), "page secret in the prompt").toBe(false); - expect(site.llm.prompts[0]).toContain("Apple 1 USD"); - }, - 90_000, - ); + }, + sb.env, + ); + const client = await start("reader"); + await call(client, "browser_navigate", { url: `${site.url}/form` }); + const out = await call(client, "browser_extract", { instruction: "each fruit and its price" }); + expect(out.error, out.text).toBe(false); + expect(out.text).toMatch(/Model: chat-completions fake-model at 127\.0\.0\.1:\d+/); + expect(out.text).toContain('"name": "Pear"'); + expect(out.text).toMatch(/### Budget\nabout 940 of 50,000 tokens/); + expect(site.llm.auth.length).toBe(1); + expect(site.llm.auth[0] === `Bearer ${MODEL_KEY}`, "the provider got the stored key").toBe(true); + expect(out.text.includes(MODEL_KEY), "key in the result").toBe(false); + expect(site.llm.prompts[0]!.includes(PAGE_SECRET), "page secret in the prompt").toBe(false); + expect(site.llm.prompts[0]).toContain("Apple 1 USD"); + }, 90_000); - it.skipIf(noFakeSecretStore)( - "solves a captcha widget through the configured solver, puts the token in the page and logs it", - async () => { - const site = await web(() => ""); - onTestFinished(() => site.close()); - store.write("captcha-solver", SOLVER_KEY); - addIdentity("shop", sb.env); - writeIdentitySettings( - "shop", - { captcha: { provider: "task-api", endpoint: `${site.url}/solver`, key: "keychain:captcha-solver" } }, - sb.env, - ); - const client = await start("shop"); - expect((await client.listTools()).tools.map((t) => t.name)).toContain("browser_solve_captcha"); - await call(client, "browser_navigate", { url: `${site.url}/captcha` }); - const solved = await call(client, "browser_solve_captcha"); - expect(solved.error, solved.text).toBe(false); - expect(solved.text).toContain("Widget: reCAPTCHA v2"); - expect(solved.text).toContain("Token put into the page (1 response field); the widget's callback onToken ran."); - expect(solved.text.includes(SOLVER_KEY), "key in the result").toBe(false); + it("solves a captcha widget through the configured solver, puts the token in the page and logs it", async () => { + const site = await web(() => ""); + onTestFinished(() => site.close()); + store.write("captcha-solver", SOLVER_KEY); + addIdentity("shop", sb.env); + writeIdentitySettings( + "shop", + { captcha: { provider: "task-api", endpoint: `${site.url}/solver`, key: "keychain:captcha-solver" } }, + sb.env, + ); + const client = await start("shop"); + expect((await client.listTools()).tools.map((t) => t.name)).toContain("browser_solve_captcha"); + await call(client, "browser_navigate", { url: `${site.url}/captcha` }); + const solved = await call(client, "browser_solve_captcha"); + expect(solved.error, solved.text).toBe(false); + expect(solved.text).toContain("Widget: reCAPTCHA v2"); + expect(solved.text).toContain("Token put into the page (1 response field); the widget's callback onToken ran."); + expect(solved.text.includes(SOLVER_KEY), "key in the result").toBe(false); - const value = await call(client, "browser_evaluate", { - function: "() => document.getElementById('g-recaptcha-response').value === '" + TOKEN + "' && document.title", - }); - expect(value.text).toContain(`solved ${TOKEN.length}`); - const task = site.solver.bodies[0] as { clientKey: string; task: Record }; - expect(task.clientKey === SOLVER_KEY, "the solver got the stored key").toBe(true); - expect(task.task).toEqual({ - type: "RecaptchaV2TaskProxyless", - websiteURL: `${site.url}/captcha`, - websiteKey: "test-site-key-123", - }); + const value = await call(client, "browser_evaluate", { + function: "() => document.getElementById('g-recaptcha-response').value === '" + TOKEN + "' && document.title", + }); + expect(value.text).toContain(`solved ${TOKEN.length}`); + const task = site.solver.bodies[0] as { clientKey: string; task: Record }; + expect(task.clientKey === SOLVER_KEY, "the solver got the stored key").toBe(true); + expect(task.task).toEqual({ + type: "RecaptchaV2TaskProxyless", + websiteURL: `${site.url}/captcha`, + websiteKey: "test-site-key-123", + }); - expect(readSolves("shop", sb.env)).toEqual([ - { - ts: expect.any(String), - site: "127.0.0.1", - kind: "solve", - widget: "recaptcha", - provider: "task-api", - ok: true, - }, - ]); - const log = readFileSync(reputationPath("shop", sb.env), "utf8"); - expect(log.includes(TOKEN) || log.includes(SOLVER_KEY), "token or key in the log").toBe(false); - }, - 90_000, - ); + expect(readSolves("shop", sb.env)).toEqual([ + { + ts: expect.any(String), + site: "127.0.0.1", + kind: "solve", + widget: "recaptcha", + provider: "task-api", + ok: true, + }, + ]); + const log = readFileSync(reputationPath("shop", sb.env), "utf8"); + expect(log.includes(TOKEN) || log.includes(SOLVER_KEY), "token or key in the log").toBe(false); + }, 90_000); }, ); diff --git a/packages/browser/test/background-chrome.test.ts b/packages/browser/test/background-chrome.test.ts index 394f5121..4e460ae0 100644 --- a/packages/browser/test/background-chrome.test.ts +++ b/packages/browser/test/background-chrome.test.ts @@ -7,7 +7,7 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { type BackgroundSession, openBackgroundSession, startBackground, stopBackground } from "../src/client.js"; -import { readLockPid } from "../src/lifecycle.js"; +import { startedChromePid } from "../src/lifecycle.js"; import { writeIdentitySettings } from "../src/settings.js"; import { alive, chromeUnavailable, stopSandboxProcesses, waitFor } from "./helpers/chrome.js"; import { type Sandbox, sandbox } from "./helpers/sandbox.js"; @@ -85,7 +85,7 @@ describe.skipIf(reason !== undefined)( const first = await openBackgroundSession(ID, { env, start: { bin, args: ["--headless"] } }); await go(first, "first"); await first.close(); - const chrome = readLockPid(profileDir()); + const chrome = startedChromePid(profileDir()); expect(chrome !== undefined && alive(chrome)).toBe(true); const again = await openBackgroundSession(ID, { @@ -100,7 +100,7 @@ describe.skipIf(reason !== undefined)( const refused = await agent.callTool({ name: "browser_navigate", arguments: { url: page("second") } }); expect(refused.isError).toBe(true); expect(textOf(refused)).toContain(`is served by its background server (pid ${again.state.pid})`); - expect(readLockPid(profileDir())).toBe(chrome); + expect(startedChromePid(profileDir())).toBe(chrome); expect(await titleOf(again)).toBe("first"); expect(await stopBackground(ID, { env })).toBe(true); @@ -123,11 +123,11 @@ describe.skipIf(reason !== undefined)( const agent = await stdioServer(); const res = await agent.callTool({ name: "browser_navigate", arguments: { url: page("agent") } }); expect(res.isError ?? false, textOf(res)).toBe(false); - const chrome = readLockPid(profileDir()); + const chrome = startedChromePid(profileDir()); await expect(startBackground(ID, { env, bin, args: ["--headless"] })).rejects.toThrow( /is in use by turno-browser-mcp .* so it starts only when no other process has it open/s, ); - expect(readLockPid(profileDir())).toBe(chrome); + expect(startedChromePid(profileDir())).toBe(chrome); expect(alive(chrome!)).toBe(true); }, 90_000); diff --git a/packages/browser/test/chrome-features.test.ts b/packages/browser/test/chrome-features.test.ts index 11a5b08a..5c7a0114 100644 --- a/packages/browser/test/chrome-features.test.ts +++ b/packages/browser/test/chrome-features.test.ts @@ -50,10 +50,13 @@ describe("storage partitioning", () => { }); let sb: Sandbox | undefined; +// Closed before the sandbox goes: a server whose working folder is the sandbox keeps Windows from deleting it. +const clients: Client[] = []; beforeEach(() => { sb = undefined; }); afterEach(async () => { + for (const c of clients.splice(0)) await c.close().catch(() => {}); if (!sb) return; await stopSandboxProcesses(sb.home); sb.cleanup(); @@ -91,7 +94,7 @@ describe.skipIf(reason !== undefined)( }); const client = new Client({ name: "partitioning", version: "0.0.0" }); await client.connect(transport); - onTestFinished(() => client.close().catch(() => {})); + clients.push(client); await client.callTool({ name: "browser_navigate", arguments: { url: `http://127.0.0.1:${port}/set` } }); const src = encodeURIComponent(`http://127.0.0.1:${port}/read`); await client.callTool({ diff --git a/packages/browser/test/chrome-lifecycle.test.ts b/packages/browser/test/chrome-lifecycle.test.ts index 6d40c40e..2f061bc6 100644 --- a/packages/browser/test/chrome-lifecycle.test.ts +++ b/packages/browser/test/chrome-lifecycle.test.ts @@ -11,7 +11,7 @@ import { findBrowser } from "../src/browsers.js"; import { runDoctor } from "../src/doctor.js"; import { readHealth } from "../src/health.js"; import { createHost, serve } from "../src/host.js"; -import { findProfileChrome, readLockPid } from "../src/lifecycle.js"; +import { startedChromePid } from "../src/lifecycle.js"; import { readChallenges } from "../src/reputation.js"; import { readRuntimeLock } from "../src/runtime-lock.js"; import { writeIdentitySettings } from "../src/settings.js"; @@ -107,9 +107,8 @@ function textOf(res: unknown): string { return ((res as { content: { text?: string }[] }).content ?? []).map((c) => c.text ?? "").join("\n"); } -/** The browser process on the identity's profile: its SingletonLock, or on Windows its lockfile and the process table. */ function chromePid(id: string): number { - const pid = process.platform === "win32" ? findProfileChrome(profileDir(id))?.pid : readLockPid(profileDir(id)); + const pid = startedChromePid(profileDir(id)); expect(pid, "Chrome holds the profile").toBeDefined(); return pid!; } @@ -338,7 +337,7 @@ describe.skipIf(reason !== undefined)(reason ? `real Chrome (skipped: ${reason}) expect(readHealth("health", sb.env)).toMatchObject({ status: "needs_auth" }); expect( await waitFor( - () => readLockPid(profileDir("health")) === undefined || !alive(readLockPid(profileDir("health"))!), + () => startedChromePid(profileDir("health")) === undefined || !alive(startedChromePid(profileDir("health"))!), 10_000, ), "Chrome closed", diff --git a/packages/browser/test/cli/bin.test.ts b/packages/browser/test/cli/bin.test.ts index 725d2961..50386b81 100644 --- a/packages/browser/test/cli/bin.test.ts +++ b/packages/browser/test/cli/bin.test.ts @@ -3,7 +3,7 @@ import { existsSync, readFileSync, readdirSync } from "node:fs"; import { dirname, join, sep } from "node:path"; import { fileURLToPath } from "node:url"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; -import { type FakeSecretStore, fakeSecretStore, noFakeSecretStore } from "../helpers/fake-secret-store.js"; +import { type FakeSecretStore, fakeSecretStore } from "../helpers/fake-secret-store.js"; import { type Sandbox, sandbox } from "../helpers/sandbox.js"; import { fakeProgram, pathWith, slashes } from "../helpers/programs.js"; @@ -126,7 +126,7 @@ describe("turno-browser", () => { ); }); - it.skipIf(noFakeSecretStore)("lists a vault without its values", () => { + it("lists a vault without its values", () => { run(["add", "school"]); const add = run( ["vault", "add", "school", "mail", "--url", "https://mail.example.com", "--username", "alice@example.com"], @@ -242,43 +242,40 @@ describe("turno-browser", () => { expect(run(["setup", "codex", "--identity", "nobody"])).toMatchObject({ code: 2 }); }); - it.skipIf(noFakeSecretStore)( - "stores, checks, lists and removes the secrets identity.json names, never printing them", - () => { - run(["add", "school"]); - run([ - "set", - "school", - "--proxy-server", - "http://proxy.example.com:8080", - "--proxy-username", - "alice", - "--proxy-password", - "keychain:school-proxy", - ]); - const missing = run(["secret", "list"]); - expect(missing.code).toBe(1); - expect(missing.out).toMatch( - /^MISSING {2}keychain:school-proxy {2}\(school\) {2}turno-browser secret set school-proxy$/m, - ); - const set = run(["secret", "set", "school-proxy"], "correct-horse-battery"); - expect(set).toMatchObject({ code: 0, out: "stored keychain:school-proxy\n" }); - expect(store.read("school-proxy")).toBe("correct-horse-battery"); - expect(run(["secret", "has", "school-proxy"]).code).toBe(0); - const list = run(["secret", "list", "--json"]); - expect(list.code).toBe(0); - expect(JSON.parse(list.out)).toEqual([ - { schemaVersion: 1, item: "school-proxy", stored: true, identities: ["school"] }, - ]); - expect(list.out + set.out).not.toContain("correct-horse"); - expect(run(["secret", "remove", "school-proxy"])).toMatchObject({ - code: 0, - out: "removed keychain:school-proxy\n", - }); - expect(run(["secret", "has", "school-proxy"]).code).toBe(1); - expect(run(["secret", "set", "empty"], "").code).toBe(2); - }, - ); + it("stores, checks, lists and removes the secrets identity.json names, never printing them", () => { + run(["add", "school"]); + run([ + "set", + "school", + "--proxy-server", + "http://proxy.example.com:8080", + "--proxy-username", + "alice", + "--proxy-password", + "keychain:school-proxy", + ]); + const missing = run(["secret", "list"]); + expect(missing.code).toBe(1); + expect(missing.out).toMatch( + /^MISSING {2}keychain:school-proxy {2}\(school\) {2}turno-browser secret set school-proxy$/m, + ); + const set = run(["secret", "set", "school-proxy"], "correct-horse-battery"); + expect(set).toMatchObject({ code: 0, out: "stored keychain:school-proxy\n" }); + expect(store.read("school-proxy")).toBe("correct-horse-battery"); + expect(run(["secret", "has", "school-proxy"]).code).toBe(0); + const list = run(["secret", "list", "--json"]); + expect(list.code).toBe(0); + expect(JSON.parse(list.out)).toEqual([ + { schemaVersion: 1, item: "school-proxy", stored: true, identities: ["school"] }, + ]); + expect(list.out + set.out).not.toContain("correct-horse"); + expect(run(["secret", "remove", "school-proxy"])).toMatchObject({ + code: 0, + out: "removed keychain:school-proxy\n", + }); + expect(run(["secret", "has", "school-proxy"]).code).toBe(1); + expect(run(["secret", "set", "empty"], "").code).toBe(2); + }); it("reports usage errors with exit 2, as text or JSON", () => { expect(run(["add"])).toMatchObject({ diff --git a/packages/browser/test/cli/remove.test.ts b/packages/browser/test/cli/remove.test.ts index 949a1ec9..adfe6d22 100644 --- a/packages/browser/test/cli/remove.test.ts +++ b/packages/browser/test/cli/remove.test.ts @@ -12,7 +12,7 @@ import { runtimeLockPath } from "../../src/runtime-lock.js"; import { recordExportFile } from "../../src/session-export.js"; import { identitySettingsPath } from "../../src/settings.js"; import { vaultPath } from "../../src/vault.js"; -import { type FakeSecretStore, fakeSecretStore, noFakeSecretStore } from "../helpers/fake-secret-store.js"; +import { type FakeSecretStore, fakeSecretStore } from "../helpers/fake-secret-store.js"; import { type Sandbox, sandbox } from "../helpers/sandbox.js"; import { cli, fakeAgentCli, fakeIo, real } from "./helpers.js"; import { fakeProgram, pathWith } from "../helpers/programs.js"; @@ -102,7 +102,7 @@ function claudeHas(id: string, env: NodeJS.ProcessEnv = sb.env): void { const json = (io: { lines: string[] }) => JSON.parse(io.lines.join("\n")); // Every case removes vault credentials from the secret store. -describe.skipIf(noFakeSecretStore)("turno-browser remove", () => { +describe("turno-browser remove", () => { it("without a terminal needs --yes and deletes nothing; an unknown identity is refused", async () => { await expect(cli(api).run("remove", ["nope", "--yes"], fakeIo(sb.env))).rejects.toThrow(/does not exist/); await school(); diff --git a/packages/browser/test/helpers/fake-secret-store.ts b/packages/browser/test/helpers/fake-secret-store.ts index d3c12960..6d87ae8e 100644 --- a/packages/browser/test/helpers/fake-secret-store.ts +++ b/packages/browser/test/helpers/fake-secret-store.ts @@ -1,20 +1,28 @@ -import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { + chmodSync, + existsSync, + mkdirSync, + readFileSync, + readdirSync, + renameSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { execFileSync } from "node:child_process"; +import { createRequire } from "node:module"; import { join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { dpapiDir } from "turno-core/secrets"; import type { Sandbox } from "./sandbox.js"; /** * A file-backed stand-in for the macOS `security` and libsecret `secret-tool` commands, put * first on the sandbox PATH. Items live under `/fake-secrets/`, never in a real * Keychain. `failWrites(true)` makes every store fail, like a locked Keychain. + * + * On Windows the store is the real one: DPAPI files under the sandbox's LOCALAPPDATA, + * encrypted for the account that runs the tests, so nothing reaches the account's own store. */ -/** - * Why a test that stores a secret cannot run here: the stand-ins replace the macOS and Linux - * commands, and Windows' DPAPI store runs Windows PowerShell instead (turno-core tests it with - * a real round trip). Undefined where the stand-ins work. - */ -export const noFakeSecretStore: string | undefined = - process.platform === "win32" ? "the stand-ins replace macOS and Linux commands" : undefined; - export interface FakeSecretStore { dir: string; read(service: string): string | undefined; @@ -81,7 +89,54 @@ if (cmd === "clear") { fs.rmSync(file(s), { force: true }); process.exit(0); } process.exit(1); `; +/** Sets (value on stdin) or gets one item through turno-core's DPAPI store, in a child process so the helper stays synchronous. */ +const DPAPI_SCRIPT = ` +const { secretStore } = await import(${JSON.stringify(pathToFileURL(createRequire(import.meta.url).resolve("turno-core/secrets")).href)}); +const store = secretStore(process.env, "win32"); +const name = process.env.TURNO_TEST_ITEM; +if (process.env.TURNO_TEST_OP === "set") { + const chunks = []; + for await (const c of process.stdin) chunks.push(c); + await store.set(name, Buffer.concat(chunks).toString("utf8")); +} else process.stdout.write(JSON.stringify((await store.get(name)) ?? null)); +`; + +function windowsStore(sb: Sandbox): FakeSecretStore { + const dir = dpapiDir(sb.env); + const call = (op: "get" | "set", service: string, value = "") => + execFileSync(process.execPath, ["--input-type=module", "-e", DPAPI_SCRIPT], { + env: { ...sb.env, TURNO_TEST_OP: op, TURNO_TEST_ITEM: service }, + input: value, + encoding: "utf8", + windowsHide: true, + }); + return { + dir, + read: (s) => (JSON.parse(call("get", s)) as string | null) ?? undefined, + write: (s, v) => void call("set", s, v), + services: () => + existsSync(dir) + ? readdirSync(dir) + .filter((f) => f.endsWith(".json")) + .map((f) => (JSON.parse(readFileSync(join(dir, f), "utf8")) as { name: string }).name) + : [], + // A file where the folder should be: every write fails, as with a locked Keychain. + failWrites(on) { + const aside = `${dir}.aside`; + if (on) { + if (existsSync(dir)) renameSync(dir, aside); + mkdirSync(join(dir, ".."), { recursive: true }); + writeFileSync(dir, ""); + } else { + rmSync(dir, { force: true }); + if (existsSync(aside)) renameSync(aside, dir); + } + }, + }; +} + export function fakeSecretStore(sb: Sandbox): FakeSecretStore { + if (process.platform === "win32") return windowsStore(sb); const bin = join(sb.home, "fakebin"); const dir = join(sb.home, "fake-secrets"); mkdirSync(bin, { recursive: true }); diff --git a/packages/browser/test/network-chrome.test.ts b/packages/browser/test/network-chrome.test.ts index b4482cfe..623f6854 100644 --- a/packages/browser/test/network-chrome.test.ts +++ b/packages/browser/test/network-chrome.test.ts @@ -12,7 +12,7 @@ import { liveStatus } from "../src/live-client.js"; import { listRecordings, recordingsDir, zipTexts } from "../src/recordings.js"; import { writeIdentitySettings } from "../src/settings.js"; import { chromeUnavailable, stopSandboxProcesses, waitFor } from "./helpers/chrome.js"; -import { type FakeSecretStore, fakeSecretStore, noFakeSecretStore } from "./helpers/fake-secret-store.js"; +import { type FakeSecretStore, fakeSecretStore } from "./helpers/fake-secret-store.js"; import { localProxy } from "./helpers/local-proxy.js"; import { type Sandbox, sandbox } from "./helpers/sandbox.js"; @@ -219,39 +219,36 @@ describe.skipIf(reason)("identity.json userAgent with a real Chrome", () => { }); describe.skipIf(reason)("identity.json proxy with a real Chrome and a local proxy", () => { - it.skipIf(noFakeSecretStore)( - "sends the traffic through the proxy with the password from the secret store, which no tool result shows", - async () => { - const proxy = await localProxy("alice", PASSWORD, listen); - store.write("proxy-pass", PASSWORD); - addIdentity("px", sb.env); - writeIdentitySettings( - "px", - { proxy: { server: proxy.server, username: "alice", password: "keychain:proxy-pass" } }, - sb.env, - ); - const site = await probeSite(); - const client = await start("px"); - // http://127.0.0.1, not localhost: Playwright sends loopback through the proxy too, and a - // plain http:// request carries Proxy-Authorization, the case a header could leak in. - const target = site.url.replace("localhost", "127.0.0.1"); - const results = [await call(client, "browser_navigate", { url: target })]; - expect(results[0]!.error, results[0]!.text).toBe(false); - await site.until(2); - expect(proxy.seen.relayed).toContain("/probe"); - expect(proxy.seen.relayed).toContain("/worker.js"); - expect(proxy.seen.wrongCredentials).toBe(0); - results.push(await call(client, "browser_network_requests", { static: true })); - for (let i = 1; i <= 3; i++) results.push(await call(client, "browser_network_request", { index: i })); - results.push(await call(client, "browser_snapshot")); - results.push(await call(client, "browser_evaluate", { function: "() => document.title" })); - const basic = Buffer.from(`alice:${PASSWORD}`).toString("base64"); - for (const r of results) { - expect(r.text.includes(PASSWORD)).toBe(false); - expect(r.text.includes(basic)).toBe(false); - } - }, - ); + it("sends the traffic through the proxy with the password from the secret store, which no tool result shows", async () => { + const proxy = await localProxy("alice", PASSWORD, listen); + store.write("proxy-pass", PASSWORD); + addIdentity("px", sb.env); + writeIdentitySettings( + "px", + { proxy: { server: proxy.server, username: "alice", password: "keychain:proxy-pass" } }, + sb.env, + ); + const site = await probeSite(); + const client = await start("px"); + // http://127.0.0.1, not localhost: Playwright sends loopback through the proxy too, and a + // plain http:// request carries Proxy-Authorization, the case a header could leak in. + const target = site.url.replace("localhost", "127.0.0.1"); + const results = [await call(client, "browser_navigate", { url: target })]; + expect(results[0]!.error, results[0]!.text).toBe(false); + await site.until(2); + expect(proxy.seen.relayed).toContain("/probe"); + expect(proxy.seen.relayed).toContain("/worker.js"); + expect(proxy.seen.wrongCredentials).toBe(0); + results.push(await call(client, "browser_network_requests", { static: true })); + for (let i = 1; i <= 3; i++) results.push(await call(client, "browser_network_request", { index: i })); + results.push(await call(client, "browser_snapshot")); + results.push(await call(client, "browser_evaluate", { function: "() => document.title" })); + const basic = Buffer.from(`alice:${PASSWORD}`).toString("base64"); + for (const r of results) { + expect(r.text.includes(PASSWORD)).toBe(false); + expect(r.text.includes(basic)).toBe(false); + } + }); it("refuses to start without the secret, naming the item and never a value", async () => { const proxy = await localProxy("alice", PASSWORD, listen); @@ -272,82 +269,76 @@ describe.skipIf(reason)("identity.json proxy with a real Chrome and a local prox expect(site.reports).toEqual([]); }); - it.skipIf(noFakeSecretStore)( - "records flows and screenshots behind a proxy with a password, and no recording holds it", - async () => { - const proxy = await localProxy("alice", PASSWORD, listen); - store.write("proxy-pass", PASSWORD); - addIdentity("rec", sb.env); - writeIdentitySettings( - "rec", - { - proxy: { server: proxy.server, username: "alice", password: "keychain:proxy-pass" }, - record: { flows: true, screenshots: true }, - }, - sb.env, - ); - const site = await probeSite(); - const client = await start("rec"); - const target = site.url.replace("localhost", "127.0.0.1"); - expect((await call(client, "browser_navigate", { url: target })).error).toBe(false); - await site.until(2); - await call(client, "browser_navigate", { url: `${target}?again` }); - await call(client, "browser_close"); - expect(await waitFor(() => listRecordings("rec", sb.env)[0]?.ended !== undefined, 15_000)).toBe(true); - expect(proxy.seen.relayed).toContain("/probe"); - expect(listRecordings("rec", sb.env)[0]?.screenshots).toBeGreaterThan(0); - const recorded = allText(recordingsDir("rec", sb.env)); - const basic = Buffer.from(`alice:${PASSWORD}`).toString("base64"); - expect(recorded.includes(PASSWORD)).toBe(false); - expect(recorded.includes(basic)).toBe(false); - }, - ); + it("records flows and screenshots behind a proxy with a password, and no recording holds it", async () => { + const proxy = await localProxy("alice", PASSWORD, listen); + store.write("proxy-pass", PASSWORD); + addIdentity("rec", sb.env); + writeIdentitySettings( + "rec", + { + proxy: { server: proxy.server, username: "alice", password: "keychain:proxy-pass" }, + record: { flows: true, screenshots: true }, + }, + sb.env, + ); + const site = await probeSite(); + const client = await start("rec"); + const target = site.url.replace("localhost", "127.0.0.1"); + expect((await call(client, "browser_navigate", { url: target })).error).toBe(false); + await site.until(2); + await call(client, "browser_navigate", { url: `${target}?again` }); + await call(client, "browser_close"); + expect(await waitFor(() => listRecordings("rec", sb.env)[0]?.ended !== undefined, 15_000)).toBe(true); + expect(proxy.seen.relayed).toContain("/probe"); + expect(listRecordings("rec", sb.env)[0]?.screenshots).toBeGreaterThan(0); + const recorded = allText(recordingsDir("rec", sb.env)); + const basic = Buffer.from(`alice:${PASSWORD}`).toString("base64"); + expect(recorded.includes(PASSWORD)).toBe(false); + expect(recorded.includes(basic)).toBe(false); + }); - it.skipIf(noFakeSecretStore)( - "keeps the proxy credentials out of the act model's prompt and the live view's tab list", - async () => { - const proxy = await localProxy("alice", PASSWORD, listen); - store.write("proxy-pass", PASSWORD); - addIdentity("act", sb.env); - writeIdentitySettings( - "act", - { - proxy: { server: proxy.server, username: "alice", password: "keychain:proxy-pass" }, - act: {}, - live: { enabled: true }, - }, - sb.env, - ); - // A page that shows the credentials, as a page that echoed them would. - const basic = Buffer.from(`alice:${PASSWORD}`).toString("base64"); - const shown = PASSWORD.replace(/&/g, "&").replace(//g, ">"); - const port = await listen( - createServer((_req, res) => { - res.setHeader("content-type", "text/html"); - res.end(`echo ${shown}

alice:${shown}

${basic}

`); - }), - ); - const prompts: string[] = []; - const client = await start("act", (prompt) => { - prompts.push(prompt); - return JSON.stringify({ done: true, success: true, summary: "read the page" }); - }); - const nav = await call(client, "browser_navigate", { url: `http://127.0.0.1:${port}/echo` }); - expect(nav.error, nav.text).toBe(false); - expect(proxy.seen.relayed).toContain("/echo"); - const acted = await call(client, "browser_act", { instruction: "Read the page" }); - expect(acted.error, acted.text).toBe(false); - expect(prompts.length).toBeGreaterThan(0); - const status = JSON.stringify(await liveStatus("act", sb.env)); - expect(status).toContain("/echo"); - for (const text of [...prompts, acted.text, nav.text, status]) { - expect(text.includes(PASSWORD)).toBe(false); - expect(text.includes(basic)).toBe(false); - } - }, - ); + it("keeps the proxy credentials out of the act model's prompt and the live view's tab list", async () => { + const proxy = await localProxy("alice", PASSWORD, listen); + store.write("proxy-pass", PASSWORD); + addIdentity("act", sb.env); + writeIdentitySettings( + "act", + { + proxy: { server: proxy.server, username: "alice", password: "keychain:proxy-pass" }, + act: {}, + live: { enabled: true }, + }, + sb.env, + ); + // A page that shows the credentials, as a page that echoed them would. + const basic = Buffer.from(`alice:${PASSWORD}`).toString("base64"); + const shown = PASSWORD.replace(/&/g, "&").replace(//g, ">"); + const port = await listen( + createServer((_req, res) => { + res.setHeader("content-type", "text/html"); + res.end(`echo ${shown}

alice:${shown}

${basic}

`); + }), + ); + const prompts: string[] = []; + const client = await start("act", (prompt) => { + prompts.push(prompt); + return JSON.stringify({ done: true, success: true, summary: "read the page" }); + }); + const nav = await call(client, "browser_navigate", { url: `http://127.0.0.1:${port}/echo` }); + expect(nav.error, nav.text).toBe(false); + expect(proxy.seen.relayed).toContain("/echo"); + const acted = await call(client, "browser_act", { instruction: "Read the page" }); + expect(acted.error, acted.text).toBe(false); + expect(prompts.length).toBeGreaterThan(0); + const status = JSON.stringify(await liveStatus("act", sb.env)); + expect(status).toContain("/echo"); + for (const text of [...prompts, acted.text, nav.text, status]) { + expect(text.includes(PASSWORD)).toBe(false); + expect(text.includes(basic)).toBe(false); + } + }); - it.skipIf(noFakeSecretStore)("works with userAgent coherent, humanize and tab sharing on one identity", async () => { + it("works with userAgent coherent, humanize and tab sharing on one identity", async () => { const proxy = await localProxy("alice", PASSWORD, listen); store.write("proxy-pass", PASSWORD); addIdentity("all", sb.env); diff --git a/packages/browser/test/network.test.ts b/packages/browser/test/network.test.ts index 7ed3babe..5a123334 100644 --- a/packages/browser/test/network.test.ts +++ b/packages/browser/test/network.test.ts @@ -24,7 +24,7 @@ import { } from "../src/network.js"; import { type IdentitySettings, readIdentitySettings, writeIdentitySettings } from "../src/settings.js"; import type { McpConfig } from "../src/upstream.js"; -import { type FakeSecretStore, fakeSecretStore, noFakeSecretStore } from "./helpers/fake-secret-store.js"; +import { type FakeSecretStore, fakeSecretStore } from "./helpers/fake-secret-store.js"; import { type Sandbox, sandbox } from "./helpers/sandbox.js"; /** @@ -144,7 +144,7 @@ describe("identity.json userAgent and proxy (format 11)", () => { }); describe("the proxy credentials", () => { - it.skipIf(noFakeSecretStore)("come from the secret store, and every form of them joins the redactor", async () => { + it("come from the secret store, and every form of them joins the redactor", async () => { store.write("proxy-pass", PASSWORD); store.write("proxy-user", "alice-zone-1"); const hidden: [string, string][] = []; @@ -160,7 +160,7 @@ describe("the proxy credentials", () => { expect(hidden.map(([v]) => v).includes(basic)).toBe(true); }); - it.skipIf(noFakeSecretStore)("fails with the item's name, never a value, when the store lacks it", async () => { + it("fails with the item's name, never a value, when the store lacks it", async () => { const error = await resolveProxy( { server: "http://127.0.0.1:3128", username: "alice", password: "keychain:missing-item" }, sb.env, @@ -413,37 +413,34 @@ describe("combinations refused before anything starts", () => { }); describe("turno browser doctor", () => { - it.skipIf(noFakeSecretStore)( - "says whether the secret store holds the proxy credentials, without reading them", - async () => { - addIdentity("px", sb.env); - writeIdentitySettings( - "px", - { proxy: { server: "http://proxy.example.com:8080", username: "alice", password: "keychain:px-pass" } }, - sb.env, - ); - const run = () => - runDoctor({ - env: sb.env, - launch: false, - chrome: () => ({ path: "/chrome", version: "157.0.0.1" }), - lightpanda: () => undefined, - camoufox: () => undefined, - playwrightCore: () => undefined, - procTable: () => new Map(), - }); - const missing = (await run()).checks.filter((c) => c.area === "identity px"); - expect( - missing.find((c) => /proxy http:\/\/proxy\.example\.com:8080: the proxy's operator sees/.test(c.text))?.level, - ).toBe("info"); - const fail = missing.find((c) => c.text.startsWith("proxy credentials")); - expect(fail).toMatchObject({ level: "fail", fix: "turno-browser secret set px-pass" }); - store.write("px-pass", PASSWORD); - const present = (await run()).checks.filter((c) => c.area === "identity px"); - expect(present.find((c) => c.text.startsWith("proxy credentials"))?.level).toBe("ok"); - expect(JSON.stringify(present)).not.toContain(PASSWORD); - }, - ); + it("says whether the secret store holds the proxy credentials, without reading them", async () => { + addIdentity("px", sb.env); + writeIdentitySettings( + "px", + { proxy: { server: "http://proxy.example.com:8080", username: "alice", password: "keychain:px-pass" } }, + sb.env, + ); + const run = () => + runDoctor({ + env: sb.env, + launch: false, + chrome: () => ({ path: "/chrome", version: "157.0.0.1" }), + lightpanda: () => undefined, + camoufox: () => undefined, + playwrightCore: () => undefined, + procTable: () => new Map(), + }); + const missing = (await run()).checks.filter((c) => c.area === "identity px"); + expect( + missing.find((c) => /proxy http:\/\/proxy\.example\.com:8080: the proxy's operator sees/.test(c.text))?.level, + ).toBe("info"); + const fail = missing.find((c) => c.text.startsWith("proxy credentials")); + expect(fail).toMatchObject({ level: "fail", fix: "turno-browser secret set px-pass" }); + store.write("px-pass", PASSWORD); + const present = (await run()).checks.filter((c) => c.area === "identity px"); + expect(present.find((c) => c.text.startsWith("proxy credentials"))?.level).toBe("ok"); + expect(JSON.stringify(present)).not.toContain(PASSWORD); + }); it("fails on a missing Camoufox or playwright-core only when an identity uses the engine", async () => { const run = () => diff --git a/packages/browser/test/vault.test.ts b/packages/browser/test/vault.test.ts index 71c136fe..2ad1afe5 100644 --- a/packages/browser/test/vault.test.ts +++ b/packages/browser/test/vault.test.ts @@ -19,7 +19,7 @@ import { vaultSetSubmit, vaultSite, } from "../src/vault.js"; -import { type FakeSecretStore, fakeSecretStore, noFakeSecretStore } from "./helpers/fake-secret-store.js"; +import { type FakeSecretStore, fakeSecretStore } from "./helpers/fake-secret-store.js"; import { type Sandbox, sandbox, expectMode } from "./helpers/sandbox.js"; let sb: Sandbox; @@ -36,36 +36,33 @@ const TOTP_SECRET = "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP"; const opts = () => ({ env: sb.env, store: secretStore(sb.env, "darwin")! }); describe("the credential vault", () => { - it.skipIf(noFakeSecretStore)( - "keeps the values in the secret store and only names and origins in the index", - async () => { - const site = await vaultAdd( - "work", - "github", - { - urls: ["https://github.com/login", "https://github.com/session"], - username: "alice@example.com", - password: PASSWORD, - totp: TOTP_SECRET, - }, - opts(), - ); - expect(site).toMatchObject({ site: "github", origins: ["https://github.com"], totp: true }); - const index = readFileSync(vaultPath("work", sb.env), "utf8"); - expect(index).not.toContain("alice"); - expect(index).not.toContain("battery"); - expect(index).not.toContain(TOTP_SECRET); - expectMode(vaultPath("work", sb.env), 0o600); - expect(fake.services()).toEqual([vaultItem("work", "github")]); - expect(fake.read(vaultItem("work", "github"))).not.toContain("\n"); - const cred = await readCredential("work", "github", opts()); - expect(cred.username === "alice@example.com" && cred.password === PASSWORD).toBe(true); - expect(cred.totp).toMatchObject({ algorithm: "SHA1", digits: 6, period: 30 }); - expect(totp(cred.totp!, 0)).toMatch(/^\d{6}$/); - }, - ); + it("keeps the values in the secret store and only names and origins in the index", async () => { + const site = await vaultAdd( + "work", + "github", + { + urls: ["https://github.com/login", "https://github.com/session"], + username: "alice@example.com", + password: PASSWORD, + totp: TOTP_SECRET, + }, + opts(), + ); + expect(site).toMatchObject({ site: "github", origins: ["https://github.com"], totp: true }); + const index = readFileSync(vaultPath("work", sb.env), "utf8"); + expect(index).not.toContain("alice"); + expect(index).not.toContain("battery"); + expect(index).not.toContain(TOTP_SECRET); + expectMode(vaultPath("work", sb.env), 0o600); + expect(fake.services()).toEqual([vaultItem("work", "github")]); + expect(fake.read(vaultItem("work", "github"))).not.toContain("\n"); + const cred = await readCredential("work", "github", opts()); + expect(cred.username === "alice@example.com" && cred.password === PASSWORD).toBe(true); + expect(cred.totp).toMatchObject({ algorithm: "SHA1", digits: 6, period: 30 }); + expect(totp(cred.totp!, 0)).toMatch(/^\d{6}$/); + }); - it.skipIf(noFakeSecretStore)("lists sites without reading a value, and says when an item went missing", async () => { + it("lists sites without reading a value, and says when an item went missing", async () => { await vaultAdd( "work", "github", @@ -90,46 +87,40 @@ describe("the credential vault", () => { await expect(readCredential("work", "mail", opts())).rejects.toThrow(/missing from the secret store/); }); - it.skipIf(noFakeSecretStore)( - "replaces a site's credentials by deleting the item first, keeping its creation date", - async () => { - const first = await vaultAdd( - "work", - "github", - { urls: ["https://github.com"], username: "alice", password: "first-pass" }, - { ...opts(), now: new Date("2026-01-01T00:00:00Z") }, - ); - const second = await vaultAdd( - "work", - "github", - { urls: ["https://github.com"], username: "alice", password: "second-pass" }, - { ...opts(), now: new Date("2026-02-01T00:00:00Z") }, - ); - expect(second.created).toBe(first.created); - expect(second.updated).toBe("2026-02-01T00:00:00.000Z"); - expect((await readCredential("work", "github", opts())).password === "second-pass").toBe(true); - }, - ); + it("replaces a site's credentials by deleting the item first, keeping its creation date", async () => { + const first = await vaultAdd( + "work", + "github", + { urls: ["https://github.com"], username: "alice", password: "first-pass" }, + { ...opts(), now: new Date("2026-01-01T00:00:00Z") }, + ); + const second = await vaultAdd( + "work", + "github", + { urls: ["https://github.com"], username: "alice", password: "second-pass" }, + { ...opts(), now: new Date("2026-02-01T00:00:00Z") }, + ); + expect(second.created).toBe(first.created); + expect(second.updated).toBe("2026-02-01T00:00:00.000Z"); + expect((await readCredential("work", "github", opts())).password === "second-pass").toBe(true); + }); - it.skipIf(noFakeSecretStore)( - "removes one site, then everything, and refuses to remove an identity that still has credentials", - async () => { - await vaultAdd("work", "github", { urls: ["https://github.com"], username: "alice", password: PASSWORD }, opts()); - await vaultAdd( - "work", - "mail", - { urls: ["https://mail.example.com"], username: "alice", password: PASSWORD }, - opts(), - ); - expect(await vaultRemove("work", "github", opts())).toBe(true); - expect(await vaultRemove("work", "github", opts())).toBe(false); - expect(vaultHasSites("work", sb.env)).toBe(true); - expect(() => removeIdentity("work", sb.env)).toThrow(/still has vault credentials/); - expect(await vaultClear("work", opts())).toBe(1); - expect(fake.services()).toEqual([]); - removeIdentity("work", sb.env); - }, - ); + it("removes one site, then everything, and refuses to remove an identity that still has credentials", async () => { + await vaultAdd("work", "github", { urls: ["https://github.com"], username: "alice", password: PASSWORD }, opts()); + await vaultAdd( + "work", + "mail", + { urls: ["https://mail.example.com"], username: "alice", password: PASSWORD }, + opts(), + ); + expect(await vaultRemove("work", "github", opts())).toBe(true); + expect(await vaultRemove("work", "github", opts())).toBe(false); + expect(vaultHasSites("work", sb.env)).toBe(true); + expect(() => removeIdentity("work", sb.env)).toThrow(/still has vault credentials/); + expect(await vaultClear("work", opts())).toBe(1); + expect(fake.services()).toEqual([]); + removeIdentity("work", sb.env); + }); it("binds credentials to https origins (http only on this machine)", async () => { expect(vaultOrigin("https://github.com/login?x=1")).toBe("https://github.com"); @@ -165,7 +156,7 @@ describe("the credential vault", () => { expect(fake.services()).toEqual([]); }); - it.skipIf(noFakeSecretStore)("records the submit policy per identity", async () => { + it("records the submit policy per identity", async () => { expect(vaultSetSubmit("work", "auto", { env: sb.env })).toBe("auto"); await vaultAdd("work", "github", { urls: ["https://github.com"], username: "alice", password: PASSWORD }, opts()); expect(vaultSite("work", "github", sb.env)?.submit).toBe("auto"); From 5d4bb813b09b61dd1ad264846a8c386fbc5e609c Mon Sep 17 00:00:00 2001 From: William Frank Monroy Mamani Date: Sun, 22 Nov 2026 14:58:50 -0600 Subject: [PATCH 12/15] ci: time Windows PowerShell under a trimmed environment (temporary) --- .github/workflows/ci.yml | 59 ++++++++++++++++++++++++---------------- 1 file changed, 36 insertions(+), 23 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 62a5085c..bb47a41b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -70,41 +70,54 @@ jobs: - run: pnpm install --frozen-lockfile - run: pnpm --filter turno-core --filter turno-browser run build - run: pnpm --filter turno-core --filter turno-browser run typecheck - - name: Trace the CLI's child processes (temporary) + - name: PowerShell timings (temporary) continue-on-error: true shell: pwsh run: | - $trace = @' - const cp = require("node:child_process"); - for (const k of ["spawn", "spawnSync", "execFile", "execFileSync"]) { - const f = cp[k]; - cp[k] = function (...a) { - const t = Date.now(); - const r = f.apply(this, a); - const log = () => process.stderr.write(`[trace ${process.pid}] ${k} ${String(a[0]).slice(-60)} ${JSON.stringify(Array.isArray(a[1]) ? a[1].slice(0, 3) : "").slice(0, 100)} ${Date.now() - t}ms\n`); - if (r && typeof r.on === "function") r.on("exit", log); else log(); - return r; - }; - } - require("node:module").syncBuiltinESMExports(); - '@ - Set-Content -Path "$env:RUNNER_TEMP\trace.cjs" -Value $trace $js = @' const { spawnSync } = require("node:child_process"); const { mkdtempSync } = require("node:fs"); const { tmpdir } = require("node:os"); const { join } = require("node:path"); const e = process.env; - const home = mkdtempSync(join(tmpdir(), "tr-")); + console.log("PSModulePath=" + e.PSModulePath); + const ps = join(e.SystemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"); const keep = ["SystemRoot", "windir", "ComSpec", "PATHEXT", "TEMP", "TMP", "ProgramFiles", "ProgramFiles(x86)", "PATH"]; - const env = { ...Object.fromEntries(keep.map((k) => [k, e[k]])), HOME: home, USERPROFILE: home, APPDATA: join(home, "AppData", "Roaming"), LOCALAPPDATA: join(home, "AppData", "Local"), XDG_CONFIG_HOME: join(home, ".config"), XDG_STATE_HOME: join(home, ".local", "state"), XDG_DATA_HOME: join(home, ".local", "share"), TURNO_NO_INPUT: "1", NODE_OPTIONS: `--require ${join(e.RUNNER_TEMP, "trace.cjs")}` }; - const cli = join("packages", "browser", "dist", "cli", "main.js"); - for (const args of [["add", "school"], ["doctor", "--no-launch", "--json"], ["do", "school", "session"], ["do", "school", "end"]]) { + const sys32 = `${e.SystemRoot}\\System32\\WindowsPowerShell\\v1.0\\Modules`; + const scripts = { + one: "1", + cim: "(Get-CimInstance Win32_Process).Count", + wmi: "Add-Type -AssemblyName System.Management; (New-Object System.Management.ManagementObjectSearcher('SELECT ProcessId FROM Win32_Process')).Get().Count", + dotnet: "[void][Reflection.Assembly]::LoadWithPartialName('System.Management'); ([System.Management.ManagementObjectSearcher]::new('SELECT ProcessId,ParentProcessId,CommandLine FROM Win32_Process')).Get().Count", + dpapi: "Add-Type -AssemblyName System.Security; [Security.Cryptography.ProtectedData]::Protect([byte[]](1,2,3), $null, 'CurrentUser').Length", + modpath: "$env:PSModulePath", + }; + const envs = { + unset: {}, + sys32: { PSModulePath: sys32 }, + triple: { PSModulePath: `${e.ProgramFiles}\\WindowsPowerShell\\Modules;${sys32}` }, + real: { PSModulePath: e.PSModulePath }, + }; + for (const [en, extra] of Object.entries(envs)) for (const [sn, script] of Object.entries(scripts)) { + if (en !== "unset" && (sn === "one" || sn === "modpath")) continue; + const home = mkdtempSync(join(tmpdir(), "ps-")); + const env = { ...Object.fromEntries(keep.map((k) => [k, e[k]])), HOME: home, USERPROFILE: home, APPDATA: join(home, "r"), LOCALAPPDATA: join(home, "l"), ...extra }; const t = Date.now(); - const r = spawnSync(process.execPath, [cli, ...args], { env, encoding: "utf8", timeout: 60000 }); - console.log(`== ${args.join(" ")}: ${Date.now() - t}ms status=${r.status} ${r.error ? r.error.code : ""}`); - console.log((r.stderr || "").split("\n").filter((l) => l.startsWith("[trace")).join("\n")); + const r = spawnSync(ps, ["-NoProfile", "-NonInteractive", "-Command", script], { env, encoding: "utf8", timeout: 25000, windowsHide: true }); + console.log(`${en} ${sn}: ${((Date.now() - t) / 1000).toFixed(1)}s status=${r.status} out=${(r.stdout || "").trim().slice(0, 200)} err=${(r.stderr || "").trim().split("\n")[0].slice(0, 150)} ${r.error ? r.error.code : ""}`); } + (async () => { + const { secretStore } = await import("./packages/core/dist/secrets.js"); + for (const [en, extra] of Object.entries(envs)) { + const home = mkdtempSync(join(tmpdir(), "dp-")); + const env = { ...Object.fromEntries(keep.map((k) => [k, e[k]])), HOME: home, USERPROFILE: home, APPDATA: join(home, "r"), LOCALAPPDATA: join(home, "l"), ...extra }; + const store = secretStore(env, "win32"); + let t = Date.now(); + try { await store.set("diag", "v1"); console.log(`dpapi ${en} set: ${Date.now() - t}ms`); } catch (err) { console.log(`dpapi ${en} set failed after ${Date.now() - t}ms: ${err.message}`); } + t = Date.now(); + try { const v = await store.get("diag"); console.log(`dpapi ${en} get: ${Date.now() - t}ms value=${v}`); } catch (err) { console.log(`dpapi ${en} get failed after ${Date.now() - t}ms: ${err.message}`); } + } + })(); '@ node -e $js # The core suite, the Windows secret store's DPAPI round trip included. From c8a347a6f15a4591198d52a4cb0c6f04d3d44935 Mon Sep 17 00:00:00 2001 From: William Frank Monroy Mamani Date: Sun, 22 Nov 2026 15:33:19 -0600 Subject: [PATCH 13/15] fix(core): call WMI and DPAPI through .NET in Windows PowerShell, with no cmdlet --- .changeset/feat-browser-windows.md | 2 +- .github/workflows/ci.yml | 50 ------------------------------ packages/core/src/process.ts | 18 ++++++++--- packages/core/src/secrets.ts | 21 ++++++++----- packages/core/test/process.test.ts | 15 ++++----- 5 files changed, 33 insertions(+), 73 deletions(-) diff --git a/.changeset/feat-browser-windows.md b/.changeset/feat-browser-windows.md index 6967837a..bad989f4 100644 --- a/.changeset/feat-browser-windows.md +++ b/.changeset/feat-browser-windows.md @@ -5,4 +5,4 @@ turno-browser runs on Windows 10 and 11 (x64): `npm install --global turno-browser`, no admin rights. It finds Google Chrome, Microsoft Edge and Brave in `Program Files`, `Program Files (x86)` and `%LOCALAPPDATA%`, and `install-browser` puts Chrome for Testing in `%LOCALAPPDATA%\ms-playwright`. Identities live in `%LOCALAPPDATA%\turno\data`, settings in `%APPDATA%\turno` and runtime state in `%LOCALAPPDATA%\turno\state`; the `TURNO_*_DIR` and `XDG_*` variables still move them. The background server and the live view listen on named pipes (`\\.\pipe\turno-browser--`) instead of socket files. A Chrome left running is found through its profile's lock and the process table, and ended with its helpers by `taskkill /T`; messages say `taskkill /PID /T /F` where they said `kill `. `setup` and `init` register the server as `cmd /c turno-browser-mcp --identity `, and `init --yes` runs an agent's `.cmd` command through `cmd.exe` with each argument quoted. The vault and `keychain:` secrets use turno-core's Windows secret store (DPAPI files). Lightpanda has no Windows build. -turno-core: the turno folders follow Windows' conventions (`%APPDATA%`, `%LOCALAPPDATA%`), `findOnPath` reads `PATHEXT`, a file replaced while another process reads it is retried instead of failing, and `killTree` ends a process tree on every platform. +turno-core: the turno folders follow Windows' conventions (`%APPDATA%`, `%LOCALAPPDATA%`), `findOnPath` reads `PATHEXT`, a file replaced while another process reads it is retried instead of failing, and `killTree` ends a process tree on every platform. The Windows process table and the DPAPI store call WMI and DPAPI through .NET only, with no cmdlet, so Windows PowerShell answers in a fraction of a second even in the few variables an agent passes its servers (a cmdlet there took 20 seconds). diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bb47a41b..0ac282b3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -70,56 +70,6 @@ jobs: - run: pnpm install --frozen-lockfile - run: pnpm --filter turno-core --filter turno-browser run build - run: pnpm --filter turno-core --filter turno-browser run typecheck - - name: PowerShell timings (temporary) - continue-on-error: true - shell: pwsh - run: | - $js = @' - const { spawnSync } = require("node:child_process"); - const { mkdtempSync } = require("node:fs"); - const { tmpdir } = require("node:os"); - const { join } = require("node:path"); - const e = process.env; - console.log("PSModulePath=" + e.PSModulePath); - const ps = join(e.SystemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"); - const keep = ["SystemRoot", "windir", "ComSpec", "PATHEXT", "TEMP", "TMP", "ProgramFiles", "ProgramFiles(x86)", "PATH"]; - const sys32 = `${e.SystemRoot}\\System32\\WindowsPowerShell\\v1.0\\Modules`; - const scripts = { - one: "1", - cim: "(Get-CimInstance Win32_Process).Count", - wmi: "Add-Type -AssemblyName System.Management; (New-Object System.Management.ManagementObjectSearcher('SELECT ProcessId FROM Win32_Process')).Get().Count", - dotnet: "[void][Reflection.Assembly]::LoadWithPartialName('System.Management'); ([System.Management.ManagementObjectSearcher]::new('SELECT ProcessId,ParentProcessId,CommandLine FROM Win32_Process')).Get().Count", - dpapi: "Add-Type -AssemblyName System.Security; [Security.Cryptography.ProtectedData]::Protect([byte[]](1,2,3), $null, 'CurrentUser').Length", - modpath: "$env:PSModulePath", - }; - const envs = { - unset: {}, - sys32: { PSModulePath: sys32 }, - triple: { PSModulePath: `${e.ProgramFiles}\\WindowsPowerShell\\Modules;${sys32}` }, - real: { PSModulePath: e.PSModulePath }, - }; - for (const [en, extra] of Object.entries(envs)) for (const [sn, script] of Object.entries(scripts)) { - if (en !== "unset" && (sn === "one" || sn === "modpath")) continue; - const home = mkdtempSync(join(tmpdir(), "ps-")); - const env = { ...Object.fromEntries(keep.map((k) => [k, e[k]])), HOME: home, USERPROFILE: home, APPDATA: join(home, "r"), LOCALAPPDATA: join(home, "l"), ...extra }; - const t = Date.now(); - const r = spawnSync(ps, ["-NoProfile", "-NonInteractive", "-Command", script], { env, encoding: "utf8", timeout: 25000, windowsHide: true }); - console.log(`${en} ${sn}: ${((Date.now() - t) / 1000).toFixed(1)}s status=${r.status} out=${(r.stdout || "").trim().slice(0, 200)} err=${(r.stderr || "").trim().split("\n")[0].slice(0, 150)} ${r.error ? r.error.code : ""}`); - } - (async () => { - const { secretStore } = await import("./packages/core/dist/secrets.js"); - for (const [en, extra] of Object.entries(envs)) { - const home = mkdtempSync(join(tmpdir(), "dp-")); - const env = { ...Object.fromEntries(keep.map((k) => [k, e[k]])), HOME: home, USERPROFILE: home, APPDATA: join(home, "r"), LOCALAPPDATA: join(home, "l"), ...extra }; - const store = secretStore(env, "win32"); - let t = Date.now(); - try { await store.set("diag", "v1"); console.log(`dpapi ${en} set: ${Date.now() - t}ms`); } catch (err) { console.log(`dpapi ${en} set failed after ${Date.now() - t}ms: ${err.message}`); } - t = Date.now(); - try { const v = await store.get("diag"); console.log(`dpapi ${en} get: ${Date.now() - t}ms value=${v}`); } catch (err) { console.log(`dpapi ${en} get failed after ${Date.now() - t}ms: ${err.message}`); } - } - })(); - '@ - node -e $js # The core suite, the Windows secret store's DPAPI round trip included. - run: pnpm --filter turno-core run test - run: pnpm --filter turno-browser run test diff --git a/packages/core/src/process.ts b/packages/core/src/process.ts index a9fdc44c..6d16afe6 100644 --- a/packages/core/src/process.ts +++ b/packages/core/src/process.ts @@ -1,5 +1,5 @@ import { execFileSync } from "node:child_process"; -import { windowsPowerShell, windowsPowerShellEnv } from "./secrets.js"; +import { loadAssembly, windowsPowerShell, windowsPowerShellEnv } from "./secrets.js"; /** * Process helpers shared by turno-cli and turno-browser: whether a PID lives, a signal that @@ -65,10 +65,18 @@ export function parseWindowsProcTable(stdout: string): ProcTable { return t; } -/** Lists every process as `parseWindowsProcTable` reads it, in UTF-8 whatever the console code page. */ -const WINDOWS_PROC_SCRIPT = - "[Console]::OutputEncoding = [Text.Encoding]::UTF8; " + - "Get-CimInstance Win32_Process | ForEach-Object { ($_.ProcessId, $_.ParentProcessId, $_.CommandLine) -join [char]9 }"; +/** + * Lists every process as `parseWindowsProcTable` reads it, in UTF-8 whatever the console code + * page, through WMI's .NET classes rather than Get-CimInstance (see loadAssembly). + */ +const WINDOWS_PROC_SCRIPT = [ + "[Console]::OutputEncoding = [Text.Encoding]::UTF8", + loadAssembly("System.Management"), + "$s = [Management.ManagementObjectSearcher]::new('SELECT ProcessId, ParentProcessId, CommandLine FROM Win32_Process')", + "$b = [Text.StringBuilder]::new()", + "foreach ($p in $s.Get()) { $null = $b.Append([string]$p['ProcessId']).Append([char]9).Append([string]$p['ParentProcessId']).Append([char]9).Append([string]$p['CommandLine']).Append([char]10) }", + "[Console]::Out.Write($b.ToString())", +].join("; "); /** * Every process with its full command line, or undefined when the table cannot be read (no diff --git a/packages/core/src/secrets.ts b/packages/core/src/secrets.ts index 08173923..0e673e81 100644 --- a/packages/core/src/secrets.ts +++ b/packages/core/src/secrets.ts @@ -233,7 +233,7 @@ export function dpapiScript(op: DpapiOp): string { return [ "$ErrorActionPreference = 'Stop'", "try {", - " Add-Type -AssemblyName System.Security", + ` ${loadAssembly("System.Security")}`, " $ms = [IO.MemoryStream]::new()", " [Console]::OpenStandardInput().CopyTo($ms)", " $all = $ms.ToArray()", @@ -272,15 +272,20 @@ export function dpapiInput(service: string, data: Buffer): Buffer { export type DpapiRunner = (op: DpapiOp, input: Buffer) => Promise; /** - * The environment Windows PowerShell gets: the caller's, with what it needs when the caller - * trimmed it (an agent hands its MCP servers a few variables). SystemRoot it cannot start - * without; without PSModulePath it searches for its modules for 20 seconds and more - * (measured on windows-latest), so it gets the folder of the modules that come with Windows. + * The environment Windows PowerShell gets: the caller's, with SystemRoot, which it cannot start + * without, even when the caller trimmed it (an agent hands its MCP servers a few variables). */ export function windowsPowerShellEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { - const root = env.SystemRoot || env.SYSTEMROOT || process.env.SystemRoot || "C:\\Windows"; - const modules = env.PSModulePath || env.PSMODULEPATH || `${root}\\System32\\WindowsPowerShell\\v1.0\\Modules`; - return { ...env, SystemRoot: root, PSModulePath: modules }; + return { ...env, SystemRoot: env.SystemRoot || env.SYSTEMROOT || process.env.SystemRoot || "C:\\Windows" }; +} + +/** + * Loads a .NET Framework assembly by its full name. The scripts here call .NET only, never a + * cmdlet such as Add-Type: with the trimmed environment an agent gives its servers, the first + * cmdlet that PowerShell loads from a module takes 20 seconds (measured on windows-latest). + */ +export function loadAssembly(name: "System.Security" | "System.Management"): string { + return `$null = [Reflection.Assembly]::Load('${name}, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')`; } function powershellRunner(env: NodeJS.ProcessEnv): DpapiRunner { diff --git a/packages/core/test/process.test.ts b/packages/core/test/process.test.ts index 15499d6f..3efb6b6b 100644 --- a/packages/core/test/process.test.ts +++ b/packages/core/test/process.test.ts @@ -46,8 +46,9 @@ describe("process helpers", () => { it("reads this process from the real process table", () => { const t = readProcTable(); - if (!t) return; // no ps here - expect(t.get(process.pid)?.ppid).toBe(process.ppid); + if (!t && process.platform !== "win32") return; // no ps here; Windows always has PowerShell + expect(t?.get(process.pid)?.ppid).toBe(process.ppid); + expect(t?.get(process.pid)?.command).toMatch(/node/i); }); it("tells a live process from a gone one, and signals without throwing", async () => { @@ -63,12 +64,8 @@ describe("process helpers", () => { }); describe("Windows PowerShell's environment", () => { - it("fills in SystemRoot and the modules folder a trimmed environment leaves out, and keeps the caller's", () => { - expect(windowsPowerShellEnv({ SystemRoot: "D:\\Win", PATH: "x" })).toEqual({ - SystemRoot: "D:\\Win", - PSModulePath: "D:\\Win\\System32\\WindowsPowerShell\\v1.0\\Modules", - PATH: "x", - }); - expect(windowsPowerShellEnv({ SystemRoot: "D:\\Win", PSModulePath: "E:\\m" }).PSModulePath).toBe("E:\\m"); + it("fills in SystemRoot that a trimmed environment leaves out, and keeps the caller's", () => { + expect(windowsPowerShellEnv({ SystemRoot: "D:\\Win", PATH: "x" })).toEqual({ SystemRoot: "D:\\Win", PATH: "x" }); + expect(windowsPowerShellEnv({ SYSTEMROOT: "E:\\W" }).SystemRoot).toBe("E:\\W"); }); }); From 73dfe4d377a114f9667f362a574669bb2838d8b5 Mon Sep 17 00:00:00 2001 From: William Frank Monroy Mamani Date: Sun, 22 Nov 2026 15:46:30 -0600 Subject: [PATCH 14/15] test(browser): Windows paths and the DPAPI test store in the remove, vault and lock tests --- .../browser/test/chrome-lifecycle.test.ts | 4 +- packages/browser/test/cli/remove.test.ts | 102 ++++++++++-------- .../browser/test/helpers/fake-secret-store.ts | 6 +- packages/browser/test/vault.test.ts | 5 +- 4 files changed, 64 insertions(+), 53 deletions(-) diff --git a/packages/browser/test/chrome-lifecycle.test.ts b/packages/browser/test/chrome-lifecycle.test.ts index 2f061bc6..d6fc70de 100644 --- a/packages/browser/test/chrome-lifecycle.test.ts +++ b/packages/browser/test/chrome-lifecycle.test.ts @@ -13,7 +13,7 @@ import { readHealth } from "../src/health.js"; import { createHost, serve } from "../src/host.js"; import { startedChromePid } from "../src/lifecycle.js"; import { readChallenges } from "../src/reputation.js"; -import { readRuntimeLock } from "../src/runtime-lock.js"; +import { readRuntimeLock, stopCommand } from "../src/runtime-lock.js"; import { writeIdentitySettings } from "../src/settings.js"; import { type TurnoTool, turnoZod } from "../src/tools.js"; import { upstream } from "../src/upstream.js"; @@ -300,7 +300,7 @@ describe.skipIf(reason !== undefined)(reason ? `real Chrome (skipped: ${reason}) expect(textOf(res)).toContain( `browser identity "locked" is in use by turno-browser-mcp (pid ${r.pid}, Chrome pid ${pid})`, ); - expect(textOf(res)).toContain(`kill ${r.pid}`); + expect(textOf(res)).toContain(stopCommand(r.pid)); expect(alive(pid), "the first Chrome is untouched").toBe(true); await r.client.close(); diff --git a/packages/browser/test/cli/remove.test.ts b/packages/browser/test/cli/remove.test.ts index adfe6d22..4c207af3 100644 --- a/packages/browser/test/cli/remove.test.ts +++ b/packages/browser/test/cli/remove.test.ts @@ -15,7 +15,7 @@ import { vaultPath } from "../../src/vault.js"; import { type FakeSecretStore, fakeSecretStore } from "../helpers/fake-secret-store.js"; import { type Sandbox, sandbox } from "../helpers/sandbox.js"; import { cli, fakeAgentCli, fakeIo, real } from "./helpers.js"; -import { fakeProgram, pathWith } from "../helpers/programs.js"; +import { fakeProgram, pathWith, slashes } from "../helpers/programs.js"; /** * `turno-browser remove`: everything an identity left, removed and checked. The secret store is @@ -134,8 +134,8 @@ describe("turno-browser remove", () => { failed: [], left: [], }); - const deleted = r.deleted.map( - (d: { kind: string; item?: string; path?: string; agent?: string }) => d.item ?? d.path ?? d.agent, + const deleted = r.deleted.map((d: { kind: string; item?: string; path?: string; agent?: string }) => + slashes(d.item ?? d.path ?? d.agent ?? ""), ); expect(deleted).toEqual( expect.arrayContaining([ @@ -180,7 +180,7 @@ describe("turno-browser remove", () => { ); const r = json(io); expect(r.complete).toBe(false); - expect(r.left).toEqual( + expect(r.left.map((l: { file?: string }) => ({ ...l, file: slashes(l.file ?? "") }))).toEqual( expect.arrayContaining([ expect.objectContaining({ kind: "mcp", @@ -234,50 +234,58 @@ describe("turno-browser remove", () => { expect(store.services()).toContain("turno-browser/vault/school/mail"); }); - it("stops the background server, the Chrome on the profile and the identity's servers first", async () => { - await school(); - const script = join(sb.home, "turno-browser-mcp"); - writeFileSync(script, "setInterval(() => {}, 1000);\n"); - const start = (args: string[], env: NodeJS.ProcessEnv = sb.env) => { - const child = spawn(process.execPath, [script, ...args], { stdio: "ignore", detached: true, env }); - children.push(child); - return child.pid!; - }; - const background = start(["--identity", "school", "--background"]); - mkdirSync(join(identityStateDir("school", sb.env), "background"), { recursive: true }); - writeFileSync( - backgroundStatePath("school", sb.env), - JSON.stringify({ v: 1, pid: background, identity: "school", version: "0", startedAt: "s", idleMs: 0 }), - ); - const stdio = start(["--identity", "school"]); - writeFileSync(runtimeLockPath("school", sb.env), JSON.stringify({ nodePid: stdio, holder: "mcp", startedAt: "s" })); - const chrome = start([`--user-data-dir=${identityDir("school", sb.env)}`]); - symlinkSync(`${hostname()}-${chrome}`, join(identityDir("school", sb.env), "SingletonLock")); - const idle = start(["--identity", "school"]); // an agent's server that never opened Chrome - const other = start(["--identity", "work"]); - // The same id under another HOME is another machine's identity as far as this one goes. - const elsewhere = start(["--identity", "school"], { ...sb.env, HOME: join(sb.home, "elsewhere") }); - // Each child is in the process table with its arguments before remove looks. - const pids = [background, stdio, chrome, idle, other, elsewhere]; - for (let i = 0; i < 100; i++) { - const table = readProcTable(); - if (pids.every((pid) => table?.get(pid)?.command.includes(script))) break; - await new Promise((r) => setTimeout(r, 20)); - } + // Its stand-ins are POSIX: a SingletonLock for Chrome, and servers told apart by their HOME, + // which Windows' process table does not show. + it.skipIf(process.platform === "win32")( + "stops the background server, the Chrome on the profile and the identity's servers first", + async () => { + await school(); + const script = join(sb.home, "turno-browser-mcp"); + writeFileSync(script, "setInterval(() => {}, 1000);\n"); + const start = (args: string[], env: NodeJS.ProcessEnv = sb.env) => { + const child = spawn(process.execPath, [script, ...args], { stdio: "ignore", detached: true, env }); + children.push(child); + return child.pid!; + }; + const background = start(["--identity", "school", "--background"]); + mkdirSync(join(identityStateDir("school", sb.env), "background"), { recursive: true }); + writeFileSync( + backgroundStatePath("school", sb.env), + JSON.stringify({ v: 1, pid: background, identity: "school", version: "0", startedAt: "s", idleMs: 0 }), + ); + const stdio = start(["--identity", "school"]); + writeFileSync( + runtimeLockPath("school", sb.env), + JSON.stringify({ nodePid: stdio, holder: "mcp", startedAt: "s" }), + ); + const chrome = start([`--user-data-dir=${identityDir("school", sb.env)}`]); + symlinkSync(`${hostname()}-${chrome}`, join(identityDir("school", sb.env), "SingletonLock")); + const idle = start(["--identity", "school"]); // an agent's server that never opened Chrome + const other = start(["--identity", "work"]); + // The same id under another HOME is another machine's identity as far as this one goes. + const elsewhere = start(["--identity", "school"], { ...sb.env, HOME: join(sb.home, "elsewhere") }); + // Each child is in the process table with its arguments before remove looks. + const pids = [background, stdio, chrome, idle, other, elsewhere]; + for (let i = 0; i < 100; i++) { + const table = readProcTable(); + if (pids.every((pid) => table?.get(pid)?.command.includes(script))) break; + await new Promise((r) => setTimeout(r, 20)); + } - const io = fakeIo(sb.env); - expect(await cli(api).run("remove", ["school", "--yes", "--json"], io)).toBe(0); - const r = json(io); - expect( - r.deleted - .filter((d: { kind: string }) => d.kind === "process") - .map((d: { pid: number }) => d.pid) - .sort(), - ).toEqual([background, stdio, chrome, idle].sort()); - for (const pid of [background, stdio, chrome, idle]) expect(pidAlive(pid)).toBe(false); - expect(pidAlive(other)).toBe(true); - expect(pidAlive(elsewhere)).toBe(true); - }); + const io = fakeIo(sb.env); + expect(await cli(api).run("remove", ["school", "--yes", "--json"], io)).toBe(0); + const r = json(io); + expect( + r.deleted + .filter((d: { kind: string }) => d.kind === "process") + .map((d: { pid: number }) => d.pid) + .sort(), + ).toEqual([background, stdio, chrome, idle].sort()); + for (const pid of [background, stdio, chrome, idle]) expect(pidAlive(pid)).toBe(false); + expect(pidAlive(other)).toBe(true); + expect(pidAlive(elsewhere)).toBe(true); + }, + ); it("keeps Chrome's own cookie key with keychain system, and reads the sites of a broken vault index", async () => { api.addIdentity("school", sb.env); diff --git a/packages/browser/test/helpers/fake-secret-store.ts b/packages/browser/test/helpers/fake-secret-store.ts index 6d87ae8e..6f4734d6 100644 --- a/packages/browser/test/helpers/fake-secret-store.ts +++ b/packages/browser/test/helpers/fake-secret-store.ts @@ -12,7 +12,7 @@ import { execFileSync } from "node:child_process"; import { createRequire } from "node:module"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; -import { dpapiDir } from "turno-core/secrets"; +import { dpapiDir, dpapiFileName } from "turno-core/secrets"; import type { Sandbox } from "./sandbox.js"; /** @@ -27,6 +27,8 @@ export interface FakeSecretStore { dir: string; read(service: string): string | undefined; write(service: string, value: string): void; + /** Deletes an item behind turno's back, as a person could in Keychain Access. */ + remove(service: string): void; services(): string[]; failWrites(on: boolean): void; } @@ -114,6 +116,7 @@ function windowsStore(sb: Sandbox): FakeSecretStore { dir, read: (s) => (JSON.parse(call("get", s)) as string | null) ?? undefined, write: (s, v) => void call("set", s, v), + remove: (s) => rmSync(join(dir, dpapiFileName(s))), services: () => existsSync(dir) ? readdirSync(dir) @@ -152,6 +155,7 @@ export function fakeSecretStore(sb: Sandbox): FakeSecretStore { dir, read: (s) => (existsSync(file(s)) ? readFileSync(file(s), "utf8") : undefined), write: (s, v) => writeFileSync(file(s), v), + remove: (s) => rmSync(file(s)), services: () => readdirSync(dir) .filter((f) => !f.startsWith(".")) diff --git a/packages/browser/test/vault.test.ts b/packages/browser/test/vault.test.ts index 2ad1afe5..91d06607 100644 --- a/packages/browser/test/vault.test.ts +++ b/packages/browser/test/vault.test.ts @@ -1,5 +1,4 @@ -import { readFileSync, rmSync } from "node:fs"; -import { join } from "node:path"; +import { readFileSync } from "node:fs"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { secretStore } from "turno-core/secrets"; import { addIdentity, removeIdentity } from "../src/identities.js"; @@ -81,7 +80,7 @@ describe("the credential vault", () => { ["github", true, false], ["mail", true, false], ]); - rmSync(join(fake.dir, encodeURIComponent(vaultItem("work", "mail")))); + fake.remove(vaultItem("work", "mail")); info = await vaultList("work", opts()); expect(info.sites.find((s) => s.site === "mail")?.stored).toBe(false); await expect(readCredential("work", "mail", opts())).rejects.toThrow(/missing from the secret store/); From 8e969039c6fa3714602e9cbf70e377ed31b782d4 Mon Sep 17 00:00:00 2001 From: William Frank Monroy Mamani Date: Sun, 22 Nov 2026 22:17:33 -0600 Subject: [PATCH 15/15] test(browser): let the guard ignore what Windows and Playwright cache under LOCALAPPDATA --- packages/browser/test/helpers/global-setup.ts | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/browser/test/helpers/global-setup.ts b/packages/browser/test/helpers/global-setup.ts index 23badd94..77ce90c5 100644 --- a/packages/browser/test/helpers/global-setup.ts +++ b/packages/browser/test/helpers/global-setup.ts @@ -26,13 +26,18 @@ const LIVE = /^(TURNO_|CLAUDE|CODEX_|CURSOR_|ANTHROPIC_|XDG_)/; /** * What may appear under the guard HOME on Windows: the folders the setup itself makes (above), - * and PowerShell's own caches, which every powershell.exe (the process table) writes under - * LOCALAPPDATA. + * and what Windows and Playwright keep under LOCALAPPDATA for any process, whatever turno does: + * PowerShell's caches (every powershell.exe, the process table's included), Windows' own + * caches, and Playwright's list of the browsers it serves (`ms-playwright\b`). */ const SETUP_DIRS = new Set(["AppData", join("AppData", "Local"), join("AppData", "Roaming")]); -const POWERSHELL = join("AppData", "Local", "Microsoft", "Windows", "PowerShell"); +const SYSTEM_DIRS = [ + join("AppData", "Local", "Microsoft", "Windows", "PowerShell"), + join("AppData", "Local", "Microsoft", "Windows", "Caches"), + join("AppData", "Local", "ms-playwright", "b"), +]; const allowed = (p: string) => - SETUP_DIRS.has(p) || POWERSHELL === p || POWERSHELL.startsWith(`${p}${sep}`) || p.startsWith(`${POWERSHELL}${sep}`); + SETUP_DIRS.has(p) || SYSTEM_DIRS.some((d) => d === p || d.startsWith(`${p}${sep}`) || p.startsWith(`${d}${sep}`)); /** Paths written under the guard HOME, relative to it. */ export function guardFindings(home: string): string[] {