The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Merge batch 11-02 aq: #2605 #2614 #2644 #2635 (#2649)
0xken15f81c67a70957
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 4b6bf6399..ac26f44c9 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -2722,7 +2722,14 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma&& stepOwner && stepOwner !== actor.agentId ? stepOwner: actor.kind === 'agent' && activeWork(group) && group.assignment?.agentId === actor.agentId&& group.leadId && group.leadId !== actor.agentId && group.agentIds.includes(group.leadId) ? group.leadId : null- const agentRecipient = leadToWorker ?? workerToLead+ // The task's owner talks to its step's agent the same way (Diego, 2026-11-02: an Engineer's "fixed, please re-check" in its+ // Review step woke the PM and the Reviewer never heard it). Its unnamed post there reaches that agent alone, never the+ // coordinator. A reply to someone else, or a post leadWorkerBounced holds back, falls back to the coordinator as before:+ // nothing is dropped.+ const ownerToStepAgent = actor.kind === 'agent' && isStep(group) && assigned && assigned !== actor.agentId+ && taskOwner(state, group) === actor.agentId && group.agentIds.includes(assigned) && (!context.reply || replyAgent === assigned)+ && !leadWorkerBounced(context.recent, actor.agentId, assigned) ? assigned : null+ const agentRecipient = leadToWorker ?? workerToLead ?? ownerToStepAgent// Any other agent's unnamed post in the group reaches its Lead: an agent whose task here was lost, moved or cancelled has// its status and results refused, so its posts are all the Lead hears from it. They reached no one until 10-29, when a// moved prod-watch agent's "the backend worker is down" alarm and its answers to the Lead's questions had no delivery,@@ -2738,7 +2745,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaconst stepTold = actor.kind === 'agent' && isStep(group) && actor.agentId !== group.leadId ? taskOwner(state, group) : nullconst ownerInStep = actor.kind === 'agent' && stepTold && stepTold !== actor.agentId ? stepTold : nullconst memberToLead = actor.kind === 'agent' && !command.agentOnly && !addressed.length && assigned !== actor.agentId && (ownerHere ?? ownerInStep) ? [(ownerHere ?? ownerInStep)!]- : actor.kind === 'agent' && !command.agentOnly && !addressed.length && assigned !== actor.agentId && group.leadId+ : actor.kind === 'agent' && !command.agentOnly && !addressed.length && assigned !== actor.agentId && !ownerToStepAgent && group.leadId&& group.leadId !== actor.agentId && group.agentIds.includes(group.leadId) ? [group.leadId] : []// Buddy thread sessions (buddySessions.ts): a session thread's replies reach its session alone and stay in its thread; the// main Buddy hears the rest. Decided here from the thread, so every client, an old one or the phone, is routed alike.diff --git a/backend/src/superTabs/steps.test.ts b/backend/src/superTabs/steps.test.tsindex 9a7154d1e..15d46c9a9 100644--- a/backend/src/superTabs/steps.test.ts+++ b/backend/src/superTabs/steps.test.ts@@ -4,7 +4,7 @@* readers show it inside its task. No step name means anything to the server.*/import { describe, expect, it } from 'vitest'-import { applyCommand, type Command, type CommandContext } from './commands.js'+import { applyCommand, PAIR_CHAIN_LIMIT, type Command, type CommandContext } from './commands.js'import { agent, createSuperTab, type Actor, type AgentConfiguration } from './model.js'import { extracted } from './parts/write.js'import { stepEndedRows, stepSleeps } from './steps.js'@@ -225,6 +225,34 @@ describe('who hears a step', () => {expect(to(post(f.task), f.task)).toEqual([[f.dev]])})+ // Diego, 2026-11-02: "Fixed in abc123, please re-check" from the Engineer woke the PM and the Reviewer never heard it.+ it('the owner\'s unnamed post in its active step reaches the step\'s agent only', () => {+ const { f, id, rev, post } = reviewing()+ expect(to(post(id, f.dev), id)).toEqual([[rev]])+ })++ it('the owner\'s post in its step naming the coordinator still reaches the coordinator', () => {+ const { f, id } = reviewing()+ const named = f.run({ type: 'message.send', conversationId: id, text: 'Need a ruling.', replyTo: null, recipientIds: [f.lead] } as Command, f.as(f.dev)).messages+ expect(to(named, id)).toEqual([[f.lead]])+ })++ // Cleo's review of #2635: nothing is dropped. Where the owner's post does not go to the step's agent, it falls back as before.+ it('the owner\'s unnamed post after the pair\'s loop guard stops still reaches the coordinator', () => {+ const { f, id, rev } = reviewing()+ const recent = Array.from({ length: PAIR_CHAIN_LIMIT }, (_, i) => ({ author: { kind: 'agent', id: i % 2 ? rev : f.dev } as never, recipients: [i % 2 ? f.dev : rev] }))+ const sent = f.run({ type: 'message.send', conversationId: id, text: 'Fixed, please re-check.', replyTo: null, recipientIds: [] } as Command, f.as(f.dev), { recent }).messages+ expect(to(sent, id)).toEqual([[f.lead]])+ })++ it('the owner\'s unnamed reply to someone else in its step still reaches the coordinator', () => {+ const { f, id } = reviewing()+ const asked = f.run({ type: 'message.send', conversationId: id, text: 'Status?', replyTo: null, recipientIds: [f.dev] } as Command, f.as(f.lead)).messages[0]!+ const answer = f.run({ type: 'message.send', conversationId: id, text: 'Almost.', replyTo: asked.id, recipientIds: [] } as Command, f.as(f.dev),+ { reply: { id: asked.id, conversationId: id, author: asked.author, createdAt: 0 } }).messages+ expect(to(answer, id)).toEqual([[f.lead]])+ })+it('an agent with no open step in the task still reaches the coordinator', () => {const { f, post } = reviewing()const other = f.add('other', f.task)diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjsindex c4f616c85..7e1472a2c 100644--- a/cli/hook/notify.mjs+++ b/cli/hook/notify.mjs@@ -16,7 +16,7 @@import http from 'node:http'import { execFile, execFileSync } from 'node:child_process'-import { createHash, randomUUID } from 'node:crypto'+import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto'import {accessSync,closeSync,@@ -315,28 +315,81 @@ function daemonSocket(port, dataDir) {return null}+/** Mirrors LOCAL_PIPE_RE in src/lib/windows/pipeAuth.ts: a pipe on this computer named harness-<id>, nothing else. A+ * file, or another computer's pipe (an SMB connection that can carry this user's NTLM credentials), is none. */+const LOCAL_PIPE_RE = /^\\\\\.\\pipe\\harness-([0-9a-f]{32})$/+/** Mirrors TOKEN_TEXT in src/lib/windows/pipeAuth.ts. */+const DAEMON_TOKEN_RE = /^[0-9a-f]{64}\n?$/++/**+ * The record's daemon still runs. Once it is gone, any account can create a pipe of the recorded name, and would hear+ * this request, the prompt in it, before its answer can fail the proof. The daemon is this account's, so a pid that+ * answers EPERM is another account's process now, one that took the pid since: no daemon (Quinn 2's review of #2605).+ * Unlike processProof.ts pidAlive, which counts it alive for callers that also read the process table.+ */+function pidRuns(pid) {+ try { process.kill(pid, 0); return true } catch { return false }+}++/**+ * The daemon's pipe on Windows, as the CLI finds it (src/lib/windows/daemonPipe.ts): the record the core writes,+ * `daemon-<configured port>.json`, names the pipe and the core's pid, both new on each start. This hook's port may be the+ * one the daemon was given instead, so the records say which. Null with no record of a local pipe, no token, or a core+ * that has exited. The pipe auth (src/lib/windows/pipeAuth.ts) proves the token without sending it, and the answer must+ * prove it back.+ */+function windowsDaemonPipe(port, dataDir) {+ const read = (name) => { try { return JSON.parse(readWindowsStateFile(dataDir, join(dataDir, name), 4096)) } catch { return null } }+ let record = read(`daemon-${port}.json`)+ if (!record) {+ try {+ for (const name of readdirSync(dataDir)) {+ if (!/^daemon-\d+\.json$/.test(name)) continue+ const candidate = read(name)+ if (candidate?.port === port) { record = candidate; break }+ }+ } catch { /* An unreadable folder has no record to offer. */ }+ }+ const id = typeof record?.pipe === 'string' ? LOCAL_PIPE_RE.exec(record.pipe)?.[1] : null+ if (!id || !Number.isSafeInteger(record.pid) || record.pid <= 0 || !pidRuns(record.pid)) return null+ let text = ''+ try { text = readWindowsStateFile(dataDir, join(dataDir, 'daemon-token'), 128) } catch { return null }+ if (!DAEMON_TOKEN_RE.test(text)) return null+ const token = Buffer.from(text.slice(0, 64), 'hex')+ const nonce = id + randomBytes(16).toString('hex')+ const mac = (separator) => createHmac('sha256', token).update(Buffer.of(separator)).update(nonce, 'utf8').digest('hex')+ const proof = Buffer.from(mac(0x00), 'hex')+ return {+ address: { socketPath: record.pipe },+ headers: { 'X-Harness-Auth': `${nonce}.${mac(0x01)}` },+ proven: (value) => typeof value === 'string' && /^[0-9a-f]{64}$/.test(value) && timingSafeEqual(Buffer.from(value, 'hex'), proof),+ }+}+/*** How this hook reaches the daemon, and what it shows. Any account can bind the TCP port while the daemon restarts (audit* H1, docs/security/2026-11-02-team-account-boundary.md), and whoever holds it would hear this request, the user's* prompt in it included. So on macOS and Linux it goes over the 0600 socket; with none there the daemon is down, and- * this is the same as a failed post. A data folder too long to hold a socket has one under the home folder (socketIn). A home too long as well is the one case with no way but TCP, and- * then the hook-only token goes, never the credential. Over the socket the credential still goes because a daemon from- * before the hook token (an update not yet handed over) checks it there. Windows is unchanged.+ * this is the same as a failed post. A data folder too long to hold a socket has one under the home folder (socketIn). A+ * home too long as well is the one case with no way but TCP, and then the hook-only token goes, never the credential. Over the socket the credential still goes because a daemon from+ * before the hook token (an update not yet handed over) checks it there. On Windows it goes over the daemon's pipe, and+ * never to the port: the Team account's daemon starts at boot, before the owner's, and could hold it (audit W1,+ * docs/security/2026-11-02-team-account-windows.md).*/function hookRoute(port) {const dataDir = paths().dataDir- if (process.platform === 'win32') return { address: { host: '127.0.0.1', port }, token: readHookCredential() }- if (!socketIn(dataDir, port)) return { address: { host: '127.0.0.1', port }, token: readHookCredential('hook-token') }+ if (process.platform === 'win32') return windowsDaemonPipe(port, dataDir)+ const tokenRoute = (address, token) => token ? { address, headers: { 'X-Harness-Hook-Token': token } } : null+ if (!socketIn(dataDir, port)) return tokenRoute({ host: '127.0.0.1', port }, readHookCredential('hook-token'))const socketPath = daemonSocket(port, dataDir)- return socketPath ? { address: { socketPath }, token: readHookCredential() } : null+ return socketPath ? tokenRoute({ socketPath }, readHookCredential()) : null}function post(port, path, body, onResponse) {return new Promise((resolve) => {const payload = JSON.stringify(body)const route = hookRoute(port)- const credential = route?.token- if (!credential) { resolve(false); return }+ if (!route) { resolve(false); return }let connected = falseconst req = http.request({@@ -346,7 +399,7 @@ function post(port, path, body, onResponse) {headers: {'Content-Type': 'application/json','Content-Length': Buffer.byteLength(payload),- 'X-Harness-Hook-Token': credential,+ ...route.headers,// When the engine ran this hook: this process's start, not its arrival, which can be seconds later on// a loaded machine, after the engine has moved on to its next prompt (src/hookServer.ts hookFiredAt).'X-Harness-Hook-Fired-At': String(FIRED_AT),@@ -355,6 +408,9 @@ function post(port, path, body, onResponse) {timeout: Math.max(1, Math.min(500, remainingBudget())),},(res) => {+ // Before the body is read: an answer on the pipe without the daemon's proof is whatever took its name, not the+ // daemon, and is never taken (src/lib/windows/pipeClient.ts pipeRequest).+ if (route.proven && !route.proven(res.headers['x-harness-proof'])) { resolve(false); req.destroy(); return }let response = ''res.setEncoding('utf8')res.on('data', (chunk) => { if (response.length < 16_384) response += chunk })@@ -455,7 +511,10 @@ function readHookCredential(name = 'hook-credential') {let fd = nulltry {const dataDir = paths().dataDir- if (process.platform === 'win32') return readWindowsHookCredential(dataDir, join(dataDir, name))+ if (process.platform === 'win32') {+ const value = readWindowsStateFile(dataDir, join(dataDir, name), 128).trim()+ return /^[A-Za-z0-9_-]{43}$/.test(value) ? value : ''+ }secureStateDirectory(dataDir, false)const uid = typeof process.getuid === 'function' ? process.getuid() : nullconst file = join(dataDir, name)@@ -472,26 +531,26 @@ function readHookCredential(name = 'hook-credential') {/*** NTFS gives Node no owner or mode bits, so on Windows the hook trusts its own data folder (the --data-dir it was- * installed with) and the profile. Below the data folder, the credential must be a plain file, not a link or- * junction (lstat does not call one a file): that check is what protects it. Its real path must also lie inside the- * profile or the data folder, as defence in depth. The file is opened and must be the very file lstat saw, so it- * cannot be swapped between the check and the read.+ * installed with) and the profile. Below the data folder, a state file (the credential, the daemon's token and record)+ * must be a plain file, not a link or junction (lstat does not call one a file): that check is what protects it. Its+ * real path must also lie inside the profile or the data folder, as defence in depth. The file is opened and must be the+ * very file lstat saw, so it cannot be swapped between the check and the read. Throws when there is none; '' when it is+ * refused.*/-function readWindowsHookCredential(dataDir, file) {+function readWindowsStateFile(dataDir, file, maxBytes) {const roots = [homedir(), dataDir].flatMap((root) => { try { return [realpathSync.native(root)] } catch { return [] } })const inside = (target) => roots.some((root) => {const rel = win32.relative(root, target)return rel === '' || (rel !== '..' && !rel.startsWith('..\\') && !win32.isAbsolute(rel))})const link = lstatSync(file, { bigint: true })- if (!link.isFile() || link.size > 128n || !inside(realpathSync.native(file))) return ''+ if (!link.isFile() || link.size > BigInt(maxBytes) || !inside(realpathSync.native(file))) return ''let fd = nulltry {fd = openSync(file, 'r')const opened = fstatSync(fd, { bigint: true })if (!opened.isFile() || opened.dev !== link.dev || opened.ino !== link.ino) return ''- const value = readFileSync(fd, 'utf8').trim()- return /^[A-Za-z0-9_-]{43}$/.test(value) ? value : ''+ return readFileSync(fd, 'utf8')} finally {if (fd !== null) closeSync(fd)}diff --git a/cli/scripts/windows-ci/check-install.ps1 b/cli/scripts/windows-ci/check-install.ps1index 4badea9fb..0380f8cfe 100644--- a/cli/scripts/windows-ci/check-install.ps1+++ b/cli/scripts/windows-ci/check-install.ps1@@ -136,3 +136,11 @@ if (-not @($mine | Where-Object { $_.ProcessName -eq 'node' }).Count) { Fail "no$slow = @($mine | Where-Object { "$($_.PriorityClass)" -ne 'Normal' })if ($slow.Count) { Fail "not at normal priority: $(($slow | ForEach-Object { "$($_.ProcessName) $($_.Id) $($_.PriorityClass)" }) -join ', ')" }Write-Host "ok priority Normal for $($mine.Count) process(es): $(($mine | ForEach-Object { "$($_.ProcessName) $($_.Id)" }) -join ', ')"+# The Store packages against this daemon (task #2161, audit W1): each reaches it over its named pipe with the pipe auth, and+# never its TCP port, which the Team account's daemon can hold from boot. From a checkout, which has them beside this script.+$storePipe = Join-Path $PSScriptRoot '..\..\..\store\tools\windows-ci\store-pipe.mjs'+if (Test-Path -LiteralPath $storePipe) {+ & node $storePipe+ if ($LASTEXITCODE -ne 0) { Fail "a Store package did not reach the daemon over its pipe ($storePipe printed why above)" }+ Write-Host "ok the Store packages reach the daemon over its pipe"+} else { Write-Host "skip the Store packages: no checkout of store\ beside this script" }diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex ac4e01d85..500782353 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -72,7 +72,6 @@ import { remoteCommand } from './remoteCommand.js'import { tuiCommand } from './tui/index.js'import { machineChoices, newCommand, type MachineRow, type NewMachine } from './lib/newCommand.js'import { gridSetupCommand } from './lib/gridSetupCommand.js'-import { localCredentialHeaders } from './lib/localCredential.js'import { WebSocket as NewCommandSocket } from 'ws'import { describeMasterStatus, readStatusFile } from './harnessd/master.js'import { namedNode } from './harnessd/processName.js'@@ -2955,7 +2954,7 @@ switch (cmd) {port: daemonPort(),localMachineId: wantedDaemonIdentity(),daemonRunning: isDaemonRunning, unreachable: () => daemonUnreachableText(),- connect: (url) => new NewCommandSocket(url, { headers: localCredentialHeaders(env.ADAPTER_DATA_DIR) }),+ connect: (url, headers) => new NewCommandSocket(url, { headers }),output: (line) => console.log(line),error: (line) => console.error(line),}).then((code) => { process.exitCode = code }).catch(onError)@@ -2990,7 +2989,7 @@ switch (cmd) {localMachineId: wantedDaemonIdentity(),daemonRunning: isDaemonRunning, unreachable: () => daemonUnreachableText(),listMachines: usableMachines,- connect: (url) => new NewCommandSocket(url, { headers: localCredentialHeaders(env.ADAPTER_DATA_DIR) }),+ connect: (url, headers) => new NewCommandSocket(url, { headers }),output: (line) => console.log(line),error: (line) => console.error(line),origin: () => agentOrigin(),diff --git a/cli/src/devices/client.ts b/cli/src/devices/client.tsindex 2be5e0100..203d22c74 100644--- a/cli/src/devices/client.ts+++ b/cli/src/devices/client.ts@@ -2,7 +2,7 @@import { randomUUID } from 'node:crypto'import { env } from '../config/env.js'import { localCredentialHeaders } from '../lib/localCredential.js'-import { daemonFetch, localWsTarget } from '../lib/localTransport.js'+import { daemonFetch, openLocalWs } from '../lib/localTransport.js'import type { ClientSocket } from '../lib/clientSocket.js'import { deviceSettingsPatchSchema } from '../lib/harnessDevices.js'@@ -22,8 +22,7 @@ export interface DevicesClientDeps {export function deviceRequest(deps: DevicesClientDeps, machineId: string, type: string, payload: Record<string, unknown> = {}): Promise<Record<string, unknown>> {return new Promise((resolve, reject) => {- const line = localWsTarget(deps.dataDir ?? env.ADAPTER_DATA_DIR, deps.port)- const socket = deps.connect(line.url, line.headers)+ const socket = openLocalWs(deps.dataDir ?? env.ADAPTER_DATA_DIR, deps.port, deps.connect)const requestId = randomUUID()let settled = false, sent = falseconst finish = (error: Error | null, reply?: Record<string, unknown>): void => {diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.tsindex aff75e31e..7c75f7dcd 100644--- a/cli/src/hookNotify.spec.ts+++ b/cli/src/hookNotify.spec.ts@@ -1,4 +1,5 @@import { execFileSync, spawn, spawnSync } from 'child_process'+import { randomBytes } from 'crypto'import { createServer } from 'http'import { connect as netConnect, createServer as createNetServer } from 'net'import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'fs'@@ -9,6 +10,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'import { ENGINES } from './engines/types.js'import { HARNESS_OWNER_OPTION, HARNESS_SESSION_PREFIX, harnessPaneOwner, ownerCommand, paneOwnerFormat } from './lib/harnessSessionLabel.js'import { hookRouteFile, publishHookRoute } from './lib/hookRoutes.js'+import { isTrustedLocal, listenLocalSocket } from './lib/localSocket.js'// Every case here spawns the real hook as a child process, and several spawn shell shims for tmux, ps// and sqlite3 on top of that. On a loaded machine — this file runs alongside 88 others — that chain@@ -22,6 +24,13 @@ const CLOCK_SHIFT = fileURLToPath(new URL('../e2e/harness/clockShift.mjs', imporconst servers: ReturnType<typeof createServer>[] = []const netServers: ReturnType<typeof createNetServer>[] = []const tmpDirs: string[] = []+/** The daemon's pipe servers of the Windows cases, each closed with its own close. */+const pipeServers: Array<() => Promise<void>> = []++/** A pid that ran and has exited: a daemon that is gone. */+function exitedPid(): number {+ return spawnSync(process.execPath, ['-e', '']).pid!+}function writeLegacyStateFile(path: string, value: string): void {writeFileSync(path, value, { mode: 0o644 })@@ -31,6 +40,7 @@ function writeLegacyStateFile(path: string, value: string): void {afterEach(async () => {await Promise.all(servers.splice(0).map((server) => new Promise<void>((resolve) => server.close(() => resolve()))))await Promise.all(netServers.splice(0).map((server) => new Promise<void>((resolve) => server.close(() => resolve()))))+ await Promise.all(pipeServers.splice(0).map((close) => close()))for (const dir of tmpDirs.splice(0)) rmSync(dir, { recursive: true, force: true })})@@ -1957,37 +1967,145 @@ describe('hook notify in a Harness pty host pane (Windows)', () => {await runHook({ port: empty.port, env: { HARNESS_PANE: '' }, input: sessionStart() })expect(empty.requests).toEqual([])})+})- it('reads its credential on Windows, where NTFS reports no owner and no private mode', async () => {- const dataDir = mkdtempSync(join(tmpdir(), 'adapter-hook-win-')); tmpDirs.push(dataDir)- writeFileSync(join(dataDir, 'hook-credential'), `${'b'.repeat(43)}\n`, { mode: 0o644 })- const preload = join(dataDir, 'win32.mjs')- writeFileSync(preload, "Object.defineProperty(process, 'platform', { value: 'win32' })\n")- const { port, requests } = await collect({}, 'b'.repeat(43))- await runHook({ port, dataDir, env: { HARNESS_PANE: 'p1:%1', NODE_OPTIONS: `--import ${pathToFileURL(preload).href}` }, input: sessionStart() })+/**+ * Audit W1 (docs/security/2026-11-02-team-account-windows.md): on Windows the hook posted the full local credential to+ * the daemon's TCP port, which the Team account's daemon can hold from boot. It now posts over the daemon's pipe, proving+ * the daemon's token, and with no live pipe it posts nothing, as on macOS with no socket. Node on a Mac cannot open a+ * Windows pipe, so a preload sets the platform to win32 and dials a Unix socket named for the pipe's id instead.+ */+describe('hook notify posts over the daemon\'s pipe on Windows (W1)', () => {+ const sessionStart = () => {+ const recordings = JSON.parse(readFileSync(new URL('./lib/__fixtures__/swarm-prompt-hooks.json', import.meta.url), 'utf8'))+ return { ...recordings.claude.input, hook_event_name: 'SessionStart' }+ }++ /** A data folder short enough for a socket, with the daemon's token, and a preload that runs the hook as on Windows. */+ function windowsData(): { dataDir: string; token: Buffer; id: string; socket: string; preload: string } {+ const dataDir = mkdtempSync('/tmp/hkp-'); tmpDirs.push(dataDir)+ const token = randomBytes(32), id = randomBytes(16).toString('hex')+ writeFileSync(join(dataDir, 'daemon-token'), `${token.toString('hex')}\n`, { mode: 0o644 })+ const preload = join(dataDir, 'win32-pipe.mjs')+ writeFileSync(preload, [+ "import http from 'node:http'",+ "Object.defineProperty(process, 'platform', { value: 'win32' })",+ 'const dial = http.Agent.prototype.createConnection',+ 'http.Agent.prototype.createConnection = function (options, ...rest) {',+ // Any name ending in harness-<id>, local pipe or not: the hook's own check is what refuses one.+ ' const id = /harness-([0-9a-f]{32})$/.exec(options.socketPath ?? "")?.[1]',+ ` const socket = id && ${JSON.stringify(dataDir)} + '/harness-' + id`,+ ' return dial.call(this, socket ? { ...options, socketPath: socket, path: socket } : options, ...rest)',+ '}',+ ].join('\n') + '\n')+ return { dataDir, token, id, socket: join(dataDir, `harness-${id}`), preload }+ }++ function record(dataDir: string, port: number, fields: Record<string, unknown>): void {+ writeFileSync(join(dataDir, `daemon-${port}.json`), JSON.stringify({ port, ...fields }) + '\n', { mode: 0o644 })+ }++ /** The daemon's pipe server, as the daemon serves it (lib/localSocket.ts): every request proves the token. */+ async function pipeDaemon(socket: string, token: Buffer, answer: (res: import('http').ServerResponse) => void = (res) => res.end('{}')) {+ const requests: Array<{ url: string; trusted: boolean; hookToken: unknown; credential: unknown }> = []+ const server = await listenLocalSocket((req, res) => {+ req.resume()+ req.on('end', () => {+ requests.push({ url: req.url ?? '', trusted: isTrustedLocal(req), hookToken: req.headers['x-harness-hook-token'], credential: req.headers['x-harness-local'] })+ answer(res)+ })+ }, socket, { token })+ pipeServers.push(server.close)+ return requests+ }++ const run = (port: number, dataDir: string, preload: string, extra: Partial<RunHookOpts> = {}) =>+ runHook({ port, dataDir, env: { HARNESS_PANE: 'p1:%1', NODE_OPTIONS: `--import ${pathToFileURL(preload).href}` }, input: sessionStart(), ...extra })++ it('posts over the daemon\'s pipe, with the pipe auth and no credential, and nothing to the port', async () => {+ const { dataDir, token, id, socket, preload } = windowsData()+ const tcp = await collect()+ record(dataDir, tcp.port, { pipe: `\\\\.\\pipe\\harness-${id}`, pid: process.pid })+ const requests = await pipeDaemon(socket, token)+ await run(tcp.port, dataDir, preload)+ expect(requests).toEqual([{ url: '/api/hook/session-start', trusted: true, hookToken: undefined, credential: undefined }])+ expect(tcp.requests).toEqual([])+ })++ it('finds the daemon by its record when the hook was given the port it bound, not the one it was configured with', async () => {+ const { dataDir, token, id, socket, preload } = windowsData()+ const tcp = await collect()+ writeFileSync(join(dataDir, 'daemon-18473.json'), JSON.stringify({ port: tcp.port, pipe: `\\\\.\\pipe\\harness-${id}`, pid: process.pid }))+ const requests = await pipeDaemon(socket, token)+ await run(tcp.port, dataDir, preload)expect(requests.map((request) => request.url)).toEqual(['/api/hook/session-start'])+ expect(tcp.requests).toEqual([])})- it('refuses a linked credential on Windows', async () => {- const dataDir = mkdtempSync(join(tmpdir(), 'adapter-hook-win-')); tmpDirs.push(dataDir)- const elsewhere = mkdtempSync(join(tmpdir(), 'adapter-hook-other-')); tmpDirs.push(elsewhere)- writeFileSync(join(elsewhere, 'token'), `${'b'.repeat(43)}\n`)- symlinkSync(join(elsewhere, 'token'), join(dataDir, 'hook-credential'))- const preload = join(dataDir, 'win32.mjs')- writeFileSync(preload, "Object.defineProperty(process, 'platform', { value: 'win32' })\n")- const { port, requests } = await collect({}, 'b'.repeat(43))- await runHook({ port, dataDir, env: { HARNESS_PANE: 'p1:%1', NODE_OPTIONS: `--import ${pathToFileURL(preload).href}` }, input: sessionStart() })+ it.each([+ ['no record', () => undefined],+ ['a record with no pipe', () => ({ pid: process.pid })],+ ['a record with no pid', (id: string) => ({ pipe: `\\\\.\\pipe\\harness-${id}` })],+ ['a pipe on another computer', (id: string) => ({ pipe: `\\\\fileserver\\pipe\\harness-${id}`, pid: process.pid })],+ ['a file named as a pipe', (id: string) => ({ pipe: `C:\\Users\\Public\\harness-${id}`, pid: process.pid })],+ ['a daemon that has exited', (id: string) => ({ pipe: `\\\\.\\pipe\\harness-${id}`, pid: exitedPid() })],+ // The daemon is this account's: a pid another account runs (EPERM; pid 1 is root's) is one reused since it exited,+ // and whoever has it may have created the pipe of the recorded name (Quinn 2's review of #2605).+ ...(process.getuid?.() === 0 ? [] : [['a pid another account runs now', (id: string) => ({ pipe: `\\\\.\\pipe\\harness-${id}`, pid: 1 })] as const]),+ ] as const)('posts nothing, to the pipe or the port, with %s', async (_name, fields) => {+ const { dataDir, token, id, socket, preload } = windowsData()+ const tcp = await collect()+ const value = fields(id)+ if (value) record(dataDir, tcp.port, value)+ const requests = await pipeDaemon(socket, token)+ await run(tcp.port, dataDir, preload)+ expect(requests).toEqual([])+ expect(tcp.requests).toEqual([])+ })++ it.each(['missing', 'linked', 'not a token'] as const)('posts nothing, to the pipe or the port, when the daemon\'s token is %s', async (fault) => {+ const { dataDir, token, id, socket, preload } = windowsData()+ const tcp = await collect()+ record(dataDir, tcp.port, { pipe: `\\\\.\\pipe\\harness-${id}`, pid: process.pid })+ rmSync(join(dataDir, 'daemon-token'))+ if (fault === 'linked') {+ // A link is refused even to a token file inside the data folder: NTFS gives the hook no owner to check.+ writeFileSync(join(dataDir, 'token'), `${token.toString('hex')}\n`)+ symlinkSync(join(dataDir, 'token'), join(dataDir, 'daemon-token'))+ }+ if (fault === 'not a token') writeFileSync(join(dataDir, 'daemon-token'), `${token.toString('hex').toUpperCase()}\n`)+ const requests = await pipeDaemon(socket, token)+ await run(tcp.port, dataDir, preload)expect(requests).toEqual([])+ expect(tcp.requests).toEqual([])})- it('refuses a credential that links to a file inside the data folder: the link itself is refused', async () => {- const dataDir = mkdtempSync(join(tmpdir(), 'adapter-hook-win-')); tmpDirs.push(dataDir)- writeFileSync(join(dataDir, 'token'), `${'b'.repeat(43)}\n`)- symlinkSync(join(dataDir, 'token'), join(dataDir, 'hook-credential'))- const preload = join(dataDir, 'win32.mjs')- writeFileSync(preload, "Object.defineProperty(process, 'platform', { value: 'win32' })\n")- const { port, requests } = await collect({}, 'b'.repeat(43))- await runHook({ port, dataDir, env: { HARNESS_PANE: 'p1:%1', NODE_OPTIONS: `--import ${pathToFileURL(preload).href}` }, input: sessionStart() })- expect(requests).toEqual([])+ // What the hook does with an answer: a held Hermes admission is retried (four posts in all). Whatever answers on the+ // pipe without the daemon's proof is not the daemon, and its answer is not taken: one post, then the hook moves on.+ it.each([['the daemon\'s proof', 4], ['a wrong proof', 1]] as const)('takes an answer only with the daemon\'s proof: %s', async (proof, posts) => {+ const { dataDir, token, id, socket, preload } = windowsData()+ const tcp = await collect()+ record(dataDir, tcp.port, { pipe: `\\\\.\\pipe\\harness-${id}`, pid: process.pid })+ const held = (res: import('http').ServerResponse) => { res.writeHead(202); res.end(JSON.stringify({ pending: false, retry: true })) }+ let attempts = 0+ if (proof === 'a wrong proof') {+ const impostor = createServer((req, res) => {+ req.resume()+ req.on('end', () => { attempts++; res.setHeader('x-harness-proof', 'a'.repeat(64)); held(res) })+ })+ servers.push(impostor)+ await new Promise<void>((resolve) => { impostor.listen(socket, resolve) })+ } else {+ const requests = await pipeDaemon(socket, token, (res) => { attempts++; held(res) })+ void requests+ }+ await run(tcp.port, dataDir, preload, {+ tmuxPane: '%82', engine: 'hermes', processEngine: 'hermes', windowsProcessTable: true,+ processExecutable: 'python3', processArgs: 'python3 /opt/venvs/hermes/lib/python3.12/site-packages/hermes-agent/hermes',+ hermesHome: join(dataDir, 'hermes'), hermesSource: 'cli',+ input: { hook_event_name: 'on_session_start', session_id: '20260810_120000_a1b2c3' },+ })+ expect(attempts).toBe(posts)+ expect(tcp.requests).toEqual([])})})diff --git a/cli/src/lib/daemonEndpoint.spec.ts b/cli/src/lib/daemonEndpoint.spec.tsindex bbbb5e467..8a12eb133 100644--- a/cli/src/lib/daemonEndpoint.spec.ts+++ b/cli/src/lib/daemonEndpoint.spec.ts@@ -7,6 +7,7 @@ import { loadOrCreateHookCredential } from './hookAuth.js'import { legacyDaemonStatus, localDaemonCall, localDaemonStatus, saveDaemonPort, savedDaemonPort } from './daemonEndpoint.js'import { readDaemonRecord } from './daemonRecord.js'import { listenLocalSocket, localSocketPath } from './localSocket.js'+import type { PipeTarget } from './windows/pipeClient.js'// A folder too long for a socket now has one under the home folder: only a home too long as well is left on the port.beforeEach(() => { vi.stubEnv('HOME', `/${'h'.repeat(120)}`) })@@ -135,23 +136,21 @@ describe('per-user daemon discovery', () => {expect(seen).toEqual([credential, undefined])})- it("shows this user's credential when a Windows control call falls back to TCP", async () => {+ // Audit W1 (docs/security/2026-11-02-team-account-windows.md): it fell back to the port with this user's credential, and+ // the Team account's daemon, started at boot, can hold that port.+ it.each([+ ['no pipe', async (): Promise<PipeTarget | null> => null],+ ['nothing listening on the pipe', async (): Promise<PipeTarget | null> => ({ pipe: join(directory(), `harness-${'0'.repeat(32)}`), token: Buffer.alloc(32, 1) })],+ ] as const)('never tries the port on Windows: with %s it fails as a daemon that is down', async (_name, pipe) => {const dataDir = directory()- const credential = loadOrCreateHookCredential(dataDir)- let seen: string | null = null- const response = await localDaemonCall(dataDir, 19418, 'POST', '/api/pair', { code: 'one-use' }, {- platform: 'win32',- pipe: async () => null,- tcpPort: 24567,- fetch: async (url, init) => {- expect(String(url)).toBe('http://127.0.0.1:24567/api/pair')- const headers = new Headers(init?.headers)- expect(headers.get('x-adapter-local')).toBe('1')- seen = headers.get('x-harness-local')- return new Response('{}', { status: 200 })- },- })- expect(response.ok).toBe(true)- expect(seen).toBe(credential)+ loadOrCreateHookCredential(dataDir)+ let called = false+ const failed = await localDaemonCall(dataDir, 19418, 'POST', '/api/pair', { code: 'one-use' }, {+ platform: 'win32', pipe, tcpPort: 24567,+ fetch: async () => { called = true; return new Response('{}', { status: 200 }) },+ }).catch((error: unknown) => error)+ expect(failed).toBeInstanceOf(TypeError)+ expect((failed as TypeError).message).toBe('fetch failed')+ expect(called).toBe(false)})})diff --git a/cli/src/lib/daemonEndpoint.ts b/cli/src/lib/daemonEndpoint.tsindex 653841ba1..f2c505d89 100644--- a/cli/src/lib/daemonEndpoint.ts+++ b/cli/src/lib/daemonEndpoint.ts@@ -1,7 +1,7 @@import { request } from 'node:http'import { lstatSync } from 'node:fs'import { localCredentialHeaders } from './localCredential.js'-import { daemonFetch } from './localTransport.js'+import { daemonFetch, notThere } from './localTransport.js'import { localSocketPath } from './localSocket.js'import { readDaemonRecord, writeDaemonRecord, type DaemonPipeRecord } from './daemonRecord.js'import { daemonPipe, type LocalDaemonOptions } from './windows/daemonPipe.js'@@ -72,9 +72,10 @@ const NULL_BODY = new Set([204, 205, 304])/*** A control call to the running daemon (cli.ts `daemonCall`: `harness pair`, `harness devices`, …). On Windows it- * goes over the daemon's pipe when there is one, and only an answer that proves the token is taken. It falls back- * to loopback TCP when there is nothing to reach: no record, a daemon proven gone, or nothing listening. On macOS and- * Linux it goes over the daemon's private socket, and never the port while a socket can exist (lib/localTransport.ts).+ * goes over the daemon's pipe, and only an answer that proves the token is taken. With nothing to reach there (no+ * record, a daemon proven gone, or nothing listening) it fails as a daemon that is down, and never tries the port:+ * the Team account's daemon may hold it (audit W1). On macOS and Linux it goes over the daemon's private socket, and+ * never the port while a socket can exist (lib/localTransport.ts).* A pipe that answers without the proof is not retried over TCP: whatever answered took the* daemon's name, and the caller is told so.*/@@ -86,15 +87,14 @@ export async function localDaemonCall(const text = body ? JSON.stringify(body) : undefinedif ((options.platform ?? process.platform) === 'win32') {const target = await (options.pipe ?? daemonPipe)(dataDir, configuredPort)- if (target) {- try {- const reply = await pipeRequest(target, { method, path, headers, body: text, timeoutMs: 60_000 })- const type = reply.headers['content-type']- return new Response(NULL_BODY.has(reply.status) ? null : reply.body,- { status: reply.status, headers: typeof type === 'string' ? { 'content-type': type } : {} })- } catch (error) {- if (!pipeAbsent(error)) throw error- }+ if (!target) throw notThere()+ try {+ const reply = await pipeRequest(target, { method, path, headers, body: text, timeoutMs: 60_000 })+ const type = reply.headers['content-type']+ return new Response(NULL_BODY.has(reply.status) ? null : reply.body,+ { status: reply.status, headers: typeof type === 'string' ? { 'content-type': type } : {} })+ } catch (error) {+ throw pipeAbsent(error) ? Object.assign(new TypeError('fetch failed'), { cause: error }) : error}}return (options.fetch ?? daemonFetch(dataDir, configuredPort, fetch, options.platform))(`http://127.0.0.1:${options.tcpPort}${path}`, {diff --git a/cli/src/lib/localCredential.spec.ts b/cli/src/lib/localCredential.spec.tsindex 4e0c710c4..37fb7bfa0 100644--- a/cli/src/lib/localCredential.spec.ts+++ b/cli/src/lib/localCredential.spec.ts@@ -3,7 +3,7 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, describe, expect, it } from 'vitest'import { hookCredentialPath, loadOrCreateHookCredential } from './hookAuth.js'-import { LOCAL_CREDENTIAL_HEADER, localCredentialHeaders, localCredentialMatches, readLocalCredential, suppliedLocalCredential } from './localCredential.js'+import { localCredentialHeaders, localCredentialMatches, readLocalCredential, suppliedLocalCredential } from './localCredential.js'const dirs: string[] = []afterEach(() => dirs.splice(0).forEach((dir) => rmSync(dir, { recursive: true, force: true })))@@ -14,12 +14,12 @@ function dataDir(): string {}describe('the daemon\'s local credential', () => {- it('is the hook credential, sent as X-Harness-Local by a process that can read it', () => {+ it('is the hook credential, read by a process that can read it, and put on no request on Windows', () => {const dir = dataDir()const credential = loadOrCreateHookCredential(dir)expect(readLocalCredential(dir)).toBe(credential)- // Windows, whose rules are its callers'. On macOS and Linux see team/localCredential.spec.ts.- expect(localCredentialHeaders(dir, 'win32')).toEqual({ [LOCAL_CREDENTIAL_HEADER]: credential })+ // Windows clients use the daemon's pipe (audit W1). On macOS and Linux see team/localCredential.spec.ts.+ expect(localCredentialHeaders(dir, 'win32')).toEqual({})})it('adds no header when there is no credential to read, or one another user could have written', () => {diff --git a/cli/src/lib/localCredential.ts b/cli/src/lib/localCredential.tsindex df0beaa88..cbcf4da69 100644--- a/cli/src/lib/localCredential.ts+++ b/cli/src/lib/localCredential.ts@@ -14,8 +14,9 @@ import { unixSocketPath } from './localSocket.js'* can only set that one.** Reaching a port proves nothing: another account can bind it while the daemon restarts, and would hear the credential- * (audit H1). So where the socket can exist, nothing here adds the credential to a TCP request, and clients use the- * socket (lib/localTransport.ts). The daemon also refuses it from another account (lib/peerAccount.ts), for old clients.+ * (audit H1). So where the socket or, on Windows, the pipe can exist, nothing here adds the credential to a TCP request,+ * and clients use them (lib/localTransport.ts). The daemon also refuses it from another account (lib/peerAccount.ts), for+ * old clients.*/export const LOCAL_CREDENTIAL_HEADER = 'X-Harness-Local'@@ -28,11 +29,13 @@ export function readLocalCredential(dataDir: string): string | null {}/**- * The headers a client adds to a loopback TCP request: none when it cannot read the credential, and none on macOS and- * Linux unless the data folder's path is too long to hold the socket, the one case with no way but TCP.+ * The headers a client adds to a loopback TCP request: none when it cannot read the credential, none on Windows, and none+ * on macOS and Linux unless the data folder's path is too long to hold the socket, the one case with no way but TCP.+ * Windows clients reach the daemon over its proven pipe (lib/localTransport.ts): the Team account's daemon starts at boot,+ * before the owner's, and can hold the port from then on (audit W1, docs/security/2026-11-02-team-account-windows.md).*/export function localCredentialHeaders(dataDir: string, platform: NodeJS.Platform = process.platform): Record<string, string> {- if (platform !== 'win32' && unixSocketPath(dataDir, 65_535, platform)) return {}+ if (platform === 'win32' || unixSocketPath(dataDir, 65_535, platform)) return {}const credential = readLocalCredential(dataDir)return credential ? { [LOCAL_CREDENTIAL_HEADER]: credential } : {}}diff --git a/cli/src/lib/localTransport.spec.ts b/cli/src/lib/localTransport.spec.tsnew file mode 100644index 000000000..b9260ca62--- /dev/null+++ b/cli/src/lib/localTransport.spec.ts@@ -0,0 +1,192 @@+/**+ * Audit W1 (docs/security/2026-11-02-team-account-windows.md): on Windows the CLI's clients put the owner's local+ * credential on every loopback TCP request, and the Team account's daemon, started at boot, can hold that port. They now+ * go over the daemon's proven pipe, and with none they fail as a daemon that is down, never TCP. A Unix socket with a+ * pipe's name stands for the pipe on macOS and Linux, with the same auth (lib/windows/pipeAuth.ts).+ */+import { randomBytes } from 'node:crypto'+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { createServer, type IncomingMessage, type Server } from 'node:http'+import type { AddressInfo } from 'node:net'+import { join } from 'node:path'+import { spawnSync } from 'node:child_process'+import { afterEach, describe, expect, it } from 'vitest'+import { WebSocketServer, type WebSocket } from 'ws'+import { writeDaemonRecord } from './daemonRecord.js'+import { isTrustedLocal, listenLocalSocket, pipeProofOf } from './localSocket.js'+import { daemonFetch, daemonPipeNow, openLocalWs } from './localTransport.js'+import { NOT_RUNNING } from './unreachable.js'+import { PIPE_PROOF_HEADER } from './windows/pipeAuth.js'+import { PipeUnproven, type PipeTarget } from './windows/pipeClient.js'++const cleanup: Array<() => unknown> = []+afterEach(async () => { for (const step of cleanup.splice(0).reverse()) await step() })++/** A data folder short enough to hold a socket, and a pipe's name in it. */+function folder(): { data: string; pipe: string } {+ const data = mkdtempSync('/tmp/hlt-')+ cleanup.push(() => rmSync(data, { recursive: true, force: true }))+ return { data, pipe: join(data, `harness-${randomBytes(16).toString('hex')}`) }+}++async function listen(server: Server, at: number | string): Promise<void> {+ tolerant(server)+ cleanup.push(() => new Promise<void>((resolve) => { server.closeAllConnections(); server.close(() => resolve()) }))+ await new Promise<void>((resolve) => { typeof at === 'number' ? server.listen(at, '127.0.0.1', resolve) : server.listen(at, resolve) })+}++/**+ * A test server's own sockets may be written to after the client has gone: an answer the client refused for want of the+ * proof, then destroyed. On Linux that write is an EPIPE on the server's end, which nobody here needs to hear (CI on #2605).+ */+function tolerant(server: Server): void {+ server.on('connection', (socket) => { socket.on('error', () => {}) })+}++/** Whoever holds the daemon's port: it records everything it is sent. */+async function portHolder(): Promise<{ port: number; heard: string[] }> {+ const heard: string[] = []+ const server = createServer((req, res) => { heard.push(req.url ?? ''); req.resume(); res.end('{}') })+ server.on('upgrade', (req, socket) => { heard.push(req.url ?? ''); socket.destroy() })+ await listen(server, 0)+ return { port: (server.address() as AddressInfo).port, heard }+}++type Seen = { method: string; url: string; trusted: boolean; type: string | undefined; credential: unknown; body: Buffer }++/** The daemon's pipe, as the daemon serves it (lib/localSocket.ts): every request proves the token. */+async function pipeDaemon(pipe: string, token: Buffer): Promise<Seen[]> {+ const seen: Seen[] = []+ const served = await listenLocalSocket((req: IncomingMessage, res) => {+ const chunks: Buffer[] = []+ req.on('data', (chunk: Buffer) => chunks.push(chunk))+ req.on('end', () => {+ seen.push({ method: req.method ?? '', url: req.url ?? '', trusted: isTrustedLocal(req), type: req.headers['content-type'],+ credential: req.headers['x-harness-local'], body: Buffer.concat(chunks) })+ res.writeHead(200, { 'content-type': 'application/json' })+ res.end(JSON.stringify({ ok: true }))+ })+ }, pipe, { token })+ tolerant(served.server)+ cleanup.push(served.close)+ return seen+}++const never = (async () => { throw new Error('plain fetch was called') }) as unknown as typeof fetch++describe('daemonFetch on Windows goes over the daemon\'s pipe, never its port (W1)', () => {+ it('a JSON request reaches the pipe with the auth and no credential, and its answer is taken', async () => {+ const { pipe } = folder(), token = randomBytes(32)+ const seen = await pipeDaemon(pipe, token)+ const holder = await portHolder()+ const fetcher = daemonFetch('/nowhere', holder.port, never, 'win32', async () => ({ pipe, token }))+ const answer = await fetcher(`http://127.0.0.1:${holder.port}/api/machines?x=1`, {+ method: 'POST', headers: { 'content-type': 'application/json', 'x-adapter-local': '1' }, body: '{"a":1}',+ })+ expect(answer.status).toBe(200)+ expect(await answer.json()).toEqual({ ok: true })+ expect(seen.map(({ body, ...rest }) => ({ ...rest, body: body.toString() }))).toEqual([+ { method: 'POST', url: '/api/machines?x=1', trusted: true, type: 'application/json', credential: undefined, body: '{"a":1}' },+ ])+ expect(holder.heard).toEqual([])+ })++ it('a 10 MB form goes whole over the pipe, with its content type', async () => {+ const { pipe } = folder(), token = randomBytes(32)+ const seen = await pipeDaemon(pipe, token)+ const form = new FormData()+ const bytes = randomBytes(10 * 1024 * 1024)+ form.append('file', new Blob([bytes]), 'big.bin')+ const answer = await daemonFetch('/nowhere', 4242, never, 'win32', async () => ({ pipe, token }))('http://127.0.0.1:4242/api/super-tabs/t/attachments', { method: 'POST', body: form })+ expect(answer.status).toBe(200)+ expect(seen[0]!.type).toMatch(/^multipart\/form-data; boundary=/)+ expect(seen[0]!.body.includes(bytes)).toBe(true)+ })++ it('with no pipe it fails as fetch does when the daemon is down, and the port hears nothing', async () => {+ const holder = await portHolder()+ const failed = await daemonFetch('/nowhere', holder.port, never, 'win32', async () => null)(`http://127.0.0.1:${holder.port}/api/status`).catch((error: unknown) => error)+ expect(failed).toBeInstanceOf(TypeError)+ expect((failed as TypeError).message).toBe('fetch failed')+ expect(((failed as TypeError).cause as NodeJS.ErrnoException).code).toBe('ECONNREFUSED')+ expect(holder.heard).toEqual([])+ })++ it('takes no answer without the daemon\'s proof: whatever took the pipe\'s name is not the daemon', async () => {+ const { pipe } = folder(), token = randomBytes(32)+ await listen(createServer((req, res) => { req.resume(); res.writeHead(200, { [PIPE_PROOF_HEADER]: 'a'.repeat(64) }); res.end('{"ok":true}') }), pipe)+ await expect(daemonFetch('/nowhere', 4242, never, 'win32', async () => ({ pipe, token }))('http://127.0.0.1:4242/api/status')).rejects.toBeInstanceOf(PipeUnproven)+ })++ it('leaves every other address to plain fetch: a storage link is not the daemon', async () => {+ const seen: string[] = []+ const base = (async (input: Parameters<typeof fetch>[0]) => { seen.push(String(input)); return new Response('{}') }) as typeof fetch+ const pipe = async (): Promise<PipeTarget | null> => { throw new Error('the pipe was looked up') }+ await daemonFetch('/nowhere', 4242, base, 'win32', pipe)('http://127.0.0.1:9999/upload')+ await daemonFetch('/nowhere', 4242, base, 'win32', pipe)('https://storage.example/upload')+ expect(seen).toEqual(['http://127.0.0.1:9999/upload', 'https://storage.example/upload'])+ })+})++describe('openLocalWs: a WebSocket to the daemon on Windows opens the pipe and never the port (W1)', () => {+ it('opens the pipe, proving the token, and is open only once the daemon has proven itself', async () => {+ const { pipe } = folder(), token = randomBytes(32)+ const served = await listenLocalSocket((_req, res) => res.end(), pipe, { token })+ cleanup.push(served.close)+ const wss = new WebSocketServer({ noServer: true })+ cleanup.push(() => wss.close())+ let trusted = false+ served.server.on('upgrade', (req: IncomingMessage, socket, head) => {+ trusted = isTrustedLocal(req)+ wss.once('headers', (headers) => { headers.push(`${PIPE_PROOF_HEADER}: ${pipeProofOf(req)}`) })+ // Only the client closes, and the server's end is told nothing it could fail on: both closing at once wrote a close+ // frame to a socket already gone, an EPIPE with no listener (CI on #2605).+ wss.handleUpgrade(req, socket, head, (ws) => { ws.on('error', () => {}) })+ })+ let connected = false+ const socket = openLocalWs<WebSocket>('/nowhere', 4242, () => { connected = true; throw new Error('connect was called') }, 'win32', () => ({ pipe, token }))+ await new Promise<void>((resolve, reject) => { socket.on('open', () => resolve()); socket.on('error', reject) })+ await new Promise<void>((resolve) => { socket.once('close', () => resolve()); socket.close() })+ expect(trusted).toBe(true)+ expect(connected).toBe(false)+ })++ it('with no pipe it says Harness is not running, and never calls connect', () => {+ let connected = false+ expect(() => openLocalWs('/nowhere', 4242, () => { connected = true }, 'win32', () => null)).toThrow(NOT_RUNNING)+ expect(connected).toBe(false)+ })++ it('elsewhere connects to the daemon\'s socket, with no credential', () => {+ const { data } = folder()+ const asked: Array<[string, Record<string, string>]> = []+ openLocalWs(data, 4242, (url, headers) => { asked.push([url, headers]) }, 'darwin')+ expect(asked).toEqual([[`ws+unix://${join(data, 'daemon-4242.sock')}:/api/local-ws`, {}]])+ })+})++describe('daemonPipeNow: the daemon\'s pipe for a client that opens at once', () => {+ const token = randomBytes(32)+ const prepared = (pid: number | null, withToken = true) => {+ const { data, pipe } = folder()+ if (withToken) writeFileSync(join(data, 'daemon-token'), `${token.toString('hex')}\n`, { mode: 0o600 })+ if (pid !== null) writeDaemonRecord(data, 4242, 50_000, { pipe, pid })+ return { data, pipe }+ }++ it('is the recorded pipe and the token while the recorded daemon runs', () => {+ const { data, pipe } = prepared(process.pid)+ expect(daemonPipeNow(data, 4242)).toEqual({ pipe, token })+ })++ it('is none with no record, no token, or a daemon that has exited', () => {+ expect(daemonPipeNow(prepared(null).data, 4242)).toBeNull()+ expect(daemonPipeNow(prepared(process.pid, false).data, 4242)).toBeNull()+ expect(daemonPipeNow(prepared(spawnSync(process.execPath, ['-e', '']).pid!).data, 4242)).toBeNull()+ })++ // The daemon is this account's: a pid another account runs (EPERM; pid 1 is root's) was reused since it exited.+ it.skipIf(process.getuid?.() === 0)('is none when another account runs the recorded pid now', () => {+ expect(daemonPipeNow(prepared(1).data, 4242)).toBeNull()+ })+})diff --git a/cli/src/lib/localTransport.ts b/cli/src/lib/localTransport.tsindex 734d19f47..a1226af5b 100644--- a/cli/src/lib/localTransport.ts+++ b/cli/src/lib/localTransport.ts@@ -3,7 +3,10 @@* folder, and only that: any account can bind the TCP port while the daemon restarts (a Team agent, audit H1), and would* hear what is sent to it, which is the local credential and also the request itself: a message, a file. With the* socket gone the daemon is down, and the client says so. TCP remains where a socket cannot exist, a data folder whose- * path is too long for one, and on Windows, whose own proven pipe is handled by its callers.+ * path is too long for one. On Windows it is the daemon's pipe, and only that: the Team account's daemon starts at boot,+ * before the owner's, and can hold the port from then on (audit W1, docs/security/2026-11-02-team-account-windows.md).+ * Reaching the pipe is no trust there, so every request proves the daemon's token and takes only an answer that proves+ * it back (lib/windows/pipeAuth.ts).** The folder's mode is the guarantee here, as for every client of this socket (lib/localSocket.ts): nobody else can* have put a socket in it.@@ -16,6 +19,10 @@ import type { ReadableStream as NodeReadableStream } from 'node:stream/web'import { readDaemonRecord } from './daemonRecord.js'import { localCredentialHeaders } from './localCredential.js'import { unixSocketPath } from './localSocket.js'+import { NOT_RUNNING } from './unreachable.js'+import { daemonPipe } from './windows/daemonPipe.js'+import { newPipeNonce, PIPE_AUTH_HEADER, pipeAuthValue, pipeProven, readDaemonToken } from './windows/pipeAuth.js'+import { pipeWebSocket, PipeUnproven, type PipeTarget } from './windows/pipeClient.js'const LOCAL_WS_PATH = '/api/local-ws'@@ -49,14 +56,26 @@ export function localWsTarget(dataDir: string, port: number, platform: NodeJS.Plreturn { url: `ws://127.0.0.1:${readDaemonRecord(dataDir, port, platform)?.port ?? port}${LOCAL_WS_PATH}`, headers: localCredentialHeaders(dataDir, platform) }}-/** One request over the socket, answered as `fetch` answers. The body is whole first: these are JSON and forms up to 10 MB. */-async function overSocket(socketPath: string, input: Request): Promise<Response> {+/**+ * One request over the socket, or the Windows pipe of [pipe], answered as `fetch` answers. The body is whole first: these+ * are JSON and forms up to 10 MB. Over the pipe it carries a fresh auth, and an answer without the daemon's proof is+ * refused before its body is read (lib/windows/pipeClient.ts `pipeRequest`).+ */+async function overSocket(socketPath: string, input: Request, pipe?: PipeTarget): Promise<Response> {const url = new URL(input.url)const body = input.body ? Buffer.from(await input.arrayBuffer()) : nullconst headers = Object.fromEntries(input.headers)if (body) headers['content-length'] = String(body.length)+ const nonce = pipe ? newPipeNonce(pipe.pipe) : null+ if (pipe && nonce) headers[PIPE_AUTH_HEADER] = pipeAuthValue(pipe.token, nonce)return new Promise((resolve, reject) => {const req = request({ socketPath, method: input.method, path: `${url.pathname}${url.search}`, headers, signal: input.signal }, (res) => {+ if (pipe && nonce && !pipeProven(res.headers, pipe.token, nonce)) {+ reject(new PipeUnproven(pipe.pipe))+ res.destroy()+ req.destroy()+ return+ }const answer = new Headers()for (const [name, value] of Object.entries(res.headers)) {if (value !== undefined) answer.set(name, Array.isArray(value) ? value.join(', ') : value)@@ -68,10 +87,18 @@ async function overSocket(socketPath: string, input: Request): Promise<Response>})// As fetch fails: a TypeError with the reason as its cause, which the callers' "is it running" texts read.req.on('error', (error) => { reject(input.signal.aborted ? error : Object.assign(new TypeError('fetch failed'), { cause: error })) })+ // A write the socket finishes after the answer was refused and the request destroyed fails with EPIPE on Linux, when+ // nothing listens on the socket any more: the request has settled by then (Linux CI on #2605).+ req.on('socket', (socket) => { socket.on('error', () => {}) })req.end(body ?? undefined)})}+/** What `fetch` throws for a daemon that is not there: the callers' "is it running" texts read its cause. */+export function notThere(): TypeError {+ return Object.assign(new TypeError('fetch failed'), { cause: Object.assign(new Error('connect ECONNREFUSED: no Harness pipe'), { code: 'ECONNREFUSED' }) })+}+/** Whether [path] is what the daemon makes: a socket of this account's, owner only, in a real folder nobody else can write to. */export function socketIsPrivate(path: string): boolean {const uid = process.getuid?.()@@ -93,14 +120,66 @@ export function fetchOverSocket(socketPath: string): typeof fetch {/*** `fetch` for the daemon on [port] of [dataDir]: a request to its loopback address goes over its socket where it can- * have one. Any other address, such as a storage link, is the ordinary [base].+ * have one, and on Windows over its pipe ([pipe], `daemonPipe` by default) or nowhere. Any other address, such as a+ * storage link, is the ordinary [base].*/-export function daemonFetch(dataDir: string, port: number, base: typeof fetch = fetch, platform: NodeJS.Platform = process.platform): typeof fetch {- return (input, init) => {+export function daemonFetch(+ dataDir: string, port: number, base: typeof fetch = fetch, platform: NodeJS.Platform = process.platform,+ pipe: (dataDir: string, configuredPort: number) => Promise<PipeTarget | null> = daemonPipe,+): typeof fetch {+ return async (input, init) => {const url = new URL(input instanceof Request ? input.url : String(input))const saved = readDaemonRecord(dataDir, port, platform)?.portconst daemon = url.hostname === '127.0.0.1' && (Number(url.port) === port || Number(url.port) === saved)+ if (daemon && platform === 'win32') {+ const target = await pipe(dataDir, port)+ if (!target) throw notThere()+ return overSocket(target.pipe, new Request(input, init), target)+ }const socket = daemon ? localSocketRoute(dataDir, port, platform) : nullreturn socket ? overSocket(socket, new Request(input, init)) : base(input, init)}}++/**+ * Whether this account's process [pid] runs. The daemon is this account's, so EPERM is another account's process, one+ * that took the pid since the daemon exited (processProof.ts `pidAlive` counts it alive): not the daemon.+ */+function ownProcessRuns(pid: number): boolean {+ try {+ process.kill(pid, 0)+ return true+ } catch {+ return false+ }+}++/**+ * The daemon's pipe for a client that opens its WebSocket at once (`openLocalWs`): the recorded pipe while the recorded+ * daemon runs, and its token. Not the process table `daemonPipe` also reads: the socket's upgrade must prove the token+ * (`pipeWebSocket`), so a squatter is refused before any frame is sent to it.+ */+export function daemonPipeNow(dataDir: string, port: number): PipeTarget | null {+ const record = readDaemonRecord(dataDir, port)+ if (!record?.pipe || !record.pid || !ownProcessRuns(record.pid)) return null+ const token = readDaemonToken(dataDir)+ return token ? { pipe: record.pipe, token } : null+}++/**+ * A WebSocket to the daemon on [port] of [dataDir]: [connect] to its socket (or, for a data folder too long to hold one,+ * its port) on macOS and Linux, and on Windows its pipe ([pipe], `daemonPipeNow` by default), never the port. With no+ * pipe there it throws that Harness is not running.+ */+export function openLocalWs<S>(+ dataDir: string, port: number, connect: (url: string, headers: Record<string, string>) => S,+ platform: NodeJS.Platform = process.platform, pipe: (dataDir: string, port: number) => PipeTarget | null = daemonPipeNow,+): S {+ if (platform !== 'win32') {+ const target = localWsTarget(dataDir, port, platform)+ return connect(target.url, target.headers)+ }+ const target = pipe(dataDir, port)+ if (!target) throw new Error(NOT_RUNNING)+ return pipeWebSocket(target) as unknown as S+}diff --git a/cli/src/lib/newCommand.ts b/cli/src/lib/newCommand.tsindex 8ccb12544..5ac6ae36e 100644--- a/cli/src/lib/newCommand.ts+++ b/cli/src/lib/newCommand.ts@@ -1,6 +1,6 @@import { randomUUID } from 'node:crypto'import { env } from '../config/env.js'-import { localWsTarget } from './localTransport.js'+import { openLocalWs } from './localTransport.js'import { readdir, readFile, realpath } from 'node:fs/promises'import { dirname, isAbsolute, join, posix, resolve, win32 } from 'node:path'import { addressOf, atMachineRefusal, EXIT, machineOption, refusalNext, REFUSED_CODES, step, VIA_MCP_ENV } from '../agentClient/commands.js'@@ -343,7 +343,8 @@ export interface NewCommandDeps {/** What to say when the daemon cannot be reached: stopped, or kept out by a sandbox (lib/unreachable.ts). */unreachable?: () => stringlistMachines: () => Promise<NewMachine[]>- connect: (url: string) => NewSocket+ /** A WebSocket to [url] with [headers]; on Windows the daemon's pipe is opened instead (lib/localTransport.ts). */+ connect: (url: string, headers: Record<string, string>) => NewSocketoutput: (line: string) => voiderror: (line: string) => voidtimeoutMs?: number@@ -485,7 +486,7 @@ export function daemonSession(deps: Pick<NewCommandDeps, 'port' | 'connect' | 'tclose: () => void}> {return new Promise((resolveSession, rejectSession) => {- const socket = deps.connect(localWsTarget(env.ADAPTER_DATA_DIR, deps.port).url)+ const socket = openLocalWs(env.ADAPTER_DATA_DIR, deps.port, deps.connect)const waiting = new Map<string, { done: (payload: Record<string, unknown>) => void; fail: (error: Error) => void; timer: NodeJS.Timeout }>()let ready = falseconst failAll = (error: Error): void => {diff --git a/cli/src/lib/peerAccount.spec.ts b/cli/src/lib/peerAccount.spec.tsindex c31df5521..525f3abc0 100644--- a/cli/src/lib/peerAccount.spec.ts+++ b/cli/src/lib/peerAccount.spec.ts@@ -1,6 +1,6 @@import { createServer, connect, type AddressInfo, type Socket } from 'node:net'import { afterEach, describe, expect, it } from 'vitest'-import { lsofShowsPeer, peerIsThisAccount, portHolderIsThisAccount, procNetListener, procNetOwner } from './peerAccount.js'+import { lsofShowsPeer, peerIsThisAccount, portHolderIsThisAccount, procNetListener, procNetOwner, WINDOWS_PEER_LOOKUPS, WINDOWS_PEER_MS, WINDOWS_PEER_QUEUE, windowsPeerQuery, type WindowsPeerRun } from './peerAccount.js'describe('who is at the other end of a loopback connection', () => {const opened: Array<() => unknown> = []@@ -46,8 +46,161 @@ describe('who is at the other end of a loopback connection', () => {expect(peerIsThisAccount(socket)).toBe(peerIsThisAccount(socket))})- it('leaves Windows to its proven pipe', async () => {- expect(await peerIsThisAccount({} as unknown as Socket, 'win32')).toBe(true)+ // Audit W1 (docs/security/2026-11-02-team-account-windows.md): Windows answered yes without asking, so the Team account,+ // holding the port at boot, heard the credential and opened the daemon with it.+ describe('on Windows, by asking Windows who owns the calling end', () => {+ const socket = (over: Partial<Socket> = {}) =>+ ({ remoteAddress: '127.0.0.1', remotePort: 50_001, localAddress: '127.0.0.1', localPort: 18473, ...over }) as Socket+ const answering = (stdout: string, status: number | null = 0) => {+ const asked: Array<Record<string, string>> = []+ const run: WindowsPeerRun = async (_script, inputs) => { asked.push(inputs); return { status, stdout } }+ return { run, asked }+ }++ it('says yes only when the lookup found the connection and its process is this account\'s', async () => {+ const yes = answering('yes\r\n')+ expect(await peerIsThisAccount(socket(), 'win32', yes.run)).toBe(true)+ // The client's end, as Windows lists it: its own port local, the daemon's remote.+ expect(yes.asked).toEqual([{ HARNESS_PEER_PORT: '50001', HARNESS_OWN_PORT: '18473', HARNESS_DAEMON_PID: String(process.pid) }])+ })++ it('says no for another account, any other answer, a failure, or a lookup that never answered', async () => {+ for (const [stdout, status] of [['no', 0], ['', 0], ['yes yes', 0], ['yes', 1], ['yes', null]] as const) {+ expect(await peerIsThisAccount(socket({ remotePort: 50_002 + (status ?? 9) }), 'win32', answering(stdout, status).run), `${stdout}/${status}`).toBe(false)+ }+ const thrown: WindowsPeerRun = async () => { throw new Error('powershell.exe is not there') }+ expect(await peerIsThisAccount(socket({ remotePort: 50_020 }), 'win32', thrown)).toBe(false)+ })++ it('says no without asking for a caller off 127.0.0.1 at either end, or with no ports', async () => {+ const yes = answering('yes')+ for (const over of [{ remoteAddress: '127.0.0.2' }, { localAddress: '::1' }, { remotePort: undefined }, { localPort: undefined }] as Partial<Socket>[]) {+ expect(await peerIsThisAccount(socket(over), 'win32', yes.run)).toBe(false)+ }+ expect(yes.asked).toEqual([])+ })++ // Windows PowerShell's start and its CIM queries took 20 to 25 s on the Windows ARM runner (the Windows runs on #2605).+ it('gives a lookup long enough for a slow PC: Windows PowerShell and CIM on the ARM runner took 20 to 25 s', () => {+ expect(WINDOWS_PEER_MS).toBeGreaterThanOrEqual(45_000)+ })++ it('asks Windows by the connection\'s ports, given as inputs, and compares the owner by SID', () => {+ const query = windowsPeerQuery(50_001, 18473, 42_424)+ expect(query.inputs).toEqual({ HARNESS_PEER_PORT: '50001', HARNESS_OWN_PORT: '18473', HARNESS_DAEMON_PID: '42424' })+ expect(query.script).not.toMatch(/50001|18473|42424/)+ expect(query.script).toContain('Get-NetTCPConnection')+ expect(query.script).toContain('GetOwnerSid')+ expect(query.script).toContain('[Security.Principal.WindowsIdentity]::GetCurrent().User.Value')+ })++ /** Answers every lookup asked so far, and those that start as slots free, until none is left. */+ const drain = async (finish: Array<() => void>): Promise<void> => {+ for (;;) {+ await new Promise((resolve) => { setImmediate(resolve) })+ if (finish.length === 0) return+ for (const done of finish.splice(0)) done()+ }+ }+ const held = () => {+ let asked = 0+ const finish: Array<() => void> = []+ const run: WindowsPeerRun = () => { asked++; return new Promise((resolve) => { finish.push(() => resolve({ status: 0, stdout: 'yes' })) }) }+ return { run, finish, asked: () => asked }+ }++ // The owner's bridge asks once per new connection, and an agent may open several at start: past the four running, a+ // lookup waits its turn, and nobody is told "unknown address" for it (Reed's review of #2605).+ it('gives a burst of ten connections all their answer: past four running, they wait their turn', async () => {+ let running = 0, most = 0+ const run: WindowsPeerRun = async () => {+ running+++ most = Math.max(most, running)+ await new Promise((resolve) => { setTimeout(resolve, 5) })+ running--+ return { status: 0, stdout: 'yes' }+ }+ const answers = await Promise.all(Array.from({ length: 10 }, (_, i) => peerIsThisAccount(socket({ remotePort: 51_000 + i }), 'win32', run)))+ expect(answers).toEqual(answers.map(() => true))+ expect(most).toBe(WINDOWS_PEER_LOOKUPS)+ })++ // Whoever heard the hook token could open connections without end, each a PowerShell in the owner's account for up to+ // 45 s (Luna's review of #2605): past the running ones and a bounded queue, the answer is no, without asking.+ it('answers no, without asking, once the running lookups and the queue are full', async () => {+ const slow = held()+ const pending = Array.from({ length: WINDOWS_PEER_LOOKUPS + WINDOWS_PEER_QUEUE }, (_, i) => peerIsThisAccount(socket({ remotePort: 51_100 + i }), 'win32', slow.run))+ expect(await peerIsThisAccount(socket({ remotePort: 51_300 }), 'win32', slow.run)).toBe(false)+ expect(slow.asked()).toBe(WINDOWS_PEER_LOOKUPS)+ await drain(slow.finish)+ expect(await Promise.all(pending)).toEqual(pending.map(() => true))+ expect(slow.asked()).toBe(WINDOWS_PEER_LOOKUPS + WINDOWS_PEER_QUEUE)+ })++ // A lookup that waited its turn is not run for a connection that has gone meanwhile (Remy's review of #2605).+ it('does not run a queued lookup for a connection that closed while it waited', async () => {+ const slow = held()+ const pending = Array.from({ length: WINDOWS_PEER_LOOKUPS }, (_, i) => peerIsThisAccount(socket({ remotePort: 53_000 + i }), 'win32', slow.run))+ const gone = socket({ remotePort: 53_100 })+ const answer = peerIsThisAccount(gone, 'win32', slow.run)+ Object.assign(gone, { destroyed: true })+ await drain(slow.finish)+ await Promise.all(pending)+ expect(await answer).toBe(false)+ expect(slow.asked()).toBe(WINDOWS_PEER_LOOKUPS)+ })++ // A keep-alive client (an MCP client on the bridge) asks again on the same connection: a no for being busy must not+ // stick to it, and is not "another account" (Luna's review of #2605).+ it('keeps no busy refusal on the connection: the same socket is asked again once a slot frees', async () => {+ const slow = held()+ const pending = Array.from({ length: WINDOWS_PEER_LOOKUPS + WINDOWS_PEER_QUEUE }, (_, i) => peerIsThisAccount(socket({ remotePort: 52_000 + i }), 'win32', slow.run))+ const caller = socket({ remotePort: 52_300 })+ const warned: string[] = []+ const warn = console.warn+ console.warn = (line: string) => { warned.push(line) }+ try {+ expect(await peerIsThisAccount(caller, 'win32', slow.run)).toBe(false)+ } finally {+ console.warn = warn+ }+ expect(warned.join('\n')).toMatch(/busy/)+ expect(warned.join('\n')).not.toMatch(/not this account/)+ await drain(slow.finish)+ await Promise.all(pending)+ expect(await peerIsThisAccount(caller, 'win32', answering('yes').run)).toBe(true)+ })++ // Windows keeps naming a socket's creator after it exits when a child inherited the handle, and the id can go to one of+ // the owner's processes since: an account that heard the credential could wait for that and be read as the owner (Luna's+ // review of #2605). The process found must have started before the connection was made.+ it('takes the owning process only when it started before the connection was made: never a recycled process id', () => {+ const { script } = windowsPeerQuery(50_001, 18473)+ // Windows gives the connection's time to the second, the process's finer: the Windows run on #2605 read a process+ // started at 13:32:35 as after its connection of 13:32:35. So the process's time is cut to the second and compared+ // with no slack: slack let the lookup's own PowerShell, started just after, take a freed id and pass (Remy's review).+ expect(script).toContain('$started = $process.CreationDate.AddTicks(-($process.CreationDate.Ticks % [TimeSpan]::TicksPerSecond))')+ expect(script).toMatch(/\$started -gt \$rows\[0\]\.CreationTime\)/)+ expect(script).not.toMatch(/AddSeconds/)+ // The lookup's own process is never the caller.+ expect(script).toMatch(/\$rows\[0\]\.OwningProcess -eq \$PID/)+ const creation = script.indexOf('CreationDate'), owner = script.indexOf('GetOwnerSid')+ expect(creation).toBeGreaterThan(-1)+ expect(creation).toBeLessThan(owner)+ })++ // Up to four lookups run at once: a sibling's PowerShell or its console host, started by the daemon in the+ // connection's second, could take an id the caller freed (Remy's review of #2605). Nothing of that kind the daemon+ // starts calls its port with a secret, so one whose parent or grandparent is the daemon is no.+ it('never takes a PowerShell or console host the daemon started, a sibling lookup', () => {+ const { script } = windowsPeerQuery(50_001, 18473, 42_424)+ expect(script).toContain('$daemon = [int]$env:HARNESS_DAEMON_PID')+ expect(script).toMatch(/\$process\.Name -match '\^\(powershell\|conhost\)\\\.exe\$'/)+ expect(script).toMatch(/\$process\.ParentProcessId -eq \$daemon/)+ expect(script).toMatch(/\$parent\.ParentProcessId -eq \$daemon/)+ const sibling = script.indexOf('$daemon'), owner = script.indexOf('GetOwnerSid')+ expect(sibling).toBeLessThan(owner)+ })})it('reads the owner of the client end from /proc/net/tcp, not the server end', () => {diff --git a/cli/src/lib/peerAccount.ts b/cli/src/lib/peerAccount.tsindex fdaececd7..f71de44e5 100644--- a/cli/src/lib/peerAccount.ts+++ b/cli/src/lib/peerAccount.ts@@ -12,6 +12,7 @@import { execFile } from 'node:child_process'import { readFile } from 'node:fs/promises'import type { Socket } from 'node:net'+import { runPowershellAsync } from './windows/powershell.js'export type PeerAccount = (socket: Socket) => Promise<boolean>@@ -105,16 +106,130 @@ export async function portHolderIsThisAccount(port: number, platform: NodeJS.Pla})}+/**+ * Windows PowerShell's start and its CIM queries: about a second on x64, 20 to 25 s on the Windows ARM runner (the+ * Windows runs on #2605), so a slow or busy PC is given 45 s. A lookup past that is no for its connection. A native lookup+ * in harness-pty, in milliseconds, is its own task.+ */+export const WINDOWS_PEER_MS = 45_000++/** How the daemon runs [windowsPeerQuery]: Windows PowerShell, off its event loop. Tests give their own. */+export type WindowsPeerRun = (script: string, inputs: Record<string, string>) => Promise<{ status: number | null; stdout: string }>+const runWindowsPeer: WindowsPeerRun = (script, inputs) => runPowershellAsync(script, inputs, WINDOWS_PEER_MS)++/**+ * Windows: whether the client end of the connection 127.0.0.1:[peerPort] → 127.0.0.1:[ownPort] belongs to a process of+ * this account. Prints `yes`, or `no: <why>` for the daemon's log. Windows lists the client's end with its own port as the local one. The owner is+ * compared by SID, never by name; a process of another account, one whose owner Windows will not give, one gone, one+ * that started after the connection was made (an id reused since its creator exited), or more than one row (which cannot+ * be told apart) is `no`. The ports are inputs, never in the script's text.+ */+export function windowsPeerQuery(peerPort: number, ownPort: number, daemonPid: number = process.pid): { script: string; inputs: Record<string, string> } {+ return {+ script: [+ '$rows = @(Get-NetTCPConnection -State Established -LocalAddress 127.0.0.1 -LocalPort ([int]$env:HARNESS_PEER_PORT) -RemoteAddress 127.0.0.1 -RemotePort ([int]$env:HARNESS_OWN_PORT) -ErrorAction SilentlyContinue)',+ "if ($rows.Count -ne 1) { 'no: ' + $rows.Count + ' connections match'; exit 0 }",+ '$process = Get-CimInstance Win32_Process -Filter ("ProcessId = " + [int]$rows[0].OwningProcess)',+ "if (-not $process) { 'no: its process is gone'; exit 0 }",+ // The lookup's own process is never the caller: it could have taken a freed id.+ "if ($rows[0].OwningProcess -eq $PID) { 'no: the lookup itself owns it'; exit 0 }",+ // Windows keeps naming a socket's creator after it exits when a child inherited the handle, and the id may have gone+ // to another process since: only one that started before the connection was made can be its owner. Windows gives the+ // connection's time to the second and the process's finer (the Windows run on #2605 read a process started at+ // 13:32:35 as after its connection of 13:32:35), so the process's time is cut to the second and compared with no+ // slack. Slack let the lookup's own PowerShell, started just after, take the freed id and pass (Remy's review). A+ // reuse within the connection's own second is left to the native lookup.+ "if (-not $process.CreationDate -or -not $rows[0].CreationTime) { 'no: Windows gave no start time'; exit 0 }",+ '$started = $process.CreationDate.AddTicks(-($process.CreationDate.Ticks % [TimeSpan]::TicksPerSecond))',+ "if ($started -gt $rows[0].CreationTime) { 'no: its process started ' + $process.CreationDate.ToString('o') + ', the connection ' + $rows[0].CreationTime.ToString('o'); exit 0 }",+ // Nor another lookup running at once: a PowerShell the daemon started, or that PowerShell's console host, started in+ // the connection's second, could have taken the freed id (Remy's review of #2605). Nothing of that kind the daemon+ // starts calls its port with a secret.+ '$daemon = [int]$env:HARNESS_DAEMON_PID',+ "if ($process.Name -match '^(powershell|conhost)\\.exe$') {",+ " if ($process.ParentProcessId -eq $daemon) { 'no: a PowerShell the daemon started owns it'; exit 0 }",+ ' $parent = Get-CimInstance Win32_Process -Filter ("ProcessId = " + [int]$process.ParentProcessId)',+ " if ($parent -and $parent.ParentProcessId -eq $daemon) { 'no: a console host of a PowerShell the daemon started owns it'; exit 0 }",+ '}',+ '$owner = Invoke-CimMethod -InputObject $process -MethodName GetOwnerSid',+ "if ($owner.ReturnValue -eq 0 -and $owner.Sid -and $owner.Sid -eq [Security.Principal.WindowsIdentity]::GetCurrent().User.Value) { 'yes' } else { 'no: its owner is ' + $owner.Sid + ' (' + $owner.ReturnValue + ')' }",+ ].join('\n'),+ inputs: { HARNESS_PEER_PORT: String(peerPort), HARNESS_OWN_PORT: String(ownPort), HARNESS_DAEMON_PID: String(daemonPid) },+ }+}++/**+ * How many lookups run at once. Each is a PowerShell in this account for up to WINDOWS_PEER_MS, and whoever heard the+ * hook token could open connections without end (Luna's review of #2605). Past these a lookup waits its turn, so the+ * owner's own burst of new connections (an agent's MCP clients on the bridge at start) is answered, not told "unknown+ * address" (Reed's review). Only past the queue too is it no, for now: that no is not kept on the connection, so a+ * keep-alive client asking again on it is asked of Windows once a slot frees.+ */+export const WINDOWS_PEER_LOOKUPS = 4+export const WINDOWS_PEER_QUEUE = 32+let windowsLookups = 0+const waiting: Array<() => void> = []++/** A Windows answer: yes, no and why, or not asked: too many lookups were running and waiting, or the lookup never finished. */+type WindowsAnswer = boolean | 'busy' | 'timeout' | { no: string }++async function askWindows(socket: Socket, run: WindowsPeerRun): Promise<WindowsAnswer> {+ const peerPort = socket.remotePort, ownPort = socket.localPort+ // As on Linux and macOS: only an exact pair of addresses makes the pair of ports name one connection.+ if (!peerPort || !ownPort || socket.remoteAddress !== '127.0.0.1' || socket.localAddress !== '127.0.0.1') return false+ if (windowsLookups >= WINDOWS_PEER_LOOKUPS) {+ if (waiting.length >= WINDOWS_PEER_QUEUE) return 'busy'+ // The slot is handed over by the lookup that ends (below), so the count never drops between them.+ await new Promise<void>((resolve) => { waiting.push(resolve) })+ } else {+ windowsLookups+++ }+ // A connection that went while it waited needs no answer: pass the slot on (Remy's review of #2605).+ if (socket.destroyed) {+ release()+ return false+ }+ const query = windowsPeerQuery(peerPort, ownPort)+ try {+ const result = await run(query.script, query.inputs)+ // runPowershellAsync gives a null status to a script it ended at its limit, or one that never started.+ if (result.status === null) return 'timeout'+ const said = result.stdout.trim()+ if (result.status === 0 && said === 'yes') return true+ // Only the script's own reason is logged: one line, bounded.+ return /^no: [^\r\n]{1,200}$/.test(said) ? { no: said.slice(4) } : false+ } catch {+ return false+ } finally {+ release()+ }+}++/** Hands this lookup's slot to the next one waiting, or frees it. */+function release(): void {+ const next = waiting.shift()+ if (next) next()+ else windowsLookups--+}+const answers = new WeakMap<Socket, Promise<boolean>>()-/** Windows reaches the daemon over its proven pipe and has neither lookup: its TCP rules are unchanged. */-export function peerIsThisAccount(socket: Socket, platform: NodeJS.Platform = process.platform): Promise<boolean> {- if (platform === 'win32') return Promise.resolve(true)+/**+ * Whether the caller on [socket] runs as this OS account: asked of `/proc/net/tcp`, `lsof`, or on Windows of Windows itself+ * ([run], audit W1: Windows answered yes without asking, and the Team account, holding the port at boot, opened the daemon+ * with the credential it heard).+ */+export function peerIsThisAccount(socket: Socket, platform: NodeJS.Platform = process.platform, run: WindowsPeerRun = runWindowsPeer): Promise<boolean> {let answer = answers.get(socket)if (!answer) {- answer = ask(socket, platform).then((yes) => {- if (!yes) console.warn(`[peer] refused a valid secret on 127.0.0.1:${socket.localPort}: the caller is not this account`)- return yes+ const asked: Promise<WindowsAnswer> = platform === 'win32' ? askWindows(socket, run) : ask(socket, platform)+ answer = asked.then((result) => {+ const why = result === 'busy' ? 'busy, too many lookups are running; asked again on its next request'+ : result === 'timeout' ? 'Windows did not say who the caller is in time'+ : typeof result === 'object' ? `the caller is not this account (${result.no})` : 'the caller is not this account'+ if (result !== true) console.warn(`[peer] refused a valid secret on 127.0.0.1:${socket.localPort}: ${why}`)+ if (result === 'busy') answers.delete(socket)+ return result === true})answers.set(socket, answer)}diff --git a/cli/src/lib/windows/daemonPipe.spec.ts b/cli/src/lib/windows/daemonPipe.spec.tsindex c70a7e31e..79b788ddb 100644--- a/cli/src/lib/windows/daemonPipe.spec.ts+++ b/cli/src/lib/windows/daemonPipe.spec.ts@@ -60,7 +60,9 @@ describe('the daemon over its Windows pipe', () => {expect(foreign).toBeNull()})- it('makes control calls over the pipe, falls back to TCP only where nothing is there, and never after an unproven answer', async () => {+ // Audit W1 (docs/security/2026-11-02-team-account-windows.md): with nothing on the pipe it fell back to TCP, which the Team+ // account's daemon, started at boot, can hold. Now it fails there as a daemon that is down.+ it('makes control calls over the pipe, never TCP: not with nothing there, not after an unproven answer', async () => {let got = ''const { dir, port, pipe } = await windowsDaemon((req, res) => {got = `${req.method} ${req.url} ${req.headers['x-adapter-local']}`@@ -73,15 +75,13 @@ describe('the daemon over its Windows pipe', () => {const over = await call()expect(await over.json()).toEqual({ ok: true })expect(got).toBe('POST /api/pair 1')- expect(tcp).not.toHaveBeenCalled()- // No pipe to reach: as on every other OS.- expect(await (await call({ pipe: async () => null })).json()).toEqual({ tcp: true })- expect(await (await call({ platform: 'darwin' })).json()).toEqual({ tcp: true })- // A recorded pipe nothing listens on any more.+ // No pipe to reach, or a recorded pipe nothing listens on any more: the daemon is down.+ await expect(call({ pipe: async () => null })).rejects.toThrow('fetch failed')const gone = pipeName(pipeDir())- expect(await (await call({ pipe: async () => ({ pipe: gone, token: randomBytes(32) }) })).json()).toEqual({ tcp: true })- expect(tcp).toHaveBeenCalledTimes(3)+ await expect(call({ pipe: async () => ({ pipe: gone, token: randomBytes(32) }) })).rejects.toThrow('fetch failed')await expect(call({ pipe: async () => ({ pipe, token: randomBytes(32) }) })).rejects.toBeInstanceOf(PipeUnproven)- expect(tcp).toHaveBeenCalledTimes(3)+ expect(tcp).not.toHaveBeenCalled()+ // Elsewhere the call is the transport's: here the test's stand-in for it.+ expect(await (await call({ platform: 'darwin' })).json()).toEqual({ tcp: true })})})diff --git a/cli/src/lib/windows/daemonPipeClients.windows.real.spec.ts b/cli/src/lib/windows/daemonPipeClients.windows.real.spec.tsnew file mode 100644index 000000000..01062832b--- /dev/null+++ b/cli/src/lib/windows/daemonPipeClients.windows.real.spec.ts@@ -0,0 +1,69 @@+// Audit W1 (docs/security/2026-11-02-team-account-windows.md), on real Windows: an engine hook and the CLI's fetch reach the+// daemon over a real named pipe, proving its token, and nothing goes to the port. The unit specs fake win32 over a Unix+// socket (hookNotify.spec.ts, lib/localTransport.spec.ts); this is the one run of the real pipe. Windows only; the Windows+// workflow runs it with src/lib/windows.+import { spawn } from 'node:child_process'+import { randomBytes } from 'node:crypto'+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { createServer, type IncomingMessage } from 'node:http'+import type { AddressInfo } from 'node:net'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { afterEach, describe, expect, it } from 'vitest'+import { writeDaemonRecord } from '../daemonRecord.js'+import { isTrustedLocal, listenLocalSocket } from '../localSocket.js'+import { daemonFetch } from '../localTransport.js'+import { newPipePath } from './pipeAuth.js'++const WINDOWS = process.platform === 'win32'+const HOOK = fileURLToPath(new URL('../../../hook/notify.mjs', import.meta.url))+const cleanup: Array<() => unknown> = []+afterEach(async () => { for (const step of cleanup.splice(0).reverse()) await step() })++/** A data folder with the daemon's token and its record of a real pipe, the daemon's served on it, and a holder on the port. */+async function daemon(): Promise<{ data: string; port: number; seen: Array<{ url: string; trusted: boolean; credential: unknown }>; heard: string[] }> {+ const data = mkdtempSync(join(tmpdir(), 'w1-pipe-'))+ cleanup.push(() => rmSync(data, { recursive: true, force: true }))+ const token = randomBytes(32), pipe = newPipePath()+ writeFileSync(join(data, 'daemon-token'), `${token.toString('hex')}\n`)+ const seen: Array<{ url: string; trusted: boolean; credential: unknown }> = []+ const served = await listenLocalSocket((req: IncomingMessage, res) => {+ req.resume()+ req.on('end', () => {+ seen.push({ url: req.url ?? '', trusted: isTrustedLocal(req), credential: req.headers['x-harness-local'] ?? req.headers['x-harness-hook-token'] })+ res.writeHead(200, { 'content-type': 'application/json' })+ res.end('{}')+ })+ }, pipe, { token })+ cleanup.push(served.close)+ const heard: string[] = []+ const holder = createServer((req, res) => { heard.push(req.url ?? ''); req.resume(); res.end('{}') })+ await new Promise<void>((resolve) => { holder.listen(0, '127.0.0.1', resolve) })+ cleanup.push(() => new Promise<void>((resolve) => { holder.closeAllConnections(); holder.close(() => resolve()) }))+ const port = (holder.address() as AddressInfo).port+ writeDaemonRecord(data, port, port, { pipe, pid: process.pid })+ return { data, port, seen, heard }+}++describe.runIf(WINDOWS)('the daemon\'s clients over a real pipe on Windows', () => {+ it('an engine hook posts over the pipe, proving the token, and the port hears nothing', async () => {+ const { data, port, seen, heard } = await daemon()+ const env: NodeJS.ProcessEnv = { ...process.env, HARNESS_PANE: 'p1:%1', HARNESS_HOOK_DEADLINE_MS: '30000' }+ delete env.TMUX+ delete env.TMUX_PANE+ const hook = spawn(process.execPath, [HOOK, '--port', String(port), '--data-dir', data], { env, stdio: ['pipe', 'ignore', 'inherit'] })+ hook.stdin.end(JSON.stringify({ hook_event_name: 'SessionStart', session_id: '11111111-1111-4111-8111-111111111111', cwd: data }))+ await new Promise<void>((resolve) => { hook.on('exit', () => resolve()) })+ expect(seen).toEqual([{ url: '/api/hook/session-start', trusted: true, credential: undefined }])+ expect(heard).toEqual([])+ }, 60_000)++ it('the CLI\'s fetch goes over the pipe, and the port hears nothing', async () => {+ const { data, port, seen, heard } = await daemon()+ const answer = await daemonFetch(data, port)(`http://127.0.0.1:${port}/api/machines`, { headers: { 'x-adapter-local': '1' } })+ expect(answer.status).toBe(200)+ expect(seen).toEqual([{ url: '/api/machines', trusted: true, credential: undefined }])+ expect(heard).toEqual([])+ }, 60_000)+})diff --git a/cli/src/lib/windows/peerAccount.windows.real.spec.ts b/cli/src/lib/windows/peerAccount.windows.real.spec.tsnew file mode 100644index 000000000..5243029f2--- /dev/null+++ b/cli/src/lib/windows/peerAccount.windows.real.spec.ts@@ -0,0 +1,58 @@+// The daemon's question of who is calling over loopback TCP (lib/peerAccount.ts, audit W1), asked of real Windows: a+// connection this process made is this account's. Windows only; the Windows workflow runs it with src/lib/windows.+// Another account's connection cannot be made from one account's test run; that answer is pinned by the unit spec. The yes+// below also shows Windows gives both times the check compares: the process started before its connection was made.+import { spawn } from 'node:child_process'+import { connect, createServer, type AddressInfo, type Socket } from 'node:net'+import { afterEach, describe, expect, it } from 'vitest'+import { peerIsThisAccount, windowsPeerQuery } from '../peerAccount.js'+import { runPowershellAsync } from './powershell.js'++const WINDOWS = process.platform === 'win32'+const cleanup: Array<() => void> = []++/** What Windows answered for [socket], word for word: the message of a failed case, so one run says which check refused. */+async function asked(socket: Socket): Promise<string> {+ const query = windowsPeerQuery(socket.remotePort!, socket.localPort!)+ const row = '$r = @(Get-NetTCPConnection -State Established -LocalPort ([int]$env:HARNESS_PEER_PORT) -ErrorAction SilentlyContinue); $r | Format-List LocalAddress,LocalPort,RemoteAddress,RemotePort,OwningProcess,CreationTime | Out-String; foreach ($x in $r) { (Get-CimInstance Win32_Process -Filter ("ProcessId = " + [int]$x.OwningProcess)) | Format-List ProcessId,Name,CreationDate | Out-String }; "pid $PID current $([Security.Principal.WindowsIdentity]::GetCurrent().User.Value)"'+ const answer = await runPowershellAsync(query.script, query.inputs, 60_000)+ const facts = await runPowershellAsync(row, query.inputs, 60_000)+ return `query: ${answer.status} ${answer.stdout.trim()} ${answer.stderr.trim()}\nfacts: ${facts.stdout.trim()} ${facts.stderr.trim()}\ntest pid ${process.pid}`+}+afterEach(() => { for (const close of cleanup.splice(0)) close() })++describe.runIf(WINDOWS)('who is calling, asked of Windows', () => {+ it('says yes for a connection of this account, and no once it has gone', async () => {+ const server = createServer()+ cleanup.push(() => server.close())+ await new Promise<void>((resolve) => { server.listen(0, '127.0.0.1', resolve) })+ const accepted = new Promise<Socket>((resolve) => { server.once('connection', resolve) })+ const client = connect((server.address() as AddressInfo).port, '127.0.0.1')+ cleanup.push(() => client.destroy())+ const socket = await accepted+ cleanup.push(() => socket.destroy())+ if (!await peerIsThisAccount(socket, 'win32')) expect.fail(await asked(socket))++ const accepted2 = new Promise<Socket>((resolve) => { server.once('connection', resolve) })+ const gone = connect((server.address() as AddressInfo).port, '127.0.0.1')+ const socket2 = await accepted2+ cleanup.push(() => socket2.destroy())+ await new Promise<void>((resolve) => { gone.once('close', () => resolve()); gone.destroy() })+ expect(await peerIsThisAccount(socket2, 'win32')).toBe(false)+ }, 240_000)++ // The check takes only a process that started before its connection was made. A process that connects in its first+ // moments must still read as yes, whatever the two times' precision (Reed's review of #2605).+ it('says yes for a fresh process that connects at once', async () => {+ const server = createServer()+ cleanup.push(() => server.close())+ await new Promise<void>((resolve) => { server.listen(0, '127.0.0.1', resolve) })+ const accepted = new Promise<Socket>((resolve) => { server.once('connection', resolve) })+ const port = (server.address() as AddressInfo).port+ const child = spawn(process.execPath, ['-e', `require('net').connect(${port}, '127.0.0.1'); setTimeout(() => {}, 20000)`], { stdio: 'ignore' })+ cleanup.push(() => child.kill())+ const socket = await accepted+ cleanup.push(() => socket.destroy())+ if (!await peerIsThisAccount(socket, 'win32')) expect.fail(await asked(socket))+ }, 240_000)+})diff --git a/cli/src/lib/windows/powershell.ts b/cli/src/lib/windows/powershell.tsindex 8141159a3..4bc07c194 100644--- a/cli/src/lib/windows/powershell.ts+++ b/cli/src/lib/windows/powershell.ts@@ -3,7 +3,7 @@* it, and a `powershell` earlier on PATH is not ours to run), the script as -EncodedCommand (UTF-16LE, base64) so* nothing in it is quoted twice by cmd and PowerShell, and its inputs in environment variables, never in its text.*/-import { spawnSync } from 'node:child_process'+import { execFile, spawnSync } from 'node:child_process'import { win32 } from 'node:path'export const POWERSHELL_TIMEOUT_MS = 30_000@@ -45,3 +45,16 @@ export const runPowershell: PowershellRun = (script, inputs = {}) => {})return { status: result.status, stdout: result.stdout ?? '', stderr: result.stderr ?? '', ...(result.error ? { error: result.error } : {}) }}++/** [runPowershell] without blocking: for the daemon, whose event loop must not wait on a PowerShell. Never rejects; a+ * script that could not start or ran past [timeoutMs] has a null status. */+export function runPowershellAsync(script: string, inputs: Record<string, string> = {}, timeoutMs = POWERSHELL_TIMEOUT_MS): Promise<PowershellResult> {+ return new Promise((resolve) => {+ execFile(powershellPath(), encodedCommandArgs(withPrelude(script)), {+ env: { ...process.env, ...inputs }, encoding: 'utf8', timeout: timeoutMs, windowsHide: true,+ }, (error, stdout, stderr) => {+ const status = !error ? 0 : typeof error.code === 'number' && !error.killed ? error.code : null+ resolve({ status, stdout: stdout ?? '', stderr: stderr ?? '', ...(error ? { error } : {}) })+ })+ })+}diff --git a/cli/src/lib/windows/storePackagesPipe.windows.spec.ts b/cli/src/lib/windows/storePackagesPipe.windows.spec.tsnew file mode 100644index 000000000..532d06994--- /dev/null+++ b/cli/src/lib/windows/storePackagesPipe.windows.spec.ts@@ -0,0 +1,17 @@+/**+ * The Store packages' Windows transport, on a real named pipe (task #2161, audit W1): no package sends anything to the daemon's+ * TCP port, and each reaches the daemon over its pipe with the pipe auth. The cases are node:test ones in+ * store/tools/windows-pipe.test.mjs, since a Store package stands alone and has no vitest. This runs them on the Windows jobs+ * (windows.yml runs every spec in src/lib/windows); elsewhere they run against a socket of the pipe's name, in the store checks.+ */+import { spawnSync } from 'node:child_process'+import { join } from 'node:path'+import { describe, expect, it } from 'vitest'++describe('Store packages on Windows', () => {+ it.runIf(process.platform === 'win32')('reach the daemon over its proven pipe, and send nothing to its port', () => {+ const run = spawnSync(process.execPath, ['--test', join('..', 'store', 'tools', 'windows-pipe.test.mjs')], { encoding: 'utf8', timeout: 120_000 })+ expect(run.status, `${run.stdout}\n${run.stderr}`).toBe(0)+ expect(run.stdout).toMatch(/^# fail 0$/m)+ }, 130_000)+})diff --git a/cli/src/orchestrator/command.ts b/cli/src/orchestrator/command.tsindex e6912c708..083fd26d8 100644--- a/cli/src/orchestrator/command.ts+++ b/cli/src/orchestrator/command.ts@@ -1,5 +1,5 @@import { randomBytes } from 'node:crypto'-import { localWsTarget } from '../lib/localTransport.js'+import { openLocalWs } from '../lib/localTransport.js'import { WebSocket } from 'ws'import { env } from '../config/env.js'import { readAuthSession } from '../lib/authSession.js'@@ -7,8 +7,7 @@ import { readAuthSession } from '../lib/authSession.js'export function localOrchestratorRequest(port: number, machineId: string, payload: Record<string, unknown>, timeoutMs = 30_000): Promise<Record<string, unknown>> {return new Promise((resolve, reject) => {const requestId = randomBytes(16).toString('hex')- const line = localWsTarget(env.ADAPTER_DATA_DIR, port)- const ws = new WebSocket(line.url, { headers: line.headers })+ const ws = openLocalWs(env.ADAPTER_DATA_DIR, port, (url, headers) => new WebSocket(url, { headers }))let settled = falseconst finish = (error?: Error, reply?: Record<string, unknown>): void => {if (settled) returndiff --git a/cli/src/remoteCommand.spec.ts b/cli/src/remoteCommand.spec.tsindex 83d207765..0219cf6b9 100644--- a/cli/src/remoteCommand.spec.ts+++ b/cli/src/remoteCommand.spec.ts@@ -6,7 +6,6 @@ import { describe, expect, it, vi } from 'vitest'import {LoopbackClient, LoopbackError, handoffTerminal, openRemoteTerminal, orderForPicker, pickMachine, remoteCommand, remoteFailureLine,type LoopbackSocket, type RemoteCommandDeps, type RemoteMachineChoice,- loopbackUrl,} from './remoteCommand.js'const machines: RemoteMachineChoice[] = [@@ -171,7 +170,7 @@ describe('the loopback calls', () => {it('a daemon that never answers is a TIMEOUT, not a hang', async () => {const silent = new FakeDaemon(() => {})- const client = new LoopbackClient(loopbackUrl(18473), silent.connect)+ const client = new LoopbackClient(18473, silent.connect)await expect(client.select('box-1', 30)).rejects.toMatchObject({ code: 'TIMEOUT' })client.close()})diff --git a/cli/src/remoteCommand.ts b/cli/src/remoteCommand.tsindex bd7f25202..2507b2720 100644--- a/cli/src/remoteCommand.ts+++ b/cli/src/remoteCommand.ts@@ -14,8 +14,7 @@* an offline machine is listed but cannot be taken: there is nothing there to open a shell on.*/import { randomUUID } from 'node:crypto'-import { localCredentialHeaders } from './lib/localCredential.js'-import { localWsTarget } from './lib/localTransport.js'+import { openLocalWs } from './lib/localTransport.js'import { env } from './config/env.js'import { emitKeypressEvents } from 'node:readline'import { WebSocket } from 'ws'@@ -60,7 +59,7 @@ export interface RemoteCommandDeps {output: NodeJS.WriteStream & { isTTY?: boolean }error: (line: string) => void/** Test seam: what opens a loopback socket. */- connect?: (url: string) => LoopbackSocket+ connect?: (url: string, headers: Record<string, string>) => LoopbackSocket}/** The slice of `ws.WebSocket` the loopback client uses — a test stands one in. */@@ -149,9 +148,10 @@ export class LoopbackClient {private readonly socket: LoopbackSocketprivate readonly opened: Promise<void>- constructor(url: string, connect: (url: string) => LoopbackSocket = (target) =>- new WebSocket(target, { headers: localCredentialHeaders(env.ADAPTER_DATA_DIR) }) as unknown as LoopbackSocket) {- this.socket = connect(url)+ /** To the daemon on [port]: its socket, or on Windows its pipe, never the port (lib/localTransport.ts `openLocalWs`). */+ constructor(port: number, connect: (url: string, headers: Record<string, string>) => LoopbackSocket = (target, headers) =>+ new WebSocket(target, { headers }) as unknown as LoopbackSocket, dataDir: string = env.ADAPTER_DATA_DIR) {+ this.socket = openLocalWs(dataDir, port, connect)this.opened = new Promise((resolve, reject) => {this.socket.on('open', () => resolve())this.socket.on('error', (error) => reject(new LoopbackError('DAEMON_UNREACHABLE', error.message)))@@ -226,14 +226,9 @@ export class LoopbackClient {}}-/** The daemon's private socket where it can have one: never a port another account may hold (lib/localTransport.ts). */-export function loopbackUrl(port: number, dataDir: string = env.ADAPTER_DATA_DIR): string {- return localWsTarget(dataDir, port).url-}-/** A `terminal` agent on [machineId], created the way the desktop's ⌘⇧T creates one: at home. */export async function openRemoteTerminal(deps: Pick<RemoteCommandDeps, 'port' | 'connect'>, machineId: string): Promise<string> {- const client = new LoopbackClient(loopbackUrl(deps.port), deps.connect)+ const client = new LoopbackClient(deps.port, deps.connect)try {await client.select(machineId)const created = await client.rpc('agent_create', { engine: 'terminal', bypassPermission: false })@@ -251,7 +246,7 @@ export async function handoffTerminal(localMachineId: string,handoff: { tmuxPane: string; machineId: string; agentId: string },): Promise<{ fromAgentId: string; windows: number }> {- const client = new LoopbackClient(loopbackUrl(deps.port), deps.connect)+ const client = new LoopbackClient(deps.port, deps.connect)try {await client.select(localMachineId)const reply = await client.rpc('remote_terminal_handoff', handoff, 10_000)diff --git a/cli/src/team/localCredential.spec.ts b/cli/src/team/localCredential.spec.tsindex befdcaec6..9c648cd9f 100644--- a/cli/src/team/localCredential.spec.ts+++ b/cli/src/team/localCredential.spec.ts@@ -156,9 +156,9 @@ describe('audit H1: whoever holds the daemon\'s port hears nothing it can use',expect(localCredentialHeaders(data)).toEqual({})})- it('keeps the credential for the one case with no socket, and for Windows', () => {+ it('keeps the credential for the one case with no socket, and never on Windows, which has its pipe (audit W1)', () => {expect(localCredentialHeaders(dataFolder(true).data)).toEqual({ 'X-Harness-Local': CREDENTIAL })- expect(localCredentialHeaders(dataFolder().data, 'win32')).toEqual({ 'X-Harness-Local': CREDENTIAL })+ expect(localCredentialHeaders(dataFolder(true).data, 'win32')).toEqual({})})it('agentClient: with the socket gone, the port hears nothing and the caller is told', async () => {diff --git a/cli/src/team/windowsBoundary.spec.ts b/cli/src/team/windowsBoundary.spec.tsindex a0742fce4..e05060809 100644--- a/cli/src/team/windowsBoundary.spec.ts+++ b/cli/src/team/windowsBoundary.spec.ts@@ -5,7 +5,8 @@* - What each account may do in the folders the elevated setup script makes, read from the security descriptors it writes* and decoded bit by bit: the team account adds nothing to the sign-in handover folder and cannot remove it, and no other* account reads the code or the relay's token.- * - The owner's local credential over TCP on Windows, pinned as it is today (finding W1, still open): closing it turns these red.+ * - The owner's local credential over TCP on Windows (finding W1, fixed): no client puts it on a TCP request, and the daemon+ * counts it from no other account.*/import { mkdtempSync } from 'node:fs'import type { Socket } from 'node:net'@@ -13,7 +14,7 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import { describe, expect, it } from 'vitest'import { loadOrCreateHookCredential } from '../lib/hookAuth.js'-import { LOCAL_CREDENTIAL_HEADER, localCredentialHeaders } from '../lib/localCredential.js'+import { localCredentialHeaders } from '../lib/localCredential.js'import { peerIsThisAccount } from '../lib/peerAccount.js'import { buildWindowsSetupScript, type WindowsSetupScriptInput } from './windowsScript.js'@@ -122,16 +123,16 @@ describe('the folders the Windows setup script makes, by what each account may d})})-describe('W1, still open: the owner\'s local credential over TCP on Windows', () => {- it('a client puts the credential on a loopback TCP request, where macOS and Linux send none', () => {+describe('W1: the owner\'s local credential never goes over TCP on Windows', () => {+ it('a client puts no credential on a loopback TCP request, on Windows as on macOS and Linux', () => {const data = mkdtempSync(join(tmpdir(), 'team-win-boundary-'))loadOrCreateHookCredential(data)expect(localCredentialHeaders(data, 'darwin')).toEqual({})- expect(Object.keys(localCredentialHeaders(data, 'win32'))).toEqual([LOCAL_CREDENTIAL_HEADER])+ expect(localCredentialHeaders(data, 'win32')).toEqual({})})- it('the daemon counts it from any account: Windows answers yes without asking who is calling', async () => {+ it('the daemon counts it only from this account: Windows is asked who is calling, and another account is refused', async () => {const stranger = { remoteAddress: '127.0.0.1', remotePort: 50_001, localAddress: '127.0.0.1', localPort: 18473 } as Socket- await expect(peerIsThisAccount(stranger, 'win32')).resolves.toBe(true)+ await expect(peerIsThisAccount(stranger, 'win32', async () => ({ status: 0, stdout: 'no\r\n' }))).resolves.toBe(false)})})diff --git a/desktop/lib/super_tabs/activity.dart b/desktop/lib/super_tabs/activity.dartindex bc144753c..608200e63 100644--- a/desktop/lib/super_tabs/activity.dart+++ b/desktop/lib/super_tabs/activity.dart@@ -1,6 +1,6 @@import 'dart:async';-import 'package:flutter/foundation.dart';+import 'package:flutter/widgets.dart';import 'controller.dart';import 'decisions.dart';@@ -398,6 +398,9 @@ class SuperTabChatNotices {/// Told with the chat and how far it now goes.void Function(SuperTabConversation group, int sequence)? onMessage;+ /// Set by the view on screen: whether a person can see its chat now.+ bool Function()? chatShown;+final _seen = <String, int>{};int? _epoch;bool _disposed = false;@@ -420,12 +423,21 @@ class SuperTabChatNotices {_seen[group.id] = top;if (before == null || top <= before) continue;if (controller.notifyOf(group.id) != SuperTabNotify.all) continue;- if (controller.selectedId == group.id) continue;+ if (controller.selectedId == group.id && _openChatRead) continue;if (top <= controller.readMark(group.id)) continue;onMessage?.call(group, top);}}+ /// Whether the open chat is being read now. The view on screen knows; with none up, this falls+ /// back to the Swarm showing and the app in front.+ bool get _openChatRead {+ if (chatShown case final shown?) return shown();+ final state = WidgetsBinding.instance.lifecycleState;+ return !controller.away &&+ (state == null || state == AppLifecycleState.resumed);+ }+void _dispose() {_disposed = true;controller.removeListener(_changed);diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex ca3a58ea3..e0c731558 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -267,10 +267,13 @@ class _SuperTabViewState extends State<SuperTabView>_composer.addListener(_composerMoved);c.addListener(_changed);c.buddyChatOpener = _openBuddyChat;+ SuperTabChatNotices.of(c).chatShown = _chatShown;_registerDial();_changed();}+ bool _chatShown() => _chatIsVisible;+@overridevoid didChangeDependencies() {super.didChangeDependencies();@@ -288,6 +291,10 @@ class _SuperTabViewState extends State<SuperTabView>@overridevoid didUpdateWidget(SuperTabView oldWidget) {super.didUpdateWidget(oldWidget);+ if (oldWidget.controller != c) {+ _noticesLeave(oldWidget.controller);+ SuperTabChatNotices.of(c).chatShown = _chatShown;+ }if (oldWidget.controller != c || oldWidget.app != widget.app) {_dial.cancel();_registerDial();@@ -756,8 +763,14 @@ class _SuperTabViewState extends State<SuperTabView>);}+ void _noticesLeave(SuperTabController controller) {+ final notices = SuperTabChatNotices.of(controller);+ if (notices.chatShown == _chatShown) notices.chatShown = null;+ }+@overridevoid dispose() {+ _noticesLeave(c);WidgetsBinding.instance.removeObserver(this);_board.dispose();_facts.dispose();diff --git a/desktop/test/super_tab_activity_test.dart b/desktop/test/super_tab_activity_test.dartindex 5ef542269..216f2d805 100644--- a/desktop/test/super_tab_activity_test.dart+++ b/desktop/test/super_tab_activity_test.dart@@ -570,6 +570,45 @@ void main() {await c.refresh();expect(told.map((t) => t.$1), ['offline']);});++ Future<(SuperTabController, ConversationServer, List<int>)>+ openChatSetToAll() async {+ final binding = TestWidgetsFlutterBinding.ensureInitialized();+ binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);+ final server = projectServer();+ final c = await open(server);+ final told = <int>[];+ SuperTabChatNotices.of(c).onMessage = (_, s) => told.add(s);+ await c.setNotify(c.selectedId, SuperTabNotify.all);+ return (c, server, told);+ }++ test('the open chat is told while its Swarm is away', () async {+ final (c, server, told) = await openChatSetToAll();+ c.away = true;+ fromLead(server, 'While on another Swarm');+ await c.refresh();+ expect(told, hasLength(1));+ });++ test('the open chat is told while another app is in front', () async {+ final (c, server, told) = await openChatSetToAll();+ final binding = TestWidgetsFlutterBinding.instance;+ addTearDown(+ () => binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed),+ );+ binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);+ fromLead(server, 'While in another app');+ await c.refresh();+ expect(told, hasLength(1));+ });++ test('the open chat on screen in a focused app is not told', () async {+ final (c, server, told) = await openChatSetToAll();+ fromLead(server, 'While reading it');+ await c.refresh();+ expect(told, isEmpty);+ });});group('sidebar', () {diff --git a/desktop/test/super_tab_chat_test.dart b/desktop/test/super_tab_chat_test.dartindex 5cee20911..508f1f931 100644--- a/desktop/test/super_tab_chat_test.dart+++ b/desktop/test/super_tab_chat_test.dart@@ -4,6 +4,7 @@ import 'package:flutter/services.dart';import 'package:flutter_markdown_plus/flutter_markdown_plus.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/activity.dart';import 'package:harness/super_tabs/controller.dart';import 'package:harness/super_tabs/message_row.dart';import 'package:harness/super_tabs/message_text.dart';@@ -151,6 +152,31 @@ void main() {await closeReadView(tester, c);});+ // Task #2219: All new messages goes quiet only while the open chat is read on screen.+ testWidgets(+ 'an open chat set to All is told behind the terminals, not on screen',+ (tester) async {+ final server = ConversationServer()..append('Hello');+ final c = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ final told = <int>[];+ SuperTabChatNotices.of(c).onMessage = (_, s) => told.add(s);+ await c.setNotify(c.selectedId, SuperTabNotify.all);+ await showReadView(tester, c);+ server.append('While reading it');+ await tester.runAsync(c.refresh);+ await tester.pump();+ expect(told, isEmpty);+ await showReadView(tester, c, terminals: true);+ server.append('Behind the terminals');+ await tester.runAsync(c.refresh);+ await tester.pump();+ expect(told, hasLength(1));+ await closeReadView(tester, c);+ },+ );+testWidgets('returning from terminals reads the already loaded transcript', (tester,) async {diff --git a/docs/plans/2026-11-02-windows-local-credential-pipe-plan.md b/docs/plans/2026-11-02-windows-local-credential-pipe-plan.mdnew file mode 100644index 000000000..685660434--- /dev/null+++ b/docs/plans/2026-11-02-windows-local-credential-pipe-plan.md@@ -0,0 +1,130 @@+# Windows: the Owner's Local Credential Never Reaches Whoever Holds the Daemon's Port — Implementation Plan++> **How this is worked:** by this project's Engineer, task by task, test first (the failing test committed before its+> code), as the project's instructions say. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Close audit W1 (`docs/security/2026-11-02-team-account-windows.md`): on Windows no client sends the daemon's local+credential over loopback TCP, and the daemon counts it over TCP only from a process of its own account.++**Architecture:** Three layers, each closing the hole alone. (1) The daemon asks Windows who owns the calling end of a TCP+connection that carried a valid secret (`lib/peerAccount.ts`), as it already asks `lsof` and `/proc` elsewhere. (2) Engine+hooks post over the daemon's proven pipe (`hook/notify.mjs`), the pipe auth that Desktop and the agent verbs use. (3) The CLI's+fetch helper and its WebSocket clients go over that pipe on Windows, and `localCredentialHeaders` gives TCP nothing there.++**Tech Stack:** TypeScript, Node, Windows PowerShell 5.1 (`Get-NetTCPConnection`, CIM), Vitest.++**Spec:** Task #2095's brief, and W1 of the report above.++## Global Constraints++- macOS and Linux behave exactly as before.+- Never run a test that signs this Mac out of the real CLI; never test against the real daemon, port 18473 or data folder.+- A lookup that fails, times out or is ambiguous answers no: this guards a credential.+- The token never travels: only the pipe auth's HMAC and the daemon's proof.+- `hook/notify.mjs` stays one file with no imports but Node's: Windows copies it alone to `cli\notify.mjs`.+- Two independent security reviews before merge (Quinn 2, Luna).++## Design++- Growth: N/A, nothing stored.+- Concurrency: the peer lookup runs once per TCP connection, after the secret matched, cached on the socket as on macOS.+- Read cost: one PowerShell per TCP connection carrying a valid secret on Windows, about a second: old engine plugins+ until their pane restarts, old CLIs, and every new connection to the connectors bridge (an MCP client can only dial its+ configured HTTP address). New CLI clients and hooks use the pipe and cost nothing. A native lookup in `harness-pty` would+ take this to milliseconds: a follow-up.+- Scale: hooks fire per prompt; after this change they no longer touch TCP, so the lookup does not scale with prompts.+- Compatibility: an old CLI or a loaded plugin with the old `notify.mjs` still sends the credential over TCP; the daemon+ takes it from this account and refuses it from another. A new client with an old daemon (no pipe record) gets "Harness+ is not running" from the pipe-only paths. Every Windows daemon since the native CLI writes its pipe in its record.+- Migration and rollback: none; reverting restores TCP.+- Audience: the daemon enforces it (the peer check), not the client.+- Identity: the account is the process's token SID, never a name.+- Failure: a refused credential is logged once per connection (`[peer] refused a valid secret`); a client with no pipe says+ the daemon is not running.+- Platforms: Windows only; macOS and Linux unchanged.++## Review Focus++- A lookup that says yes for another account: two connections on the same ports (127.0.0.2), a process that exited, a+ PowerShell that printed something else.+- A hook that still reaches TCP on Windows: no record, a dead pid, a record naming something that is not a local pipe.+- An answer taken without the daemon's proof: the hook must drop a reply whose proof is wrong.+- A CLI path still putting the credential on TCP on Windows: every caller of `localCredentialHeaders`.+- An upload over the pipe: a 10 MB multipart body, not a string.++---++### Task 1: The daemon refuses the credential over TCP from another account on Windows++**Files:** Modify `cli/src/lib/peerAccount.ts`; test `cli/src/lib/peerAccount.spec.ts`, `cli/src/team/windowsBoundary.spec.ts`;+create `cli/src/lib/windows/peerAccount.windows.real.spec.ts` (runs on Windows only).++**Interfaces:** Produces `windowsPeerQuery(peerPort, ownPort): { script; inputs }` and+`peerIsThisAccount(socket, platform, run?)`, with `run` the PowerShell runner (async), injected by tests.++- [ ] **Step 1:** Turn the W1 test around: a stranger's socket on Windows reads as not this account. Add: yes only when the+ query printed `yes`; no for `no`, other text, a failure, a timeout, or addresses other than 127.0.0.1 at both ends.+- [ ] **Step 2:** Run; expected FAIL (Windows answers yes today).+- [ ] **Step 3:** Implement the query and the Windows branch.+- [ ] **Step 4:** Run; expected PASS. Red evidence: the old `return Promise.resolve(true)` back.++### Task 2: Hooks post over the daemon's pipe on Windows++**Files:** Modify `cli/hook/notify.mjs` (`hookRoute`, `post`); test `cli/src/hookNotify.spec.ts`.++**Interfaces:**+- Consumes: the record `daemon-<port>.json` (`{ port, pipe, pid }`, `lib/daemonRecord.ts`), the token file `daemon-token`+ (64 hex digits, `lib/windows/pipeAuth.ts`), the auth `x-harness-auth: <nonce>.<HMAC-SHA256(token, 0x01‖nonce)>` with a+ nonce of the pipe's 32-hex id then 32 random hex digits, and the proof `x-harness-proof: HMAC-SHA256(token, 0x00‖nonce)`.+- Produces: in `notify.mjs`, `hookRoute(port)` on Windows returns `{ address: { socketPath: pipe }, token: '', pipe: { token, nonce } }`+ or null; `post` sends the auth and no credential, and takes a reply only with the proof.++- [ ] **Step 1: Write the failing tests** in `hookNotify.spec.ts`, with a preload that sets `process.platform` to `win32` and+ maps a `\\.\pipe\harness-<id>` socket path to a Unix socket of that id (Node on a Mac cannot open a Windows pipe):+ - "posts over the daemon's pipe on Windows, with the pipe auth and no credential": a `listenLocalSocket` server with the+ token gets `/api/hook/session-start`, `isTrustedLocal(req)` is true, no `x-harness-hook-token`; a TCP listener on the+ port gets nothing.+ - "posts nothing on Windows without a live pipe": no record, a record whose pid is not running, a record whose pipe is not+ a local `\\.\pipe\harness-<32 hex>`, no token, a token that is a link: the pipe server and the TCP listener get nothing.+ - "takes no reply on Windows without the daemon's proof": a server answering 200 with a wrong proof and a reply that would+ print context; the hook prints nothing of it.+- [ ] **Step 2: Run** `npx vitest run src/hookNotify.spec.ts -t Windows`. Expected: FAIL (hooks use TCP).+- [ ] **Step 3: Implement** the route and the proof check in `notify.mjs`; the three existing Windows credential tests move+ to the token file (the same refusals of a link).+- [ ] **Step 4: Run** `npx vitest run src/hookNotify.spec.ts`. Expected: PASS.++### Task 3: The CLI never puts the credential on TCP on Windows++**Files:** Modify `cli/src/lib/localCredential.ts`, `lib/localTransport.ts`, `lib/daemonEndpoint.ts` (control calls stop+falling back to TCP on Windows), `lib/newCommand.ts`, `cli.ts`, `remoteCommand.ts`, `devices/client.ts`,+`orchestrator/command.ts`; tests in `lib/localTransport.spec.ts`, `lib/daemonEndpoint.spec.ts`,+`lib/windows/daemonPipe.spec.ts`, `team/localCredential.spec.ts`, `team/windowsBoundary.spec.ts`.++**Interfaces:**+- `localCredentialHeaders(dataDir, platform)`: `{}` on Windows.+- `PipeRequest.body?: string | Buffer`, `PipeRequest.signal?: AbortSignal`.+- `daemonFetch(dataDir, port, base?, platform?, pipe?: (dataDir, port) => Promise<PipeTarget | null>)`: on Windows a request+ to the daemon goes over `pipe` (`daemonPipe` by default), and with none it fails as `fetch` does (`TypeError('fetch failed')`,+ cause `ECONNREFUSED`), never TCP.+- `openLocalWs<S>(dataDir, port, connect: (url, headers) => S, platform?, pipe?: (dataDir, port) => PipeTarget | null): S`:+ elsewhere `connect(localWsTarget(...))`; on Windows `pipeWebSocket(target)`, and with no target it throws the "Harness+ is not running" text. `daemonPipeNow(dataDir, port)` is that sync target: the record, the token, the pid alive (the+ socket's upgrade proof refuses a squatter before anything is sent).++- [ ] **Step 1: Write the failing tests:**+ - `windowsBoundary.spec.ts` "a client never puts the credential on a TCP request on Windows":+ `localCredentialHeaders(data, 'win32')` is `{}`.+ - `localTransport.spec.ts` "on Windows, daemonFetch goes over the pipe": a JSON request and a 10 MB multipart body reach a+ pipe server with the auth, the reply is taken; `base` is never called. "with no pipe it fails as fetch does": rejects+ with a `TypeError`, `base` never called. A request to another address uses `base`.+ - "openLocalWs on Windows opens the pipe and never the port": with a target, a pipe WebSocket (its upgrade carries the+ auth); with none, it throws "not running" and `connect` is never called; elsewhere it calls `connect` with the socket URL.+- [ ] **Step 2: Run** `npx vitest run src/lib/localTransport.spec.ts src/team/windowsBoundary.spec.ts`. Expected: FAIL.+- [ ] **Step 3: Implement**, and move the four WebSocket clients to `openLocalWs`.+- [ ] **Step 4: Run** the specs of every file changed, then `npm run typecheck` and `npm test`. Expected: PASS.++### Task 4: Pull request++- [ ] Report: W1 marked fixed in `docs/security/2026-11-02-team-account-windows.md`.+- [ ] Pull request with the "Requested by" line, the checklist, red/green evidence, and the one Windows command as a+ release note; two review steps (Quinn 2, Luna).diff --git a/docs/plans/2026-11-02-windows-store-local-credential-pipe-plan.md b/docs/plans/2026-11-02-windows-store-local-credential-pipe-plan.mdnew file mode 100644index 000000000..e45a3fa47--- /dev/null+++ b/docs/plans/2026-11-02-windows-store-local-credential-pipe-plan.md@@ -0,0 +1,123 @@+# Windows: the Store Packages Reach the Daemon over Its Proven Pipe, Never Its Port — Implementation Plan++> **How this is worked:** by this project's Engineer, task by task, test first (the failing test committed before its+> code), as the project's instructions say. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Close audit W1 for the Store packages (`docs/security/2026-11-02-team-account-windows.md`): on Windows the machine+monitor, harness monitor, memories, autonomous grid and `store/tools` never send the owner's local credential to the daemon's+TCP port; they reach the daemon over its named pipe with W1's proof.++**Architecture:** Every package already carries one identical file for the daemon's transport, `lib/localDaemon.mjs` (a copy of+`store/tools/local-daemon.mjs`, pinned by `store/tools/port-holder.test.mjs`). It learns the Windows pipe exactly as W1's hook does+(`cli/hook/notify.mjs` `windowsDaemonPipe`): the daemon's record `daemon-<port>.json` names the pipe and the core's pid, the pid must+run, the token file is read under the same link and junction rules, each request carries a fresh `X-Harness-Auth`, and an answer or a+WebSocket open is taken only with the daemon's `X-Harness-Proof`. With no pipe it says Harness is not running and never tries the+port. The five `localCredentialHeaders` give nothing on Windows, and their 401 probe never runs there.++**Tech Stack:** Node ES modules with no dependencies (each package stands alone), `node:test`, GitHub Actions on Windows.++**Spec:** Task #2161's brief; W1 of the report above; PR #2605 (W1), whose pipe auth (`cli/src/lib/windows/pipeAuth.ts`) is the+protocol.++## Global Constraints++- macOS and Linux behave exactly as before (the socket, or TCP only for a home too long to hold one).+- On Windows nothing goes to the TCP port: no credential, no probe, no fallback.+- The token never travels: only `<nonce>.<HMAC-SHA256(token, 0x01‖nonce)>`, the nonce starting with the pipe's id; the answer must+ carry `HMAC-SHA256(token, 0x00‖nonce)`.+- `localDaemon.mjs` stays one file with no imports but Node's, byte-identical in every package and `store/tools`.+- Swarm code stays out of `cli/src/core`.+- Two independent security reviews before merge (Reed, Quinn 2), and a real Windows workflow run on the final head.++## Design++- Growth: N/A, nothing is stored.+- Concurrency: N/A, no shared state; each request reads the record and token once.+- Read cost: two small file reads (record, token) and a `kill(pid, 0)` per request or WebSocket; the packages keep one socket per+ machine, so this is per poll at most, a few per minute.+- Scale: 10x panes is 10x those reads, microseconds each; the first warning would be the daemon's nonce window (4,096), far above.+- Compatibility: a new package with an old daemon that records no pipe says Harness is not running (every native Windows daemon+ records it). An old package on Windows still sends the credential to the port; W1's peer check makes it useless to another+ account, and a Store update replaces the package.+- Migration and rollback: none; reverting restores TCP.+- Audience: the daemon enforces the pipe auth; the client refuses any answer without the proof.+- Identity: the token in this account's data folder, never a name.+- Failure: no pipe, a dead pid, a bad token or an unproven answer each fail the call with a sentence (Harness is not running, or+ something other than Harness answered); nothing falls back silently.+- Platforms: Windows only; macOS and Linux unchanged (their tests pass as they are).++## Review Focus++- A Windows path that still reaches TCP: no record, a record naming a file or `\\host\pipe\…`, a dead pid, no token, a linked token.+- An answer taken without the daemon's proof: a REST body read, or a WebSocket `open` fired, before the proof is checked.+- A 401 probe or credential read that still runs on Windows (`credentialRefused`, `localCredentialHeaders`).+- The record found by the bound port when the URL names the port the daemon was given instead (`daemon-<configured>.json`).+- The copies drifting: one package's `localDaemon.mjs` differing from `store/tools/local-daemon.mjs`.++---++### Task 1: The shared transport reaches the daemon over its pipe on Windows, and never the port++**Files:** Modify `store/tools/local-daemon.mjs` and its four copies `store/agents/{machine-monitor,harness-monitor,memories,autonomous-grid}/lib/localDaemon.mjs`;+test: create `store/tools/windows-pipe.test.mjs`.++**Interfaces:**+- Produces: `daemonPipe(port: number, env = process.env, platform = process.platform): { path: string, headers: { 'X-Harness-Auth': string }, proven(value: unknown): boolean } | null`+ — a fresh one-request route each call; null off Windows or with nothing to dial.+- `DaemonWebSocket` and `daemonFetch` keep their signatures; on Windows they use `daemonPipe`, and with none they fail with+ `HARNESS_NOT_RUNNING` (exported string) without dialling anything.++- [ ] **Step 1: Write the failing tests** in `store/tools/windows-pipe.test.mjs`, with `process.platform` set to `win32`, a TCP+ holder on the URL's port recording all it hears, and a daemon listening at `\\.\pipe\harness-<id>` (a real pipe on Windows; on+ macOS and Linux a socket of that name in the test's working folder) that checks the auth and answers with the proof:+ - `no Windows client sends anything to the port with no pipe`: each package's REST call (`listMachines`), and WebSocket call+ (`listAgents` ×2, `listHarnesses`, `harnessExecute`) fails, and the holder heard nothing.+ - `each package reaches the daemon over its pipe with the proof, and the port hears nothing`: the same calls succeed; every request+ the pipe daemon got carried a valid `x-harness-auth` and no `x-harness-local`; the holder heard nothing.+ - `an answer without the daemon's proof is never taken`: a pipe daemon answering with a wrong proof: REST fails, the WebSocket+ never opens, no frame is sent.+ - `nothing is dialled for a record that is not a live local pipe`: a record naming a file, `\\host\pipe\harness-<id>`, a dead pid;+ a missing token; a token reached through a link.+ - `the record is found by the bound port`: `daemon-18473.json` holding `port: <url port>`.+- [ ] **Step 2: Run** `node --test store/tools/windows-pipe.test.mjs` — expected FAIL: the holder hears the credential (main sends it).+- [ ] **Step 3: Implement** `daemonPipe` in `store/tools/local-daemon.mjs` (the rules of `cli/hook/notify.mjs` `windowsDaemonPipe`+ and `readWindowsStateFile`); `UnixWebSocket` takes `{ headers, proven }` and checks the proof on the upgrade before `open`, and the+ private-socket check only when no proof is given; `daemonFetch` checks the proof before reading the body. Copy the file to the four+ packages.+- [ ] **Step 4: Run** the new test, `store/tools/local-daemon.test.mjs` and `store/tools/port-holder.test.mjs` — expected PASS.+- [ ] **Step 5: Commit.**++### Task 2: The five credential readers give nothing on Windows, and never probe the port++**Files:** Modify `store/agents/machine-monitor/lib/daemon.mjs`, `store/agents/harness-monitor/lib/bridge.mjs`,+`store/agents/memories/lib/bridge.mjs`, `store/agents/autonomous-grid/lib/harness.mjs`, `store/tools/local-credential.mjs`;+tests: each package's `test/credential.test.mjs`, `store/tools/local-credential.test.mjs`.++**Interfaces:**+- Consumes: `daemonPipe`, `HARNESS_NOT_RUNNING` from Task 1.+- Produces: `localCredentialHeaders(env)` returns `{}` on Windows; `credentialRefused` returns false there without a request.+ `store/tools/local-credential.mjs` `daemonBridge(port, env)` on Windows returns+ `{ url: 'ws://localhost/api/local-ws', headers, createConnection, proven }`, and `openDaemonBridge(WebSocket, port?, env?)` opens a+ `ws` WebSocket from it that is terminated on an unproven upgrade; the `dsh-*.mjs` tools use `openDaemonBridge`.++- [ ] **Step 1: Turn around the failing tests:** "on Windows the credential is read whatever mode…" becomes "on Windows no credential+ is read: it never goes to the port", asserting `{}` for a valid credential file; `daemonBridge` on Windows gives the pipe route's+ auth and no `X-Harness-Local`, and throws `HARNESS_NOT_RUNNING` with no pipe.+- [ ] **Step 2: Run** each `credential.test.mjs` and `local-credential.test.mjs` — expected FAIL (the credential is still read).+- [ ] **Step 3: Implement:** `process.platform === 'win32'` returns `{}` before anything is read, and the Windows mode exception goes;+ `credentialRefused` returns false on Windows; `daemonBridge`/`openDaemonBridge` as above; the three `dsh-*.mjs` call it.+- [ ] **Step 4: Run** all store package tests touched — expected PASS.+- [ ] **Step 5: Commit.**++### Task 3: A real Windows run, the README and the report++**Files:** Create `store/tools/windows-ci/store-pipe.mjs` and `cli/src/lib/windows/storePackagesPipe.windows.spec.ts`; modify+`cli/scripts/windows-ci/check-install.ps1`, `store/tools/README.md`, `docs/security/2026-11-02-team-account-windows.md` (the W1 line).+No workflow file changes: this project's GitHub App may not push them, and the Windows workflow already runs every spec in+`cli/src/lib/windows` and `check-install.ps1`.++- [ ] **Step 1:** `store-pipe.mjs` runs, against the installed daemon, machine monitor `daemonStatus` (REST) and `listHarnesses`,+ harness monitor and memories `listAgents`, and the grid's `harnessExecute`, over the pipe: it prints each result and exits 1 on any+ failure; `check-install.ps1` runs it last. The vitest spec runs `store/tools/windows-pipe.test.mjs` on Windows on a real pipe.+- [ ] **Step 2:** README's "Daemon checks" and the report's W1 row and Fixed list name the Store packages.+- [ ] **Step 3: Commit,** then ask the PM to start the Windows workflow on the final head.diff --git a/docs/security/2026-11-02-team-account-windows.md b/docs/security/2026-11-02-team-account-windows.mdindex 65a225684..728e75fdc 100644--- a/docs/security/2026-11-02-team-account-windows.md+++ b/docs/security/2026-11-02-team-account-windows.md@@ -9,14 +9,15 @@ text and values the code produces. Nothing on a real account, permission or file## Answer**The folders hold; the daemon's port does not.** Ports were covered only in part: the Team daemon's own port was not read. The ACLs setup writes keep the Team account out of the owner's profile.-Other accounts can't read the sign-in code or the relay's token, and the daemon's pipe proves both ends. But on Windows the owner's-local credential still goes over TCP to whoever holds the daemon's port, and the daemon accepts it from any account (W1).+Other accounts can't read the sign-in code or the relay's token, and the daemon's pipe proves both ends. On Windows the owner's+local credential went over TCP to whoever holds the daemon's port, and the daemon accepted it from any account (W1, fixed in+task #2095; the connectors bridge's port is still open, its own task, so Team accounts on Windows are not closed yet).The Team account's daemon starts at boot, before the owner signs in. Purge was written for POSIX paths. It never deleted aCodex Product Manager's own home on Windows (W2, fixed in this pull request), and it can't finish a Claude Code one there (W3).| ID | Rating | Finding | Status ||---|---|---|---|-| W1 | **High** | The owner's local credential goes to whoever holds the daemon's port, and opens the daemon from any account | Read in code, pinned by a test; fix requested |+| W1 | **High** | The owner's local credential goes to whoever holds the daemon's port, and opens the daemon from any account | **Fixed** in task #2095 for every client, test first. The Store add-ons over the pipe (task #2161): fixed, and run on real Windows x64 and Arm against the installed daemon (Windows workflow run 41464966703). The connectors bridge is still open (own task) || W2 | **High** | Purge left a Codex Product Manager's whole home on Windows, and could take every PM's home on any platform | **Fixed here**, test first || W3 | Medium | Purge can't scrub a Claude Code Product Manager on Windows: the account stays held, its memory stays | Read in code, fix requested || W4 | Medium | The Team account can stall the owner's read of its status file | Read in code, fix requested |@@ -52,13 +53,49 @@ This is the macOS H1 again, but on Windows nothing of the #2016 fix applies:The messages RPC uses only the pipe (`messages/rpc.ts:20-25`). The pipe proves both ends without sending the token(`lib/windows/pipeAuth.ts`).-**Proof:** `cli/src/team/windowsBoundary.spec.ts`, "W1, still open": on Windows a client puts the credential on a TCP request,-and the daemon counts it from a caller it never looked up. Closing the hole turns these red. Not tried on Windows.+**Proof:** `cli/src/team/windowsBoundary.spec.ts`, "W1" (named "W1, still open" until the fix): on Windows a client put the credential on a TCP request,+and the daemon counted it from a caller it never looked up. Not tried on Windows.**Fix:** on Windows, send hooks and every CLI request over the daemon's proven pipe, and never the credential over TCP. Until then,make the daemon refuse the credential over TCP from another account. Windows can say who owns a loopback connection(`GetExtendedTcpTable` gives the owning process, whose token names its account).+**Fixed (task #2095).** All three parts, each test first; the W1 tests above are turned around:+- The daemon asks Windows who owns the calling end of a TCP connection that showed a valid secret (`lib/peerAccount.ts`+ `windowsPeerQuery`: `Get-NetTCPConnection`, then the process's owner SID against this account's). Anything but a clear yes is+ no. This alone makes a credential heard on the port useless to another account, from an old client or plugin too.+ It takes only a process that started before the connection was made, compared in whole seconds (the connection's time comes+ only to the second), never the lookup's own process, and never a PowerShell or console host the daemon started (another+ lookup running at once). A process id taken within the connection's own second by some other process of the owner's is+ still open until the native lookup. At most four+ lookups run at once and up to 32 wait their turn; one past those is no for now, and is asked again on its next request. A+ lookup that times out (45 s: about a second on x64, 20 to 25 s on the Windows ARM runner) stays no for that connection; a+ native lookup in harness-pty is its own task.+- Hooks post over the daemon's pipe (`hook/notify.mjs` `windowsDaemonPipe`), proving the token without sending it, and take an+ answer only with the daemon's proof. With no live pipe they post nothing, as on macOS with no socket.+- CLI clients never put the credential on TCP (`localCredentialHeaders` gives nothing on Windows). Their fetch helper and their+ WebSockets go over the pipe (`lib/localTransport.ts` `daemonFetch`, `openLocalWs`), and with no pipe they say Harness is not+ running.+- The Store add-ons (Harness Monitor, Machine Monitor, Memories, Autonomous Grid) and the Store's dev tools sent the credential to+ `127.0.0.1:18473` on Windows, the default port the Team daemon takes at boot. Task #2095 stopped that; task #2161 makes them work again:+ their one shared transport (`lib/localDaemon.mjs`, a copy of `store/tools/local-daemon.mjs`) reaches the daemon over its pipe as+ the hook does, with the pipe auth and the daemon's proof before any answer or WebSocket open, and with no live pipe says Harness+ is not running. Their `localCredentialHeaders` give nothing on Windows and their 401 probe never runs there+ (`store/tools/windows-pipe.test.mjs`, run on Windows by the Windows workflow, with `store/tools/windows-ci/store-pipe.mjs`+ against the installed daemon).+- Still open, rated Medium, its own task: the connectors bridge. Its default port (51793) is the same for every account, the Team+ daemon also starts connectors, and on Windows `portHolderIsThisAccount` answers null, so the owner's bridge never moves off a+ held port (`services/connectors.ts`). Whoever holds it from boot reads every tool call of the owner's agents and can answer them+ falsely, and Harness's own `bridgeRoute` trusts those answers too. The key opens nothing from another account now. macOS has the+ stdio shim and the move-off (#2558, #2550); Windows has neither. The fix is the shim and Harness's route over the proven pipe;+ a Windows listener-owner lookup, so the bridge moves off a held port, is a cheap first step.+- Still open: the OpenCode, Kilo, Pi and Amp plugins (`engines/kit/pluginFetch.ts`) have no socket on Windows and post to the+ port with the hook-only token and the session's details. The token opens nothing from another account now, but whoever holds+ the port hears both, and each new connection costs the daemon's one-second lookup. They need the pipe too, a separate task.+- A recorded daemon pid that another account runs now is no daemon to the hook and the CLI's WebSockets (EPERM), so a pipe made+ under a dead daemon's name is never dialled for it. A pid this account's own process took since is still dialled; then only the+ pipe's proof refuses the answer, after the request was sent. That needs the pid reused by chance, not by choice.+### W2. Purge left a Codex Product Manager's home on Windows (High, fixed here)`superTabs/inCore/teamPurge.ts` deletes a purged Codex PM's own engine home only if its path starts with `<home>/.harness-pm-homes/`.@@ -176,7 +213,7 @@ as `privacy.ts` `statusText` does.needs a right on the process that it doesn't give across accounts. Not checked.- Ports were covered only in part: the Team daemon's own loopback port (18493) was not read beyond what the macOS audit says.The terminal host's pipe was read (under "What holds", security review 2 of this pull request); nothing about it ran on Windows.-- Which callers of `localCredentialHeaders` speak TCP on Windows (W1): `cli.ts`, `remoteCommand.ts`, `superTabs/attach.ts`,- `devices/client.ts`, `agentClient/settings.ts`, `lib/daemonEndpoint.ts`, `lib/autonomous-device/addonCommand.ts`. Not traced.+- Which callers of `localCredentialHeaders` speak TCP on Windows (W1): the CLI's were traced and moved to the pipe in task #2095;+ the Store add-ons' own copies send nothing to the port on Windows, and reach the daemon over its pipe since task #2161.- Whether a standard account can register a scheduled task for itself that runs while it is not signed in (W5).- The integration suite was not run: this change touches no backend code.diff --git a/store/agents/autonomous-grid/lib/harness.mjs b/store/agents/autonomous-grid/lib/harness.mjsindex 202b6877e..d19816254 100644--- a/store/agents/autonomous-grid/lib/harness.mjs+++ b/store/agents/autonomous-grid/lib/harness.mjs@@ -36,23 +36,21 @@ export function bridgeUrl(env = process.env) {* The same function, by the same name, is in every Store package that talks to the daemon.*/export function localCredentialHeaders(env = process.env) {- // Where a socket can be, nothing carries the credential: a holder of the TCP port would hear it (localDaemon.mjs).- if (daemonSocketPath(65_535, env)) return {};+ // Where a socket can be, and on Windows, where the daemon's pipe is the way, nothing carries the credential: a holder of the+ // TCP port would hear it (localDaemon.mjs; on Windows the Team account's daemon can hold it from boot, audit W1).+ if (process.platform === 'win32' || daemonSocketPath(65_535, env)) return {};const dir = env.ADAPTER_DATA_DIR || join(homedir(), '.harness', 'cli', 'data');const uid = typeof process.getuid === 'function' ? process.getuid() : null;- // Windows reports every file as 0o666 and every folder as 0o777, so the mode checks below would always refuse- // the credential the daemon wrote; there its protection is the profile folder's ACL (cli hookAuth.ts).- const posixModes = process.platform !== 'win32';const opened = [];try {const folder = openSync(dir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);opened.push(folder);const where = fstatSync(folder);- if (!where.isDirectory() || (uid !== null && where.uid !== uid) || (posixModes && (where.mode & 0o022) !== 0)) return {};+ if (!where.isDirectory() || (uid !== null && where.uid !== uid) || (where.mode & 0o022) !== 0) return {};const file = openSync(join(dir, 'hook-credential'), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);opened.push(file);const stat = fstatSync(file);- if (!stat.isFile() || stat.size > 128 || (uid !== null && stat.uid !== uid) || (posixModes && (stat.mode & 0o777) !== 0o600)) return {};+ if (!stat.isFile() || stat.size > 128 || (uid !== null && stat.uid !== uid) || (stat.mode & 0o777) !== 0o600) return {};const value = readFileSync(file, 'utf8').trim();return /^[A-Za-z0-9_-]{43}$/.test(value) ? { 'X-Harness-Local': value } : {};} catch {@@ -67,8 +65,8 @@ export const CREDENTIAL_REFUSED = "Harness refused this process's local credenti/** Whether the daemon behind a bridge socket that would not open refused the credential: a WebSocket* cannot report the 401, so the same headers are shown once over plain HTTP, which can. */export async function credentialRefused(url, headers, env = process.env) {- // Over the socket no credential is shown, and the port may be anyone's: there is nothing to ask it.- if (daemonSocketPath(65_535, env)) return false;+ // Over the socket or the pipe no credential is shown, and the port may be anyone's: there is nothing to ask it.+ if (process.platform === 'win32' || daemonSocketPath(65_535, env)) return false;try {const answer = await fetch(url.replace(/^ws:/, 'http:'), { headers, signal: AbortSignal.timeout(2000) });await answer.body?.cancel();diff --git a/store/agents/autonomous-grid/lib/localDaemon.mjs b/store/agents/autonomous-grid/lib/localDaemon.mjsindex b7a10e28d..cbf7f2550 100644--- a/store/agents/autonomous-grid/lib/localDaemon.mjs+++ b/store/agents/autonomous-grid/lib/localDaemon.mjs@@ -1,16 +1,18 @@/*** How a Store package reaches the Harness daemon on this computer: its Unix socket, owner only, and on macOS and Linux only that. Any* account can bind the daemon's TCP port while the daemon restarts, and would hear whatever is sent to it (audit H1). With the socket- * gone the daemon is down, and the caller says so. TCP remains where a socket cannot be: Windows, or a data folder too long for one.+ * gone the daemon is down, and the caller says so. On Windows it goes over the daemon's named pipe, proving the daemon's token, and+ * never to the port: the Team account's daemon starts at boot, before the owner's, and could hold it (audit W1,+ * docs/security/2026-11-02-team-account-windows.md). TCP remains only for a home too long to hold a socket.** One file, the same in every package that talks to the daemon, and in store/tools: a package stands alone and has no dependencies* (store/tools/port-holder.test.mjs pins the copies). The rules are the CLI's: cli/src/lib/localSocket.ts.*/-import { createHash, randomBytes } from 'node:crypto'-import { lstatSync } from 'node:fs'+import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto'+import { closeSync, fstatSync, lstatSync, openSync, readdirSync, readFileSync, realpathSync } from 'node:fs'import { request } from 'node:http'import { homedir } from 'node:os'-import { join } from 'node:path'+import { join, win32 } from 'node:path'/** sockaddr_un has 104 bytes on macOS, and the daemon creates the socket under a name 4 bytes longer. */const MAX_SOCKET_PATH_BYTES = 96@@ -48,6 +50,92 @@ export function socketIsPrivate(path) {}}+/** Mirrors LOCAL_PIPE_RE in cli/src/lib/windows/pipeAuth.ts: a pipe on this computer named harness-<id>, nothing else. A file, or+ * another computer's pipe (an SMB connection that can carry this user's NTLM credentials), is none. */+const LOCAL_PIPE_RE = /^\\\\\.\\pipe\\harness-([0-9a-f]{32})$/+/** Mirrors TOKEN_TEXT in cli/src/lib/windows/pipeAuth.ts. */+const DAEMON_TOKEN_RE = /^[0-9a-f]{64}\n?$/++export const HARNESS_NOT_RUNNING = 'Harness is not running on this computer. Start it with: harness start'+const PIPE_UNPROVEN = 'Something other than Harness answered on its local pipe. Restart Harness: harness stop && harness start'++/**+ * A state file of the daemon's on Windows, as cli/hook/notify.mjs `readWindowsStateFile` reads it. NTFS gives Node no owner or mode+ * bits, so the profile's ACL is the protection: the file must be a plain file, not a link or junction, whose real path lies inside+ * the profile or the data folder, and the file opened must be the one lstat saw. '' when it is refused; throws when there is none.+ */+function windowsStateFile(dataDir, name, maxBytes) {+ const file = join(dataDir, name)+ const roots = [homedir(), dataDir].flatMap((root) => { try { return [realpathSync.native(root)] } catch { return [] } })+ const inside = (target) => roots.some((root) => {+ const rel = win32.relative(root, target)+ return rel === '' || (rel !== '..' && !rel.startsWith('..\\') && !win32.isAbsolute(rel))+ })+ const link = lstatSync(file, { bigint: true })+ if (!link.isFile() || link.size > BigInt(maxBytes) || !inside(realpathSync.native(file))) return ''+ const fd = openSync(file, 'r')+ try {+ const opened = fstatSync(fd, { bigint: true })+ return opened.isFile() && opened.dev === link.dev && opened.ino === link.ino ? readFileSync(fd, 'utf8') : ''+ } finally {+ closeSync(fd)+ }+}++/**+ * The record's daemon still runs. Once it is gone any account can create a pipe of the recorded name, and would hear the request+ * before its answer can fail the proof. The daemon is this account's, so a pid that answers EPERM is another account's process now.+ */+function pidRuns(pid) {+ try { process.kill(pid, 0); return true } catch { return false }+}++/**+ * The daemon's pipe for `port` on Windows, as the CLI and its hook find it (cli/hook/notify.mjs `windowsDaemonPipe`): the record the+ * core writes, `daemon-<configured port>.json`, names the pipe and the core's pid, both new on each start; `port` may be the one the+ * daemon bound instead, so the records say which. One request's route: the pipe, its auth for a fresh nonce, and the check of the+ * daemon's proof (cli/src/lib/windows/pipeAuth.ts). The token never travels. Null off Windows, or with no record of a local pipe, no+ * token, or a core that has exited: then there is nothing to dial, and the port is never the way instead.+ */+export function daemonPipe(port, env = process.env, platform = process.platform) {+ if (platform !== 'win32') return null+ const dataDir = daemonDataDir(env)+ const read = (name) => { try { return JSON.parse(windowsStateFile(dataDir, name, 4096)) } catch { return null } }+ let record = read(`daemon-${port}.json`)+ if (!record) {+ try {+ for (const name of readdirSync(dataDir)) {+ if (!/^daemon-\d+\.json$/.test(name)) continue+ const candidate = read(name)+ if (candidate?.port === port) { record = candidate; break }+ }+ } catch { /* An unreadable folder has no record to offer. */ }+ }+ const id = typeof record?.pipe === 'string' ? LOCAL_PIPE_RE.exec(record.pipe)?.[1] : null+ if (!id || !Number.isSafeInteger(record.pid) || record.pid <= 0 || !pidRuns(record.pid)) return null+ let text = ''+ try { text = windowsStateFile(dataDir, 'daemon-token', 128) } catch { return null }+ if (!DAEMON_TOKEN_RE.test(text)) return null+ const token = Buffer.from(text.slice(0, 64), 'hex')+ const nonce = id + randomBytes(16).toString('hex')+ const mac = (separator) => createHmac('sha256', token).update(Buffer.of(separator)).update(nonce, 'utf8').digest('hex')+ const proof = Buffer.from(mac(0x00), 'hex')+ return {+ path: record.pipe,+ headers: { 'X-Harness-Auth': `${nonce}.${mac(0x01)}` },+ proven: (value) => typeof value === 'string' && /^[0-9a-f]{64}$/.test(value) && timingSafeEqual(Buffer.from(value, 'hex'), proof),+ }+}++/** How a request reaches the daemon here: its pipe on Windows, its private socket elsewhere; null when there is neither to use. */+function localRoute(port, env) {+ if (process.platform === 'win32') return daemonPipe(port, env)+ const path = daemonSocketPath(port, env)+ return path && socketIsPrivate(path) ? { path, headers: {}, proven: null } : null+}++const routeMissing = () => new Error(process.platform === 'win32' ? HARNESS_NOT_RUNNING : 'The Harness socket is missing or not private.')+const portOf = (url) => Number(url.port) || (url.protocol === 'https:' || url.protocol === 'wss:' ? 443 : 80)/** One client frame: clients mask (RFC 6455 5.3). */@@ -65,23 +153,28 @@ class SocketEvent extends Event {constructor(type, fields) { super(type); Object.assign(this, fields) }}-/** The WebSocket client these packages use, over the daemon's socket: open, message (text), error, close, send, close. */-class UnixWebSocket extends EventTarget {+/** The WebSocket client these packages use, over the daemon's socket or pipe: open, message (text), error, close, send, close. */+class LocalWebSocket extends EventTarget {static CONNECTING = 0; static OPEN = 1; static CLOSING = 2; static CLOSED = 3readyState = 0#asked = null; #stream = null; #closed = false; #held = Buffer.alloc(0); #parts = []; #size = 0; #timer = null- constructor(path, resource) {+ /** `route` is localRoute's: null is no daemon to dial. */+ constructor(route, resource) {super()// Told after this returns, as a WebSocket always is: the caller adds its listeners first.- if (!socketIsPrivate(path)) { queueMicrotask(() => this.#end(1006, new Error('The Harness socket is missing or not private.'))); return }+ if (!route) { const error = routeMissing(); queueMicrotask(() => this.#end(1006, error)); return }const key = randomBytes(16).toString('base64')- const asked = this.#asked = request({ socketPath: path, path: resource, headers: { Connection: 'Upgrade', Upgrade: 'websocket', 'Sec-WebSocket-Version': '13', 'Sec-WebSocket-Key': key } })+ const asked = this.#asked = request({ socketPath: route.path, path: resource,+ headers: { ...route.headers, Connection: 'Upgrade', Upgrade: 'websocket', 'Sec-WebSocket-Version': '13', 'Sec-WebSocket-Key': key } })asked.on('error', (error) => this.#end(1006, error))asked.on('response', (answer) => { answer.resume(); this.#end(1006, new Error(`The daemon answered ${answer.statusCode}.`)) })asked.on('upgrade', (answer, stream, head) => {// Given up on while it was on its way: the caller has been told, so it never comes back to life.if (this.#closed) { stream.destroy(); return }+ // A pipe's name can be taken by any account once its daemon is gone: an upgrade without the daemon's proof never opens,+ // so a caller that sends its first frame on `open` sends it nothing.+ if (route.proven && !route.proven(answer.headers['x-harness-proof'])) { stream.destroy(); this.#end(1006, new Error(PIPE_UNPROVEN)); return }const accept = createHash('sha1').update(key + WS_GUID).digest('base64')if (answer.headers['sec-websocket-accept'] !== accept) { stream.destroy(); this.#end(1006, new Error('The daemon answered no WebSocket.')); return }this.#stream = stream@@ -171,27 +264,32 @@ class UnixWebSocket extends EventTarget {}/**- * What a package opens to the daemon's `/api/local-ws`: `new DaemonWebSocket(url, { headers, env })`, over the socket where one can be.- * Elsewhere Node's own WebSocket on `url`, with the headers given.+ * What a package opens to the daemon's `/api/local-ws`: `new DaemonWebSocket(url, { headers, env })`, over the socket where one can be+ * and over the pipe on Windows. Only a home too long to hold a socket gets Node's own WebSocket on `url`, with the headers given.*/export class DaemonWebSocket {constructor(url, { headers = {}, env = process.env } = {}) {- const parsed = new URL(url)- const path = daemonSocketPath(portOf(parsed), env)- return path ? new UnixWebSocket(path, parsed.pathname) : new globalThis.WebSocket(url, { headers })+ const parsed = new URL(url), port = portOf(parsed)+ if (process.platform !== 'win32' && !daemonSocketPath(port, env)) return new globalThis.WebSocket(url, { headers })+ return new LocalWebSocket(localRoute(port, env), parsed.pathname)}}-/** `fetch` for the daemon's REST API at `url`, over its socket where one can be. Answers `status`, `ok`, `json()` and `text()`. */+/**+ * `fetch` for the daemon's REST API at `url`, over its socket where one can be and over its pipe on Windows, where an answer is taken+ * only with the daemon's proof. Answers `status`, `ok`, `json()` and `text()`.+ */export function daemonFetch(url, { method = 'GET', headers = {}, body, signal, env = process.env } = {}) {- const parsed = new URL(url)- const path = daemonSocketPath(portOf(parsed), env)- if (!path) return fetch(url, { method, headers, ...(body === undefined ? {} : { body }), ...(signal ? { signal } : {}) })+ const parsed = new URL(url), port = portOf(parsed)+ if (process.platform !== 'win32' && !daemonSocketPath(port, env)) return fetch(url, { method, headers, ...(body === undefined ? {} : { body }), ...(signal ? { signal } : {}) })return new Promise((resolve, reject) => {- if (!socketIsPrivate(path)) { reject(new Error('The Harness socket is missing or not private.')); return }+ const route = localRoute(port, env)+ if (!route) { reject(routeMissing()); return }const payload = body === undefined ? null : Buffer.from(body)- const asked = request({ socketPath: path, method, path: `${parsed.pathname}${parsed.search}`, ...(signal ? { signal } : {}),- headers: { ...headers, ...(payload ? { 'content-length': String(payload.length) } : {}) } }, (answer) => {+ const asked = request({ socketPath: route.path, method, path: `${parsed.pathname}${parsed.search}`, ...(signal ? { signal } : {}),+ headers: { ...headers, ...route.headers, ...(payload ? { 'content-length': String(payload.length) } : {}) } }, (answer) => {+ // Before the body is read: an answer on the pipe without the daemon's proof is whatever took its name (cli pipeClient.ts).+ if (route.proven && !route.proven(answer.headers['x-harness-proof'])) { reject(new Error(PIPE_UNPROVEN)); asked.destroy(); return }const parts = []answer.on('data', (part) => parts.push(part))answer.on('error', reject)diff --git a/store/agents/autonomous-grid/test/credential.test.mjs b/store/agents/autonomous-grid/test/credential.test.mjsindex 983f55319..7738aad44 100644--- a/store/agents/autonomous-grid/test/credential.test.mjs+++ b/store/agents/autonomous-grid/test/credential.test.mjs@@ -37,14 +37,14 @@ test('the local credential is read the way the CLI reads it, and only then', ()assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR:dataDir({ credential:'too-short' }) }), {});});-// Windows reports every file as 0o666 and every folder as 0o777, so the POSIX mode checks would refuse the-// credential the daemon wrote and the daemon, which wants it on TCP there, would answer 401 (cli hookAuth.ts).-test('on Windows the credential is read whatever mode the folder and file report', (t) => {+// On Windows the credential never goes to the port, whose holder may be another account's: the Team account's daemon+// starts at boot, before the owner's (audit W1). The package reaches the daemon over its proven pipe instead (localDaemon.mjs).+test('on Windows no credential is read: it never goes to the port', (t) => {const platform = Object.getOwnPropertyDescriptor(process, 'platform');Object.defineProperty(process, 'platform', { value:'win32' });t.after(() => Object.defineProperty(process, 'platform', platform));- assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR:dataDir({ mode:0o666, folderMode:0o777 }) }), { 'X-Harness-Local':CREDENTIAL });- assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR:dataDir({ credential:'too-short', mode:0o666 }) }), {}, 'the value is still checked');+ assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR:dataDir({ mode:0o666, folderMode:0o777 }) }), {});+ assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR:dataDir() }), {}, 'nor a credential the POSIX checks would pass');});test('a fleet command shows the bridge the local credential', async t => {diff --git a/store/agents/harness-monitor/lib/bridge.mjs b/store/agents/harness-monitor/lib/bridge.mjsindex 2c02a4c58..8d37b77a1 100644--- a/store/agents/harness-monitor/lib/bridge.mjs+++ b/store/agents/harness-monitor/lib/bridge.mjs@@ -36,23 +36,21 @@ export const DEFAULT_BRIDGE = 'ws://127.0.0.1:18473/api/local-ws'* The same function, by the same name, is in every Store package that talks to the daemon.*/export function localCredentialHeaders(env = process.env) {- // Where a socket can be, nothing carries the credential: a holder of the TCP port would hear it (localDaemon.mjs).- if (daemonSocketPath(65_535, env)) return {}+ // Where a socket can be, and on Windows, where the daemon's pipe is the way, nothing carries the credential: a holder of the+ // TCP port would hear it (localDaemon.mjs; on Windows the Team account's daemon can hold it from boot, audit W1).+ if (process.platform === 'win32' || daemonSocketPath(65_535, env)) return {}const dir = env.ADAPTER_DATA_DIR || join(homedir(), '.harness', 'cli', 'data')const uid = typeof process.getuid === 'function' ? process.getuid() : null- // Windows reports every file as 0o666 and every folder as 0o777, so the mode checks below would always refuse- // the credential the daemon wrote; there its protection is the profile folder's ACL (cli hookAuth.ts).- const posixModes = process.platform !== 'win32'const opened = []try {const folder = openSync(dir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW)opened.push(folder)const where = fstatSync(folder)- if (!where.isDirectory() || (uid !== null && where.uid !== uid) || (posixModes && (where.mode & 0o022) !== 0)) return {}+ if (!where.isDirectory() || (uid !== null && where.uid !== uid) || (where.mode & 0o022) !== 0) return {}const file = openSync(join(dir, 'hook-credential'), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)opened.push(file)const stat = fstatSync(file)- if (!stat.isFile() || stat.size > 128 || (uid !== null && stat.uid !== uid) || (posixModes && (stat.mode & 0o777) !== 0o600)) return {}+ if (!stat.isFile() || stat.size > 128 || (uid !== null && stat.uid !== uid) || (stat.mode & 0o777) !== 0o600) return {}const value = readFileSync(file, 'utf8').trim()return /^[A-Za-z0-9_-]{43}$/.test(value) ? { 'X-Harness-Local': value } : {}} catch {@@ -67,8 +65,8 @@ const CREDENTIAL_REFUSED = "Harness refused this process's local credential. Run/** Whether the daemon behind a bridge socket that would not open refused the credential: a WebSocket* cannot report the 401, so the same headers are shown once over plain HTTP, which can. */async function credentialRefused(url, headers, env = process.env) {- // Over the socket no credential is shown, and the port may be anyone's: there is nothing to ask it.- if (daemonSocketPath(65_535, env)) return false+ // Over the socket or the pipe no credential is shown, and the port may be anyone's: there is nothing to ask it.+ if (process.platform === 'win32' || daemonSocketPath(65_535, env)) return falsetry {const answer = await fetch(url.replace(/^ws:/, 'http:'), { headers, signal: AbortSignal.timeout(2000) })await answer.body?.cancel()diff --git a/store/agents/harness-monitor/lib/localDaemon.mjs b/store/agents/harness-monitor/lib/localDaemon.mjsindex b7a10e28d..cbf7f2550 100644--- a/store/agents/harness-monitor/lib/localDaemon.mjs+++ b/store/agents/harness-monitor/lib/localDaemon.mjs@@ -1,16 +1,18 @@/*** How a Store package reaches the Harness daemon on this computer: its Unix socket, owner only, and on macOS and Linux only that. Any* account can bind the daemon's TCP port while the daemon restarts, and would hear whatever is sent to it (audit H1). With the socket- * gone the daemon is down, and the caller says so. TCP remains where a socket cannot be: Windows, or a data folder too long for one.+ * gone the daemon is down, and the caller says so. On Windows it goes over the daemon's named pipe, proving the daemon's token, and+ * never to the port: the Team account's daemon starts at boot, before the owner's, and could hold it (audit W1,+ * docs/security/2026-11-02-team-account-windows.md). TCP remains only for a home too long to hold a socket.** One file, the same in every package that talks to the daemon, and in store/tools: a package stands alone and has no dependencies* (store/tools/port-holder.test.mjs pins the copies). The rules are the CLI's: cli/src/lib/localSocket.ts.*/-import { createHash, randomBytes } from 'node:crypto'-import { lstatSync } from 'node:fs'+import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto'+import { closeSync, fstatSync, lstatSync, openSync, readdirSync, readFileSync, realpathSync } from 'node:fs'import { request } from 'node:http'import { homedir } from 'node:os'-import { join } from 'node:path'+import { join, win32 } from 'node:path'/** sockaddr_un has 104 bytes on macOS, and the daemon creates the socket under a name 4 bytes longer. */const MAX_SOCKET_PATH_BYTES = 96@@ -48,6 +50,92 @@ export function socketIsPrivate(path) {}}+/** Mirrors LOCAL_PIPE_RE in cli/src/lib/windows/pipeAuth.ts: a pipe on this computer named harness-<id>, nothing else. A file, or+ * another computer's pipe (an SMB connection that can carry this user's NTLM credentials), is none. */+const LOCAL_PIPE_RE = /^\\\\\.\\pipe\\harness-([0-9a-f]{32})$/+/** Mirrors TOKEN_TEXT in cli/src/lib/windows/pipeAuth.ts. */+const DAEMON_TOKEN_RE = /^[0-9a-f]{64}\n?$/++export const HARNESS_NOT_RUNNING = 'Harness is not running on this computer. Start it with: harness start'+const PIPE_UNPROVEN = 'Something other than Harness answered on its local pipe. Restart Harness: harness stop && harness start'++/**+ * A state file of the daemon's on Windows, as cli/hook/notify.mjs `readWindowsStateFile` reads it. NTFS gives Node no owner or mode+ * bits, so the profile's ACL is the protection: the file must be a plain file, not a link or junction, whose real path lies inside+ * the profile or the data folder, and the file opened must be the one lstat saw. '' when it is refused; throws when there is none.+ */+function windowsStateFile(dataDir, name, maxBytes) {+ const file = join(dataDir, name)+ const roots = [homedir(), dataDir].flatMap((root) => { try { return [realpathSync.native(root)] } catch { return [] } })+ const inside = (target) => roots.some((root) => {+ const rel = win32.relative(root, target)+ return rel === '' || (rel !== '..' && !rel.startsWith('..\\') && !win32.isAbsolute(rel))+ })+ const link = lstatSync(file, { bigint: true })+ if (!link.isFile() || link.size > BigInt(maxBytes) || !inside(realpathSync.native(file))) return ''+ const fd = openSync(file, 'r')+ try {+ const opened = fstatSync(fd, { bigint: true })+ return opened.isFile() && opened.dev === link.dev && opened.ino === link.ino ? readFileSync(fd, 'utf8') : ''+ } finally {+ closeSync(fd)+ }+}++/**+ * The record's daemon still runs. Once it is gone any account can create a pipe of the recorded name, and would hear the request+ * before its answer can fail the proof. The daemon is this account's, so a pid that answers EPERM is another account's process now.+ */+function pidRuns(pid) {+ try { process.kill(pid, 0); return true } catch { return false }+}++/**+ * The daemon's pipe for `port` on Windows, as the CLI and its hook find it (cli/hook/notify.mjs `windowsDaemonPipe`): the record the+ * core writes, `daemon-<configured port>.json`, names the pipe and the core's pid, both new on each start; `port` may be the one the+ * daemon bound instead, so the records say which. One request's route: the pipe, its auth for a fresh nonce, and the check of the+ * daemon's proof (cli/src/lib/windows/pipeAuth.ts). The token never travels. Null off Windows, or with no record of a local pipe, no+ * token, or a core that has exited: then there is nothing to dial, and the port is never the way instead.+ */+export function daemonPipe(port, env = process.env, platform = process.platform) {+ if (platform !== 'win32') return null+ const dataDir = daemonDataDir(env)+ const read = (name) => { try { return JSON.parse(windowsStateFile(dataDir, name, 4096)) } catch { return null } }+ let record = read(`daemon-${port}.json`)+ if (!record) {+ try {+ for (const name of readdirSync(dataDir)) {+ if (!/^daemon-\d+\.json$/.test(name)) continue+ const candidate = read(name)+ if (candidate?.port === port) { record = candidate; break }+ }+ } catch { /* An unreadable folder has no record to offer. */ }+ }+ const id = typeof record?.pipe === 'string' ? LOCAL_PIPE_RE.exec(record.pipe)?.[1] : null+ if (!id || !Number.isSafeInteger(record.pid) || record.pid <= 0 || !pidRuns(record.pid)) return null+ let text = ''+ try { text = windowsStateFile(dataDir, 'daemon-token', 128) } catch { return null }+ if (!DAEMON_TOKEN_RE.test(text)) return null+ const token = Buffer.from(text.slice(0, 64), 'hex')+ const nonce = id + randomBytes(16).toString('hex')+ const mac = (separator) => createHmac('sha256', token).update(Buffer.of(separator)).update(nonce, 'utf8').digest('hex')+ const proof = Buffer.from(mac(0x00), 'hex')+ return {+ path: record.pipe,+ headers: { 'X-Harness-Auth': `${nonce}.${mac(0x01)}` },+ proven: (value) => typeof value === 'string' && /^[0-9a-f]{64}$/.test(value) && timingSafeEqual(Buffer.from(value, 'hex'), proof),+ }+}++/** How a request reaches the daemon here: its pipe on Windows, its private socket elsewhere; null when there is neither to use. */+function localRoute(port, env) {+ if (process.platform === 'win32') return daemonPipe(port, env)+ const path = daemonSocketPath(port, env)+ return path && socketIsPrivate(path) ? { path, headers: {}, proven: null } : null+}++const routeMissing = () => new Error(process.platform === 'win32' ? HARNESS_NOT_RUNNING : 'The Harness socket is missing or not private.')+const portOf = (url) => Number(url.port) || (url.protocol === 'https:' || url.protocol === 'wss:' ? 443 : 80)/** One client frame: clients mask (RFC 6455 5.3). */@@ -65,23 +153,28 @@ class SocketEvent extends Event {constructor(type, fields) { super(type); Object.assign(this, fields) }}-/** The WebSocket client these packages use, over the daemon's socket: open, message (text), error, close, send, close. */-class UnixWebSocket extends EventTarget {+/** The WebSocket client these packages use, over the daemon's socket or pipe: open, message (text), error, close, send, close. */+class LocalWebSocket extends EventTarget {static CONNECTING = 0; static OPEN = 1; static CLOSING = 2; static CLOSED = 3readyState = 0#asked = null; #stream = null; #closed = false; #held = Buffer.alloc(0); #parts = []; #size = 0; #timer = null- constructor(path, resource) {+ /** `route` is localRoute's: null is no daemon to dial. */+ constructor(route, resource) {super()// Told after this returns, as a WebSocket always is: the caller adds its listeners first.- if (!socketIsPrivate(path)) { queueMicrotask(() => this.#end(1006, new Error('The Harness socket is missing or not private.'))); return }+ if (!route) { const error = routeMissing(); queueMicrotask(() => this.#end(1006, error)); return }const key = randomBytes(16).toString('base64')- const asked = this.#asked = request({ socketPath: path, path: resource, headers: { Connection: 'Upgrade', Upgrade: 'websocket', 'Sec-WebSocket-Version': '13', 'Sec-WebSocket-Key': key } })+ const asked = this.#asked = request({ socketPath: route.path, path: resource,+ headers: { ...route.headers, Connection: 'Upgrade', Upgrade: 'websocket', 'Sec-WebSocket-Version': '13', 'Sec-WebSocket-Key': key } })asked.on('error', (error) => this.#end(1006, error))asked.on('response', (answer) => { answer.resume(); this.#end(1006, new Error(`The daemon answered ${answer.statusCode}.`)) })asked.on('upgrade', (answer, stream, head) => {// Given up on while it was on its way: the caller has been told, so it never comes back to life.if (this.#closed) { stream.destroy(); return }+ // A pipe's name can be taken by any account once its daemon is gone: an upgrade without the daemon's proof never opens,+ // so a caller that sends its first frame on `open` sends it nothing.+ if (route.proven && !route.proven(answer.headers['x-harness-proof'])) { stream.destroy(); this.#end(1006, new Error(PIPE_UNPROVEN)); return }const accept = createHash('sha1').update(key + WS_GUID).digest('base64')if (answer.headers['sec-websocket-accept'] !== accept) { stream.destroy(); this.#end(1006, new Error('The daemon answered no WebSocket.')); return }this.#stream = stream@@ -171,27 +264,32 @@ class UnixWebSocket extends EventTarget {}/**- * What a package opens to the daemon's `/api/local-ws`: `new DaemonWebSocket(url, { headers, env })`, over the socket where one can be.- * Elsewhere Node's own WebSocket on `url`, with the headers given.+ * What a package opens to the daemon's `/api/local-ws`: `new DaemonWebSocket(url, { headers, env })`, over the socket where one can be+ * and over the pipe on Windows. Only a home too long to hold a socket gets Node's own WebSocket on `url`, with the headers given.*/export class DaemonWebSocket {constructor(url, { headers = {}, env = process.env } = {}) {- const parsed = new URL(url)- const path = daemonSocketPath(portOf(parsed), env)- return path ? new UnixWebSocket(path, parsed.pathname) : new globalThis.WebSocket(url, { headers })+ const parsed = new URL(url), port = portOf(parsed)+ if (process.platform !== 'win32' && !daemonSocketPath(port, env)) return new globalThis.WebSocket(url, { headers })+ return new LocalWebSocket(localRoute(port, env), parsed.pathname)}}-/** `fetch` for the daemon's REST API at `url`, over its socket where one can be. Answers `status`, `ok`, `json()` and `text()`. */+/**+ * `fetch` for the daemon's REST API at `url`, over its socket where one can be and over its pipe on Windows, where an answer is taken+ * only with the daemon's proof. Answers `status`, `ok`, `json()` and `text()`.+ */export function daemonFetch(url, { method = 'GET', headers = {}, body, signal, env = process.env } = {}) {- const parsed = new URL(url)- const path = daemonSocketPath(portOf(parsed), env)- if (!path) return fetch(url, { method, headers, ...(body === undefined ? {} : { body }), ...(signal ? { signal } : {}) })+ const parsed = new URL(url), port = portOf(parsed)+ if (process.platform !== 'win32' && !daemonSocketPath(port, env)) return fetch(url, { method, headers, ...(body === undefined ? {} : { body }), ...(signal ? { signal } : {}) })return new Promise((resolve, reject) => {- if (!socketIsPrivate(path)) { reject(new Error('The Harness socket is missing or not private.')); return }+ const route = localRoute(port, env)+ if (!route) { reject(routeMissing()); return }const payload = body === undefined ? null : Buffer.from(body)- const asked = request({ socketPath: path, method, path: `${parsed.pathname}${parsed.search}`, ...(signal ? { signal } : {}),- headers: { ...headers, ...(payload ? { 'content-length': String(payload.length) } : {}) } }, (answer) => {+ const asked = request({ socketPath: route.path, method, path: `${parsed.pathname}${parsed.search}`, ...(signal ? { signal } : {}),+ headers: { ...headers, ...route.headers, ...(payload ? { 'content-length': String(payload.length) } : {}) } }, (answer) => {+ // Before the body is read: an answer on the pipe without the daemon's proof is whatever took its name (cli pipeClient.ts).+ if (route.proven && !route.proven(answer.headers['x-harness-proof'])) { reject(new Error(PIPE_UNPROVEN)); asked.destroy(); return }const parts = []answer.on('data', (part) => parts.push(part))answer.on('error', reject)diff --git a/store/agents/harness-monitor/test/credential.test.mjs b/store/agents/harness-monitor/test/credential.test.mjsindex 0f2f372a7..5b48eea6e 100644--- a/store/agents/harness-monitor/test/credential.test.mjs+++ b/store/agents/harness-monitor/test/credential.test.mjs@@ -81,14 +81,14 @@ test('the local credential is read the way the CLI reads it, and only then', ()assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR: dataDir({ credential: 'too-short' }) }), {})})-// Windows reports every file as 0o666 and every folder as 0o777, so the POSIX mode checks would refuse the-// credential the daemon wrote and the daemon, which wants it on TCP there, would answer 401 (cli hookAuth.ts).-test('on Windows the credential is read whatever mode the folder and file report', (t) => {+// On Windows the credential never goes to the port, whose holder may be another account's: the Team account's daemon+// starts at boot, before the owner's (audit W1). The package reaches the daemon over its proven pipe instead (localDaemon.mjs).+test('on Windows no credential is read: it never goes to the port', (t) => {const platform = Object.getOwnPropertyDescriptor(process, 'platform')Object.defineProperty(process, 'platform', { value: 'win32' })t.after(() => Object.defineProperty(process, 'platform', platform))- assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR: dataDir({ mode: 0o666, folderMode: 0o777 }) }), { 'X-Harness-Local': CREDENTIAL })- assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR: dataDir({ credential: 'too-short', mode: 0o666 }) }), {}, 'the value is still checked')+ assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR: dataDir({ mode: 0o666, folderMode: 0o777 }) }), {})+ assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR: dataDir() }), {}, 'nor a credential the POSIX checks would pass')})test('the bridge shows the daemon its local credential', async (t) => {diff --git a/store/agents/machine-monitor/lib/daemon.mjs b/store/agents/machine-monitor/lib/daemon.mjsindex 415641db9..6f7a9c1a0 100644--- a/store/agents/machine-monitor/lib/daemon.mjs+++ b/store/agents/machine-monitor/lib/daemon.mjs@@ -52,23 +52,21 @@ export function dataDir(env = process.env) {* The same function, by the same name, is in every Store package that talks to the daemon.*/export function localCredentialHeaders(env = process.env) {- // Where a socket can be, nothing carries the credential: a holder of the TCP port would hear it (localDaemon.mjs).- if (daemonSocketPath(65_535, env)) return {};+ // Where a socket can be, and on Windows, where the daemon's pipe is the way, nothing carries the credential: a holder of the+ // TCP port would hear it (localDaemon.mjs; on Windows the Team account's daemon can hold it from boot, audit W1).+ if (process.platform === 'win32' || daemonSocketPath(65_535, env)) return {};const dir = dataDir(env);const uid = typeof process.getuid === 'function' ? process.getuid() : null;- // Windows reports every file as 0o666 and every folder as 0o777, so the mode checks below would always refuse- // the credential the daemon wrote; there its protection is the profile folder's ACL (cli hookAuth.ts).- const posixModes = process.platform !== 'win32';const opened = [];try {const folder = openSync(dir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);opened.push(folder);const where = fstatSync(folder);- if (!where.isDirectory() || (uid !== null && where.uid !== uid) || (posixModes && (where.mode & 0o022) !== 0)) return {};+ if (!where.isDirectory() || (uid !== null && where.uid !== uid) || (where.mode & 0o022) !== 0) return {};const file = openSync(join(dir, 'hook-credential'), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);opened.push(file);const stat = fstatSync(file);- if (!stat.isFile() || stat.size > 128 || (uid !== null && stat.uid !== uid) || (posixModes && (stat.mode & 0o777) !== 0o600)) return {};+ if (!stat.isFile() || stat.size > 128 || (uid !== null && stat.uid !== uid) || (stat.mode & 0o777) !== 0o600) return {};const value = readFileSync(file, 'utf8').trim();return /^[A-Za-z0-9_-]{43}$/.test(value) ? { 'X-Harness-Local': value } : {};} catch {@@ -84,8 +82,8 @@ const CREDENTIAL_REFUSED = "Harness refused this process's local credential. Run/** Whether the daemon behind a bridge socket that would not open refused the credential: a WebSocket* cannot report the 401, so the same headers are shown once over plain HTTP, which can. */async function credentialRefused(url, headers, env = process.env) {- // Over the socket no credential is shown, and the port may be anyone's: there is nothing to ask it.- if (daemonSocketPath(65_535, env)) return false;+ // Over the socket or the pipe no credential is shown, and the port may be anyone's: there is nothing to ask it.+ if (process.platform === 'win32' || daemonSocketPath(65_535, env)) return false;try {const answer = await fetch(url.replace(/^ws:/, 'http:'), { headers, signal: AbortSignal.timeout(2000) });await answer.body?.cancel();diff --git a/store/agents/machine-monitor/lib/localDaemon.mjs b/store/agents/machine-monitor/lib/localDaemon.mjsindex b7a10e28d..cbf7f2550 100644--- a/store/agents/machine-monitor/lib/localDaemon.mjs+++ b/store/agents/machine-monitor/lib/localDaemon.mjs@@ -1,16 +1,18 @@/*** How a Store package reaches the Harness daemon on this computer: its Unix socket, owner only, and on macOS and Linux only that. Any* account can bind the daemon's TCP port while the daemon restarts, and would hear whatever is sent to it (audit H1). With the socket- * gone the daemon is down, and the caller says so. TCP remains where a socket cannot be: Windows, or a data folder too long for one.+ * gone the daemon is down, and the caller says so. On Windows it goes over the daemon's named pipe, proving the daemon's token, and+ * never to the port: the Team account's daemon starts at boot, before the owner's, and could hold it (audit W1,+ * docs/security/2026-11-02-team-account-windows.md). TCP remains only for a home too long to hold a socket.** One file, the same in every package that talks to the daemon, and in store/tools: a package stands alone and has no dependencies* (store/tools/port-holder.test.mjs pins the copies). The rules are the CLI's: cli/src/lib/localSocket.ts.*/-import { createHash, randomBytes } from 'node:crypto'-import { lstatSync } from 'node:fs'+import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto'+import { closeSync, fstatSync, lstatSync, openSync, readdirSync, readFileSync, realpathSync } from 'node:fs'import { request } from 'node:http'import { homedir } from 'node:os'-import { join } from 'node:path'+import { join, win32 } from 'node:path'/** sockaddr_un has 104 bytes on macOS, and the daemon creates the socket under a name 4 bytes longer. */const MAX_SOCKET_PATH_BYTES = 96@@ -48,6 +50,92 @@ export function socketIsPrivate(path) {}}+/** Mirrors LOCAL_PIPE_RE in cli/src/lib/windows/pipeAuth.ts: a pipe on this computer named harness-<id>, nothing else. A file, or+ * another computer's pipe (an SMB connection that can carry this user's NTLM credentials), is none. */+const LOCAL_PIPE_RE = /^\\\\\.\\pipe\\harness-([0-9a-f]{32})$/+/** Mirrors TOKEN_TEXT in cli/src/lib/windows/pipeAuth.ts. */+const DAEMON_TOKEN_RE = /^[0-9a-f]{64}\n?$/++export const HARNESS_NOT_RUNNING = 'Harness is not running on this computer. Start it with: harness start'+const PIPE_UNPROVEN = 'Something other than Harness answered on its local pipe. Restart Harness: harness stop && harness start'++/**+ * A state file of the daemon's on Windows, as cli/hook/notify.mjs `readWindowsStateFile` reads it. NTFS gives Node no owner or mode+ * bits, so the profile's ACL is the protection: the file must be a plain file, not a link or junction, whose real path lies inside+ * the profile or the data folder, and the file opened must be the one lstat saw. '' when it is refused; throws when there is none.+ */+function windowsStateFile(dataDir, name, maxBytes) {+ const file = join(dataDir, name)+ const roots = [homedir(), dataDir].flatMap((root) => { try { return [realpathSync.native(root)] } catch { return [] } })+ const inside = (target) => roots.some((root) => {+ const rel = win32.relative(root, target)+ return rel === '' || (rel !== '..' && !rel.startsWith('..\\') && !win32.isAbsolute(rel))+ })+ const link = lstatSync(file, { bigint: true })+ if (!link.isFile() || link.size > BigInt(maxBytes) || !inside(realpathSync.native(file))) return ''+ const fd = openSync(file, 'r')+ try {+ const opened = fstatSync(fd, { bigint: true })+ return opened.isFile() && opened.dev === link.dev && opened.ino === link.ino ? readFileSync(fd, 'utf8') : ''+ } finally {+ closeSync(fd)+ }+}++/**+ * The record's daemon still runs. Once it is gone any account can create a pipe of the recorded name, and would hear the request+ * before its answer can fail the proof. The daemon is this account's, so a pid that answers EPERM is another account's process now.+ */+function pidRuns(pid) {+ try { process.kill(pid, 0); return true } catch { return false }+}++/**+ * The daemon's pipe for `port` on Windows, as the CLI and its hook find it (cli/hook/notify.mjs `windowsDaemonPipe`): the record the+ * core writes, `daemon-<configured port>.json`, names the pipe and the core's pid, both new on each start; `port` may be the one the+ * daemon bound instead, so the records say which. One request's route: the pipe, its auth for a fresh nonce, and the check of the+ * daemon's proof (cli/src/lib/windows/pipeAuth.ts). The token never travels. Null off Windows, or with no record of a local pipe, no+ * token, or a core that has exited: then there is nothing to dial, and the port is never the way instead.+ */+export function daemonPipe(port, env = process.env, platform = process.platform) {+ if (platform !== 'win32') return null+ const dataDir = daemonDataDir(env)+ const read = (name) => { try { return JSON.parse(windowsStateFile(dataDir, name, 4096)) } catch { return null } }+ let record = read(`daemon-${port}.json`)+ if (!record) {+ try {+ for (const name of readdirSync(dataDir)) {+ if (!/^daemon-\d+\.json$/.test(name)) continue+ const candidate = read(name)+ if (candidate?.port === port) { record = candidate; break }+ }+ } catch { /* An unreadable folder has no record to offer. */ }+ }+ const id = typeof record?.pipe === 'string' ? LOCAL_PIPE_RE.exec(record.pipe)?.[1] : null+ if (!id || !Number.isSafeInteger(record.pid) || record.pid <= 0 || !pidRuns(record.pid)) return null+ let text = ''+ try { text = windowsStateFile(dataDir, 'daemon-token', 128) } catch { return null }+ if (!DAEMON_TOKEN_RE.test(text)) return null+ const token = Buffer.from(text.slice(0, 64), 'hex')+ const nonce = id + randomBytes(16).toString('hex')+ const mac = (separator) => createHmac('sha256', token).update(Buffer.of(separator)).update(nonce, 'utf8').digest('hex')+ const proof = Buffer.from(mac(0x00), 'hex')+ return {+ path: record.pipe,+ headers: { 'X-Harness-Auth': `${nonce}.${mac(0x01)}` },+ proven: (value) => typeof value === 'string' && /^[0-9a-f]{64}$/.test(value) && timingSafeEqual(Buffer.from(value, 'hex'), proof),+ }+}++/** How a request reaches the daemon here: its pipe on Windows, its private socket elsewhere; null when there is neither to use. */+function localRoute(port, env) {+ if (process.platform === 'win32') return daemonPipe(port, env)+ const path = daemonSocketPath(port, env)+ return path && socketIsPrivate(path) ? { path, headers: {}, proven: null } : null+}++const routeMissing = () => new Error(process.platform === 'win32' ? HARNESS_NOT_RUNNING : 'The Harness socket is missing or not private.')+const portOf = (url) => Number(url.port) || (url.protocol === 'https:' || url.protocol === 'wss:' ? 443 : 80)/** One client frame: clients mask (RFC 6455 5.3). */@@ -65,23 +153,28 @@ class SocketEvent extends Event {constructor(type, fields) { super(type); Object.assign(this, fields) }}-/** The WebSocket client these packages use, over the daemon's socket: open, message (text), error, close, send, close. */-class UnixWebSocket extends EventTarget {+/** The WebSocket client these packages use, over the daemon's socket or pipe: open, message (text), error, close, send, close. */+class LocalWebSocket extends EventTarget {static CONNECTING = 0; static OPEN = 1; static CLOSING = 2; static CLOSED = 3readyState = 0#asked = null; #stream = null; #closed = false; #held = Buffer.alloc(0); #parts = []; #size = 0; #timer = null- constructor(path, resource) {+ /** `route` is localRoute's: null is no daemon to dial. */+ constructor(route, resource) {super()// Told after this returns, as a WebSocket always is: the caller adds its listeners first.- if (!socketIsPrivate(path)) { queueMicrotask(() => this.#end(1006, new Error('The Harness socket is missing or not private.'))); return }+ if (!route) { const error = routeMissing(); queueMicrotask(() => this.#end(1006, error)); return }const key = randomBytes(16).toString('base64')- const asked = this.#asked = request({ socketPath: path, path: resource, headers: { Connection: 'Upgrade', Upgrade: 'websocket', 'Sec-WebSocket-Version': '13', 'Sec-WebSocket-Key': key } })+ const asked = this.#asked = request({ socketPath: route.path, path: resource,+ headers: { ...route.headers, Connection: 'Upgrade', Upgrade: 'websocket', 'Sec-WebSocket-Version': '13', 'Sec-WebSocket-Key': key } })asked.on('error', (error) => this.#end(1006, error))asked.on('response', (answer) => { answer.resume(); this.#end(1006, new Error(`The daemon answered ${answer.statusCode}.`)) })asked.on('upgrade', (answer, stream, head) => {// Given up on while it was on its way: the caller has been told, so it never comes back to life.if (this.#closed) { stream.destroy(); return }+ // A pipe's name can be taken by any account once its daemon is gone: an upgrade without the daemon's proof never opens,+ // so a caller that sends its first frame on `open` sends it nothing.+ if (route.proven && !route.proven(answer.headers['x-harness-proof'])) { stream.destroy(); this.#end(1006, new Error(PIPE_UNPROVEN)); return }const accept = createHash('sha1').update(key + WS_GUID).digest('base64')if (answer.headers['sec-websocket-accept'] !== accept) { stream.destroy(); this.#end(1006, new Error('The daemon answered no WebSocket.')); return }this.#stream = stream@@ -171,27 +264,32 @@ class UnixWebSocket extends EventTarget {}/**- * What a package opens to the daemon's `/api/local-ws`: `new DaemonWebSocket(url, { headers, env })`, over the socket where one can be.- * Elsewhere Node's own WebSocket on `url`, with the headers given.+ * What a package opens to the daemon's `/api/local-ws`: `new DaemonWebSocket(url, { headers, env })`, over the socket where one can be+ * and over the pipe on Windows. Only a home too long to hold a socket gets Node's own WebSocket on `url`, with the headers given.*/export class DaemonWebSocket {constructor(url, { headers = {}, env = process.env } = {}) {- const parsed = new URL(url)- const path = daemonSocketPath(portOf(parsed), env)- return path ? new UnixWebSocket(path, parsed.pathname) : new globalThis.WebSocket(url, { headers })+ const parsed = new URL(url), port = portOf(parsed)+ if (process.platform !== 'win32' && !daemonSocketPath(port, env)) return new globalThis.WebSocket(url, { headers })+ return new LocalWebSocket(localRoute(port, env), parsed.pathname)}}-/** `fetch` for the daemon's REST API at `url`, over its socket where one can be. Answers `status`, `ok`, `json()` and `text()`. */+/**+ * `fetch` for the daemon's REST API at `url`, over its socket where one can be and over its pipe on Windows, where an answer is taken+ * only with the daemon's proof. Answers `status`, `ok`, `json()` and `text()`.+ */export function daemonFetch(url, { method = 'GET', headers = {}, body, signal, env = process.env } = {}) {- const parsed = new URL(url)- const path = daemonSocketPath(portOf(parsed), env)- if (!path) return fetch(url, { method, headers, ...(body === undefined ? {} : { body }), ...(signal ? { signal } : {}) })+ const parsed = new URL(url), port = portOf(parsed)+ if (process.platform !== 'win32' && !daemonSocketPath(port, env)) return fetch(url, { method, headers, ...(body === undefined ? {} : { body }), ...(signal ? { signal } : {}) })return new Promise((resolve, reject) => {- if (!socketIsPrivate(path)) { reject(new Error('The Harness socket is missing or not private.')); return }+ const route = localRoute(port, env)+ if (!route) { reject(routeMissing()); return }const payload = body === undefined ? null : Buffer.from(body)- const asked = request({ socketPath: path, method, path: `${parsed.pathname}${parsed.search}`, ...(signal ? { signal } : {}),- headers: { ...headers, ...(payload ? { 'content-length': String(payload.length) } : {}) } }, (answer) => {+ const asked = request({ socketPath: route.path, method, path: `${parsed.pathname}${parsed.search}`, ...(signal ? { signal } : {}),+ headers: { ...headers, ...route.headers, ...(payload ? { 'content-length': String(payload.length) } : {}) } }, (answer) => {+ // Before the body is read: an answer on the pipe without the daemon's proof is whatever took its name (cli pipeClient.ts).+ if (route.proven && !route.proven(answer.headers['x-harness-proof'])) { reject(new Error(PIPE_UNPROVEN)); asked.destroy(); return }const parts = []answer.on('data', (part) => parts.push(part))answer.on('error', reject)diff --git a/store/agents/machine-monitor/test/credential.test.mjs b/store/agents/machine-monitor/test/credential.test.mjsindex 560bf346c..31fff82c3 100644--- a/store/agents/machine-monitor/test/credential.test.mjs+++ b/store/agents/machine-monitor/test/credential.test.mjs@@ -83,14 +83,14 @@ test('the local credential is read the way the CLI reads it, and only then', ()assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR: dataDir({ credential: 'too-short' }) }), {});});-// Windows reports every file as 0o666 and every folder as 0o777, so the POSIX mode checks would refuse the-// credential the daemon wrote and the daemon, which wants it on TCP there, would answer 401 (cli hookAuth.ts).-test('on Windows the credential is read whatever mode the folder and file report', (t) => {+// On Windows the credential never goes to the port, whose holder may be another account's: the Team account's daemon+// starts at boot, before the owner's (audit W1). The package reaches the daemon over its proven pipe instead (localDaemon.mjs).+test('on Windows no credential is read: it never goes to the port', (t) => {const platform = Object.getOwnPropertyDescriptor(process, 'platform');Object.defineProperty(process, 'platform', { value: 'win32' });t.after(() => Object.defineProperty(process, 'platform', platform));- assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR: dataDir({ mode: 0o666, folderMode: 0o777 }) }), { 'X-Harness-Local': CREDENTIAL });- assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR: dataDir({ credential: 'too-short', mode: 0o666 }) }), {}, 'the value is still checked');+ assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR: dataDir({ mode: 0o666, folderMode: 0o777 }) }), {});+ assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR: dataDir() }), {}, 'nor a credential the POSIX checks would pass');});test('REST reads and the bridge both show the daemon its local credential', async t => {diff --git a/store/agents/memories/lib/bridge.mjs b/store/agents/memories/lib/bridge.mjsindex 48fc1cb9f..aac83bd0c 100644--- a/store/agents/memories/lib/bridge.mjs+++ b/store/agents/memories/lib/bridge.mjs@@ -37,23 +37,21 @@ export const DEFAULT_BRIDGE = 'ws://127.0.0.1:18473/api/local-ws'* The same function, by the same name, is in every Store package that talks to the daemon.*/export function localCredentialHeaders(env = process.env) {- // Where a socket can be, nothing carries the credential: a holder of the TCP port would hear it (localDaemon.mjs).- if (daemonSocketPath(65_535, env)) return {}+ // Where a socket can be, and on Windows, where the daemon's pipe is the way, nothing carries the credential: a holder of the+ // TCP port would hear it (localDaemon.mjs; on Windows the Team account's daemon can hold it from boot, audit W1).+ if (process.platform === 'win32' || daemonSocketPath(65_535, env)) return {}const dir = env.ADAPTER_DATA_DIR || join(homedir(), '.harness', 'cli', 'data')const uid = typeof process.getuid === 'function' ? process.getuid() : null- // Windows reports every file as 0o666 and every folder as 0o777, so the mode checks below would always refuse- // the credential the daemon wrote; there its protection is the profile folder's ACL (cli hookAuth.ts).- const posixModes = process.platform !== 'win32'const opened = []try {const folder = openSync(dir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW)opened.push(folder)const where = fstatSync(folder)- if (!where.isDirectory() || (uid !== null && where.uid !== uid) || (posixModes && (where.mode & 0o022) !== 0)) return {}+ if (!where.isDirectory() || (uid !== null && where.uid !== uid) || (where.mode & 0o022) !== 0) return {}const file = openSync(join(dir, 'hook-credential'), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)opened.push(file)const stat = fstatSync(file)- if (!stat.isFile() || stat.size > 128 || (uid !== null && stat.uid !== uid) || (posixModes && (stat.mode & 0o777) !== 0o600)) return {}+ if (!stat.isFile() || stat.size > 128 || (uid !== null && stat.uid !== uid) || (stat.mode & 0o777) !== 0o600) return {}const value = readFileSync(file, 'utf8').trim()return /^[A-Za-z0-9_-]{43}$/.test(value) ? { 'X-Harness-Local': value } : {}} catch {@@ -68,8 +66,8 @@ const CREDENTIAL_REFUSED = "Harness refused this process's local credential. Run/** Whether the daemon behind a bridge socket that would not open refused the credential: a WebSocket* cannot report the 401, so the same headers are shown once over plain HTTP, which can. */async function credentialRefused(url, headers, env = process.env) {- // Over the socket no credential is shown, and the port may be anyone's: there is nothing to ask it.- if (daemonSocketPath(65_535, env)) return false+ // Over the socket or the pipe no credential is shown, and the port may be anyone's: there is nothing to ask it.+ if (process.platform === 'win32' || daemonSocketPath(65_535, env)) return falsetry {const answer = await fetch(url.replace(/^ws:/, 'http:'), { headers, signal: AbortSignal.timeout(2000) })await answer.body?.cancel()diff --git a/store/agents/memories/lib/localDaemon.mjs b/store/agents/memories/lib/localDaemon.mjsindex b7a10e28d..cbf7f2550 100644--- a/store/agents/memories/lib/localDaemon.mjs+++ b/store/agents/memories/lib/localDaemon.mjs@@ -1,16 +1,18 @@/*** How a Store package reaches the Harness daemon on this computer: its Unix socket, owner only, and on macOS and Linux only that. Any* account can bind the daemon's TCP port while the daemon restarts, and would hear whatever is sent to it (audit H1). With the socket- * gone the daemon is down, and the caller says so. TCP remains where a socket cannot be: Windows, or a data folder too long for one.+ * gone the daemon is down, and the caller says so. On Windows it goes over the daemon's named pipe, proving the daemon's token, and+ * never to the port: the Team account's daemon starts at boot, before the owner's, and could hold it (audit W1,+ * docs/security/2026-11-02-team-account-windows.md). TCP remains only for a home too long to hold a socket.** One file, the same in every package that talks to the daemon, and in store/tools: a package stands alone and has no dependencies* (store/tools/port-holder.test.mjs pins the copies). The rules are the CLI's: cli/src/lib/localSocket.ts.*/-import { createHash, randomBytes } from 'node:crypto'-import { lstatSync } from 'node:fs'+import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto'+import { closeSync, fstatSync, lstatSync, openSync, readdirSync, readFileSync, realpathSync } from 'node:fs'import { request } from 'node:http'import { homedir } from 'node:os'-import { join } from 'node:path'+import { join, win32 } from 'node:path'/** sockaddr_un has 104 bytes on macOS, and the daemon creates the socket under a name 4 bytes longer. */const MAX_SOCKET_PATH_BYTES = 96@@ -48,6 +50,92 @@ export function socketIsPrivate(path) {}}+/** Mirrors LOCAL_PIPE_RE in cli/src/lib/windows/pipeAuth.ts: a pipe on this computer named harness-<id>, nothing else. A file, or+ * another computer's pipe (an SMB connection that can carry this user's NTLM credentials), is none. */+const LOCAL_PIPE_RE = /^\\\\\.\\pipe\\harness-([0-9a-f]{32})$/+/** Mirrors TOKEN_TEXT in cli/src/lib/windows/pipeAuth.ts. */+const DAEMON_TOKEN_RE = /^[0-9a-f]{64}\n?$/++export const HARNESS_NOT_RUNNING = 'Harness is not running on this computer. Start it with: harness start'+const PIPE_UNPROVEN = 'Something other than Harness answered on its local pipe. Restart Harness: harness stop && harness start'++/**+ * A state file of the daemon's on Windows, as cli/hook/notify.mjs `readWindowsStateFile` reads it. NTFS gives Node no owner or mode+ * bits, so the profile's ACL is the protection: the file must be a plain file, not a link or junction, whose real path lies inside+ * the profile or the data folder, and the file opened must be the one lstat saw. '' when it is refused; throws when there is none.+ */+function windowsStateFile(dataDir, name, maxBytes) {+ const file = join(dataDir, name)+ const roots = [homedir(), dataDir].flatMap((root) => { try { return [realpathSync.native(root)] } catch { return [] } })+ const inside = (target) => roots.some((root) => {+ const rel = win32.relative(root, target)+ return rel === '' || (rel !== '..' && !rel.startsWith('..\\') && !win32.isAbsolute(rel))+ })+ const link = lstatSync(file, { bigint: true })+ if (!link.isFile() || link.size > BigInt(maxBytes) || !inside(realpathSync.native(file))) return ''+ const fd = openSync(file, 'r')+ try {+ const opened = fstatSync(fd, { bigint: true })+ return opened.isFile() && opened.dev === link.dev && opened.ino === link.ino ? readFileSync(fd, 'utf8') : ''+ } finally {+ closeSync(fd)+ }+}++/**+ * The record's daemon still runs. Once it is gone any account can create a pipe of the recorded name, and would hear the request+ * before its answer can fail the proof. The daemon is this account's, so a pid that answers EPERM is another account's process now.+ */+function pidRuns(pid) {+ try { process.kill(pid, 0); return true } catch { return false }+}++/**+ * The daemon's pipe for `port` on Windows, as the CLI and its hook find it (cli/hook/notify.mjs `windowsDaemonPipe`): the record the+ * core writes, `daemon-<configured port>.json`, names the pipe and the core's pid, both new on each start; `port` may be the one the+ * daemon bound instead, so the records say which. One request's route: the pipe, its auth for a fresh nonce, and the check of the+ * daemon's proof (cli/src/lib/windows/pipeAuth.ts). The token never travels. Null off Windows, or with no record of a local pipe, no+ * token, or a core that has exited: then there is nothing to dial, and the port is never the way instead.+ */+export function daemonPipe(port, env = process.env, platform = process.platform) {+ if (platform !== 'win32') return null+ const dataDir = daemonDataDir(env)+ const read = (name) => { try { return JSON.parse(windowsStateFile(dataDir, name, 4096)) } catch { return null } }+ let record = read(`daemon-${port}.json`)+ if (!record) {+ try {+ for (const name of readdirSync(dataDir)) {+ if (!/^daemon-\d+\.json$/.test(name)) continue+ const candidate = read(name)+ if (candidate?.port === port) { record = candidate; break }+ }+ } catch { /* An unreadable folder has no record to offer. */ }+ }+ const id = typeof record?.pipe === 'string' ? LOCAL_PIPE_RE.exec(record.pipe)?.[1] : null+ if (!id || !Number.isSafeInteger(record.pid) || record.pid <= 0 || !pidRuns(record.pid)) return null+ let text = ''+ try { text = windowsStateFile(dataDir, 'daemon-token', 128) } catch { return null }+ if (!DAEMON_TOKEN_RE.test(text)) return null+ const token = Buffer.from(text.slice(0, 64), 'hex')+ const nonce = id + randomBytes(16).toString('hex')+ const mac = (separator) => createHmac('sha256', token).update(Buffer.of(separator)).update(nonce, 'utf8').digest('hex')+ const proof = Buffer.from(mac(0x00), 'hex')+ return {+ path: record.pipe,+ headers: { 'X-Harness-Auth': `${nonce}.${mac(0x01)}` },+ proven: (value) => typeof value === 'string' && /^[0-9a-f]{64}$/.test(value) && timingSafeEqual(Buffer.from(value, 'hex'), proof),+ }+}++/** How a request reaches the daemon here: its pipe on Windows, its private socket elsewhere; null when there is neither to use. */+function localRoute(port, env) {+ if (process.platform === 'win32') return daemonPipe(port, env)+ const path = daemonSocketPath(port, env)+ return path && socketIsPrivate(path) ? { path, headers: {}, proven: null } : null+}++const routeMissing = () => new Error(process.platform === 'win32' ? HARNESS_NOT_RUNNING : 'The Harness socket is missing or not private.')+const portOf = (url) => Number(url.port) || (url.protocol === 'https:' || url.protocol === 'wss:' ? 443 : 80)/** One client frame: clients mask (RFC 6455 5.3). */@@ -65,23 +153,28 @@ class SocketEvent extends Event {constructor(type, fields) { super(type); Object.assign(this, fields) }}-/** The WebSocket client these packages use, over the daemon's socket: open, message (text), error, close, send, close. */-class UnixWebSocket extends EventTarget {+/** The WebSocket client these packages use, over the daemon's socket or pipe: open, message (text), error, close, send, close. */+class LocalWebSocket extends EventTarget {static CONNECTING = 0; static OPEN = 1; static CLOSING = 2; static CLOSED = 3readyState = 0#asked = null; #stream = null; #closed = false; #held = Buffer.alloc(0); #parts = []; #size = 0; #timer = null- constructor(path, resource) {+ /** `route` is localRoute's: null is no daemon to dial. */+ constructor(route, resource) {super()// Told after this returns, as a WebSocket always is: the caller adds its listeners first.- if (!socketIsPrivate(path)) { queueMicrotask(() => this.#end(1006, new Error('The Harness socket is missing or not private.'))); return }+ if (!route) { const error = routeMissing(); queueMicrotask(() => this.#end(1006, error)); return }const key = randomBytes(16).toString('base64')- const asked = this.#asked = request({ socketPath: path, path: resource, headers: { Connection: 'Upgrade', Upgrade: 'websocket', 'Sec-WebSocket-Version': '13', 'Sec-WebSocket-Key': key } })+ const asked = this.#asked = request({ socketPath: route.path, path: resource,+ headers: { ...route.headers, Connection: 'Upgrade', Upgrade: 'websocket', 'Sec-WebSocket-Version': '13', 'Sec-WebSocket-Key': key } })asked.on('error', (error) => this.#end(1006, error))asked.on('response', (answer) => { answer.resume(); this.#end(1006, new Error(`The daemon answered ${answer.statusCode}.`)) })asked.on('upgrade', (answer, stream, head) => {// Given up on while it was on its way: the caller has been told, so it never comes back to life.if (this.#closed) { stream.destroy(); return }+ // A pipe's name can be taken by any account once its daemon is gone: an upgrade without the daemon's proof never opens,+ // so a caller that sends its first frame on `open` sends it nothing.+ if (route.proven && !route.proven(answer.headers['x-harness-proof'])) { stream.destroy(); this.#end(1006, new Error(PIPE_UNPROVEN)); return }const accept = createHash('sha1').update(key + WS_GUID).digest('base64')if (answer.headers['sec-websocket-accept'] !== accept) { stream.destroy(); this.#end(1006, new Error('The daemon answered no WebSocket.')); return }this.#stream = stream@@ -171,27 +264,32 @@ class UnixWebSocket extends EventTarget {}/**- * What a package opens to the daemon's `/api/local-ws`: `new DaemonWebSocket(url, { headers, env })`, over the socket where one can be.- * Elsewhere Node's own WebSocket on `url`, with the headers given.+ * What a package opens to the daemon's `/api/local-ws`: `new DaemonWebSocket(url, { headers, env })`, over the socket where one can be+ * and over the pipe on Windows. Only a home too long to hold a socket gets Node's own WebSocket on `url`, with the headers given.*/export class DaemonWebSocket {constructor(url, { headers = {}, env = process.env } = {}) {- const parsed = new URL(url)- const path = daemonSocketPath(portOf(parsed), env)- return path ? new UnixWebSocket(path, parsed.pathname) : new globalThis.WebSocket(url, { headers })+ const parsed = new URL(url), port = portOf(parsed)+ if (process.platform !== 'win32' && !daemonSocketPath(port, env)) return new globalThis.WebSocket(url, { headers })+ return new LocalWebSocket(localRoute(port, env), parsed.pathname)}}-/** `fetch` for the daemon's REST API at `url`, over its socket where one can be. Answers `status`, `ok`, `json()` and `text()`. */+/**+ * `fetch` for the daemon's REST API at `url`, over its socket where one can be and over its pipe on Windows, where an answer is taken+ * only with the daemon's proof. Answers `status`, `ok`, `json()` and `text()`.+ */export function daemonFetch(url, { method = 'GET', headers = {}, body, signal, env = process.env } = {}) {- const parsed = new URL(url)- const path = daemonSocketPath(portOf(parsed), env)- if (!path) return fetch(url, { method, headers, ...(body === undefined ? {} : { body }), ...(signal ? { signal } : {}) })+ const parsed = new URL(url), port = portOf(parsed)+ if (process.platform !== 'win32' && !daemonSocketPath(port, env)) return fetch(url, { method, headers, ...(body === undefined ? {} : { body }), ...(signal ? { signal } : {}) })return new Promise((resolve, reject) => {- if (!socketIsPrivate(path)) { reject(new Error('The Harness socket is missing or not private.')); return }+ const route = localRoute(port, env)+ if (!route) { reject(routeMissing()); return }const payload = body === undefined ? null : Buffer.from(body)- const asked = request({ socketPath: path, method, path: `${parsed.pathname}${parsed.search}`, ...(signal ? { signal } : {}),- headers: { ...headers, ...(payload ? { 'content-length': String(payload.length) } : {}) } }, (answer) => {+ const asked = request({ socketPath: route.path, method, path: `${parsed.pathname}${parsed.search}`, ...(signal ? { signal } : {}),+ headers: { ...headers, ...route.headers, ...(payload ? { 'content-length': String(payload.length) } : {}) } }, (answer) => {+ // Before the body is read: an answer on the pipe without the daemon's proof is whatever took its name (cli pipeClient.ts).+ if (route.proven && !route.proven(answer.headers['x-harness-proof'])) { reject(new Error(PIPE_UNPROVEN)); asked.destroy(); return }const parts = []answer.on('data', (part) => parts.push(part))answer.on('error', reject)diff --git a/store/agents/memories/test/credential.test.mjs b/store/agents/memories/test/credential.test.mjsindex 27b49192d..6cceac2c9 100644--- a/store/agents/memories/test/credential.test.mjs+++ b/store/agents/memories/test/credential.test.mjs@@ -81,14 +81,14 @@ test('the local credential is read the way the CLI reads it, and only then', ()assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR: dataDir({ credential: 'too-short' }) }), {})})-// Windows reports every file as 0o666 and every folder as 0o777, so the POSIX mode checks would refuse the-// credential the daemon wrote and the daemon, which wants it on TCP there, would answer 401 (cli hookAuth.ts).-test('on Windows the credential is read whatever mode the folder and file report', (t) => {+// On Windows the credential never goes to the port, whose holder may be another account's: the Team account's daemon+// starts at boot, before the owner's (audit W1). The package reaches the daemon over its proven pipe instead (localDaemon.mjs).+test('on Windows no credential is read: it never goes to the port', (t) => {const platform = Object.getOwnPropertyDescriptor(process, 'platform')Object.defineProperty(process, 'platform', { value: 'win32' })t.after(() => Object.defineProperty(process, 'platform', platform))- assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR: dataDir({ mode: 0o666, folderMode: 0o777 }) }), { 'X-Harness-Local': CREDENTIAL })- assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR: dataDir({ credential: 'too-short', mode: 0o666 }) }), {}, 'the value is still checked')+ assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR: dataDir({ mode: 0o666, folderMode: 0o777 }) }), {})+ assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR: dataDir() }), {}, 'nor a credential the POSIX checks would pass')})test('the bridge shows the daemon its local credential', async (t) => {diff --git a/store/tools/README.md b/store/tools/README.mdindex 0ed598037..87e5659ec 100644--- a/store/tools/README.md+++ b/store/tools/README.md@@ -29,9 +29,12 @@ Sources and visual-review notes are in [the asset guide](../../.github/assets/stDaemon-level checks over the same loopback WebSocket the desktop uses (`ws://127.0.0.1:18473/api/local-ws`).They need a running daemon with the harness installed on this machine, and `cli/node_modules` (for `ws`).Run them as the OS user Harness runs as: they reach the daemon over its 0600 socket in `ADAPTER_DATA_DIR`-(default `~/.harness/cli/data`, or `~/.harness/s/<hash>` for a folder too long for a socket), `local-daemon.mjs`, and nothing goes to its TCP port, which any account can hold. Only where a-socket cannot be (Windows, or a home too long as well) do they use the port, with `hook-credential` as `X-Harness-Local`-(`local-credential.mjs`).+(default `~/.harness/cli/data`, or `~/.harness/s/<hash>` for a folder too long for a socket), `local-daemon.mjs`, and nothing goes to its TCP port, which any account can hold.+On Windows they reach it over its named pipe, which the daemon's record `daemon-<port>.json` names: each request proves the+daemon's token (`daemon-token`) without sending it, and an answer counts only with the daemon's proof. With no live pipe they say+Harness is not running; nothing goes to the port, which the Team account's daemon can hold from boot (audit W1). Only a home+too long to hold a socket uses the port, with `hook-credential` as `X-Harness-Local` (`local-credential.mjs`).+The Store packages share the same transport, a copy of `local-daemon.mjs` in each (`lib/localDaemon.mjs`).```shnode store/tools/dsh-e2e.mjs <machineId> <dshId> <engine> <workspace> [--keep] [--restart] [--bypass] [--no-verdict]diff --git a/store/tools/dsh-delete.mjs b/store/tools/dsh-delete.mjsindex 4f841bea0..f6a6ea16c 100644--- a/store/tools/dsh-delete.mjs+++ b/store/tools/dsh-delete.mjs@@ -1,11 +1,10 @@// Delete an agent over the daemon's WebSocket. Usage: node dsh-delete.mjs <agentId>import ws_ from '../../cli/node_modules/ws/index.js'const { WebSocket } = ws_-import { CREDENTIAL_REFUSED, daemonBridge } from './local-credential.mjs'+import { CREDENTIAL_REFUSED, openDaemonBridge } from './local-credential.mjs'const [agentId] = process.argv.slice(2)const machineId = process.argv[3] ?? (() => { console.error('usage: node dsh-delete.mjs <agentId> <machineId>'); process.exit(2) })()-const { url, headers } = daemonBridge()-const ws = new WebSocket(url, { headers })+const ws = openDaemonBridge(WebSocket)ws.on('unexpected-response', (_req, res) => { console.error(res.statusCode === 401 ? CREDENTIAL_REFUSED : `Unexpected server response: ${res.statusCode}`); process.exit(1) })ws.on('open', () => {ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1 } }))diff --git a/store/tools/dsh-discover.mjs b/store/tools/dsh-discover.mjsindex f537d3144..2dd83286c 100644--- a/store/tools/dsh-discover.mjs+++ b/store/tools/dsh-discover.mjs@@ -2,10 +2,9 @@import ws_ from '../../cli/node_modules/ws/index.js'const { WebSocket } = ws_import { randomBytes } from 'node:crypto'-import { CREDENTIAL_REFUSED, daemonBridge } from './local-credential.mjs'+import { CREDENTIAL_REFUSED, openDaemonBridge } from './local-credential.mjs'const [machineId, workspace, action] = process.argv.slice(2)-const { url, headers } = daemonBridge()-const ws = new WebSocket(url, { headers })+const ws = openDaemonBridge(WebSocket)ws.on('unexpected-response', (_req, res) => { console.error(res.statusCode === 401 ? CREDENTIAL_REFUSED : `Unexpected server response: ${res.statusCode}`); process.exit(1) })const pending = new Map()const send = (type, payload) => ws.send(JSON.stringify({ type, payload }))diff --git a/store/tools/dsh-e2e.mjs b/store/tools/dsh-e2e.mjsindex 42e30cb9f..88f2699ca 100644--- a/store/tools/dsh-e2e.mjs+++ b/store/tools/dsh-e2e.mjs@@ -4,7 +4,7 @@ import ws_ from '../../cli/node_modules/ws/index.js'const { WebSocket } = ws_import { randomBytes } from 'node:crypto'import { execFileSync } from 'node:child_process'-import { CREDENTIAL_REFUSED, daemonBridge } from './local-credential.mjs'+import { CREDENTIAL_REFUSED, openDaemonBridge } from './local-credential.mjs'const [machineId, dshId, engine, workspace] = process.argv.slice(2)const keep = process.argv.includes('--keep')@@ -13,8 +13,7 @@ if (!machineId || !dshId || !engine || !workspace) {process.exit(2)}-const { url, headers } = daemonBridge()-const ws = new WebSocket(url, { headers })+const ws = openDaemonBridge(WebSocket)ws.on('unexpected-response', (_req, res) => { log(res.statusCode === 401 ? CREDENTIAL_REFUSED : `ws error Unexpected server response: ${res.statusCode}`); process.exit(1) })const pending = new Map()const agentFrames = []diff --git a/store/tools/experience-tests/daemon.mjs b/store/tools/experience-tests/daemon.mjsindex 4c04c542c..b5f05ed05 100644--- a/store/tools/experience-tests/daemon.mjs+++ b/store/tools/experience-tests/daemon.mjs@@ -73,8 +73,8 @@ await new Promise((resolve, reject) => {socket.addEventListener("error",() =>- // Over the socket no credential is shown, and the port may be anyone's: there is nothing to ask it.- (daemonSocketPath(18473) ? Promise.resolve(false) : fetch(bridge.replace(/^ws:/, "http:"), { headers })+ // Over the socket or the pipe no credential is shown, and the port may be anyone's: there is nothing to ask it.+ (process.platform === "win32" || daemonSocketPath(18473) ? Promise.resolve(false) : fetch(bridge.replace(/^ws:/, "http:"), { headers }).then((answer) => answer.status === 401, () => false)).then((refused) =>reject(new Error(refused ? CREDENTIAL_REFUSED : "Could not open the local Harness bridge.")),diff --git a/store/tools/local-credential.mjs b/store/tools/local-credential.mjsindex 6f996c3e4..e00a13a1e 100644--- a/store/tools/local-credential.mjs+++ b/store/tools/local-credential.mjs@@ -3,38 +3,56 @@// Since Harness 0.4.21 the loopback port (REST and `/api/local-ws`) answers 401 to a process that does// not show `X-Harness-Local: <credential>`, the 0600 `hook-credential` file in Harness's data folder// (`ADAPTER_DATA_DIR`, default `~/.harness/cli/data`). Read with the CLI's own checks-// (cli/src/lib/hookAuth.ts `readHookCredential`); anything else is no credential and no header. The-// Store packages that talk to the daemon each carry the same function, by the same name.+// (cli/src/lib/hookAuth.ts `readHookCredential`); anything else is no credential and no header. On Windows+// there is none: the checks reach the daemon over its pipe (audit W1). The Store packages that talk to the+// daemon each carry the same function, by the same name.import { closeSync, constants, fstatSync, openSync, readFileSync } from 'node:fs'+import { connect } from 'node:net'import { homedir } from 'node:os'import { join } from 'node:path'-import { daemonSocketPath, socketIsPrivate } from './local-daemon.mjs'+import { daemonPipe, daemonSocketPath, HARNESS_NOT_RUNNING, socketIsPrivate } from './local-daemon.mjs'-/** Where a check using the `ws` package opens the daemon's bridge, and what it shows: its private socket and nothing, where one can be- * (a holder of the TCP port would hear anything sent to it, audit H1). */+/**+ * Where a check using the `ws` package opens the daemon's bridge, and what it shows: its private socket and nothing, where one can be+ * (a holder of the TCP port would hear anything sent to it, audit H1). On Windows its pipe, with the pipe auth and a check of the+ * daemon's proof, and never the port (audit W1); `openDaemonBridge` applies that check.+ */export function daemonBridge(port = 18473, env = process.env) {+ if (process.platform === 'win32') {+ const pipe = daemonPipe(port, env)+ if (!pipe) throw new Error(HARNESS_NOT_RUNNING)+ return { url: 'ws://localhost/api/local-ws', headers: pipe.headers, createConnection: () => connect(pipe.path), proven: pipe.proven }+ }const socket = daemonSocketPath(port, env)if (socket && !socketIsPrivate(socket)) throw new Error(`The Harness socket is missing or not private: ${socket}. Start Harness as this user.`)return socket ? { url: `ws+unix://${socket}:/api/local-ws`, headers: {} } : { url: `ws://127.0.0.1:${port}/api/local-ws`, headers: localCredentialHeaders(env) }}+/**+ * The `ws` package's WebSocket (`WebSocket`) on the daemon's bridge. On the pipe an upgrade without the daemon's proof is ended before+ * `open`, so a check that sends its first frame on `open` sends whatever took the pipe's name nothing (cli pipeClient.ts).+ */+export function openDaemonBridge(WebSocket, port = 18473, env = process.env) {+ const { url, proven, ...options } = daemonBridge(port, env)+ const socket = new WebSocket(url, options)+ if (proven) socket.on('upgrade', (answer) => { if (!proven(answer.headers['x-harness-proof'])) socket.terminate() })+ return socket+}+export function localCredentialHeaders(env = process.env) {- if (daemonSocketPath(65_535, env)) return {}+ if (process.platform === 'win32' || daemonSocketPath(65_535, env)) return {}const dir = env.ADAPTER_DATA_DIR || join(homedir(), '.harness', 'cli', 'data')const uid = typeof process.getuid === 'function' ? process.getuid() : null- // Windows reports every file as 0o666 and every folder as 0o777, so the mode checks below would always refuse- // the credential the daemon wrote; there its protection is the profile folder's ACL (cli hookAuth.ts).- const posixModes = process.platform !== 'win32'const opened = []try {const folder = openSync(dir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW)opened.push(folder)const where = fstatSync(folder)- if (!where.isDirectory() || (uid !== null && where.uid !== uid) || (posixModes && (where.mode & 0o022) !== 0)) return {}+ if (!where.isDirectory() || (uid !== null && where.uid !== uid) || (where.mode & 0o022) !== 0) return {}const file = openSync(join(dir, 'hook-credential'), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)opened.push(file)const stat = fstatSync(file)- if (!stat.isFile() || stat.size > 128 || (uid !== null && stat.uid !== uid) || (posixModes && (stat.mode & 0o777) !== 0o600)) return {}+ if (!stat.isFile() || stat.size > 128 || (uid !== null && stat.uid !== uid) || (stat.mode & 0o777) !== 0o600) return {}const value = readFileSync(file, 'utf8').trim()return /^[A-Za-z0-9_-]{43}$/.test(value) ? { 'X-Harness-Local': value } : {}} catch {diff --git a/store/tools/local-credential.test.mjs b/store/tools/local-credential.test.mjsindex f9eefa910..1e2e96cd9 100644--- a/store/tools/local-credential.test.mjs+++ b/store/tools/local-credential.test.mjs@@ -33,14 +33,14 @@ test('the local credential is read the way the CLI reads it, and only then', ()assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR: dataDir({ credential: 'too-short' }) }), {})})-// Windows reports every file as 0o666 and every folder as 0o777, so the POSIX mode checks would refuse the-// credential the daemon wrote and the daemon, which wants it on TCP there, would answer 401 (cli hookAuth.ts).-test('on Windows the credential is read whatever mode the folder and file report', (t) => {+// On Windows the credential never goes to the port, whose holder may be another account's: the Team account's daemon+// starts at boot, before the owner's (audit W1). The package reaches the daemon over its proven pipe instead (localDaemon.mjs).+test('on Windows no credential is read: it never goes to the port', (t) => {const platform = Object.getOwnPropertyDescriptor(process, 'platform')Object.defineProperty(process, 'platform', { value: 'win32' })t.after(() => Object.defineProperty(process, 'platform', platform))- assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR: dataDir({ mode: 0o666, folderMode: 0o777 }) }), { 'X-Harness-Local': CREDENTIAL })- assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR: dataDir({ credential: 'too-short', mode: 0o666 }) }), {}, 'the value is still checked')+ assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR: dataDir({ mode: 0o666, folderMode: 0o777 }) }), {})+ assert.deepEqual(localCredentialHeaders({ ADAPTER_DATA_DIR: dataDir() }), {}, 'nor a credential the POSIX checks would pass')})test('where a socket can be, a check opens it and shows nothing, and only if it is private', async (t) => {@@ -59,3 +59,19 @@ test('where a socket can be, a check opens it and shows nothing, and only if itassert.throws(() => daemonBridge(18473, env), /missing or not private/)assert.deepEqual(daemonBridge(18473, { ADAPTER_DATA_DIR: dataDir() }).headers, { 'X-Harness-Local': CREDENTIAL })})++test('on Windows a check opens the daemon\'s pipe with the pipe auth, never the port, and with no pipe says Harness is not running', (t) => {+ const platform = Object.getOwnPropertyDescriptor(process, 'platform')+ Object.defineProperty(process, 'platform', { value: 'win32' })+ t.after(() => Object.defineProperty(process, 'platform', platform))+ const dir = dataDir()+ assert.throws(() => daemonBridge(18473, { ADAPTER_DATA_DIR: dir }), /Harness is not running/, 'no record: the port is not tried')+ const pipe = `\\\\.\\pipe\\harness-${'a'.repeat(32)}`+ writeFileSync(join(dir, 'daemon-18473.json'), JSON.stringify({ port: 18473, pipe, pid: process.pid }))+ writeFileSync(join(dir, 'daemon-token'), `${'b'.repeat(64)}\n`)+ const bridge = daemonBridge(18473, { ADAPTER_DATA_DIR: dir })+ assert.equal(bridge.url, 'ws://localhost/api/local-ws')+ assert.deepEqual(Object.keys(bridge.headers), ['X-Harness-Auth'], 'the pipe auth, and no credential')+ assert.equal(typeof bridge.createConnection, 'function')+ assert.equal(bridge.proven('0'.repeat(64)), false, 'an answer without the daemon\'s proof is refused')+})diff --git a/store/tools/local-daemon.mjs b/store/tools/local-daemon.mjsindex b7a10e28d..cbf7f2550 100644--- a/store/tools/local-daemon.mjs+++ b/store/tools/local-daemon.mjs@@ -1,16 +1,18 @@/*** How a Store package reaches the Harness daemon on this computer: its Unix socket, owner only, and on macOS and Linux only that. Any* account can bind the daemon's TCP port while the daemon restarts, and would hear whatever is sent to it (audit H1). With the socket- * gone the daemon is down, and the caller says so. TCP remains where a socket cannot be: Windows, or a data folder too long for one.+ * gone the daemon is down, and the caller says so. On Windows it goes over the daemon's named pipe, proving the daemon's token, and+ * never to the port: the Team account's daemon starts at boot, before the owner's, and could hold it (audit W1,+ * docs/security/2026-11-02-team-account-windows.md). TCP remains only for a home too long to hold a socket.** One file, the same in every package that talks to the daemon, and in store/tools: a package stands alone and has no dependencies* (store/tools/port-holder.test.mjs pins the copies). The rules are the CLI's: cli/src/lib/localSocket.ts.*/-import { createHash, randomBytes } from 'node:crypto'-import { lstatSync } from 'node:fs'+import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto'+import { closeSync, fstatSync, lstatSync, openSync, readdirSync, readFileSync, realpathSync } from 'node:fs'import { request } from 'node:http'import { homedir } from 'node:os'-import { join } from 'node:path'+import { join, win32 } from 'node:path'/** sockaddr_un has 104 bytes on macOS, and the daemon creates the socket under a name 4 bytes longer. */const MAX_SOCKET_PATH_BYTES = 96@@ -48,6 +50,92 @@ export function socketIsPrivate(path) {}}+/** Mirrors LOCAL_PIPE_RE in cli/src/lib/windows/pipeAuth.ts: a pipe on this computer named harness-<id>, nothing else. A file, or+ * another computer's pipe (an SMB connection that can carry this user's NTLM credentials), is none. */+const LOCAL_PIPE_RE = /^\\\\\.\\pipe\\harness-([0-9a-f]{32})$/+/** Mirrors TOKEN_TEXT in cli/src/lib/windows/pipeAuth.ts. */+const DAEMON_TOKEN_RE = /^[0-9a-f]{64}\n?$/++export const HARNESS_NOT_RUNNING = 'Harness is not running on this computer. Start it with: harness start'+const PIPE_UNPROVEN = 'Something other than Harness answered on its local pipe. Restart Harness: harness stop && harness start'++/**+ * A state file of the daemon's on Windows, as cli/hook/notify.mjs `readWindowsStateFile` reads it. NTFS gives Node no owner or mode+ * bits, so the profile's ACL is the protection: the file must be a plain file, not a link or junction, whose real path lies inside+ * the profile or the data folder, and the file opened must be the one lstat saw. '' when it is refused; throws when there is none.+ */+function windowsStateFile(dataDir, name, maxBytes) {+ const file = join(dataDir, name)+ const roots = [homedir(), dataDir].flatMap((root) => { try { return [realpathSync.native(root)] } catch { return [] } })+ const inside = (target) => roots.some((root) => {+ const rel = win32.relative(root, target)+ return rel === '' || (rel !== '..' && !rel.startsWith('..\\') && !win32.isAbsolute(rel))+ })+ const link = lstatSync(file, { bigint: true })+ if (!link.isFile() || link.size > BigInt(maxBytes) || !inside(realpathSync.native(file))) return ''+ const fd = openSync(file, 'r')+ try {+ const opened = fstatSync(fd, { bigint: true })+ return opened.isFile() && opened.dev === link.dev && opened.ino === link.ino ? readFileSync(fd, 'utf8') : ''+ } finally {+ closeSync(fd)+ }+}++/**+ * The record's daemon still runs. Once it is gone any account can create a pipe of the recorded name, and would hear the request+ * before its answer can fail the proof. The daemon is this account's, so a pid that answers EPERM is another account's process now.+ */+function pidRuns(pid) {+ try { process.kill(pid, 0); return true } catch { return false }+}++/**+ * The daemon's pipe for `port` on Windows, as the CLI and its hook find it (cli/hook/notify.mjs `windowsDaemonPipe`): the record the+ * core writes, `daemon-<configured port>.json`, names the pipe and the core's pid, both new on each start; `port` may be the one the+ * daemon bound instead, so the records say which. One request's route: the pipe, its auth for a fresh nonce, and the check of the+ * daemon's proof (cli/src/lib/windows/pipeAuth.ts). The token never travels. Null off Windows, or with no record of a local pipe, no+ * token, or a core that has exited: then there is nothing to dial, and the port is never the way instead.+ */+export function daemonPipe(port, env = process.env, platform = process.platform) {+ if (platform !== 'win32') return null+ const dataDir = daemonDataDir(env)+ const read = (name) => { try { return JSON.parse(windowsStateFile(dataDir, name, 4096)) } catch { return null } }+ let record = read(`daemon-${port}.json`)+ if (!record) {+ try {+ for (const name of readdirSync(dataDir)) {+ if (!/^daemon-\d+\.json$/.test(name)) continue+ const candidate = read(name)+ if (candidate?.port === port) { record = candidate; break }+ }+ } catch { /* An unreadable folder has no record to offer. */ }+ }+ const id = typeof record?.pipe === 'string' ? LOCAL_PIPE_RE.exec(record.pipe)?.[1] : null+ if (!id || !Number.isSafeInteger(record.pid) || record.pid <= 0 || !pidRuns(record.pid)) return null+ let text = ''+ try { text = windowsStateFile(dataDir, 'daemon-token', 128) } catch { return null }+ if (!DAEMON_TOKEN_RE.test(text)) return null+ const token = Buffer.from(text.slice(0, 64), 'hex')+ const nonce = id + randomBytes(16).toString('hex')+ const mac = (separator) => createHmac('sha256', token).update(Buffer.of(separator)).update(nonce, 'utf8').digest('hex')+ const proof = Buffer.from(mac(0x00), 'hex')+ return {+ path: record.pipe,+ headers: { 'X-Harness-Auth': `${nonce}.${mac(0x01)}` },+ proven: (value) => typeof value === 'string' && /^[0-9a-f]{64}$/.test(value) && timingSafeEqual(Buffer.from(value, 'hex'), proof),+ }+}++/** How a request reaches the daemon here: its pipe on Windows, its private socket elsewhere; null when there is neither to use. */+function localRoute(port, env) {+ if (process.platform === 'win32') return daemonPipe(port, env)+ const path = daemonSocketPath(port, env)+ return path && socketIsPrivate(path) ? { path, headers: {}, proven: null } : null+}++const routeMissing = () => new Error(process.platform === 'win32' ? HARNESS_NOT_RUNNING : 'The Harness socket is missing or not private.')+const portOf = (url) => Number(url.port) || (url.protocol === 'https:' || url.protocol === 'wss:' ? 443 : 80)/** One client frame: clients mask (RFC 6455 5.3). */@@ -65,23 +153,28 @@ class SocketEvent extends Event {constructor(type, fields) { super(type); Object.assign(this, fields) }}-/** The WebSocket client these packages use, over the daemon's socket: open, message (text), error, close, send, close. */-class UnixWebSocket extends EventTarget {+/** The WebSocket client these packages use, over the daemon's socket or pipe: open, message (text), error, close, send, close. */+class LocalWebSocket extends EventTarget {static CONNECTING = 0; static OPEN = 1; static CLOSING = 2; static CLOSED = 3readyState = 0#asked = null; #stream = null; #closed = false; #held = Buffer.alloc(0); #parts = []; #size = 0; #timer = null- constructor(path, resource) {+ /** `route` is localRoute's: null is no daemon to dial. */+ constructor(route, resource) {super()// Told after this returns, as a WebSocket always is: the caller adds its listeners first.- if (!socketIsPrivate(path)) { queueMicrotask(() => this.#end(1006, new Error('The Harness socket is missing or not private.'))); return }+ if (!route) { const error = routeMissing(); queueMicrotask(() => this.#end(1006, error)); return }const key = randomBytes(16).toString('base64')- const asked = this.#asked = request({ socketPath: path, path: resource, headers: { Connection: 'Upgrade', Upgrade: 'websocket', 'Sec-WebSocket-Version': '13', 'Sec-WebSocket-Key': key } })+ const asked = this.#asked = request({ socketPath: route.path, path: resource,+ headers: { ...route.headers, Connection: 'Upgrade', Upgrade: 'websocket', 'Sec-WebSocket-Version': '13', 'Sec-WebSocket-Key': key } })asked.on('error', (error) => this.#end(1006, error))asked.on('response', (answer) => { answer.resume(); this.#end(1006, new Error(`The daemon answered ${answer.statusCode}.`)) })asked.on('upgrade', (answer, stream, head) => {// Given up on while it was on its way: the caller has been told, so it never comes back to life.if (this.#closed) { stream.destroy(); return }+ // A pipe's name can be taken by any account once its daemon is gone: an upgrade without the daemon's proof never opens,+ // so a caller that sends its first frame on `open` sends it nothing.+ if (route.proven && !route.proven(answer.headers['x-harness-proof'])) { stream.destroy(); this.#end(1006, new Error(PIPE_UNPROVEN)); return }const accept = createHash('sha1').update(key + WS_GUID).digest('base64')if (answer.headers['sec-websocket-accept'] !== accept) { stream.destroy(); this.#end(1006, new Error('The daemon answered no WebSocket.')); return }this.#stream = stream@@ -171,27 +264,32 @@ class UnixWebSocket extends EventTarget {}/**- * What a package opens to the daemon's `/api/local-ws`: `new DaemonWebSocket(url, { headers, env })`, over the socket where one can be.- * Elsewhere Node's own WebSocket on `url`, with the headers given.+ * What a package opens to the daemon's `/api/local-ws`: `new DaemonWebSocket(url, { headers, env })`, over the socket where one can be+ * and over the pipe on Windows. Only a home too long to hold a socket gets Node's own WebSocket on `url`, with the headers given.*/export class DaemonWebSocket {constructor(url, { headers = {}, env = process.env } = {}) {- const parsed = new URL(url)- const path = daemonSocketPath(portOf(parsed), env)- return path ? new UnixWebSocket(path, parsed.pathname) : new globalThis.WebSocket(url, { headers })+ const parsed = new URL(url), port = portOf(parsed)+ if (process.platform !== 'win32' && !daemonSocketPath(port, env)) return new globalThis.WebSocket(url, { headers })+ return new LocalWebSocket(localRoute(port, env), parsed.pathname)}}-/** `fetch` for the daemon's REST API at `url`, over its socket where one can be. Answers `status`, `ok`, `json()` and `text()`. */+/**+ * `fetch` for the daemon's REST API at `url`, over its socket where one can be and over its pipe on Windows, where an answer is taken+ * only with the daemon's proof. Answers `status`, `ok`, `json()` and `text()`.+ */export function daemonFetch(url, { method = 'GET', headers = {}, body, signal, env = process.env } = {}) {- const parsed = new URL(url)- const path = daemonSocketPath(portOf(parsed), env)- if (!path) return fetch(url, { method, headers, ...(body === undefined ? {} : { body }), ...(signal ? { signal } : {}) })+ const parsed = new URL(url), port = portOf(parsed)+ if (process.platform !== 'win32' && !daemonSocketPath(port, env)) return fetch(url, { method, headers, ...(body === undefined ? {} : { body }), ...(signal ? { signal } : {}) })return new Promise((resolve, reject) => {- if (!socketIsPrivate(path)) { reject(new Error('The Harness socket is missing or not private.')); return }+ const route = localRoute(port, env)+ if (!route) { reject(routeMissing()); return }const payload = body === undefined ? null : Buffer.from(body)- const asked = request({ socketPath: path, method, path: `${parsed.pathname}${parsed.search}`, ...(signal ? { signal } : {}),- headers: { ...headers, ...(payload ? { 'content-length': String(payload.length) } : {}) } }, (answer) => {+ const asked = request({ socketPath: route.path, method, path: `${parsed.pathname}${parsed.search}`, ...(signal ? { signal } : {}),+ headers: { ...headers, ...route.headers, ...(payload ? { 'content-length': String(payload.length) } : {}) } }, (answer) => {+ // Before the body is read: an answer on the pipe without the daemon's proof is whatever took its name (cli pipeClient.ts).+ if (route.proven && !route.proven(answer.headers['x-harness-proof'])) { reject(new Error(PIPE_UNPROVEN)); asked.destroy(); return }const parts = []answer.on('data', (part) => parts.push(part))answer.on('error', reject)diff --git a/store/tools/windows-ci/store-pipe.mjs b/store/tools/windows-ci/store-pipe.mjsnew file mode 100644index 000000000..68d0b597c--- /dev/null+++ b/store/tools/windows-ci/store-pipe.mjs@@ -0,0 +1,52 @@+#!/usr/bin/env node+/**+ * The Store packages against the installed daemon on Windows, for the Windows workflow's install job (task #2161, audit W1+ * follow-up). Each package reaches the daemon over its named pipe with the pipe auth (lib/localDaemon.mjs `daemonPipe`), and never+ * its TCP port; store/tools/windows-pipe.test.mjs proves the port hears nothing, and this proves the real daemon answers them.+ * Nothing signs in: a signed-out daemon serves under this computer's id (cli/scripts/windows-ci/opencode.mjs).+ *+ * node store/tools/windows-ci/store-pipe.mjs prints one line per call; exits 1 when any did not reach the daemon.+ */+import { readFileSync } from 'node:fs'+import { homedir } from 'node:os'+import { join } from 'node:path'+import { closeBridges, listAgents as monitorAgents } from '../../agents/harness-monitor/lib/bridge.mjs'+import { closeBridges as closeMemories, listAgents as memoriesAgents } from '../../agents/memories/lib/bridge.mjs'+import { closeSessions, daemonStatus, listHarnesses } from '../../agents/machine-monitor/lib/daemon.mjs'+import { harnessExecute } from '../../agents/autonomous-grid/lib/harness.mjs'+import { daemonPipe, daemonSocketPath } from '../local-daemon.mjs'+import { localCredentialHeaders } from '../local-credential.mjs'++const say = (line) => console.log(`[store-pipe] ${line}`)+let failed = false+const check = (name, ok, detail) => { say(`${ok ? 'ok ' : 'FAIL'} ${name}: ${detail}`); if (!ok) failed = true }++check('platform', process.platform === 'win32', process.platform)+check('no socket, no credential', daemonSocketPath(18473) === null && Object.keys(localCredentialHeaders()).length === 0,+ 'nothing here is ever sent to the port')+check('the daemon\'s pipe', daemonPipe(18473) !== null, daemonPipe(18473)?.path ?? 'no live pipe in the record')++const machineId = readFileSync(join(homedir(), '.harness', 'computer-id'), 'utf8').trim()+const status = await daemonStatus()+check('machine monitor, REST /api/status', status.ok === true, status.ok ? `machine ${status.status?.machineId ?? '?'}` : status.error)++const roster = await listHarnesses(machineId, { timeoutMs: 20_000 })+check('machine monitor, bridge', roster.ok === true, roster.ok ? `${roster.harnesses?.length ?? 0} harnesses` : roster.error)++for (const [name, list] of [['harness monitor, bridge', monitorAgents], ['memories, bridge', memoriesAgents]]) {+ try {+ const agents = await list(machineId, { timeoutMs: 20_000 })+ check(name, Array.isArray(agents), `${agents?.length ?? 0} agents`)+ } catch (error) {+ check(name, false, error.message)+ }+}++// Grid is not installed here, so the command itself is refused; its answer is still the daemon's, over the pipe. Only a bridge+// that never opened, or a machine that never answered, fails this.+const UNREACHED = /Could not open|connection failed|could not connect|did not connect|unavailable or needs linking/i+const grid = await harnessExecute({ machineId }, ['ls'], { timeoutMs: 20_000 })+check('autonomous grid, bridge', grid.ok || !UNREACHED.test(grid.error ?? ''), grid.ok ? 'ran' : `the daemon answered: ${grid.error}`)++closeBridges(); closeMemories(); closeSessions()+process.exit(failed ? 1 : 0)diff --git a/store/tools/windows-pipe.test.mjs b/store/tools/windows-pipe.test.mjsnew file mode 100644index 000000000..6c72a6ecc--- /dev/null+++ b/store/tools/windows-pipe.test.mjs@@ -0,0 +1,255 @@+// node --test store/tools/windows-pipe.test.mjs+// On Windows no Store package sends anything to the daemon's TCP port, whose holder may be another account's: the Team+// account's daemon starts at boot, before the owner's (audit W1, docs/security/2026-11-02-team-account-windows.md). They+// reach the daemon over its named pipe instead, with the pipe auth, and take an answer only with the daemon's proof+// (cli/src/lib/windows/pipeAuth.ts). The pipe here is a real one on Windows; elsewhere a socket of the same name in this+// spec's working folder, which is where a Unix client dials `\\.\pipe\harness-<id>`.+import assert from 'node:assert/strict'+import { spawnSync } from 'node:child_process'+import { createHash, createHmac, randomBytes } from 'node:crypto'+import { mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'+import { createServer } from 'node:http'+import { join } from 'node:path'+import { after, beforeEach, test } from 'node:test'+import { closeBridges, listAgents as monitorAgents } from '../agents/harness-monitor/lib/bridge.mjs'+import { closeBridges as closeMemories, listAgents as memoriesAgents } from '../agents/memories/lib/bridge.mjs'+import { closeSessions, listHarnesses, listMachines } from '../agents/machine-monitor/lib/daemon.mjs'+import { harnessExecute } from '../agents/autonomous-grid/lib/harness.mjs'+import { openDaemonBridge } from './local-credential.mjs'+import * as localDaemon from './local-daemon.mjs'+import { removeTempFolders, tempFolder } from './test-folders.mjs'++const realWindows = process.platform === 'win32'+const platform = Object.getOwnPropertyDescriptor(process, 'platform')+Object.defineProperty(process, 'platform', { value: 'win32' })+const home = process.cwd()+// Where a Unix client finds a pipe's name: this folder, as a relative path.+if (!realWindows) process.chdir(tempFolder('pipes-'))++const CREDENTIAL = `test-local-credential-${'a'.repeat(21)}`+const closers = []+after(async () => {+ try { closeBridges(); closeMemories(); closeSessions(); for (const close of closers) await close() } finally {+ process.chdir(home)+ removeTempFolders()+ Object.defineProperty(process, 'platform', platform)+ }+})+// A kept session from an earlier test would answer instead.+beforeEach(() => { closeBridges(); closeMemories(); closeSessions() })++const mac = (token, separator, nonce) => createHmac('sha256', token).update(Buffer.of(separator)).update(nonce, 'utf8').digest('hex')++/** A data folder as the Windows daemon leaves it: the credential, the daemon's token, and (once given) its record. */+function dataDir() {+ const dir = join(tempFolder('pipe-'), 'd')+ mkdirSync(dir, { mode: 0o700 })+ writeFileSync(join(dir, 'hook-credential'), `${CREDENTIAL}\n`, { mode: 0o600 })+ const token = randomBytes(32)+ writeFileSync(join(dir, 'daemon-token'), `${token.toString('hex')}\n`, { mode: 0o600 })+ return { dir, token }+}++function record(dir, configuredPort, fields) {+ writeFileSync(join(dir, `daemon-${configuredPort}.json`), `${JSON.stringify(fields)}\n`, { mode: 0o600 })+}++/** Another account on the port: it records everything and answers nothing useful. */+async function holder() {+ const heard = []+ const server = createServer((req, res) => { heard.push({ url: req.url, headers: req.headers }); res.writeHead(401).end() })+ server.on('upgrade', (req, socket) => { heard.push({ url: req.url, headers: req.headers }); socket.on('error', () => {}); socket.destroy() })+ await new Promise(ready => server.listen(0, '127.0.0.1', ready))+ closers.push(() => new Promise(done => { server.closeAllConnections(); server.close(() => done()) }))+ return { heard, port: server.address().port }+}++const envFor = (dir, port) => ({ ...process.env, ADAPTER_DATA_DIR: dir, HPS_BRIDGE_URL: `ws://127.0.0.1:${port}/api/local-ws`,+ MEMORIES_BRIDGE_URL: `ws://127.0.0.1:${port}/api/local-ws`, HARNESS_GRID_BRIDGE_URL: `ws://127.0.0.1:${port}/api/local-ws`,+ HARNESS_MACHINES_DAEMON: `http://127.0.0.1:${port}/` })++const text = (value) => {+ const body = Buffer.from(value)+ const head = body.length < 126 ? Buffer.from([0x81, body.length]) : Buffer.from([0x81, 126, body.length >> 8, body.length & 255])+ return Buffer.concat([head, body])+}+function unmasked(buffer) {+ if (buffer.length < 6) return null+ const short = buffer[1] & 0x7f, start = short === 126 ? 4 : 2+ const size = short === 126 ? buffer.readUInt16BE(2) : short+ if (buffer.length < start + 4 + size) return null+ const mask = buffer.subarray(start, start + 4), body = Buffer.from(buffer.subarray(start + 4, start + 4 + size))+ for (let i = 0; i < size; i++) body[i] ^= mask[i % 4]+ return { opcode: buffer[0] & 0x0f, text: body.toString(), size: start + 4 + size }+}++/**+ * The Windows daemon on its pipe (cli/src/lib/localSocket.ts `listenAuthenticated`): a request whose auth is not this+ * token's, for this pipe, gets a 401; every answer carries the proof. `proof` replaces it, for something else on the name.+ */+async function daemonOnPipe(token, { proof } = {}) {+ const id = randomBytes(16).toString('hex'), pipe = `\\\\.\\pipe\\harness-${id}`+ const got = []+ const checked = (req) => {+ const [nonce, given] = String(req.headers['x-harness-auth'] ?? '').split('.')+ const valid = /^[0-9a-f]{64}$/.test(nonce ?? '') && nonce.startsWith(id) && given === mac(token, 0x01, nonce)+ got.push({ url: req.url, headers: req.headers, valid })+ return valid ? (proof ?? mac(token, 0x00, nonce)) : null+ }+ const server = createServer((req, res) => {+ const answer = checked(req)+ if (!answer) { res.writeHead(401).end(); return }+ res.writeHead(200, { 'content-type': 'application/json', 'x-harness-proof': answer })+ .end(JSON.stringify({ data: { machines: [{ machineId: 'm' }] } }))+ })+ const upgraded = new Set()+ server.on('upgrade', (req, socket) => {+ socket.on('error', () => {})+ const answer = checked(req)+ if (!answer) { socket.end('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\nContent-Length: 0\r\n\r\n'); return }+ upgraded.add(socket)+ const accept = createHash('sha1').update(`${req.headers['sec-websocket-key']}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`).digest('base64')+ socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\nX-Harness-Proof: ${answer}\r\n\r\n`)+ let held = Buffer.alloc(0)+ socket.on('data', (chunk) => {+ held = Buffer.concat([held, chunk])+ for (let frame = unmasked(held); frame; frame = unmasked(held)) {+ held = held.subarray(frame.size)+ if (frame.opcode === 8) { socket.end(); return }+ if (frame.opcode !== 1) continue+ const { type, payload } = JSON.parse(frame.text)+ got.push({ type })+ if (type === 'machine_select') socket.write(text(JSON.stringify({ type: 'connected', payload: { machineId: payload.machineId, relayIsolation: true } })))+ else if (payload?.requestId) socket.write(text(JSON.stringify({ type: `${type}_result`, payload: { requestId: payload.requestId, agents: [{ id: 'a1' }], harnesses: [], sampledAt: 1 } })))+ }+ })+ })+ await new Promise(ready => server.listen(pipe, ready))+ closers.push(() => new Promise(done => { for (const socket of upgraded) socket.destroy(); server.closeAllConnections(); server.close(() => done()) }))+ return { got, pipe }+}++const clients = {+ 'harness-monitor': env => monitorAgents('m', { env, timeoutMs: 1500 }),+ memories: env => memoriesAgents('m', { env, timeoutMs: 1500 }),+ 'machine-monitor rest': env => listMachines(env),+ 'machine-monitor bridge': env => listHarnesses('m', { env, timeoutMs: 1500 }),+ 'autonomous-grid': env => harnessExecute({ machineId: 'm' }, ['ls'], { env, timeoutMs: 1500 }),+}++const heardOf = (hold) => hold.heard.map(h => ({ url: h.url, credential: h.headers['x-harness-local'] }))++for (const [name, run] of Object.entries(clients)) {+ test(`${name}: on Windows with no pipe recorded, the holder of the port hears nothing`, async () => {+ const { dir } = dataDir(), hold = await holder()+ await run(envFor(dir, hold.port)).catch(() => null)+ assert.deepEqual(heardOf(hold), [], 'nothing reaches the port')+ })++ test(`${name}: on Windows it reaches the daemon over its pipe with the pipe auth, and the port hears nothing`, async () => {+ const { dir, token } = dataDir(), hold = await holder(), daemon = await daemonOnPipe(token)+ record(dir, hold.port, { port: hold.port, pipe: daemon.pipe, pid: process.pid })+ await run(envFor(dir, hold.port)).catch(() => null)+ assert.deepEqual(heardOf(hold), [], 'nothing reaches the port')+ const requests = daemon.got.filter(g => g.url)+ assert.ok(requests.length > 0, 'the daemon was reached over its pipe')+ assert.ok(requests.every(g => g.valid && !g.headers['x-harness-local']), 'with a valid auth, and no credential')+ if (name !== 'machine-monitor rest') assert.ok(daemon.got.some(g => g.type === 'machine_select'), 'and the bridge was used')+ })++ test(`${name}: on Windows an answer on the pipe without the daemon's proof is never taken`, async () => {+ const { dir, token } = dataDir(), hold = await holder(), daemon = await daemonOnPipe(token, { proof: '0'.repeat(64) })+ record(dir, hold.port, { port: hold.port, pipe: daemon.pipe, pid: process.pid })+ const result = await run(envFor(dir, hold.port)).catch(() => null)+ assert.deepEqual(heardOf(hold), [], 'nothing reaches the port')+ assert.equal(daemon.got.filter(g => g.type).length, 0, 'no frame is sent to whatever answered')+ if (name === 'machine-monitor rest') assert.equal(result.ok, false, 'and its body is not read as the daemon\'s')+ })+}++test('the record is found by the port the daemon bound when the URL names that one', async () => {+ const { dir, token } = dataDir(), hold = await holder(), daemon = await daemonOnPipe(token)+ record(dir, 18473, { port: hold.port, pipe: daemon.pipe, pid: process.pid })+ const result = await listMachines(envFor(dir, hold.port))+ assert.equal(result.ok, true, JSON.stringify(result))+ assert.deepEqual(heardOf(hold), [])+})++test('nothing is dialled for a record that is not a live local pipe, or with no trusted token', (t) => {+ const { daemonPipe } = localDaemon+ const { dir, token } = dataDir()+ const id = randomBytes(16).toString('hex'), pipe = `\\\\.\\pipe\\harness-${id}`+ const gone = spawnSync(process.execPath, ['-e', '']).pid+ for (const [why, fields] of [+ ['a file', { port: 1, pipe: join(dir, `harness-${id}`), pid: process.pid }],+ ["another computer's pipe", { port: 1, pipe: `\\\\host\\pipe\\harness-${id}`, pid: process.pid }],+ ['a longer name', { port: 1, pipe: `${pipe}0`, pid: process.pid }],+ ['no pid', { port: 1, pipe }],+ ['a daemon that has exited', { port: 1, pipe, pid: gone }],+ ]) {+ record(dir, 1, fields)+ assert.equal(daemonPipe(1, { ADAPTER_DATA_DIR: dir }), null, why)+ }+ record(dir, 1, { port: 1, pipe, pid: process.pid })+ const route = daemonPipe(1, { ADAPTER_DATA_DIR: dir })+ const [nonce, given] = route.headers['X-Harness-Auth'].split('.')+ assert.equal(route.path, pipe)+ assert.ok(nonce.startsWith(id) && nonce.length === 64 && given === mac(token, 0x01, nonce), 'the auth proves the token for this pipe')+ assert.ok(route.proven(mac(token, 0x00, nonce)) && !route.proven(mac(token, 0x01, nonce)) && !route.proven(undefined))+ assert.equal(JSON.stringify(route).includes(token.toString('hex')), false, 'and the token itself goes nowhere')+ assert.notEqual(daemonPipe(1, { ADAPTER_DATA_DIR: dir }).headers['X-Harness-Auth'], route.headers['X-Harness-Auth'], 'a fresh nonce each time')+ assert.equal(daemonPipe(1, { ADAPTER_DATA_DIR: dir }, 'darwin'), null, 'off Windows there is no pipe to dial')++ writeFileSync(join(dir, 'daemon-token'), 'not a token\n')+ assert.equal(daemonPipe(1, { ADAPTER_DATA_DIR: dir }), null, 'a token that is not one')+ const elsewhere = join(tempFolder('token-'), 'daemon-token')+ writeFileSync(elsewhere, `${token.toString('hex')}\n`)+ rmSync(join(dir, 'daemon-token'))+ assert.equal(daemonPipe(1, { ADAPTER_DATA_DIR: dir }), null, 'no token')+ try { symlinkSync(elsewhere, join(dir, 'daemon-token')) } catch { t.diagnostic('this account cannot make links here'); return }+ assert.equal(daemonPipe(1, { ADAPTER_DATA_DIR: dir }), null, 'a token reached through a link')+})++/** The `ws` package's client, as far as openDaemonBridge uses it: options in, `upgrade` listeners, `terminate`. */+class ScriptedWs {+ static made = []+ constructor(url, options) { this.url = url; this.options = options; this.listeners = []; this.terminated = false; ScriptedWs.made.push(this) }+ on(event, listener) { if (event === 'upgrade') this.listeners.push(listener); return this }+ terminate() { this.terminated = true }+ upgrade(headers) { for (const listener of this.listeners) listener({ headers }) }+}++test('a dev tool ends an upgrade on the pipe without the daemon\'s proof, and keeps one with it', () => {+ const { dir, token } = dataDir()+ const id = randomBytes(16).toString('hex'), pipe = `\\\\.\\pipe\\harness-${id}`+ record(dir, 18473, { port: 18473, pipe, pid: process.pid })+ const env = { ADAPTER_DATA_DIR: dir }+ const impostor = openDaemonBridge(ScriptedWs, 18473, env)+ assert.equal(impostor.url, 'ws://localhost/api/local-ws')+ assert.deepEqual(Object.keys(impostor.options).sort(), ['createConnection', 'headers'], 'the pipe, its auth, and nothing else')+ assert.deepEqual(Object.keys(impostor.options.headers), ['X-Harness-Auth'])+ impostor.upgrade({ 'x-harness-proof': '0'.repeat(64) })+ assert.equal(impostor.terminated, true, 'a wrong proof ends it before open')+ const silent = openDaemonBridge(ScriptedWs, 18473, env)+ silent.upgrade({})+ assert.equal(silent.terminated, true, 'and so does none')+ const daemon = openDaemonBridge(ScriptedWs, 18473, env)+ const [nonce] = daemon.options.headers['X-Harness-Auth'].split('.')+ daemon.upgrade({ 'x-harness-proof': mac(token, 0x00, nonce) })+ assert.equal(daemon.terminated, false, 'the daemon\'s own proof is kept')+})++// The real `ws`, where the CLI's packages are installed (the Windows workflow installs them before its specs): an upgrade+// without the daemon's proof never opens, so the tool's first frame, sent on `open`, never goes.+const ws = await import('../../cli/node_modules/ws/index.js').then((module) => module.default.WebSocket, () => null)+test('with the real ws, an upgrade on the pipe without the daemon\'s proof never opens and sends nothing', { skip: ws ? false : 'cli/node_modules has no ws here', timeout: 10_000 }, async () => {+ const { dir, token } = dataDir(), daemon = await daemonOnPipe(token, { proof: '0'.repeat(64) })+ record(dir, 18473, { port: 18473, pipe: daemon.pipe, pid: process.pid })+ const socket = openDaemonBridge(ws, 18473, { ADAPTER_DATA_DIR: dir })+ let opened = false+ socket.on('open', () => { opened = true; socket.send(JSON.stringify({ type: 'machine_select', payload: { machineId: 'm' } }), () => socket.close()) })+ await new Promise((done) => { socket.on('close', done); socket.on('error', () => {}) })+ assert.equal(opened, false)+ assert.ok(daemon.got.some(g => g.url && g.valid), 'the upgrade reached the pipe with a valid auth')+ assert.equal(daemon.got.filter(g => g.type).length, 0, 'and no frame followed it')+})