From 1a63961cb8267907d9474d9a555a29eab8cdc856 Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 21 Nov 2026 05:27:37 +0900 Subject: [PATCH 1/7] fix(link): serve ocx link status over the local control socket on Windows (#8998) #8370 gave a hub whose public listener is not loopback a private AF_UNIX socket for ocx link status, but only on macOS and Linux. A Windows hub answered the CLI with 403 on every TCP listener. Windows has AF_UNIX sockets; what it lacks is a readable socket identity (lstat refuses the file with EACCES) and a mode-based private directory. - windowsTrustedPath proves the whole path: canonical spelling, every component a real directory with no reparse point, the run directory private-runtime-directory, the config home write-private and every ancestor trusted-ancestry. The runtime checks the path above the run directory before creating it, hardens it, and serves nothing unless the check passes; the CLI checks the same before sending the token. - A Windows socket entry is one readdir lists and lstat refuses with EACCES; a readable file at the public path is left alone. - Without inode identity, release unlinks only inside the claim mutex while the lease still names this runtime's token; orphan cleanup matches the exact .c.<8 hex> name, never the lease; a failed publication removes its private name before giving the lease up, or keeps the lease and retries when it cannot. structure/remote-link.md describes the Windows rules. --- .../040_windows_control_socket.md | 64 +++ .../test-layout/layout-server-inbound.json | 1 + src/cli/link-local-control.ts | 6 +- src/lib/local-control-socket.ts | 183 +++++++- src/server/index/local-control-listener.ts | 90 +++- structure/remote-link.md | 2 +- tests/fixtures/test-layout-expected.json | 2 +- .../local-control-socket-windows.test.ts | 391 ++++++++++++++++++ tests/server/local-control-socket.test.ts | 5 +- 9 files changed, 728 insertions(+), 16 deletions(-) create mode 100644 devlog/_plan/261121_fb2100_remote_link_auth/040_windows_control_socket.md create mode 100644 tests/server/local-control-socket-windows.test.ts diff --git a/devlog/_plan/261121_fb2100_remote_link_auth/040_windows_control_socket.md b/devlog/_plan/261121_fb2100_remote_link_auth/040_windows_control_socket.md new file mode 100644 index 00000000000..33f314062d9 --- /dev/null +++ b/devlog/_plan/261121_fb2100_remote_link_auth/040_windows_control_socket.md @@ -0,0 +1,64 @@ +# 040 #8998: `ocx link status` on a Windows hub with a non-loopback listener + +Branch `codex/fb2100-win-link-socket` from `origin/dev` 70c9e2134, second PR (roadmap unit 040). + +Problem: #8370 serves `GET /api/link/status` over a private AF_UNIX socket so the CLI's admin token has trusted +ingress on a hub whose public listener is not loopback. `localControlSocketSupported()` is false on win32, so a +Windows hub answers the CLI with `403` on every TCP listener. + +Measured on this Windows 11 host, Bun 1.3.14: + +| Behaviour | Result | +|---|---| +| `Bun.serve({ unix })` and `fetch(..., { unix })` with a path under 103 bytes | work (200) | +| `lstat` of the socket file and of a hard link to it | `EACCES` (a plain file in the same directory stats fine) | +| `existsSync` on the socket | `false`; `readdirSync` lists it | +| `linkSync` to the socket, then fetch through the link | works | +| unlink of either name while the server listens; rebind after unlink | works | +| `server.stop()` | unlinks its bound name once the stop completes; a killed process leaves it behind | +| `hardenSecretDir` + `verifyWindowsEntriesAcl(private-runtime-directory)` on the run directory | 410 ms + 273 ms once; a repeat harden is memoized (0 ms) | + +Design: keep #8370's protocol (private `.c.`, public hard link `control-.sock`, per-port lease under +the claim mutex) and replace only the parts that read POSIX identity: + +- `src/lib/local-control-socket.ts`: supported on win32. `isPrivateSocketDir` on win32 = a real directory (no + symlink or junction) whose DACL passes the `private-runtime-directory` policy. A socket entry on win32 = listed by + `readdir` and `lstat` refused with `EACCES` (an AF_UNIX reparse point); a readable regular file is not ours. + `isLocalControlPrivateSocketName(port, name)` matches exactly `.c.<8 hex>`, so the lease and claim files are + never cleanup candidates. +- `src/server/index/local-control-listener.ts`: `preparePrivateDir` on win32 creates the directory, refuses a + symlink/junction or non-directory, hardens it with `hardenSecretDir` (as `src/client/lifecycle-lock.ts` does for its + runtime directory) and refuses it unless the ACL check then passes. No chmod of the socket on win32. Publication and + orphan sweep use the win32 socket test. Ownership at release on win32 is "the lease still names this token" checked + inside the claim mutex (a successor can publish only after it holds the lease), instead of inode identity; + `abort()` keeps Bun's own unlink, as on POSIX. +- `src/cli/link-local-control.ts`: unchanged flow; `usableLocalControlSocket` now answers on win32 after the same + directory ACL check, so the token goes to the socket only in a private directory. +- Trusted path (audit round 1, blocker 1): one check, `windowsTrustedRunDir(dir)`, used by the server before it binds + and by the CLI before it sends the token. The canonical path (`realpathSync.native`) must spell the same path, so no + junction, symlink or other reparse point sits anywhere on it; then one ACL batch must pass: every ancestor of the + config home under `trusted-ancestry` (owned by the user or a kernel-equivalent principal, nobody else holding write, + delete or DACL rights), the config home under `write-private`, and the run directory under + `private-runtime-directory`. Once no other principal can write anywhere on the path, the path verified before + connecting cannot be swapped before the connect. Same-user processes and administrators are inside the trust + boundary, as for every other file in the config home. Any failure (unexpected error, timeout, unverifiable path) + answers "not trusted": the server serves no socket and the CLI keeps its TCP request. +- Failed publication (audit round 1, blocker 2): `acquireLease` takes a rollback that runs inside the claim mutex + before the lease is removed. On win32 it stops the bound listener and unlinks the private name this attempt bound; + the public link is the last, atomic step of publication, so a failed attempt never published it and never touches it. +- A win32 cleanup candidate must be listed, match the exact private-name format and refuse `lstat` with `EACCES`; + any other error leaves the entry alone, and an unlink error leaves it too. +- The start stays synchronous: the one-time cost (about 0.7 s) applies only to a Windows hub whose public listener is + not loopback, and an async start would add a new in-flight state to stop and abort. + +Tests: `tests/server/local-control-socket-windows.test.ts` (win32 only: TCP 403 vs socket 200, other routes 404, +`ocx link status` over the socket, files and lease removed on stop, a crashed predecessor's socket names replaced while a +decoy and the lease format survive, a loosened directory refused by the client, a loose pre-existing directory hardened, +a config home under a parent other users can write refused by server and client while the token stays protected, a +failed publication that leaves no private name and no lease) and platform-neutral name-matcher cases. Registered in the +test layout. + +Verification: that file and `tests/server/local-control-socket.test.ts` on Windows, `bun run typecheck`, +`bun run test:changed`, `bun run structure:check`, and a real `ocx start` with `hostname: 0.0.0.0` plus +`ocx link status --json` on this host. Security review by gpt-6.1-terra. + diff --git a/scripts/test-layout/layout-server-inbound.json b/scripts/test-layout/layout-server-inbound.json index 55e5756d102..d73f4debab6 100644 --- a/scripts/test-layout/layout-server-inbound.json +++ b/scripts/test-layout/layout-server-inbound.json @@ -6,6 +6,7 @@ "claude-translated-hosted-advisor-choice.test.ts": "claude-integration", "management-provider-forward-advisor-tool.test.ts": "server", "local-control-socket.test.ts": "server", + "local-control-socket-windows.test.ts": "server", "config-concurrent-inbound-body.test.ts": "config", "inbound-body-admission.test.ts": "server", "inbound-body-budget.test.ts": "server", diff --git a/src/cli/link-local-control.ts b/src/cli/link-local-control.ts index 20a44700648..ca1925785b5 100644 --- a/src/cli/link-local-control.ts +++ b/src/cli/link-local-control.ts @@ -9,8 +9,10 @@ export interface LocalControlDeps { /** * Send one `ocx link status` read over the runtime's local control socket when it has one (#8184). * A hub whose public listener is not loopback refuses the admin token on its TCP listeners, and the - * socket is the ingress that may accept it. A runtime without the socket (Windows, a loopback bind, - * an older version), or one whose socket cannot be reached, is asked over TCP exactly as before. + * socket is the ingress that may accept it. Windows has it too (#8998), once its directory and the + * whole path to it pass the ACL and reparse checks in src/lib/local-control-socket.ts. A runtime + * without the socket (a loopback bind, an older version, a path that is not trusted), or one whose + * socket cannot be reached, is asked over TCP exactly as before. */ export async function viaLocalControlSocket( baseUrl: string, diff --git a/src/lib/local-control-socket.ts b/src/lib/local-control-socket.ts index e9492ef9cfa..8c65cc8d662 100644 --- a/src/lib/local-control-socket.ts +++ b/src/lib/local-control-socket.ts @@ -1,6 +1,8 @@ -import { lstatSync } from "node:fs"; -import { join } from "node:path"; +import { lstatSync, readdirSync, realpathSync, unlinkSync } from "node:fs"; +import { basename, dirname, join, resolve } from "node:path"; import { getConfigDir } from "../config/paths"; +import { resolveTrustedWindowsPowerShellExe } from "./windows-elevation"; +import { verifyWindowsEntriesAcl, WINDOWS_OWNER_ACL_TIMEOUT_MS, type WindowsAclEntry } from "./windows-owner-acl"; /** * The local control socket (#8184): a Unix-domain socket in a private directory under the @@ -8,6 +10,12 @@ import { getConfigDir } from "../config/paths"; * (Tailscale Serve on the hub management listener, a reverse proxy) can deliver a request to it, * so a request that arrives on it came from this machine through the filesystem. That is the * property the TCP loopback listeners cannot offer once a relay targets them. + * + * Windows (#8998) has AF_UNIX sockets too, with two differences this module absorbs: an AF_UNIX + * file is a reparse point that lstat refuses with EACCES, so neither its type nor its owner can be + * read; and the private directory is a DACL, not a mode. The directory therefore has to be proven + * private by its ACL, and the whole path to it by trusted ancestry with no reparse point on it, so + * that no other account can create, replace or redirect anything the CLI sends the token to. */ /** sun_path is 104 bytes on macOS and 108 on Linux, both including the terminating NUL. */ @@ -23,7 +31,7 @@ export function localControlSocketPathFits(path: string): boolean { } export function localControlSocketSupported(): boolean { - return process.platform !== "win32" && typeof process.getuid === "function"; + return process.platform === "win32" || typeof process.getuid === "function"; } export function localControlSocketDir(configDir: string = getConfigDir()): string { @@ -42,6 +50,17 @@ export function localControlSocketPath(port: number, configDir?: string): string * 16 bytes, `control-65535.sock` is 18), so a home that fits the public path fits this one too. */ const PRIVATE_SOCKET_TOKEN_CHARS = 8; +const PRIVATE_SOCKET_NAME = /^\.c([1-9]\d{0,4})\.[0-9a-f]{8}$/; + +/** + * Is this directory entry one runtime's private socket for this port? Exactly that name shape and + * nothing else, so the lease, its claim files or any other file in the directory are never cleanup + * candidates. + */ +export function isLocalControlPrivateSocketName(port: number, name: string): boolean { + const match = PRIVATE_SOCKET_NAME.exec(name); + return match !== null && match[1] === String(port); +} /** * The address Bun itself binds for one runtime. It is instance-specific, so a shutdown can only @@ -60,8 +79,159 @@ export function localControlLeasePath(port: number, configDir?: string): string return join(localControlSocketDir(configDir), `.c${port}.lease`); } -/** A real directory, owned by this user, that no other user can enter or list. */ +/** + * On Windows, is this an AF_UNIX socket entry? The directory lists it and lstat refuses it with + * EACCES, which is how an AF_UNIX reparse point reads; a file lstat can read is not one. This is an + * observation, not proof of the type: it is only trusted inside a directory proven private, where + * nothing but this account and the system can create entries. + */ +export function windowsSocketEntry(path: string): boolean { + return windowsSocketEntryState(path) === "socket"; +} + +/** + * The same observation with the doubt kept: "absent" only when the directory was read and does not + * list the name (or is itself gone), "other" for an entry lstat can read, "socket" as above, and + * "unknown" for any failure in between. Cleanup that must prove a name gone treats "unknown" as + * still present. + */ +export type WindowsSocketEntryState = "absent" | "socket" | "other" | "unknown"; + +export function windowsSocketEntryState(path: string): WindowsSocketEntryState { + let listed: boolean; + try { + listed = readdirSync(dirname(path)).includes(basename(path)); + } catch (error) { + return (error as { code?: unknown } | null)?.code === "ENOENT" ? "absent" : "unknown"; + } + if (!listed) return "absent"; + try { + lstatSync(path); + return "other"; + } catch (error) { + const code = (error as { code?: unknown } | null)?.code; + return code === "EACCES" ? "socket" : code === "ENOENT" ? "absent" : "unknown"; + } +} + +/** + * Remove a socket name this runtime published, or throw. A name proven absent is done, and so is an + * entry lstat can read: it is verifiably not a socket, so not one this runtime could still serve. A + * socket is unlinked and must then read absent. Anything that cannot be proven (an unreadable + * directory, an unexpected error, a failed unlink) throws, so the caller keeps its lease and retries + * instead of handing the port to a successor while the name may still exist. + */ +export function removeWindowsPrivateSocket( + path: string, + observe: (path: string) => WindowsSocketEntryState = windowsSocketEntryState, + unlink: (path: string) => void = unlinkSync, +): void { + const state = observe(path); + if (state === "absent" || state === "other") return; + if (state !== "socket") throw new Error("socket name could not be proven removed"); + unlink(path); + if (observe(path) !== "absent") throw new Error("socket name is still present after unlink"); +} + +/** + * One directory, as it is: the canonical path spells the same, lstat sees a directory and no link, + * and Windows reports no reparse point on it. Checked before anything changes the directory, so a + * pre-existing junction or other reparse point is refused before an ACL operation could follow it. + */ +export function windowsPlainDirectory(dir: string): boolean { + try { + const absolute = resolve(dir); + if (realpathSync.native(absolute).toLowerCase() !== absolute.toLowerCase()) return false; + const stat = lstatSync(absolute); + return stat.isDirectory() && !stat.isSymbolicLink() && windowsNoReparsePoint([absolute]); + } catch { + return false; + } +} + +/** The config home's ancestors, nearest first, up to the volume root. */ +function ancestorsOf(path: string): string[] { + const ancestors: string[] = []; + for (let current = dirname(path); ; current = dirname(current)) { + ancestors.push(current); + if (dirname(current) === current) return ancestors; + } +} + +/** + * The ACL entries the Windows path has to pass: the run directory private, the config home + * writable by this account alone, and every ancestor owned by this account or a kernel-equivalent + * principal with nobody else able to change it (src/lib/windows-owner-acl.ts). + */ +function windowsTrustEntries(runDir: string, includeRunDir: boolean): WindowsAclEntry[] { + const config = dirname(runDir); + return [ + ...(includeRunDir ? [{ path: runDir, directory: true, policy: "private-runtime-directory" as const }] : []), + { path: config, directory: true, policy: "write-private" as const }, + ...ancestorsOf(config).map(path => ({ path, directory: true, policy: "trusted-ancestry" as const })), + ]; +} + +// Constant script; the paths arrive as environment data and never become PowerShell source. +const REPARSE_SCRIPT = String.raw` +$ErrorActionPreference='Stop' +try { + $countText=[Environment]::GetEnvironmentVariable('OCX_LC_COUNT') + if ($countText -notmatch '^[1-9][0-9]?$') { exit 3 } + for ($i=0; $i -lt [int]$countText; $i++) { + $path=[Environment]::GetEnvironmentVariable(('OCX_LC_PATH_{0}' -f $i)) + if ([string]::IsNullOrEmpty($path)) { exit 3 } + $attributes=[System.IO.File]::GetAttributes($path) + if (($attributes -band [System.IO.FileAttributes]::Directory) -eq 0) { exit 1 } + if (($attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) { exit 1 } + } + exit 0 +} catch { exit 3 } +`; +const ENCODED_REPARSE_SCRIPT = Buffer.from(REPARSE_SCRIPT, "utf16le").toString("base64"); + +/** Every path a real directory without a reparse point, as Windows itself reports the attributes. */ +function windowsNoReparsePoint(paths: readonly string[]): boolean { + if (paths.length === 0 || paths.length > 99) return false; + const env: Record = { ...process.env, OCX_LC_COUNT: String(paths.length) }; + paths.forEach((path, index) => { env[`OCX_LC_PATH_${index}`] = path; }); + try { + const result = Bun.spawnSync([ + resolveTrustedWindowsPowerShellExe(), "-NoLogo", "-NoProfile", "-NonInteractive", + "-ExecutionPolicy", "Bypass", "-EncodedCommand", ENCODED_REPARSE_SCRIPT, + ], { env, stdin: "ignore", stdout: "ignore", stderr: "ignore", timeout: WINDOWS_OWNER_ACL_TIMEOUT_MS, windowsHide: true }); + return result.success && !result.exitedDueToTimeout && result.exitCode === 0; + } catch { + return false; + } +} + +/** + * The Windows path rule (#8998). The canonical path spells the same path and every component is + * a real directory, so no junction, symlink or other reparse point redirects it; and the ACLs + * leave no other account able to create, replace or rename anything on it, so the path checked + * now is the path a later connect uses. Any doubt, error or timeout answers false. + */ +export function windowsTrustedPath(runDir: string, includeRunDir = true): boolean { + try { + const absolute = resolve(runDir); + const entries = windowsTrustEntries(absolute, includeRunDir); + const checked = includeRunDir ? absolute : dirname(absolute); + if (realpathSync.native(checked).toLowerCase() !== checked.toLowerCase()) return false; + for (const entry of entries) { + const stat = lstatSync(entry.path); + if (!stat.isDirectory() || stat.isSymbolicLink()) return false; + } + return windowsNoReparsePoint(entries.map(entry => entry.path)) + && verifyWindowsEntriesAcl(entries, WINDOWS_OWNER_ACL_TIMEOUT_MS); + } catch { + return false; + } +} + +/** A real directory, owned by this user, that no other user can enter or list (Windows: see above). */ export function isPrivateSocketDir(dir: string): boolean { + if (process.platform === "win32") return windowsTrustedPath(dir); try { const stat = lstatSync(dir); return stat.isDirectory() && !stat.isSymbolicLink() @@ -78,6 +248,11 @@ export function isPrivateSocketDir(dir: string): boolean { export function usableLocalControlSocket(port: number, configDir?: string): string | null { if (!localControlSocketSupported() || !Number.isInteger(port) || port <= 0 || port > 65535) return null; const path = localControlSocketPath(port, configDir); + if (process.platform === "win32") { + // The cheap observation first: no listed socket means no PowerShell at all. + if (!localControlSocketPathFits(path) || !windowsSocketEntry(path)) return null; + return isPrivateSocketDir(localControlSocketDir(configDir)) && windowsSocketEntry(path) ? path : null; + } if (!localControlSocketPathFits(path) || !isPrivateSocketDir(localControlSocketDir(configDir))) return null; try { const stat = lstatSync(path); diff --git a/src/server/index/local-control-listener.ts b/src/server/index/local-control-listener.ts index 056f1b277f4..fe60675dd6a 100644 --- a/src/server/index/local-control-listener.ts +++ b/src/server/index/local-control-listener.ts @@ -20,6 +20,7 @@ import { getConfigDir } from "../../config/paths"; import { ConfigOwnershipLockError, registerOwnedConfigPath } from "../../lib/config-ownership"; import { assertNotRealHomeUnderTest } from "../../lib/test-home-guard"; import { + isLocalControlPrivateSocketName, isPrivateSocketDir, localControlLeasePath, localControlPrivateSocketPath, @@ -27,9 +28,16 @@ import { localControlSocketPath, localControlSocketPathFits, localControlSocketSupported, + removeWindowsPrivateSocket, + windowsPlainDirectory, + windowsSocketEntry, + windowsTrustedPath, } from "../../lib/local-control-socket"; +import { hardenSecretDir } from "../../lib/windows-secret-acl"; import type { OcxConfig } from "../../types"; +const WINDOWS = process.platform === "win32"; + /** * The one request the local control socket serves (#8184). `ocx link status` needs admin-token * authority on trusted loopback ingress, which a hub whose public listener is not loopback cannot @@ -68,6 +76,16 @@ export interface LocalControlListener { function preparePrivateDir(dir: string): void { assertNotRealHomeUnderTest(dirname(dir)); + if (WINDOWS) { + // Trust the path above the run directory before creating anything in it (#8998). + if (!windowsTrustedPath(dir, false)) throw new Error("socket directory path is not trusted"); + try { mkdirSync(dir); } catch (error) { if (!isCode(error, "EEXIST")) throw error; } + // Refuse a pre-existing junction or other reparse point before any ACL operation can follow it. + if (!windowsPlainDirectory(dir)) throw new Error("socket directory is not a plain directory"); + hardenSecretDir(dir, { required: true, verifyExistingRuntimeDirectory: true }); + if (!isPrivateSocketDir(dir)) throw new Error("socket directory could not be made private"); + return; + } mkdirSync(dir, { recursive: true, mode: 0o700 }); const stat = lstatSync(dir); if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid!()) { @@ -80,6 +98,14 @@ function preparePrivateDir(dir: string): void { /** Inode identity as the kernel reports it. Bigint keeps every bit of a Windows file ID. */ interface FileIdentity { dev: bigint; ino: bigint } +/** + * Windows cannot read an AF_UNIX file's identity (lstat refuses it), so a socket this runtime + * published there carries this marker instead. What makes such a path this runtime's is the lease: + * every unlink of a marked path happens inside the claim mutex while the lease still names this + * runtime's token, and a successor can publish only after it holds the lease. + */ +const WINDOWS_SOCKET_IDENTITY: FileIdentity = Object.freeze({ dev: -1n, ino: -1n }); + /** * The per-port ownership record. `host` and `processStart` come from the shared owner evidence * (`src/codex/prompt-lock-owner.ts`), so a record from another machine, or from a pid that has @@ -97,7 +123,7 @@ type LeaseDecision = | { kind: "held" } | { kind: "unsafe" } | { kind: "contended" } - | { kind: "failed"; error: unknown }; + | { kind: "failed"; error: unknown; retained?: true }; const PUBLISH_ATTEMPTS = 4; /** `withLockClaim` is a try-lock; a contender retries a bounded number of times and then refuses. */ @@ -148,6 +174,7 @@ function registerRunDirectory(root: string, dir: string): void { } function identityOf(path: string): FileIdentity | null { + if (WINDOWS) return windowsSocketEntry(path) ? WINDOWS_SOCKET_IDENTITY : null; try { const stat = lstatSync(path, { bigint: true }); return { dev: stat.dev, ino: stat.ino }; @@ -157,6 +184,7 @@ function identityOf(path: string): FileIdentity | null { } function sameIdentity(path: string, identity: FileIdentity): boolean { + if (identity === WINDOWS_SOCKET_IDENTITY) return windowsSocketEntry(path); const current = identityOf(path); return current !== null && current.dev === identity.dev && current.ino === identity.ino; } @@ -208,11 +236,15 @@ function removeOrphanPrivateSockets(port: number, configDir: string | undefined) const dir = localControlSocketDir(configDir); let entries: string[]; try { entries = readdirSync(dir); } catch { return; } - const prefix = `.c${port}.`; for (const name of entries) { - if (!name.startsWith(prefix)) continue; + // The exact private-socket name, never a prefix: the lease shares the prefix. + if (!isLocalControlPrivateSocketName(port, name)) continue; const candidate = join(dir, name); try { + if (WINDOWS) { + if (windowsSocketEntry(candidate)) unlinkSync(candidate); + continue; + } const stat = lstatSync(candidate); if (stat.isSocket() && stat.uid === process.getuid!()) unlinkSync(candidate); } catch { /* raced with another cleanup */ } @@ -233,6 +265,13 @@ function publishPublicLink(target: string, privateTarget: string): void { if (!isCode(error, "EEXIST")) throw error; } let existing: BigIntStats; + if (WINDOWS) { + // A socket left there can only be a crashed predecessor's: this runtime holds the lease and + // the directory is private. Anything lstat can read is not a socket and is left alone. + if (!windowsSocketEntry(target)) throw new Error("socket path is occupied"); + unlinkSync(target); + continue; + } try { existing = lstatSync(target, { bigint: true }); } catch (error) { @@ -251,7 +290,7 @@ function publishPublicLink(target: string, privateTarget: string): void { * rather than a recheck: no other runtime can be between its own read and its own write, so a * record judged stale cannot be replaced by a live one before this runtime publishes. */ -function acquireLease(leasePath: string, token: string, publish: () => void): LeaseDecision { +function acquireLease(leasePath: string, token: string, publish: () => void, rollback: () => void = () => {}): LeaseDecision { for (let attempt = 0; attempt < LEASE_LOCK_ATTEMPTS; attempt += 1) { const outcome = withLockClaim(leasePath, token, ownerDefaults, (): LeaseDecision => { const current = readLease(leasePath); @@ -265,6 +304,9 @@ function acquireLease(leasePath: string, token: string, publish: () => void): Le try { publish(); } catch (error) { + // Undo what this attempt bound while it still holds the lease. A rollback that fails keeps + // the lease, so no successor publishes over a name this attempt may still own. + try { rollback(); } catch { return { kind: "failed", error, retained: true }; } removeOwnedLease(leasePath, token); return { kind: "failed", error }; } @@ -317,6 +359,19 @@ function releaseFailure(outcome: Exclude): function releaseOwnedSocket(state: OwnedSocket): ReleaseOutcome { try { const outcome = withLockClaim(state.leasePath, state.token, ownerDefaults, () => { + if (WINDOWS) { + // Without inode identity, the lease is the proof: unlink only while it still names us, and + // keep the lease (the release throws) unless both names are proven gone. + const current = readLease(state.leasePath); + // An unreadable record proves nothing about who owns the names: fail, keep the retry state. + if (current.kind === "unsafe") throw new Error("the control socket ownership record could not be read"); + // Absent, or a confirmed successor's token: nothing here is this runtime's any more. + if (current.kind !== "record" || current.lease.token !== state.token) return; + if (state.publicPath) removeWindowsPrivateSocket(state.publicPath); + if (state.privatePath) removeWindowsPrivateSocket(state.privatePath); + removeOwnedLease(state.leasePath, state.token); + return; + } if (state.publicPath && state.identity && sameIdentity(state.publicPath, state.identity)) unlinkSync(state.publicPath); if (state.privatePath && state.identity && sameIdentity(state.privatePath, state.identity)) unlinkSync(state.privatePath); removeOwnedLease(state.leasePath, state.token); @@ -424,15 +479,33 @@ export function createLocalControlListener(): LocalControlListener { }, }); // The private directory is the access boundary; the socket mode is a second fence. - chmodSync(privateTarget, 0o600); + // Windows has no mode to set: its boundary is the directory's verified ACL. + if (!WINDOWS) chmodSync(privateTarget, 0o600); const socketIdentity = identityOf(privateTarget); if (!socketIdentity) throw new Error("socket identity unavailable"); publishPublicLink(target, privateTarget); published = socketIdentity; }; + // Bun unlinks its bound name only when its stop completes, after this attempt gave the lease + // up. On Windows, where no inode identity guards a later cleanup, a failed publication removes + // the name itself, inside the claim mutex and before the lease goes. POSIX keeps Bun's cleanup. + const rollback = (): void => { + if (!WINDOWS) return; + // The name is removed here, not by the stop: unlinking a listening AF_UNIX name works on + // Windows, and the stop only completes after this attempt gave the lease up. A stop that + // fails or completes late leaves a listener with no name: a nameless AF_UNIX listener + // accepts no new connection, and a successor binds its own per-token name, so neither + // can collide with it. The failure is reported. + if (bound) { + void (bound as Server).stop(true).catch(error => { + console.warn(`[local-control] a failed publication's listener did not stop: ${messageOf(error)}`); + }); + } + removeWindowsPrivateSocket(privateTarget); + }; let decision: LeaseDecision; try { - decision = acquireLease(leaseFile, token, publish); + decision = acquireLease(leaseFile, token, publish, rollback); } catch (error) { if (bound) void (bound as Server).stop(true).catch(() => {}); console.warn(hardLinkUnsupported(error) ? HARD_LINK_WARNING : `[local-control] socket unavailable: ${messageOf(error)}`); @@ -440,6 +513,11 @@ export function createLocalControlListener(): LocalControlListener { } if (decision.kind === "failed") { if (bound) void (bound as Server).stop(true).catch(() => {}); + if (decision.retained) { + // The rollback could not remove what this attempt bound; keep the port owned and let the + // next stop() or start() finish the release, exactly as a release that failed would. + pendingRelease = { leasePath: leaseFile, token, publicPath: null, privatePath: privateTarget, identity: WINDOWS_SOCKET_IDENTITY }; + } // Publishing is where a hard-link-less filesystem actually fails, and that error is // returned rather than thrown, so this branch is the one that has to classify it. console.warn(hardLinkUnsupported(decision.error) ? HARD_LINK_WARNING : `[local-control] socket unavailable: ${messageOf(decision.error)}`); diff --git a/structure/remote-link.md b/structure/remote-link.md index f56ef4ac035..7b71d815c47 100644 --- a/structure/remote-link.md +++ b/structure/remote-link.md @@ -81,7 +81,7 @@ The **Child automation** panel reads `GET /api/link/children/policy` and writes The dashboard link routes (`GET /api/link/status`, `GET /api/link/diagnostics`, `GET /api/link/candidates`, `POST /api/link/probe`, `POST /api/link/confirm-host`, `POST /api/link/apply`, `POST /api/link/{id}/reconnect`, `DELETE /api/link/{id}`, `POST /api/link/children/operations` and `GET /api/link/children/jobs/{jobId}`) admit a paired GUI session, or, on a standalone runtime only, the current loopback-issued GUI session that reached the public listener bound to a loopback hostname. `POST /api/link/join` is stricter and requires the paired session because it durably redirects this machine's client traffic. The hub-link, hub-management and claude-intercept ingresses are never trusted loopback ingress, a stale session is refused, and a hub keeps the paired-only rule. The Tailscale identity refusal runs before either check. A loopback session is minted by the loopback dashboard bootstrap without a credential, so it proves possession, not user presence: any local process can fetch the bootstrap and replay its token and CSRF value, which is why it cannot authorize joining and why `src/client/machine-listener.ts` keeps durable machine changes on the connected listener away from that session. Caller-supplied explicit routes follow the stricter [explicit-route authority check](#explicit-route). Other link operations accept this casual-path trade, the same as `POST /api/github/star` in `src/server/management/sidebar-routes.ts`; it is not a secret-backed boundary like an operator-created pairing grant or the admin token. -The admin-token link routes require trusted loopback ingress. A runtime whose public listener is not bound to loopback has no TCP listener that qualifies, because the hub management listener is relayed by Tailscale Serve and must never confer that trust (#6913). `src/server/index/local-control-listener.ts` therefore opens a Unix socket at `/run/control-.sock` (`src/lib/local-control-socket.ts`) on macOS and Linux when the public bind is not loopback. Its ingress is `local-control`, the only non-TCP ingress, and `trustedLoopbackForIngress` treats it as trusted. The boundary is the filesystem: the directory is created or tightened to `0700`, must be a real directory owned by this user, and the socket is `0600`; a TCP relay or a forged header cannot produce the ingress, which is derived from the Bun server object. Before dispatch the listener admits only `GET /api/link/status` and answers 404 for anything else, and the request still needs the admin token. Two runtimes can share a home and a public port, so the public path is not the address Bun binds: it is a hard link to an instance-specific socket, and a per-port lease records the owner's host, pid and process start time from the shared owner evidence in `src/codex/prompt-lock-owner.ts`. Reading that record, deciding it is stale, and publishing the new one all happen inside the claim mutex in `src/codex/prompt-lock-claim.ts`, so a record judged dead cannot be replaced by a live one before this runtime publishes. A live owner is never displaced — a second runtime refuses the socket and leaves it serving. A record from another machine, or one that cannot be parsed, is refused rather than treated as absent. A lease whose process is provably gone is a crashed predecessor, so its dead public link and private socket are replaced; any other file at the path is left alone and no socket is served. The run directory is registered with config ownership, so uninstall removes it. A path longer than `sun_path` in bytes is refused before anything is created, because a length in code units admits a non-ASCII home the kernel cannot bind. On shutdown the runtime gives the record up first, before it awaits its own socket teardown and before the other optional listeners shut down, so a successor that starts while that shutdown is still running is not blocked by a departing incumbent; it removes the public link only when that link is still the inode it published, because Bun's own stop unlinks the path it was given. A release that cannot take the claim mutex is retried, and if it still cannot run it is reported and retained on the listener, so the next stop or start finishes it instead of leaving a live lease nobody serves. `src/cli/link-local-control.ts` sends `ocx link status` there when the directory is still private and the socket is this user's, falls back to TCP only on a transport failure, and leaves an explicit base URL untouched. Coverage: `tests/server/local-control-socket.test.ts`. +The admin-token link routes require trusted loopback ingress. A runtime whose public listener is not bound to loopback has no TCP listener that qualifies, because the hub management listener is relayed by Tailscale Serve and must never confer that trust (#6913). `src/server/index/local-control-listener.ts` therefore opens a Unix socket at `/run/control-.sock` (`src/lib/local-control-socket.ts`) on macOS, Linux and Windows when the public bind is not loopback. Its ingress is `local-control`, the only non-TCP ingress, and `trustedLoopbackForIngress` treats it as trusted. The boundary is the filesystem: the directory is created or tightened to `0700`, must be a real directory owned by this user, and the socket is `0600`; a TCP relay or a forged header cannot produce the ingress, which is derived from the Bun server object. Before dispatch the listener admits only `GET /api/link/status` and answers 404 for anything else, and the request still needs the admin token. Two runtimes can share a home and a public port, so the public path is not the address Bun binds: it is a hard link to an instance-specific socket, and a per-port lease records the owner's host, pid and process start time from the shared owner evidence in `src/codex/prompt-lock-owner.ts`. Reading that record, deciding it is stale, and publishing the new one all happen inside the claim mutex in `src/codex/prompt-lock-claim.ts`, so a record judged dead cannot be replaced by a live one before this runtime publishes. A live owner is never displaced — a second runtime refuses the socket and leaves it serving. A record from another machine, or one that cannot be parsed, is refused rather than treated as absent. A lease whose process is provably gone is a crashed predecessor, so its dead public link and private socket are replaced; any other file at the path is left alone and no socket is served. The run directory is registered with config ownership, so uninstall removes it. A path longer than `sun_path` in bytes is refused before anything is created, because a length in code units admits a non-ASCII home the kernel cannot bind. On shutdown the runtime gives the record up first, before it awaits its own socket teardown and before the other optional listeners shut down, so a successor that starts while that shutdown is still running is not blocked by a departing incumbent; it removes the public link only when that link is still the inode it published, because Bun's own stop unlinks the path it was given. A release that cannot take the claim mutex is retried, and if it still cannot run it is reported and retained on the listener, so the next stop or start finishes it instead of leaving a live lease nobody serves. `src/cli/link-local-control.ts` sends `ocx link status` there when the directory is still private and the socket is this user's, falls back to TCP only on a transport failure, and leaves an explicit base URL untouched. Windows has the socket too (#8998). There lstat refuses an AF_UNIX file with `EACCES`, so neither its type nor its owner can be read, and the directory boundary is a DACL. `windowsTrustedPath` therefore proves the path instead: the canonical path spells the same, every component is a real directory with no reparse point (lstat and the file attributes both checked), the run directory passes the `private-runtime-directory` ACL policy, the config home `write-private` and every ancestor `trusted-ancestry` (`src/lib/windows-owner-acl.ts`). The runtime checks the path above the run directory before it creates anything, hardens the run directory with `hardenSecretDir`, and serves no socket unless the whole check then passes; the CLI runs the same check before it sends the token and otherwise keeps TCP. No other account can change anything on such a path, so the path checked is the path connected. A Windows socket entry is one the directory lists and lstat refuses with `EACCES`; a file lstat can read is never treated as a socket. Without inode identity, a release unlinks the public link and the private name only inside the claim mutex while the lease still names this runtime's token, orphan cleanup matches the exact `.c.<8 hex>` name (never the lease), and a publication that fails removes the private name it bound before the lease goes, or keeps the lease and retries the release when it cannot. Same-user processes and administrators are inside the trust boundary, as for every other file in the config home. Coverage: `tests/server/local-control-socket.test.ts`, `tests/server/local-control-socket-windows.test.ts` (Windows hub cases; `OCX_TEST_WINDOWS_SOCKET_ROOT` names a trusted root where the default temp directory is shared). A successful join restarts this proxy (a 503 drain of up to a minute while running turns finish, then a closed listener) into the client runtime on the configured port. `GET /api/link/status` tells a GUI-session caller whether it may join: the response gains `joinAvailable`, true only for a paired dashboard session on a standalone runtime whose live port is its configured port, and `joinDenied`, which is `null` when allowed or the first failed gate (`pairing_required`, `standalone_required`, then `join_port_mismatch`). On a Child whose durable connection diverges from its startup snapshot, link and machine status instead return `503 client_state_changed`, as does readiness; this reports the divergence without stopping or reconstructing the relay. An admin-token caller gets the exact K16 document without either field, because `ocx link status` validates it key by key. The dashboard reads an absent availability field as false and an absent or unknown denial as generic unavailability; while unavailable the Child role card cannot be selected by pointer or keyboard. A pairing refusal says to pair this machine first and offers code entry only on the existing same-origin literal-loopback transport. A port refusal instead asks the operator to restart on the configured port; neither status reads nor displaying this guidance mint a grant or change pairing, keys, routing, or runtime state. Before **Connect as Child** the confirmation panel says that the restart briefly interrupts Codex and that Codex keeps its local address. The dashboard reads the standalone's pid from same-origin `/healthz`, sends the join, then reads `/healthz` once a second, skipping status polls meanwhile, and reloads only when it reports `role: "client"` under another pid, so the reloaded document carries the client role and a fresh session. It never gives up by itself: past the server's own handoff budget (60 s drain plus 70 s replacement readiness, plus a margin: 145 seconds) it says the restart is slow and keeps reading `/healthz` every 5 seconds until the Child answers or the page is left. diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 12f1a3dd0b4..502d9aeaf54 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1118,7 +1118,7 @@ "logs-model-tier-confirmation.test.ts": "gui", "logs-timezone.test.ts": "server", "loop-reasoning-replay.test.ts": "images", "loop.test.ts": "images", "loopback-companion-client-targets.test.ts": "server", "loopback-listener-admission.test.ts": "server", - "local-control-socket.test.ts": "server", "loopback-listener-integration.test.ts": "server", "macos-serial-lanes.test.ts": "ci-workflows", + "local-control-socket.test.ts": "server", "local-control-socket-windows.test.ts": "server", "loopback-listener-integration.test.ts": "server", "macos-serial-lanes.test.ts": "ci-workflows", "main-account-hard-lock-auth.test.ts": "codex-integration", "main-account-hard-lock-fallback-routing.test.ts": "codex-integration", "main-account-hard-lock-usage-limit.test.ts": "codex-integration", "main-account-hard-lock-default.test.ts": "codex-integration", "main-account-hard-lock-policy.test.ts": "codex-integration", diff --git a/tests/server/local-control-socket-windows.test.ts b/tests/server/local-control-socket-windows.test.ts new file mode 100644 index 00000000000..e792d081004 --- /dev/null +++ b/tests/server/local-control-socket-windows.test.ts @@ -0,0 +1,391 @@ +/** + * #8998: the #8184 local control socket on Windows. + * + * Windows has AF_UNIX sockets, but lstat refuses an AF_UNIX file with EACCES, so neither its type + * nor its owner can be read and the POSIX identity checks in tests/server/local-control-socket.test.ts + * do not apply. These cases start real hubs on Windows and prove the same contract: the admin + * token stays refused on TCP, the socket admits it for the one status read, the files go away on + * stop, a crashed predecessor's names are replaced, and the client sends the token only when the + * run directory and the whole path to it are trusted. + * + * The test root has to have trusted ancestry itself, which a shared temp directory may not have + * (the test preload also moves tmpdir() and homedir() into a sandbox under it): this file picks the + * first of OCX_TEST_WINDOWS_SOCKET_ROOT, tmpdir() and homedir() that passes, and skips the hub cases + * with a printed reason when none does rather than weakening the check. + */ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { linkSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs"; +import { homedir, tmpdir } from "node:os"; +import { join } from "node:path"; +import { saveConfig } from "../../src/config"; +import { startServer, waitForFailedStartRollback } from "../../src/server"; +import { runLinkCommand } from "../../src/cli/link"; +import { ownEvidence, ownerDefaults, ownerState } from "../../src/codex/prompt-lock-owner"; +import { + isLocalControlPrivateSocketName, + localControlLeasePath, + localControlPrivateSocketPath, + localControlSocketDir, + localControlSocketPath, + removeWindowsPrivateSocket, + usableLocalControlSocket, + windowsSocketEntryState, + windowsTrustedPath, + type WindowsSocketEntryState, +} from "../../src/lib/local-control-socket"; +import { createLocalControlListener, LocalControlReleaseError } from "../../src/server/index/local-control-listener"; +import { AuxiliaryListenerBindError, findAvailablePort, isAddrInUse } from "../../src/server/ports"; +import type { OcxConfig } from "../../src/types"; +import { SERVER_BUDGET_MS } from "../helpers/test-budget"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +const windows = process.platform === "win32"; +const ADMIN = "admin-secret"; +const STATUS = "/api/link/status?children=1"; +const previous = { + api: process.env.OPENCODEX_API_AUTH_TOKEN, + admin: process.env.OPENCODEX_ADMIN_AUTH_TOKEN, + home: process.env.OPENCODEX_HOME, +}; + +/** A root whose own path a Windows runtime would trust, or null. */ +function trustedRoot(): string | null { + if (!windows) return null; + const override = process.env.OCX_TEST_WINDOWS_SOCKET_ROOT?.trim(); + for (const base of [...(override ? [override] : []), tmpdir(), homedir()]) { + mkdirSync(base, { recursive: true }); + const probe = mkdtempSync(join(base, "ocx-lcw-")); + try { + mkdirSync(join(probe, "home", "run"), { recursive: true }); + if (windowsTrustedPath(join(probe, "home", "run"), false)) return base; + } finally { + removeTreeWithRetry(probe); + } + } + return null; +} +const ROOT = trustedRoot(); +if (windows && ROOT === null) { + console.warn("[local-control-socket-windows] no candidate root has trusted ancestry; set OCX_TEST_WINDOWS_SOCKET_ROOT to a private directory to run the hub cases"); +} +let testDir = ""; + +function hubConfig(managementPort: number, hostname = "0.0.0.0"): OcxConfig { + return { + port: 0, + hostname, + defaultProvider: "chatgpt", + providers: { chatgpt: { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", authMode: "forward" } }, + runtimeRole: "hub", + hub: { managementPublicOrigin: "https://hub.example.test", managementIngress: { enabled: true, port: managementPort } }, + remoteGui: { allowedTailscaleUsers: ["alice@example.test"] }, + } as unknown as OcxConfig; +} + +async function startHub(publicPort = 0) { + for (let draw = 1; ; draw += 1) { + const managementPort = await findAvailablePort(0, "127.0.0.1"); + saveConfig(hubConfig(managementPort)); + try { + const server = startServer(publicPort); + return { server, managementPort, publicPort: server.port! }; + } catch (error) { + await waitForFailedStartRollback(error); + if (!(error instanceof AuxiliaryListenerBindError && isAddrInUse(error.cause)) || draw >= 3) throw error; + } + } +} + +function overSocket(socket: string, path: string, init: RequestInit = {}): Promise { + return fetch("http://localhost" + path, { ...init, unix: socket } as RequestInit); +} + +/** What the run directory lists for this port: the public name, private names and the lease. */ +function portEntries(port: number): string[] { + try { + return readdirSync(localControlSocketDir()).filter(name => name === "control-" + port + ".sock" || name.startsWith(".c" + port + ".")) + .filter(name => !name.endsWith(".lock") && !name.endsWith(".tmp")).sort(); + } catch { + return []; + } +} + +/** Give Everyone modify rights on a directory, as a careless installer or a shared parent would. */ +function loosen(dir: string): void { + const result = spawnSync(join(process.env.SystemRoot ?? "C:\\Windows", "System32", "icacls.exe"), [dir, "/grant", "*S-1-1-0:(OI)(CI)M"], { encoding: "utf8" }); + expect(result.status).toBe(0); +} + +async function runQuietly(args: string[], deps: Parameters[1]) { + const out: string[] = []; + const err: string[] = []; + const [log, error] = [console.log, console.error]; + console.log = (...values: unknown[]) => { out.push(values.join(" ")); }; + console.error = (...values: unknown[]) => { err.push(values.join(" ")); }; + try { + return { code: await runLinkCommand(args, deps), out, err: err.join("\n") }; + } finally { + console.log = log; + console.error = error; + } +} + +function cliDeps(publicPort: number) { + return { + findLiveProxy: async () => ({ pid: process.pid, port: publicPort, hostname: "0.0.0.0", source: "runtime" as const, role: "hub" }), + readAdminToken: () => ADMIN, + }; +} + +describe("private socket names", () => { + test.each([ + [".c10100.abcdef12", true], [".c10100.0123abcd", true], + [".c10100.lease", false], [".c10100.lease.lock", false], [".c10100.abcdef1", false], [".c10100.abcdef123", false], + [".c10100.ABCDEF12", false], [".c101000.abcdef12", false], [".c1010.abcdef12", false], ["control-10100.sock", false], + [".c010100.abcdef12", false], ["x.c10100.abcdef12", false], + ] as const)("%s for port 10100 is %p", (name, expected) => { + expect(isLocalControlPrivateSocketName(10100, name)).toBe(expected); + }); +}); + +describe("removing a published socket name keeps the lease unless the name is proven gone", () => { + function remove(states: WindowsSocketEntryState[], unlinkFails = false) { + const unlinked: string[] = []; + const observe = () => states.shift() ?? "unknown"; + const unlink = (path: string) => { if (unlinkFails) throw new Error("EBUSY"); unlinked.push(path); }; + let error: unknown = null; + try { removeWindowsPrivateSocket("C:\\run\\.c10100.abcdef12", observe, unlink); } catch (caught) { error = caught; } + return { unlinked, error }; + } + + test("an absent name or a readable non-socket is left alone and does not block the release", () => { + for (const state of ["absent", "other"] as const) expect(remove([state])).toEqual({ unlinked: [], error: null }); + }); + + test("a socket is unlinked and must then read absent", () => { + expect(remove(["socket", "absent"])).toEqual({ unlinked: ["C:\\run\\.c10100.abcdef12"], error: null }); + expect(remove(["socket", "socket"]).error).toBeInstanceOf(Error); + expect(remove(["socket", "unknown"]).error).toBeInstanceOf(Error); + }); + + test("an unverifiable entry or a failed unlink throws, so the caller keeps its lease", () => { + const unknown = remove(["unknown"]); + expect(unknown.unlinked).toEqual([]); + expect(unknown.error).toBeInstanceOf(Error); + expect(remove(["socket"], true).error).toBeInstanceOf(Error); + }); +}); + +describe.skipIf(!windows || ROOT === null)("Windows hub with a non-loopback public listener (#8998)", () => { + beforeEach(() => { + testDir = mkdtempSync(join(ROOT!, "ocx-lcw-")); + process.env.OPENCODEX_HOME = join(testDir, "home"); + mkdirSync(process.env.OPENCODEX_HOME, { recursive: true }); + process.env.OPENCODEX_API_AUTH_TOKEN = "public-secret"; + process.env.OPENCODEX_ADMIN_AUTH_TOKEN = ADMIN; + }); + + afterEach(() => { + for (const [key, value] of [["OPENCODEX_API_AUTH_TOKEN", previous.api], ["OPENCODEX_ADMIN_AUTH_TOKEN", previous.admin], ["OPENCODEX_HOME", previous.home]] as const) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + if (testDir) removeTreeWithRetry(testDir); + testDir = ""; + }); + + test("refuses the admin token on TCP, admits it on the socket, and removes every file on stop", async () => { + const { server, managementPort, publicPort } = await startHub(); + const socket = localControlSocketPath(publicPort); + try { + for (const port of [managementPort, publicPort]) { + const response = await fetch("http://127.0.0.1:" + port + STATUS, { headers: { "x-opencodex-api-key": ADMIN } }); + expect(response.status).toBe(403); + } + const admitted = await overSocket(socket, STATUS, { headers: { "x-opencodex-api-key": ADMIN } }); + expect(admitted.status).toBe(200); + expect(Object.keys((await admitted.json()) as Record)).toEqual(expect.arrayContaining(["role", "listener", "links"])); + expect((await overSocket(socket, STATUS)).status).toBe(401); + for (const [method, path] of [["GET", "/api/config"], ["POST", "/api/link/issue"], ["GET", "/healthz"]] as const) { + expect((await overSocket(socket, path, { method, headers: { "x-opencodex-api-key": ADMIN } })).status).toBe(404); + } + expect(usableLocalControlSocket(publicPort)).toBe(socket); + expect(portEntries(publicPort).filter(name => isLocalControlPrivateSocketName(publicPort, name))).toHaveLength(1); + } finally { + await server.stop(true); + } + expect(portEntries(publicPort)).toEqual([]); + expect(usableLocalControlSocket(publicPort)).toBeNull(); + }, SERVER_BUDGET_MS); + + test("ocx link status reads the hub through the socket instead of meeting the 403", async () => { + const { server, publicPort } = await startHub(); + try { + const viaSocket = await runQuietly(["status", "--json"], cliDeps(publicPort)); + expect(viaSocket.err).toBe(""); + expect(viaSocket.code).toBe(0); + expect(Object.keys(JSON.parse(viaSocket.out.at(-1)!))).toEqual(expect.arrayContaining(["role", "listener", "links"])); + const viaTcp = await runQuietly(["status", "--json"], { ...cliDeps(publicPort), localControlSocket: () => null }); + expect(viaTcp.code).toBe(1); + expect(viaTcp.err).toContain("Link management request failed (403)"); + } finally { + await server.stop(true); + } + }, SERVER_BUDGET_MS); + + test("a crashed predecessor's socket names are replaced; the lease shape and other files are kept", async () => { + const publicPort = await findAvailablePort(0, "0.0.0.0"); + const dir = localControlSocketDir(); + mkdirSync(dir, { recursive: true }); + // A real AF_UNIX file left by a runtime that was killed: only a completed stop unlinks it. + const stale = localControlPrivateSocketPath(publicPort, "0123456789abcdef"); + const crashed = Bun.spawn([process.execPath, "-e", + "Bun.serve({ unix: process.argv[1], fetch: () => new Response('stale') }); require('fs').writeFileSync(process.argv[1] + '-ready', '1'); setInterval(() => {}, 1000);", + stale], { stdout: "ignore", stderr: "ignore" }); + while (!readdirSync(dir).includes(".c" + publicPort + ".01234567-ready")) await Bun.sleep(10); + crashed.kill("SIGKILL"); + await crashed.exited; + unlinkSync(stale + "-ready"); + expect(readdirSync(dir)).toContain(".c" + publicPort + ".01234567"); + linkSync(stale, localControlSocketPath(publicPort)); + const deadPid = spawnSync(process.execPath, ["-e", "0"]).pid!; + const record = { ...ownEvidence(ownerDefaults), pid: deadPid, token: "0123456789abcdef" }; + expect(ownerState(record, ownerDefaults)).toBe("dead"); + writeFileSync(localControlLeasePath(publicPort), JSON.stringify(record)); + writeFileSync(join(dir, ".c" + publicPort + ".notes"), "keep me"); + const { server } = await startHub(publicPort); + try { + const entries = portEntries(publicPort); + expect(entries).not.toContain(".c" + publicPort + ".01234567"); + expect(entries).toContain(".c" + publicPort + ".notes"); + const lease = JSON.parse(readFileSync(localControlLeasePath(publicPort), "utf8")) as { token: string }; + expect(lease.token).not.toBe("0123456789abcdef"); + expect((await overSocket(localControlSocketPath(publicPort), STATUS, { headers: { "x-opencodex-api-key": ADMIN } })).status).toBe(200); + } finally { + await server.stop(true); + } + expect(portEntries(publicPort)).toEqual([".c" + publicPort + ".notes"]); + }, SERVER_BUDGET_MS); + + test("a readable file at the public path is left alone, and the failed attempt leaves no socket and no lease", async () => { + const publicPort = await findAvailablePort(0, "0.0.0.0"); + mkdirSync(localControlSocketDir(), { recursive: true }); + writeFileSync(localControlSocketPath(publicPort), "not a socket"); + const { server } = await startHub(publicPort); + try { + expect(portEntries(publicPort)).toEqual(["control-" + publicPort + ".sock"]); + expect(readFileSync(localControlSocketPath(publicPort), "utf8")).toBe("not a socket"); + expect(usableLocalControlSocket(publicPort)).toBeNull(); + } finally { + await server.stop(true); + } + }, SERVER_BUDGET_MS); + + test("a loose pre-existing run directory is hardened before the socket binds", async () => { + mkdirSync(localControlSocketDir(), { recursive: true }); + loosen(localControlSocketDir()); + expect(windowsTrustedPath(localControlSocketDir())).toBe(false); + const { server, publicPort } = await startHub(); + try { + expect(windowsTrustedPath(localControlSocketDir())).toBe(true); + expect(usableLocalControlSocket(publicPort)).toBe(localControlSocketPath(publicPort)); + } finally { + await server.stop(true); + } + }, SERVER_BUDGET_MS); + + test("the client refuses a run directory another account can write, and the CLI keeps TCP", async () => { + const { server, publicPort } = await startHub(); + try { + expect(usableLocalControlSocket(publicPort)).toBe(localControlSocketPath(publicPort)); + loosen(localControlSocketDir()); + expect(usableLocalControlSocket(publicPort)).toBeNull(); + const result = await runQuietly(["status", "--json"], cliDeps(publicPort)); + expect(result.code).toBe(1); + expect(result.err).toContain("Link management request failed (403)"); + } finally { + await server.stop(true); + } + }, SERVER_BUDGET_MS); + + test("a config home under a parent other accounts can write gets no socket, from server or client", async () => { + const shared = join(testDir, "shared"); + mkdirSync(shared); + loosen(shared); + process.env.OPENCODEX_HOME = join(shared, "home"); + mkdirSync(process.env.OPENCODEX_HOME); + const { server, publicPort } = await startHub(); + try { + expect(portEntries(publicPort)).toEqual([]); + expect(usableLocalControlSocket(publicPort)).toBeNull(); + const result = await runQuietly(["status", "--json"], cliDeps(publicPort)); + expect(result.code).toBe(1); + expect(result.err).toContain("Link management request failed (403)"); + } finally { + await server.stop(true); + } + }, SERVER_BUDGET_MS); + + test("a loopback public listener serves no socket and spawns no ACL check in the client", async () => { + const managementPort = await findAvailablePort(0, "127.0.0.1"); + saveConfig(hubConfig(managementPort, "127.0.0.1")); + const server = startServer(0); + try { + expect(portEntries(server.port!)).toEqual([]); + expect(usableLocalControlSocket(server.port!)).toBeNull(); + } finally { + await server.stop(true); + } + }, SERVER_BUDGET_MS); + + test("a pre-existing junction at the run directory is refused before any ACL operation follows it", async () => { + const target = join(testDir, "elsewhere"); + mkdirSync(target); + loosen(target); + const made = spawnSync("cmd.exe", ["/c", "mklink", "/J", localControlSocketDir(), target], { encoding: "utf8" }); + expect(made.status).toBe(0); + const before = spawnSync(join(process.env.SystemRoot ?? "C:\\Windows", "System32", "icacls.exe"), [target], { encoding: "utf8" }).stdout; + const { server, publicPort } = await startHub(); + try { + expect(readdirSync(target)).toEqual([]); + expect(usableLocalControlSocket(publicPort)).toBeNull(); + // Hardening never ran on the junction's target: its loose ACL is exactly as it was. + expect(spawnSync(join(process.env.SystemRoot ?? "C:\\Windows", "System32", "icacls.exe"), [target], { encoding: "utf8" }).stdout).toBe(before); + } finally { + await server.stop(true); + spawnSync("cmd.exe", ["/c", "rmdir", localControlSocketDir()]); + } + }, SERVER_BUDGET_MS); + + test("the socket entry observation tells a socket, a readable file, absence and a missing directory apart", async () => { + const { server, publicPort } = await startHub(); + try { + expect(windowsSocketEntryState(localControlSocketPath(publicPort))).toBe("socket"); + writeFileSync(join(localControlSocketDir(), "plain"), "x"); + expect(windowsSocketEntryState(join(localControlSocketDir(), "plain"))).toBe("other"); + expect(windowsSocketEntryState(join(localControlSocketDir(), "missing"))).toBe("absent"); + expect(windowsSocketEntryState(join(testDir, "no-such-dir", "x"))).toBe("absent"); + } finally { + await server.stop(true); + } + }, SERVER_BUDGET_MS); + + test("an unreadable ownership record fails the release and keeps it for the next stop", async () => { + const publicPort = await findAvailablePort(0, "0.0.0.0"); + const listener = createLocalControlListener(); + listener.start({ config: { hostname: "0.0.0.0" } as OcxConfig, publicPort, dispatch: async () => Response.json({ ok: true }) }); + expect(listener.socketPath()).toBe(localControlSocketPath(publicPort)); + const lease = localControlLeasePath(publicPort); + const record = readFileSync(lease, "utf8"); + writeFileSync(lease, "{not json"); + const failed = await listener.stop().then(() => null, (error: unknown) => error); + expect(failed).toBeInstanceOf(LocalControlReleaseError); + // Nothing was handed over: the public name is still there for the retained release. + expect(portEntries(publicPort)).toContain("control-" + publicPort + ".sock"); + writeFileSync(lease, record); + await listener.stop(); + expect(portEntries(publicPort)).toEqual([]); + }, SERVER_BUDGET_MS); +}); + diff --git a/tests/server/local-control-socket.test.ts b/tests/server/local-control-socket.test.ts index bfa11ec088e..3e25b24cc3a 100644 --- a/tests/server/local-control-socket.test.ts +++ b/tests/server/local-control-socket.test.ts @@ -275,8 +275,9 @@ describe("local control socket route table", () => { }); test("is wanted only when the public listener is not loopback", () => { - expect(localControlSocketWanted({ hostname: "0.0.0.0" })).toBe(unixSupported); - expect(localControlSocketWanted({ hostname: "10.0.0.5" })).toBe(unixSupported); + // Every platform, Windows included since #8998. + expect(localControlSocketWanted({ hostname: "0.0.0.0" })).toBe(true); + expect(localControlSocketWanted({ hostname: "10.0.0.5" })).toBe(true); for (const hostname of ["127.0.0.1", "localhost", "::1", undefined]) { expect(localControlSocketWanted({ hostname } as Pick)).toBe(false); } From 03afe39772768085b14775d84796797304569955 Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 21 Nov 2026 06:05:20 +0900 Subject: [PATCH 2/7] docs(devlog): record the #8998 branch base after #9018 --- .../040_windows_control_socket.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/devlog/_plan/261121_fb2100_remote_link_auth/040_windows_control_socket.md b/devlog/_plan/261121_fb2100_remote_link_auth/040_windows_control_socket.md index 33f314062d9..c6e3f466c4f 100644 --- a/devlog/_plan/261121_fb2100_remote_link_auth/040_windows_control_socket.md +++ b/devlog/_plan/261121_fb2100_remote_link_auth/040_windows_control_socket.md @@ -1,6 +1,6 @@ # 040 #8998: `ocx link status` on a Windows hub with a non-loopback listener -Branch `codex/fb2100-win-link-socket` from `origin/dev` 70c9e2134, second PR (roadmap unit 040). +Branch `codex/fb2100-win-link-socket` from `origin/dev` a8f689f2c (after #9018 merged), second PR (roadmap unit 040). Problem: #8370 serves `GET /api/link/status` over a private AF_UNIX socket so the CLI's admin token has trusted ingress on a hub whose public listener is not loopback. `localControlSocketSupported()` is false on win32, so a From c49e1832dc21db12389794b2ca11efc468df1e94 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 10:50:16 +0900 Subject: [PATCH 3/7] fix(link): keep a lease that could not be deleted for the next stop or start removeOwnedLease treated every unlink error as "already gone". When Windows removed the socket names but the lease unlink failed, the release reported success, stop() dropped pendingRelease, and a later start() in the same process read its own record as a live owner and served no socket. Only ENOENT now counts as removed; any other failure makes the release fail and keeps it for retry. A publish rollback whose lease unlink fails retains just the record. The Windows test holds the lease open without FILE_SHARE_DELETE from another process, expects stop() to throw LocalControlReleaseError, then expects start() to finish the retained release and serve again. --- src/server/index/local-control-listener.ts | 25 +++++++++---- .../local-control-socket-windows.test.ts | 35 +++++++++++++++++++ 2 files changed, 54 insertions(+), 6 deletions(-) diff --git a/src/server/index/local-control-listener.ts b/src/server/index/local-control-listener.ts index fe60675dd6a..0b1c8790c88 100644 --- a/src/server/index/local-control-listener.ts +++ b/src/server/index/local-control-listener.ts @@ -123,7 +123,7 @@ type LeaseDecision = | { kind: "held" } | { kind: "unsafe" } | { kind: "contended" } - | { kind: "failed"; error: unknown; retained?: true }; + | { kind: "failed"; error: unknown; retained?: "socket" | "lease" }; const PUBLISH_ATTEMPTS = 4; /** `withLockClaim` is a try-lock; a contender retries a bounded number of times and then refuses. */ @@ -220,11 +220,19 @@ function writeLease(path: string, lease: LocalControlLease): void { } } -/** Remove the record only when it is still this instance's; the caller holds the claim mutex. */ +/** + * Remove the record only when it is still this instance's; the caller holds the claim mutex. + * Only a record that is already gone counts as removed: any other unlink failure throws, so the + * caller keeps its retry state instead of reporting a release that left a live lease behind. + */ function removeOwnedLease(path: string, token: string): void { const current = readLease(path); if (current.kind !== "record" || current.lease.token !== token) return; - try { unlinkSync(path); } catch { /* already gone */ } + try { + unlinkSync(path); + } catch (error) { + if (!isCode(error, "ENOENT")) throw error; + } } /** @@ -306,8 +314,10 @@ function acquireLease(leasePath: string, token: string, publish: () => void, rol } catch (error) { // Undo what this attempt bound while it still holds the lease. A rollback that fails keeps // the lease, so no successor publishes over a name this attempt may still own. - try { rollback(); } catch { return { kind: "failed", error, retained: true }; } - removeOwnedLease(leasePath, token); + try { rollback(); } catch { return { kind: "failed", error, retained: "socket" }; } + // The names are gone; a lease that cannot be deleted still names this runtime, so it is + // retained for the next stop() or start() exactly like a release that failed. + try { removeOwnedLease(leasePath, token); } catch { return { kind: "failed", error, retained: "lease" }; } return { kind: "failed", error }; } return { kind: "acquired" }; @@ -513,10 +523,13 @@ export function createLocalControlListener(): LocalControlListener { } if (decision.kind === "failed") { if (bound) void (bound as Server).stop(true).catch(() => {}); - if (decision.retained) { + if (decision.retained === "socket") { // The rollback could not remove what this attempt bound; keep the port owned and let the // next stop() or start() finish the release, exactly as a release that failed would. pendingRelease = { leasePath: leaseFile, token, publicPath: null, privatePath: privateTarget, identity: WINDOWS_SOCKET_IDENTITY }; + } else if (decision.retained === "lease") { + // The names are gone and only the record survived its unlink: retry just the record. + pendingRelease = { leasePath: leaseFile, token, publicPath: null, privatePath: null, identity: null }; } // Publishing is where a hard-link-less filesystem actually fails, and that error is // returned rather than thrown, so this branch is the one that has to classify it. diff --git a/tests/server/local-control-socket-windows.test.ts b/tests/server/local-control-socket-windows.test.ts index e792d081004..6ca9bef0b3c 100644 --- a/tests/server/local-control-socket-windows.test.ts +++ b/tests/server/local-control-socket-windows.test.ts @@ -387,5 +387,40 @@ describe.skipIf(!windows || ROOT === null)("Windows hub with a non-loopback publ await listener.stop(); expect(portEntries(publicPort)).toEqual([]); }, SERVER_BUDGET_MS); + + test("a lease that cannot be deleted fails the stop, and the next start retries it before serving again", async () => { + const publicPort = await findAvailablePort(0, "0.0.0.0"); + const ctx = { config: { hostname: "0.0.0.0" } as OcxConfig, publicPort, dispatch: async () => Response.json({ ok: true }) }; + const listener = createLocalControlListener(); + listener.start(ctx); + expect(listener.socketPath()).toBe(localControlSocketPath(publicPort)); + const lease = localControlLeasePath(publicPort); + // Another process holds the record open without FILE_SHARE_DELETE: it stays readable, but no + // unlink can remove it until that handle closes. + const holder = Bun.spawn(["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", + "$f = [IO.File]::Open($env:OCX_HELD_LEASE, 'Open', 'Read', 'Read'); [Console]::Out.WriteLine('held'); [Console]::Out.Flush(); [void][Console]::In.ReadLine(); $f.Close()"], + { env: { ...process.env, OCX_HELD_LEASE: lease }, stdin: "pipe", stdout: "pipe", stderr: "ignore" }); + try { + const reader = holder.stdout.getReader(); + let seen = ""; + while (!seen.includes("held")) { + const chunk = await reader.read(); + if (chunk.done) throw new Error("the lease holder exited before opening the record"); + seen += new TextDecoder().decode(chunk.value); + } + const failed = await listener.stop().then(() => null, (error: unknown) => error); + expect(failed).toBeInstanceOf(LocalControlReleaseError); + expect(readFileSync(lease, "utf8")).toContain("token"); + } finally { + holder.stdin.write("\n"); + await holder.stdin.end(); + await holder.exited; + } + // The retained release runs first, so this runtime's own stale record does not read as a live owner. + listener.start(ctx); + expect(listener.socketPath()).toBe(localControlSocketPath(publicPort)); + await listener.stop(); + expect(portEntries(publicPort)).toEqual([]); + }, SERVER_BUDGET_MS); }); From 2ea021da6192486d4154b92436cdde22b196cf33 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 11:02:08 +0900 Subject: [PATCH 4/7] test(link): pass the held lease path to the PowerShell holder as a literal --- tests/server/local-control-socket-windows.test.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/server/local-control-socket-windows.test.ts b/tests/server/local-control-socket-windows.test.ts index 6ca9bef0b3c..8f951576ce5 100644 --- a/tests/server/local-control-socket-windows.test.ts +++ b/tests/server/local-control-socket-windows.test.ts @@ -396,10 +396,12 @@ describe.skipIf(!windows || ROOT === null)("Windows hub with a non-loopback publ expect(listener.socketPath()).toBe(localControlSocketPath(publicPort)); const lease = localControlLeasePath(publicPort); // Another process holds the record open without FILE_SHARE_DELETE: it stays readable, but no - // unlink can remove it until that handle closes. + // unlink can remove it until that handle closes. The path travels as a quoted literal: copying + // process.env into the child can carry both SYSTEMROOT and SystemRoot, which breaks the spawn. + const quoted = "'" + lease.replaceAll("'", "''") + "'"; const holder = Bun.spawn(["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", - "$f = [IO.File]::Open($env:OCX_HELD_LEASE, 'Open', 'Read', 'Read'); [Console]::Out.WriteLine('held'); [Console]::Out.Flush(); [void][Console]::In.ReadLine(); $f.Close()"], - { env: { ...process.env, OCX_HELD_LEASE: lease }, stdin: "pipe", stdout: "pipe", stderr: "ignore" }); + "$ErrorActionPreference = 'Stop'; $f = [IO.File]::Open(" + quoted + ", 'Open', 'Read', 'Read'); [Console]::Out.WriteLine('held'); [Console]::Out.Flush(); [void][Console]::In.ReadLine(); $f.Close()"], + { stdin: "pipe", stdout: "pipe", stderr: "ignore" }); try { const reader = holder.stdout.getReader(); let seen = ""; From 539b0594fe2b313a9475725041c053fe7700ac91 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 11:10:12 +0900 Subject: [PATCH 5/7] fix(link): refuse a Windows run directory that already existed without private permissions Hardening such a directory would make whatever it already held look trusted to the client, which checks only the directory's current permissions. The runtime now leaves it loose and serves no socket, so the client keeps refusing it as well. No released runtime creates this directory, so only a directory made outside opencodex is affected; removing it re-enables the socket. --- .../040_windows_control_socket.md | 2 +- src/server/index/local-control-listener.ts | 10 +++++++++- structure/remote-link.md | 2 +- tests/server/local-control-socket-windows.test.ts | 7 ++++--- 4 files changed, 15 insertions(+), 6 deletions(-) diff --git a/devlog/_plan/261121_fb2100_remote_link_auth/040_windows_control_socket.md b/devlog/_plan/261121_fb2100_remote_link_auth/040_windows_control_socket.md index c6e3f466c4f..cefae82b971 100644 --- a/devlog/_plan/261121_fb2100_remote_link_auth/040_windows_control_socket.md +++ b/devlog/_plan/261121_fb2100_remote_link_auth/040_windows_control_socket.md @@ -53,7 +53,7 @@ the claim mutex) and replace only the parts that read POSIX identity: Tests: `tests/server/local-control-socket-windows.test.ts` (win32 only: TCP 403 vs socket 200, other routes 404, `ocx link status` over the socket, files and lease removed on stop, a crashed predecessor's socket names replaced while a -decoy and the lease format survive, a loosened directory refused by the client, a loose pre-existing directory hardened, +decoy and the lease format survive, a loosened directory refused by the client, a loose pre-existing directory refused and left loose, a config home under a parent other users can write refused by server and client while the token stays protected, a failed publication that leaves no private name and no lease) and platform-neutral name-matcher cases. Registered in the test layout. diff --git a/src/server/index/local-control-listener.ts b/src/server/index/local-control-listener.ts index 0b1c8790c88..61c257a8722 100644 --- a/src/server/index/local-control-listener.ts +++ b/src/server/index/local-control-listener.ts @@ -79,9 +79,17 @@ function preparePrivateDir(dir: string): void { if (WINDOWS) { // Trust the path above the run directory before creating anything in it (#8998). if (!windowsTrustedPath(dir, false)) throw new Error("socket directory path is not trusted"); - try { mkdirSync(dir); } catch (error) { if (!isCode(error, "EEXIST")) throw error; } + let created = true; + try { mkdirSync(dir); } catch (error) { if (!isCode(error, "EEXIST")) throw error; created = false; } // Refuse a pre-existing junction or other reparse point before any ACL operation can follow it. if (!windowsPlainDirectory(dir)) throw new Error("socket directory is not a plain directory"); + // A run directory that already existed without private permissions may hold a socket and lease + // someone else planted while it was open. Hardening it would make those entries look trusted to + // the client, which checks only the directory's current permissions, so refuse instead and leave + // it loose: the client then refuses it too. No released runtime creates this directory loose. + if (!created && !isPrivateSocketDir(dir)) { + throw new Error("socket directory already existed without private permissions; remove it to enable the control socket"); + } hardenSecretDir(dir, { required: true, verifyExistingRuntimeDirectory: true }); if (!isPrivateSocketDir(dir)) throw new Error("socket directory could not be made private"); return; diff --git a/structure/remote-link.md b/structure/remote-link.md index e1e7e0f832a..cd8b6c5c066 100644 --- a/structure/remote-link.md +++ b/structure/remote-link.md @@ -81,7 +81,7 @@ The **Child automation** panel reads `GET /api/link/children/policy` and writes The dashboard link routes (`GET /api/link/status`, `GET /api/link/diagnostics`, `GET /api/link/candidates`, `POST /api/link/probe`, `POST /api/link/confirm-host`, `POST /api/link/apply`, `POST /api/link/{id}/reconnect`, `DELETE /api/link/{id}`, `POST /api/link/children/operations` and `GET /api/link/children/jobs/{jobId}`) admit a paired GUI session, or, on a standalone runtime only, the current loopback-issued GUI session that reached the public listener bound to a loopback hostname. `POST /api/link/join` is stricter and requires the paired session because it durably redirects this machine's client traffic. The hub-link, hub-management and claude-intercept ingresses are never trusted loopback ingress, a stale session is refused, and a hub keeps the paired-only rule. The Tailscale identity refusal runs before either check. A loopback session is minted by the loopback dashboard bootstrap without a credential, so it proves possession, not user presence: any local process can fetch the bootstrap and replay its token and CSRF value, which is why it cannot authorize joining and why `src/client/machine-listener.ts` keeps durable machine changes on the connected listener away from that session. Caller-supplied explicit routes follow the stricter [explicit-route authority check](#explicit-route). Other link operations accept this casual-path trade, the same as `POST /api/github/star` in `src/server/management/sidebar-routes.ts`; it is not a secret-backed boundary like an operator-created pairing grant or the admin token. -The admin-token link routes require trusted loopback ingress. A runtime whose public listener is not bound to loopback has no TCP listener that qualifies, because the hub management listener is relayed by Tailscale Serve and must never confer that trust (#6913). `src/server/index/local-control-listener.ts` therefore opens a Unix socket at `/run/control-.sock` (`src/lib/local-control-socket.ts`) on macOS, Linux and Windows when the public bind is not loopback. Its ingress is `local-control`, the only non-TCP ingress, and `trustedLoopbackForIngress` treats it as trusted. The boundary is the filesystem: the directory is created or tightened to `0700`, must be a real directory owned by this user, and the socket is `0600`; a TCP relay or a forged header cannot produce the ingress, which is derived from the Bun server object. Before dispatch the listener admits only `GET /api/link/status` and answers 404 for anything else, and the request still needs the admin token. Two runtimes can share a home and a public port, so the public path is not the address Bun binds: it is a hard link to an instance-specific socket, and a per-port lease records the owner's host, pid and process start time from the shared owner evidence in `src/codex/prompt-lock-owner.ts`. Reading that record, deciding it is stale, and publishing the new one all happen inside the claim mutex in `src/codex/prompt-lock-claim.ts`, so a record judged dead cannot be replaced by a live one before this runtime publishes. A live owner is never displaced — a second runtime refuses the socket and leaves it serving. A record from another machine, or one that cannot be parsed, is refused rather than treated as absent. A lease whose process is provably gone is a crashed predecessor, so its dead public link and private socket are replaced; any other file at the path is left alone and no socket is served. The run directory is registered with config ownership, so uninstall removes it. A path longer than `sun_path` in bytes is refused before anything is created, because a length in code units admits a non-ASCII home the kernel cannot bind. On shutdown the runtime gives the record up first, before it awaits its own socket teardown and before the other optional listeners shut down, so a successor that starts while that shutdown is still running is not blocked by a departing incumbent; it removes the public link only when that link is still the inode it published, because Bun's own stop unlinks the path it was given. A release that cannot take the claim mutex is retried, and if it still cannot run it is reported and retained on the listener, so the next stop or start finishes it instead of leaving a live lease nobody serves. `src/cli/link-local-control.ts` sends `ocx link status` there when the directory is still private and the socket is this user's, falls back to TCP only on a transport failure, and leaves an explicit base URL untouched. Windows has the socket too (#8998). There lstat refuses an AF_UNIX file with `EACCES`, so neither its type nor its owner can be read, and the directory boundary is a DACL. `windowsTrustedPath` therefore proves the path instead: the canonical path spells the same, every component is a real directory with no reparse point (lstat and the file attributes both checked), the run directory passes the `private-runtime-directory` ACL policy, the config home `write-private` and every ancestor `trusted-ancestry` (`src/lib/windows-owner-acl.ts`). The runtime checks the path above the run directory before it creates anything, hardens the run directory with `hardenSecretDir`, and serves no socket unless the whole check then passes; the CLI runs the same check before it sends the token and otherwise keeps TCP. No other account can change anything on such a path, so the path checked is the path connected. A Windows socket entry is one the directory lists and lstat refuses with `EACCES`; a file lstat can read is never treated as a socket. Without inode identity, a release unlinks the public link and the private name only inside the claim mutex while the lease still names this runtime's token, orphan cleanup matches the exact `.c.<8 hex>` name (never the lease), and a publication that fails removes the private name it bound before the lease goes, or keeps the lease and retries the release when it cannot. Same-user processes and administrators are inside the trust boundary, as for every other file in the config home. Coverage: `tests/server/local-control-socket.test.ts`, `tests/server/local-control-socket-windows.test.ts` (Windows hub cases; `OCX_TEST_WINDOWS_SOCKET_ROOT` names a trusted root where the default temp directory is shared). +The admin-token link routes require trusted loopback ingress. A runtime whose public listener is not bound to loopback has no TCP listener that qualifies, because the hub management listener is relayed by Tailscale Serve and must never confer that trust (#6913). `src/server/index/local-control-listener.ts` therefore opens a Unix socket at `/run/control-.sock` (`src/lib/local-control-socket.ts`) on macOS, Linux and Windows when the public bind is not loopback. Its ingress is `local-control`, the only non-TCP ingress, and `trustedLoopbackForIngress` treats it as trusted. The boundary is the filesystem: the directory is created or tightened to `0700`, must be a real directory owned by this user, and the socket is `0600`; a TCP relay or a forged header cannot produce the ingress, which is derived from the Bun server object. Before dispatch the listener admits only `GET /api/link/status` and answers 404 for anything else, and the request still needs the admin token. Two runtimes can share a home and a public port, so the public path is not the address Bun binds: it is a hard link to an instance-specific socket, and a per-port lease records the owner's host, pid and process start time from the shared owner evidence in `src/codex/prompt-lock-owner.ts`. Reading that record, deciding it is stale, and publishing the new one all happen inside the claim mutex in `src/codex/prompt-lock-claim.ts`, so a record judged dead cannot be replaced by a live one before this runtime publishes. A live owner is never displaced — a second runtime refuses the socket and leaves it serving. A record from another machine, or one that cannot be parsed, is refused rather than treated as absent. A lease whose process is provably gone is a crashed predecessor, so its dead public link and private socket are replaced; any other file at the path is left alone and no socket is served. The run directory is registered with config ownership, so uninstall removes it. A path longer than `sun_path` in bytes is refused before anything is created, because a length in code units admits a non-ASCII home the kernel cannot bind. On shutdown the runtime gives the record up first, before it awaits its own socket teardown and before the other optional listeners shut down, so a successor that starts while that shutdown is still running is not blocked by a departing incumbent; it removes the public link only when that link is still the inode it published, because Bun's own stop unlinks the path it was given. A release that cannot take the claim mutex is retried, and if it still cannot run it is reported and retained on the listener, so the next stop or start finishes it instead of leaving a live lease nobody serves. `src/cli/link-local-control.ts` sends `ocx link status` there when the directory is still private and the socket is this user's, falls back to TCP only on a transport failure, and leaves an explicit base URL untouched. Windows has the socket too (#8998). There lstat refuses an AF_UNIX file with `EACCES`, so neither its type nor its owner can be read, and the directory boundary is a DACL. `windowsTrustedPath` therefore proves the path instead: the canonical path spells the same, every component is a real directory with no reparse point (lstat and the file attributes both checked), the run directory passes the `private-runtime-directory` ACL policy, the config home `write-private` and every ancestor `trusted-ancestry` (`src/lib/windows-owner-acl.ts`). The runtime checks the path above the run directory before it creates anything, creates and hardens the run directory with `hardenSecretDir`, and serves no socket unless the whole check then passes; a run directory that already exists without private permissions is refused and left as it is, because hardening it would make a socket or lease planted while it was open look trusted to the client, which then refuses the loose directory too; the CLI runs the same check before it sends the token and otherwise keeps TCP. No other account can change anything on such a path, so the path checked is the path connected. A Windows socket entry is one the directory lists and lstat refuses with `EACCES`; a file lstat can read is never treated as a socket. Without inode identity, a release unlinks the public link and the private name only inside the claim mutex while the lease still names this runtime's token, orphan cleanup matches the exact `.c.<8 hex>` name (never the lease), and a publication that fails removes the private name it bound before the lease goes, or keeps the lease and retries the release when it cannot. Only an already-absent lease counts as removed: a lease whose unlink fails fails the release, which is retained for the next stop or start. Same-user processes and administrators are inside the trust boundary, as for every other file in the config home. Coverage: `tests/server/local-control-socket.test.ts`, `tests/server/local-control-socket-windows.test.ts` (Windows hub cases; `OCX_TEST_WINDOWS_SOCKET_ROOT` names a trusted root where the default temp directory is shared). A successful join restarts this proxy (a 503 drain of up to a minute while running turns finish, then a closed listener) into the client runtime on the configured port. `GET /api/link/status` tells a GUI-session caller whether it may join: the response gains `joinAvailable`, true only for a paired dashboard session on a standalone runtime whose live port is its configured port, and `joinDenied`, which is `null` when allowed or the first failed gate (`pairing_required`, `standalone_required`, then `join_port_mismatch`). On a Child whose durable connection diverges from its startup snapshot, link and machine status instead return `503 client_state_changed`, as does readiness; this reports the divergence without stopping or reconstructing the relay. An admin-token caller gets the exact K16 document without either field, because `ocx link status` validates it key by key. The dashboard reads an absent availability field as false and an absent or unknown denial as generic unavailability; while unavailable the Child role card cannot be selected by pointer or keyboard. A pairing refusal says to pair this machine first and offers code entry only on the existing same-origin literal-loopback transport. A port refusal instead asks the operator to restart on the configured port; neither status reads nor displaying this guidance mint a grant or change pairing, keys, routing, or runtime state. Before **Connect as Child** the confirmation panel says that the restart briefly interrupts Codex and that Codex keeps its local address. The dashboard reads the standalone's pid from same-origin `/healthz`, sends the join, then reads `/healthz` once a second, skipping status polls meanwhile, and reloads only when it reports `role: "client"` under another pid, so the reloaded document carries the client role and a fresh session. It never gives up by itself: past the server's own handoff budget (60 s drain plus 70 s replacement readiness, plus a margin: 145 seconds) it says the restart is slow and keeps reading `/healthz` every 5 seconds until the Child answers or the page is left. diff --git a/tests/server/local-control-socket-windows.test.ts b/tests/server/local-control-socket-windows.test.ts index 8f951576ce5..b7bcfb794e3 100644 --- a/tests/server/local-control-socket-windows.test.ts +++ b/tests/server/local-control-socket-windows.test.ts @@ -282,14 +282,15 @@ describe.skipIf(!windows || ROOT === null)("Windows hub with a non-loopback publ } }, SERVER_BUDGET_MS); - test("a loose pre-existing run directory is hardened before the socket binds", async () => { + test("a loose pre-existing run directory is refused and left loose, so no client trusts what it holds", async () => { mkdirSync(localControlSocketDir(), { recursive: true }); loosen(localControlSocketDir()); expect(windowsTrustedPath(localControlSocketDir())).toBe(false); const { server, publicPort } = await startHub(); try { - expect(windowsTrustedPath(localControlSocketDir())).toBe(true); - expect(usableLocalControlSocket(publicPort)).toBe(localControlSocketPath(publicPort)); + expect(windowsTrustedPath(localControlSocketDir())).toBe(false); + expect(portEntries(publicPort)).toEqual([]); + expect(usableLocalControlSocket(publicPort)).toBeNull(); } finally { await server.stop(true); } From 7ef3b99969058ca2c6f8ea668d8e03703c5cfb3b Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 11:12:45 +0900 Subject: [PATCH 6/7] test(link): start predecessor fixtures from a private run directory --- tests/server/local-control-socket-windows.test.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/server/local-control-socket-windows.test.ts b/tests/server/local-control-socket-windows.test.ts index b7bcfb794e3..2bd7cb79c5c 100644 --- a/tests/server/local-control-socket-windows.test.ts +++ b/tests/server/local-control-socket-windows.test.ts @@ -39,6 +39,7 @@ import { AuxiliaryListenerBindError, findAvailablePort, isAddrInUse } from "../. import type { OcxConfig } from "../../src/types"; import { SERVER_BUDGET_MS } from "../helpers/test-budget"; import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { hardenSecretDir } from "../../src/lib/windows-secret-acl"; const windows = process.platform === "win32"; const ADMIN = "admin-secret"; @@ -101,6 +102,11 @@ function overSocket(socket: string, path: string, init: RequestInit = {}): Promi return fetch("http://localhost" + path, { ...init, unix: socket } as RequestInit); } +/** A run directory as a previous runtime leaves it: created, then made private the way startup does. */ +function privateRunDir(dir: string): void { + hardenSecretDir(dir, { required: true, verifyExistingRuntimeDirectory: true }); +} + /** What the run directory lists for this port: the public name, private names and the lease. */ function portEntries(port: number): string[] { try { @@ -238,6 +244,7 @@ describe.skipIf(!windows || ROOT === null)("Windows hub with a non-loopback publ const publicPort = await findAvailablePort(0, "0.0.0.0"); const dir = localControlSocketDir(); mkdirSync(dir, { recursive: true }); + privateRunDir(dir); // A real AF_UNIX file left by a runtime that was killed: only a completed stop unlinks it. const stale = localControlPrivateSocketPath(publicPort, "0123456789abcdef"); const crashed = Bun.spawn([process.execPath, "-e", @@ -271,6 +278,7 @@ describe.skipIf(!windows || ROOT === null)("Windows hub with a non-loopback publ test("a readable file at the public path is left alone, and the failed attempt leaves no socket and no lease", async () => { const publicPort = await findAvailablePort(0, "0.0.0.0"); mkdirSync(localControlSocketDir(), { recursive: true }); + privateRunDir(localControlSocketDir()); writeFileSync(localControlSocketPath(publicPort), "not a socket"); const { server } = await startHub(publicPort); try { From 5077530e988a8a1124d965bf99b5ed9a03d1c8ac Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 11:19:42 +0900 Subject: [PATCH 7/7] test(link): cover run-directory creation under the config home and a directory loosened later; document the Windows trust boundary --- src/lib/local-control-socket.ts | 4 ++ structure/remote-link.md | 2 +- .../local-control-socket-windows.test.ts | 41 ++++++++++++++++++- 3 files changed, 45 insertions(+), 2 deletions(-) diff --git a/src/lib/local-control-socket.ts b/src/lib/local-control-socket.ts index 8c65cc8d662..b17f817c202 100644 --- a/src/lib/local-control-socket.ts +++ b/src/lib/local-control-socket.ts @@ -249,6 +249,10 @@ export function usableLocalControlSocket(port: number, configDir?: string): stri if (!localControlSocketSupported() || !Number.isInteger(port) || port <= 0 || port > 65535) return null; const path = localControlSocketPath(port, configDir); if (process.platform === "win32") { + // Trust boundary: the current user and administrators are trusted, as for every file in the + // config home. Windows cannot report an AF_UNIX file's owner, so endpoint ownership is not + // verified here; what is verified is that the run directory is private. The runtime creates + // it only under a write-private config home and refuses one that already existed loose. // The cheap observation first: no listed socket means no PowerShell at all. if (!localControlSocketPathFits(path) || !windowsSocketEntry(path)) return null; return isPrivateSocketDir(localControlSocketDir(configDir)) && windowsSocketEntry(path) ? path : null; diff --git a/structure/remote-link.md b/structure/remote-link.md index cd8b6c5c066..7e2e31c7137 100644 --- a/structure/remote-link.md +++ b/structure/remote-link.md @@ -81,7 +81,7 @@ The **Child automation** panel reads `GET /api/link/children/policy` and writes The dashboard link routes (`GET /api/link/status`, `GET /api/link/diagnostics`, `GET /api/link/candidates`, `POST /api/link/probe`, `POST /api/link/confirm-host`, `POST /api/link/apply`, `POST /api/link/{id}/reconnect`, `DELETE /api/link/{id}`, `POST /api/link/children/operations` and `GET /api/link/children/jobs/{jobId}`) admit a paired GUI session, or, on a standalone runtime only, the current loopback-issued GUI session that reached the public listener bound to a loopback hostname. `POST /api/link/join` is stricter and requires the paired session because it durably redirects this machine's client traffic. The hub-link, hub-management and claude-intercept ingresses are never trusted loopback ingress, a stale session is refused, and a hub keeps the paired-only rule. The Tailscale identity refusal runs before either check. A loopback session is minted by the loopback dashboard bootstrap without a credential, so it proves possession, not user presence: any local process can fetch the bootstrap and replay its token and CSRF value, which is why it cannot authorize joining and why `src/client/machine-listener.ts` keeps durable machine changes on the connected listener away from that session. Caller-supplied explicit routes follow the stricter [explicit-route authority check](#explicit-route). Other link operations accept this casual-path trade, the same as `POST /api/github/star` in `src/server/management/sidebar-routes.ts`; it is not a secret-backed boundary like an operator-created pairing grant or the admin token. -The admin-token link routes require trusted loopback ingress. A runtime whose public listener is not bound to loopback has no TCP listener that qualifies, because the hub management listener is relayed by Tailscale Serve and must never confer that trust (#6913). `src/server/index/local-control-listener.ts` therefore opens a Unix socket at `/run/control-.sock` (`src/lib/local-control-socket.ts`) on macOS, Linux and Windows when the public bind is not loopback. Its ingress is `local-control`, the only non-TCP ingress, and `trustedLoopbackForIngress` treats it as trusted. The boundary is the filesystem: the directory is created or tightened to `0700`, must be a real directory owned by this user, and the socket is `0600`; a TCP relay or a forged header cannot produce the ingress, which is derived from the Bun server object. Before dispatch the listener admits only `GET /api/link/status` and answers 404 for anything else, and the request still needs the admin token. Two runtimes can share a home and a public port, so the public path is not the address Bun binds: it is a hard link to an instance-specific socket, and a per-port lease records the owner's host, pid and process start time from the shared owner evidence in `src/codex/prompt-lock-owner.ts`. Reading that record, deciding it is stale, and publishing the new one all happen inside the claim mutex in `src/codex/prompt-lock-claim.ts`, so a record judged dead cannot be replaced by a live one before this runtime publishes. A live owner is never displaced — a second runtime refuses the socket and leaves it serving. A record from another machine, or one that cannot be parsed, is refused rather than treated as absent. A lease whose process is provably gone is a crashed predecessor, so its dead public link and private socket are replaced; any other file at the path is left alone and no socket is served. The run directory is registered with config ownership, so uninstall removes it. A path longer than `sun_path` in bytes is refused before anything is created, because a length in code units admits a non-ASCII home the kernel cannot bind. On shutdown the runtime gives the record up first, before it awaits its own socket teardown and before the other optional listeners shut down, so a successor that starts while that shutdown is still running is not blocked by a departing incumbent; it removes the public link only when that link is still the inode it published, because Bun's own stop unlinks the path it was given. A release that cannot take the claim mutex is retried, and if it still cannot run it is reported and retained on the listener, so the next stop or start finishes it instead of leaving a live lease nobody serves. `src/cli/link-local-control.ts` sends `ocx link status` there when the directory is still private and the socket is this user's, falls back to TCP only on a transport failure, and leaves an explicit base URL untouched. Windows has the socket too (#8998). There lstat refuses an AF_UNIX file with `EACCES`, so neither its type nor its owner can be read, and the directory boundary is a DACL. `windowsTrustedPath` therefore proves the path instead: the canonical path spells the same, every component is a real directory with no reparse point (lstat and the file attributes both checked), the run directory passes the `private-runtime-directory` ACL policy, the config home `write-private` and every ancestor `trusted-ancestry` (`src/lib/windows-owner-acl.ts`). The runtime checks the path above the run directory before it creates anything, creates and hardens the run directory with `hardenSecretDir`, and serves no socket unless the whole check then passes; a run directory that already exists without private permissions is refused and left as it is, because hardening it would make a socket or lease planted while it was open look trusted to the client, which then refuses the loose directory too; the CLI runs the same check before it sends the token and otherwise keeps TCP. No other account can change anything on such a path, so the path checked is the path connected. A Windows socket entry is one the directory lists and lstat refuses with `EACCES`; a file lstat can read is never treated as a socket. Without inode identity, a release unlinks the public link and the private name only inside the claim mutex while the lease still names this runtime's token, orphan cleanup matches the exact `.c.<8 hex>` name (never the lease), and a publication that fails removes the private name it bound before the lease goes, or keeps the lease and retries the release when it cannot. Only an already-absent lease counts as removed: a lease whose unlink fails fails the release, which is retained for the next stop or start. Same-user processes and administrators are inside the trust boundary, as for every other file in the config home. Coverage: `tests/server/local-control-socket.test.ts`, `tests/server/local-control-socket-windows.test.ts` (Windows hub cases; `OCX_TEST_WINDOWS_SOCKET_ROOT` names a trusted root where the default temp directory is shared). +The admin-token link routes require trusted loopback ingress. A runtime whose public listener is not bound to loopback has no TCP listener that qualifies, because the hub management listener is relayed by Tailscale Serve and must never confer that trust (#6913). `src/server/index/local-control-listener.ts` therefore opens a Unix socket at `/run/control-.sock` (`src/lib/local-control-socket.ts`) on macOS, Linux and Windows when the public bind is not loopback. Its ingress is `local-control`, the only non-TCP ingress, and `trustedLoopbackForIngress` treats it as trusted. The boundary is the filesystem: the directory is created or tightened to `0700`, must be a real directory owned by this user, and the socket is `0600`; a TCP relay or a forged header cannot produce the ingress, which is derived from the Bun server object. Before dispatch the listener admits only `GET /api/link/status` and answers 404 for anything else, and the request still needs the admin token. Two runtimes can share a home and a public port, so the public path is not the address Bun binds: it is a hard link to an instance-specific socket, and a per-port lease records the owner's host, pid and process start time from the shared owner evidence in `src/codex/prompt-lock-owner.ts`. Reading that record, deciding it is stale, and publishing the new one all happen inside the claim mutex in `src/codex/prompt-lock-claim.ts`, so a record judged dead cannot be replaced by a live one before this runtime publishes. A live owner is never displaced — a second runtime refuses the socket and leaves it serving. A record from another machine, or one that cannot be parsed, is refused rather than treated as absent. A lease whose process is provably gone is a crashed predecessor, so its dead public link and private socket are replaced; any other file at the path is left alone and no socket is served. The run directory is registered with config ownership, so uninstall removes it. A path longer than `sun_path` in bytes is refused before anything is created, because a length in code units admits a non-ASCII home the kernel cannot bind. On shutdown the runtime gives the record up first, before it awaits its own socket teardown and before the other optional listeners shut down, so a successor that starts while that shutdown is still running is not blocked by a departing incumbent; it removes the public link only when that link is still the inode it published, because Bun's own stop unlinks the path it was given. A release that cannot take the claim mutex is retried, and if it still cannot run it is reported and retained on the listener, so the next stop or start finishes it instead of leaving a live lease nobody serves. `src/cli/link-local-control.ts` sends `ocx link status` there when the directory is still private and the socket is this user's, falls back to TCP only on a transport failure, and leaves an explicit base URL untouched. Windows has the socket too (#8998). There lstat refuses an AF_UNIX file with `EACCES`, so neither its type nor its owner can be read, and the directory boundary is a DACL. `windowsTrustedPath` therefore proves the path instead: the canonical path spells the same, every component is a real directory with no reparse point (lstat and the file attributes both checked), the run directory passes the `private-runtime-directory` ACL policy, the config home `write-private` and every ancestor `trusted-ancestry` (`src/lib/windows-owner-acl.ts`). The runtime checks the path above the run directory before it creates anything, creates and hardens the run directory with `hardenSecretDir`, and serves no socket unless the whole check then passes; a run directory that already exists without private permissions is refused and left as it is, because hardening it would make a socket or lease planted while it was open look trusted to the client, which then refuses the loose directory too; the CLI runs the same check before it sends the token and otherwise keeps TCP. No other account can change anything on such a path, so the path checked is the path connected. A Windows socket entry is one the directory lists and lstat refuses with `EACCES`; a file lstat can read is never treated as a socket. Without inode identity, a release unlinks the public link and the private name only inside the claim mutex while the lease still names this runtime's token, orphan cleanup matches the exact `.c.<8 hex>` name (never the lease), and a publication that fails removes the private name it bound before the lease goes, or keeps the lease and retries the release when it cannot. Only an already-absent lease counts as removed: a lease whose unlink fails fails the release, which is retained for the next stop or start. Same-user processes and administrators are inside the trust boundary, as for every other file in the config home. On Windows endpoint ownership is not verified, because an AF_UNIX file reports no owner there: the client trusts a socket in a run directory that is private when it looks, and the runtime keeps that sound by creating the directory only under a write-private config home, whose inheritable grants admit no other account, and by refusing a directory that already existed without private permissions. Coverage: `tests/server/local-control-socket.test.ts`, `tests/server/local-control-socket-windows.test.ts` (Windows hub cases; `OCX_TEST_WINDOWS_SOCKET_ROOT` names a trusted root where the default temp directory is shared). A successful join restarts this proxy (a 503 drain of up to a minute while running turns finish, then a closed listener) into the client runtime on the configured port. `GET /api/link/status` tells a GUI-session caller whether it may join: the response gains `joinAvailable`, true only for a paired dashboard session on a standalone runtime whose live port is its configured port, and `joinDenied`, which is `null` when allowed or the first failed gate (`pairing_required`, `standalone_required`, then `join_port_mismatch`). On a Child whose durable connection diverges from its startup snapshot, link and machine status instead return `503 client_state_changed`, as does readiness; this reports the divergence without stopping or reconstructing the relay. An admin-token caller gets the exact K16 document without either field, because `ocx link status` validates it key by key. The dashboard reads an absent availability field as false and an absent or unknown denial as generic unavailability; while unavailable the Child role card cannot be selected by pointer or keyboard. A pairing refusal says to pair this machine first and offers code entry only on the existing same-origin literal-loopback transport. A port refusal instead asks the operator to restart on the configured port; neither status reads nor displaying this guidance mint a grant or change pairing, keys, routing, or runtime state. Before **Connect as Child** the confirmation panel says that the restart briefly interrupts Codex and that Codex keeps its local address. The dashboard reads the standalone's pid from same-origin `/healthz`, sends the join, then reads `/healthz` once a second, skipping status polls meanwhile, and reloads only when it reports `role: "client"` under another pid, so the reloaded document carries the client role and a fresh session. It never gives up by itself: past the server's own handoff budget (60 s drain plus 70 s replacement readiness, plus a margin: 145 seconds) it says the restart is slow and keeps reading `/healthz` every 5 seconds until the Child answers or the page is left. diff --git a/tests/server/local-control-socket-windows.test.ts b/tests/server/local-control-socket-windows.test.ts index 2bd7cb79c5c..7dbabdac95f 100644 --- a/tests/server/local-control-socket-windows.test.ts +++ b/tests/server/local-control-socket-windows.test.ts @@ -15,7 +15,7 @@ */ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { spawnSync } from "node:child_process"; -import { linkSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs"; +import { existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs"; import { homedir, tmpdir } from "node:os"; import { join } from "node:path"; import { saveConfig } from "../../src/config"; @@ -433,5 +433,44 @@ describe.skipIf(!windows || ROOT === null)("Windows hub with a non-loopback publ await listener.stop(); expect(portEntries(publicPort)).toEqual([]); }, SERVER_BUDGET_MS); + + test("a config home whose inheritable grants would let another account write gets no run directory", async () => { + // A new directory inherits its parent's grants before hardening runs, so the parent check + // has to refuse first: the run directory is never created where it could start out writable. + const grant = spawnSync(join(process.env.SystemRoot ?? "C:\\Windows", "System32", "icacls.exe"), + [process.env.OPENCODEX_HOME!, "/grant", "*S-1-1-0:(OI)(CI)(IO)M"], { encoding: "utf8" }); + expect(grant.status).toBe(0); + const publicPort = await findAvailablePort(0, "0.0.0.0"); + const listener = createLocalControlListener(); + listener.start({ config: { hostname: "0.0.0.0" } as OcxConfig, publicPort, dispatch: async () => Response.json({ ok: true }) }); + try { + expect(listener.socketPath()).toBeNull(); + expect(existsSync(localControlSocketDir())).toBe(false); + expect(usableLocalControlSocket(publicPort)).toBeNull(); + } finally { + await listener.stop(); + } + }, SERVER_BUDGET_MS); + + test("a run directory loosened after a runtime created it is refused at the next start and left loose", async () => { + const publicPort = await findAvailablePort(0, "0.0.0.0"); + const ctx = { config: { hostname: "0.0.0.0" } as OcxConfig, publicPort, dispatch: async () => Response.json({ ok: true }) }; + const first = createLocalControlListener(); + first.start(ctx); + expect(first.socketPath()).toBe(localControlSocketPath(publicPort)); + expect(windowsTrustedPath(localControlSocketDir())).toBe(true); + await first.stop(); + loosen(localControlSocketDir()); + const next = createLocalControlListener(); + next.start(ctx); + try { + expect(next.socketPath()).toBeNull(); + expect(windowsTrustedPath(localControlSocketDir())).toBe(false); + expect(portEntries(publicPort)).toEqual([]); + expect(usableLocalControlSocket(publicPort)).toBeNull(); + } finally { + await next.stop(); + } + }, SERVER_BUDGET_MS); });