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 1102-o: #2579 (#2592)
0xken1598268bd05eeb
diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.ymlindex b03753cf8..28ee2812f 100644--- a/.github/workflows/windows.yml+++ b/.github/workflows/windows.yml@@ -168,7 +168,7 @@ jobs:# serialWindows.spec.ts runs the real harness-serial.exe, placed beside the host by the payload step.HARNESS_SERIAL_BIN: ${{ github.workspace }}\pty\target\${{ matrix.target }}\release\harness-serial.exerun: |- $paths = @('src/lib/ptyHostBackend.contract.spec.ts', 'src/lib/ptyHost', 'src/lib/windows', 'src/scripts/windowsCiChecks.spec.ts', 'src/lib/uninstall', 'src/engines/kit/hookRemoval.spec.ts', 'src/engines/kit/windowsHooks.spec.ts', 'src/engines/kit/windowsFiles.spec.ts', 'src/engines/kit/nativePaths.windows.spec.ts', 'src/engines/kit/launchExecutable.windows.spec.ts', 'src/dsh/runtime.windows.spec.ts', 'src/engines/removeHooks.spec.ts', 'src/engines/windowsHomes.spec.ts', 'src/cable/windowsSerial.spec.ts', 'src/cable/serialWindows.spec.ts')+ $paths = @('src/lib/ptyHostBackend.contract.spec.ts', 'src/lib/ptyHost', 'src/lib/windows', 'src/scripts/windowsCiChecks.spec.ts', 'src/team/windowsTeamRemove.real.spec.ts', 'src/lib/uninstall', 'src/engines/kit/hookRemoval.spec.ts', 'src/engines/kit/windowsHooks.spec.ts', 'src/engines/kit/windowsFiles.spec.ts', 'src/engines/kit/nativePaths.windows.spec.ts', 'src/engines/kit/launchExecutable.windows.spec.ts', 'src/dsh/runtime.windows.spec.ts', 'src/engines/removeHooks.spec.ts', 'src/engines/windowsHomes.spec.ts', 'src/cable/windowsSerial.spec.ts', 'src/cable/serialWindows.spec.ts')npx vitest run @paths --maxWorkers=1# Two real builds (sub-project G): the rollover from the previous host to this one (hostMove.real.spec.ts, and# drain.spec.ts's two-build case), and the payload install (the bin\ replacement, and install.ps1 in Windowsdiff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex 060a1426b..e6ef6d412 100644--- a/cli/src/superTabs/service.ts+++ b/cli/src/superTabs/service.ts@@ -25,7 +25,7 @@ import { openDaemon } from '../agentClient/daemon.js'import { readTeamConfig } from '../team/config.js'import { realTeamRelayPublisher, TEAM_RELAY_GRANT_FILE, type TeamRelayPublisher } from '../team/relay.js'import { readLastTry, refreshCreationId, refreshTeamAccount, teamRefreshFile, writeLastTry, type TeamRefreshDeps } from '../team/refresh.js'-import { readTeamStatus } from '../team/privacy.js'+import { readTeamStatusOffThread } from '../team/privacy.js'import { ensureTeamTmux, TMUX_MANIFEST_URL, tmuxRunsAt, untarGz, type TeamTmuxDeps, type TeamTmuxOutcome } from '../team/tmux.js'import { downloadVerified } from '../lib/selfUpdate.js'import { managedTmuxPath, tmuxInstallDirectories } from '../lib/tmuxOnPath.js'@@ -882,7 +882,8 @@ function realTeamRefreshDeps(core: CoreApi, publishedAt: number | null): TeamRefconst file = teamRefreshFile(core.dataDir)return {config: () => readTeamConfig(),- status: readTeamStatus,+ // Never on this thread on Windows: the Team account can hold its file's open for as long as it likes (audit W4).+ status: (path) => readTeamStatusOffThread(path),publishedAt: () => publishedAt,machines: async () => {const reply = await core.account.backend('GET', '/api/machines')diff --git a/cli/src/team/privacy.spec.ts b/cli/src/team/privacy.spec.tsindex be4a4659d..2dd0f0e0f 100644--- a/cli/src/team/privacy.spec.ts+++ b/cli/src/team/privacy.spec.ts@@ -1,11 +1,12 @@-import { execFileSync, spawn } from 'node:child_process'+import { execFileSync, spawn, type ChildProcess } from 'node:child_process'+import { EventEmitter } from 'node:events'import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync, readFileSync, statSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, describe, expect, it, vi } from 'vitest'import { readTeamConfig, teamConfigJson, type TeamConfig } from './config.js'import {- PRIVACY_RECHECK_MS, TeamPrivacyObserver, adminGroupIds, privacyProbes, readTeamStatus, realPrivacyDeps, runPrivacyCheck, writeTeamStatus,+ PRIVACY_RECHECK_MS, TeamPrivacyObserver, readStatusFile, readTeamStatusOffThread, resetStatusChild, adminGroupIds, privacyProbes, readTeamStatus, realPrivacyDeps, runPrivacyCheck, writeTeamStatus,type PrivacyDeps, type PrivacyResult,} from './privacy.js'@@ -356,3 +357,99 @@ describe('what a status says, as it reaches a terminal', () => {expect(status?.signIn?.detail).toBe('Không đăng nhập được · 失敗')})})++// Audit W4: on Windows a Team process can hold the owner's open of its status file with an oplock, for as long as it likes. A FIFO+// is the same stall where this runs: a plain open waits on it until someone writes. Windows itself: windowsTeamRemove.real.spec.ts.+describe.skipIf(process.platform === 'win32')('reading the status file in a child, as on Windows', () => {+ const dir = () => mkdtempSync(join(tmpdir(), 'team-status-'))+ const stalled = () => { const fifo = join(dir(), 'status.json'); execFileSync('mkfifo', [fifo]); return fifo }+ const options = (over = {}) => ({ platform: 'win32' as NodeJS.Platform, deadlineMs: 400, log: () => {}, ...over })+ afterEach(() => resetStatusChild())++ it('reads a plain file, as the status it holds', async () => {+ const file = join(dir(), 'status.json')+ writeFileSync(file, JSON.stringify({ version: 1, privacy: { passed: true, checkedAt: 3 } }))+ expect(await readTeamStatusOffThread(file, options({ deadlineMs: 15_000 }))).toEqual({ version: 1, privacy: { passed: true, checkedAt: 3 } })+ expect(readTeamStatus(file, (path) => readStatusFile(path, 'win32', 15_000))).toEqual({ version: 1, privacy: { passed: true, checkedAt: 3 } })+ })++ it('never stops the daemon on a stalled open: other work runs, the read ends at its deadline as no status, and says so', async () => {+ const log = vi.fn()+ let ticks = 0+ const timer = setInterval(() => { ticks++ }, 20)+ const started = Date.now()+ const status = await readTeamStatusOffThread(stalled(), options({ log }))+ clearInterval(timer)+ expect(status).toBeNull()+ expect(Date.now() - started).toBeLessThan(5_000)+ expect(ticks).toBeGreaterThan(5)+ expect(log).toHaveBeenCalledWith(expect.stringContaining('status file'))+ })++ it('kills the child at the deadline', async () => {+ const children: ChildProcess[] = []+ const spawnChild = ((...args: Parameters<typeof spawn>) => { const child = spawn(...args); children.push(child); return child }) as typeof spawn+ await readTeamStatusOffThread(stalled(), options({ spawn: spawnChild }))+ expect(children).toHaveLength(1)+ await vi.waitFor(() => expect(children[0].exitCode !== null || children[0].signalCode !== null).toBe(true))+ })++ it('runs one child at a time, so a stuck one never piles up, and reads again once it has gone', async () => {+ const fake = Object.assign(new EventEmitter(), { stdout: new EventEmitter(), stderr: new EventEmitter(), kill: vi.fn(), unref: vi.fn() })+ const spawnChild = vi.fn(() => fake) as unknown as typeof spawn+ const first = readTeamStatusOffThread('/s', options({ spawn: spawnChild, deadlineMs: 20 }))+ expect(await first).toBeNull()+ expect(fake.kill).toHaveBeenCalled()+ expect(await readTeamStatusOffThread('/s', options({ spawn: spawnChild }))).toBeNull()+ expect(spawnChild).toHaveBeenCalledTimes(1)+ fake.emit('close', null)+ void readTeamStatusOffThread('/s', options({ spawn: spawnChild, deadlineMs: 20 }))+ expect(spawnChild).toHaveBeenCalledTimes(2)+ })++ it('does not keep the daemon alive, and asks for no window', async () => {+ const spawnChild = vi.fn(spawn)+ const file = join(dir(), 'status.json')+ writeFileSync(file, '{"version":1}')+ await readTeamStatusOffThread(file, options({ spawn: spawnChild as unknown as typeof spawn, deadlineMs: 15_000 }))+ expect(spawnChild.mock.calls[0][2]).toMatchObject({ windowsHide: true })+ })++ it('lets go of the child\'s pipe too, which would otherwise hold the daemon\'s exit until the kill lands', async () => {+ const fake = Object.assign(new EventEmitter(), { stdout: Object.assign(new EventEmitter(), { unref: vi.fn() }), kill: vi.fn(), unref: vi.fn() })+ await readTeamStatusOffThread('/s', options({ spawn: vi.fn(() => fake) as unknown as typeof spawn, deadlineMs: 10 }))+ expect(fake.unref).toHaveBeenCalled()+ expect(fake.stdout.unref).toHaveBeenCalled()+ })++ it.each([+ ['a file over the limit', (at: string) => writeFileSync(at, 'x'.repeat(64 * 1024 + 1))],+ ['a folder', (at: string) => mkdirSync(at)],+ ['nothing', () => {}],+ ['not JSON', (at: string) => writeFileSync(at, 'nope')],+ ])('answers no status for %s', async (_, make) => {+ const file = join(dir(), 'status.json')+ make(file)+ expect(await readTeamStatusOffThread(file, options({ deadlineMs: 15_000 }))).toBeNull()+ })++ it('still removes escape codes from what the child read', async () => {+ const file = join(dir(), 'status.json')+ writeFileSync(file, JSON.stringify({ version: 1, signIn: { state: 'failed', at: 2, detail: '\u001b[31mred\u0007' } }))+ expect((await readTeamStatusOffThread(file, options({ deadlineMs: 15_000 })))?.signIn?.detail).toBe('[31mred')+ })++ it('the blocking form used by harness team status ends at the deadline too', () => {+ const started = Date.now()+ expect(readTeamStatus(stalled(), (path) => readStatusFile(path, 'win32', 400))).toBeNull()+ expect(Date.now() - started).toBeLessThan(5_000)+ })++ it('leaves other platforms on the plain read, with no child', async () => {+ const spawnChild = vi.fn() as unknown as typeof spawn+ const file = join(dir(), 'status.json')+ writeFileSync(file, '{"version":1}')+ expect(await readTeamStatusOffThread(file, options({ platform: 'darwin', spawn: spawnChild }))).toEqual({ version: 1 })+ expect(spawnChild).not.toHaveBeenCalled()+ })+})diff --git a/cli/src/team/privacy.ts b/cli/src/team/privacy.tsindex 665be4e93..0b0af0e7b 100644--- a/cli/src/team/privacy.ts+++ b/cli/src/team/privacy.ts@@ -10,7 +10,7 @@* time. Each probe must be refused with EACCES or EPERM. Reading it, or any other answer (a missing file means the* folder above it was searchable), fails the check, and the first failing item is what the machine reports.*/-import { spawnSync } from 'node:child_process'+import { spawn, spawnSync, type ChildProcess } from 'node:child_process'import { closeSync, constants, fstatSync, mkdirSync, openSync, readSync, readdirSync, renameSync, writeFileSync } from 'node:fs'import { dirname } from 'node:path'import type { TeamConfig } from './config.js'@@ -154,6 +154,73 @@ export function enginesOf(value: unknown): TeamEngines | undefined {/** A status is well under 1 KiB: its one free text is capped at 300 characters. */const STATUS_MAX_BYTES = 64 * 1024+/** Plenty for a small file and a Node start on a busy machine; a read still waiting then is being held (audit W4). */+const STATUS_READ_DEADLINE_MS = 5_000++/**+ * On Windows an open waits for an oplock the file's owner holds, for as long as it holds it, and the Team account owns this file+ * (audit W4): it would stop whoever opens it. So the open happens in a child, which can be killed: unlike a worker stuck in a+ * synchronous call, or a thread-pool thread every file operation shares. It keeps the same limits as the read below.+ */+const STATUS_CHILD_SOURCE = `const fs = require('fs'), max = ${STATUS_MAX_BYTES}+const fd = fs.openSync(process.argv[1], 'r'), stat = fs.fstatSync(fd)+if (!stat.isFile() || stat.size > max) process.exit(3)+const buffer = Buffer.alloc(max + 1)+let length = 0+for (let got = 1; got > 0 && length < buffer.length; length += got) got = fs.readSync(fd, buffer, length, buffer.length - length, null)+if (length > max) process.exit(3)+process.stdout.write(buffer.subarray(0, length))`+const statusChildArgs = (path: string): string[] => ['-e', STATUS_CHILD_SOURCE, '--', path]+/** No window, and none of this process's settings, NODE_OPTIONS among them. */+const statusChildOptions = () => ({ windowsHide: true, env: process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {} })++/** For `harness team status` and setup, which wait for their answer. The daemon uses readTeamStatusOffThread. */+function readStatusInChild(path: string, deadlineMs: number): string {+ const result = spawnSync(process.execPath, statusChildArgs(path), { ...statusChildOptions(), timeout: deadlineMs, maxBuffer: STATUS_MAX_BYTES + 1,+ encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })+ if (result.status !== 0) throw new Error('not a status file')+ return result.stdout+}++let statusChildRunning = false+export function resetStatusChild(): void { statusChildRunning = false }++export interface StatusReadOptions { platform?: NodeJS.Platform; deadlineMs?: number; spawn?: typeof spawn; log?: (line: string) => void }++/**+ * The status as the owner's daemon reads it about once a minute, never waiting on the file (audit W4). One child at a time: while a+ * killed one has not gone, a read answers no status, as an unreadable file does, rather than start another for the same stall.+ */+export async function readTeamStatusOffThread(path: string, options: StatusReadOptions = {}): Promise<TeamStatus | null> {+ if ((options.platform ?? process.platform) !== 'win32') return readTeamStatus(path)+ if (statusChildRunning) return null+ statusChildRunning = true+ const log = options.log ?? ((line: string) => console.log(`[team] ${line}`))+ const text = await new Promise<string | null>((resolve) => {+ const chunks: Buffer[] = []+ let size = 0+ let child: ChildProcess+ try {+ child = (options.spawn ?? spawn)(process.execPath, statusChildArgs(path), { ...statusChildOptions(), stdio: ['ignore', 'pipe', 'ignore'] })+ } catch { statusChildRunning = false; resolve(null); return }+ const timer = setTimeout(() => {+ log(`the status file ${path} did not answer in ${options.deadlineMs ?? STATUS_READ_DEADLINE_MS} ms; reading on without it`)+ child.kill()+ resolve(null)+ }, options.deadlineMs ?? STATUS_READ_DEADLINE_MS)+ timer.unref?.()+ child.stdout?.on('data', (chunk: Buffer) => {+ size += chunk.length+ if (size > STATUS_MAX_BYTES) { child.kill(); resolve(null) } else chunks.push(chunk)+ })+ const done = (code: number | null) => { statusChildRunning = false; clearTimeout(timer); resolve(code === 0 ? Buffer.concat(chunks).toString('utf8') : null) }+ child.once('error', () => done(null))+ child.once('close', done)+ child.unref?.()+ ;(child.stdout as (NodeJS.ReadableStream & { unref?: () => void }) | null)?.unref?.()+ })+ return text === null ? null : readTeamStatus(path, () => text)+}/*** The status file, which the Team account may replace with anything, and which the owner's daemon reads about once a minute@@ -161,7 +228,8 @@ const STATUS_MAX_BYTES = 64 * 1024* link to /dev/zero would run until memory is gone (audit M5). So: never through a link, never waiting on a FIFO, a plain file* only, and never more than the limit, whatever fstat said a moment ago. As ./handoff.ts reads its code. Throws otherwise.*/-export function readStatusFile(path: string): string {+export function readStatusFile(path: string, platform: NodeJS.Platform = process.platform, deadlineMs: number = STATUS_READ_DEADLINE_MS): string {+ if (platform === 'win32') return readStatusInChild(path, deadlineMs)const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)try {const stat = fstatSync(fd)@@ -193,7 +261,7 @@ function privacyOf(value: unknown): PrivacyResult | undefined {return undefined}-export function readTeamStatus(path: string, read: (path: string) => string = readStatusFile): TeamStatus | null {+export function readTeamStatus(path: string, read: (path: string) => string = (at) => readStatusFile(at)): TeamStatus | null {let raw: unknowntry { raw = JSON.parse(read(path)) } catch { return null }if (!raw || typeof raw !== 'object' || (raw as { version?: unknown }).version !== 1) return nulldiff --git a/cli/src/team/refresh.spec.ts b/cli/src/team/refresh.spec.tsindex e65b354d6..d781b143b 100644--- a/cli/src/team/refresh.spec.ts+++ b/cli/src/team/refresh.spec.ts@@ -104,3 +104,9 @@ describe('a Harness Team account on a build too old for its owner\'s subscriptioexpect(validCreationId(refreshCreationId())).toBe(true)})})++it('waits for a status read that happens off the main thread (audit W4)', async () => {+ const look = vi.fn(() => null)+ await refreshTeamAccount(deps({ status: async () => { await new Promise((r) => setTimeout(r, 5)); return signedOut(2_000) }, lastTry: look }))+ expect(look).toHaveBeenCalled()+})diff --git a/cli/src/team/refresh.ts b/cli/src/team/refresh.tsindex 4c6f7bdc9..d645c9c5b 100644--- a/cli/src/team/refresh.ts+++ b/cli/src/team/refresh.ts@@ -28,7 +28,7 @@ export const TEAM_REFRESH_RETRY_MS = 24 * 60 * 60_000export interface TeamRefreshDeps {config(): TeamConfig | null- status(path: string): TeamStatus | null+ status(path: string): TeamStatus | null | Promise<TeamStatus | null>/** When this daemon last published the owner's relay (team/relay.ts), or null before it has. */publishedAt(): number | null/** The account's machines, from `GET /api/machines`: the team account of this Mac is among them. */@@ -72,7 +72,7 @@ export function teamUpdateArgv(config: Pick<TeamConfig, 'node' | 'cli' | 'home'>export async function refreshTeamAccount(deps: TeamRefreshDeps): Promise<void> {try {const config = deps.config()- if (!config || !teamBuildStale(deps.status(config.statusFile), deps.publishedAt())) return+ if (!config || !teamBuildStale(await deps.status(config.statusFile), deps.publishedAt())) returnconst last = deps.lastTry()if (last !== null && deps.now() - last < TEAM_REFRESH_RETRY_MS && deps.now() >= last) returnconst here = deps.machineId()diff --git a/cli/src/team/windowsScript.spec.ts b/cli/src/team/windowsScript.spec.tsindex 3fa6b3839..d0ba7b584 100644--- a/cli/src/team/windowsScript.spec.ts+++ b/cli/src/team/windowsScript.spec.ts@@ -324,7 +324,7 @@ describe('the Windows remove script', () => {it('stops the task and the team account\'s processes, then the profile, then the account, then the task\'s definition', () => {const script = buildWindowsRemoveScript(removeInput())const order = ['Disable-ScheduledTask', 'GetOwnerSid', 'Remove-CimInstance', 'Remove-LocalUser', 'Unregister-ScheduledTask', 'Set-BatchLogon $teamSid $false',- 'Remove-Tree $STATUS_DIR']+ 'Remove-Held $STATUS_DIR'].map((s) => at(script, s))expect(order).toEqual([...order].sort((a, b) => a - b))})@@ -361,7 +361,7 @@ describe('the Windows remove script', () => {// Nothing the team account wrote is read as an administrator to name a machine to remove (audit L3).expect(script).not.toContain('computer-id')expect(script).not.toContain('$COMPUTER_ID')- expect(at(script, 'Test-Path -LiteralPath $SHARED_MARK')).toBeGreaterThan(at(script, 'Remove-Tree $STATUS_DIR'))+ expect(at(script, 'Test-Path -LiteralPath $SHARED_MARK')).toBeGreaterThan(at(script, 'Remove-Held $STATUS_DIR'))// A line ending in LF alone: the owner's side splits this output at LF.expect(script).toContain('[Console]::Out.Write("harness: $m`n")')})@@ -373,3 +373,115 @@ describe('the Windows remove script', () => {it.skipIf(!pwsh)('parses', () => parses(buildWindowsRemoveScript(removeInput())))})++// Audit W7: what the Team account wrote goes to the administrator's console.+describe('what the elevated setup prints of the Team account\'s output', () => {+ it('has no control or format characters, read where every print gets it', () => {+ const script = buildWindowsSetupScript(input())+ expect(script).toContain("[regex]::Replace($text, '[\\p{Cc}\\p{Cf}\\p{Cs}\\p{Zl}\\p{Zp}]', '')")+ expect(script).toMatch(/\$lines = @\(Get-Content -LiteralPath \$out[^\n]*\| ForEach-Object \{ Clean-Line \$_ \} \| Where-Object \{ \$_ \}\)/)+ expect(script.indexOf('function Clean-Line')).toBeLessThan(script.indexOf('function As-Team'))+ })+})++// Audit W5: removal runs as an administrator on folders the Team account could write.+describe('what the elevated removal deletes of the Team account\'s', () => {+ const script = () => buildWindowsRemoveScript(removeInput())++ it('compiles its helper before anything changes, and stops with nothing removed if it cannot', () => {+ const text = script()+ expect(text).toContain('Add-Type -TypeDefinition $HELPER')+ expect(text).toMatch(/try \{ Load-Helper \} catch \{ die "[^"]*nothing was removed/)+ expect(text.indexOf('try { Load-Helper }')).toBeLessThan(text.indexOf('# 1. The team daemon'))+ })++ it('never walks them by path', () => {+ const text = script()+ for (const path of ['$TEAM_HOME', '$STATUS_DIR', '$relay.FullName']) {+ expect(text).toContain(`Remove-Held ${path}`)+ expect(text).not.toContain(`Remove-Tree ${path}`)+ }+ })++ it('renames first, into a name nobody knows, and goes on where Windows will not let it', () => {+ const text = script()+ expect(text).toContain('[guid]::NewGuid()')+ expect(text).toMatch(/try \{ \[IO\.Directory\]::Move\(\$path, \$moved\); \$at = \$moved \} catch \{ \}/)+ expect(text.indexOf('[IO.Directory]::Move($path, $moved)')).toBeLessThan(text.indexOf('[HarnessTeamRemove]::Delete($at)'))+ })++ it('opens each child relative to its parent\'s handle, never following a link', () => {+ const text = script()+ expect(text).toContain('NtOpenFile')+ expect(text).toContain('RootDirectory')+ expect(text).toContain('FILE_OPEN_REPARSE_POINT')+ expect(text).toContain('FILE_FLAG_OPEN_REPARSE_POINT')+ expect(text).toContain('SetFileInformationByHandle')+ })++ it('keeps what cannot be deleted for the next restart, and says what could not go elsewhere', () => {+ const text = script()+ expect(text).toContain('Remove-Held $TEAM_HOME $left')+ expect(text).toMatch(/throw "could not delete/)+ })++ it('stops the tasks the Team account registered before its processes, and restores them if removal stops', () => {+ const text = script()+ expect(text).toContain('function Team-Tasks')+ expect(text).toMatch(/\$_\.Principal\.UserId/)+ expect(text.indexOf('Disable-ScheduledTask -InputObject')).toBeLessThan(text.indexOf('# 2. Every process running as the team account'))+ expect(text.match(/Restore-Tasks/g)!.length).toBeGreaterThanOrEqual(3)+ })++ it('deletes them once the account is gone, its own daemon\'s task apart', () => {+ const text = script()+ expect(text).toContain('Delete-Task $own')+ expect(text.indexOf('foreach ($own in @($script:seenTasks')).toBeGreaterThan(text.indexOf('# 4. The account.'))+ })++ it('takes what a removal that stopped partway left renamed, by its own prefix alone', () => {+ const text = script()+ expect(text).toContain("-Filter '.harness-removing-*'")+ expect(text).toContain('Remove-Renamed (Split-Path -Parent $TEAM_HOME)')+ expect(text).toContain('Remove-Renamed $SHARED')+ })++ it('matches a task by the Team account alone: this computer\'s, never a same-named domain account', () => {+ const text = script()+ expect(text).toContain("$parts = $user -split '\\\\'")+ expect(text).toContain('($teamSid -and $user -eq $teamSid) -or ($parts[-1] -eq $TEAM -and ($parts.Count -eq 1 -or $parts[0] -eq $env:COMPUTERNAME))')+ })++ // A Team process alive at the first look can register a task after it (security review of #2579).+ it('looks for its tasks again after the processes stop, and stops what is still running before step 5', () => {+ const text = script()+ const kill = text.indexOf('foreach ($process in @(Team-Processes)) { Stop-Process')+ const again = text.indexOf('Hold-Tasks', kill)+ expect(again).toBeGreaterThan(kill)+ expect(again).toBeLessThan(text.indexOf('# 3. The profile.'))+ const fifth = text.indexOf('# 5. What it left')+ const last = text.lastIndexOf('foreach ($process in @(Team-Processes)) { Stop-Process', fifth)+ expect(last).toBeGreaterThan(text.indexOf('# 4. The account.'))+ })++ it('unregisters the tasks it found while the account was there, as the name may not match once it has gone', () => {+ const text = script()+ expect(text).toContain('foreach ($own in @($script:seenTasks + @(Team-Tasks)))')+ expect(text).toContain('Task-There $_')+ })++ // These take wildcards: a Team task named [G]oogleUpdate could match the real GoogleUpdate (security review 2 of #2579).+ it('never passes a task name the Team account chose to a command that reads wildcards', () => {+ const text = script()+ expect(text).not.toContain('-TaskName $own.TaskName')+ expect(text).toContain('.DeleteTask($own.TaskName, 0)')+ expect(text).toContain('.GetTask($own.TaskName)')+ })++ it('cleans what the Team account named before printing it', () => {+ const text = script()+ expect(text).toContain('function Clean-Line')+ expect(text).toContain('Clean-Line $failed[0]')+ expect(text).toContain('Clean-Line $_.TaskName')+ })+})diff --git a/cli/src/team/windowsScript.ts b/cli/src/team/windowsScript.tsindex a4b5128cd..b6d6c6dec 100644--- a/cli/src/team/windowsScript.ts+++ b/cli/src/team/windowsScript.ts@@ -388,6 +388,7 @@ export function buildWindowsSetupScript(input: WindowsSetupScriptInput): string// the new logon. Task Scheduler gives the run a desktop of its own from any session, as it does the team daemon.// The output is appended to a file this process made in the stage folder, writable by the team account alone, so// nothing is written in the team account's home as the administrator.+ WINDOWS_CLEAN_LINE,'function As-Team([string]$what, [string]$line, [int]$minutes) {'," if (-not $script:scheduler) { $script:scheduler = New-Object -ComObject Schedule.Service; $script:scheduler.Connect() }",' $out = Join-Path $script:RT "$what.out"',@@ -413,7 +414,8 @@ export function buildWindowsSetupScript(input: WindowsSetupScriptInput): string' $status = $registered.LastTaskResult',' } finally { $root.DeleteTask($name, 0) }',' if ($late) { die "the team account\'s $what did not finish in $minutes minutes" }',- ' $lines = @(Get-Content -LiteralPath $out -ErrorAction SilentlyContinue | Where-Object { $_ })',+ // The Team account wrote these, and they go to the administrator\'s console (audit W7).+ ' $lines = @(Get-Content -LiteralPath $out -ErrorAction SilentlyContinue | ForEach-Object { Clean-Line $_ } | Where-Object { $_ })',' return @($status, $lines)','}','',@@ -693,6 +695,175 @@ ${exec(daemon)}* gone: registering it again would need a password, and nobody knows the account's. The profile goes before the account,* so a profile Windows keeps (a process still holds it) leaves the account and its task as they were, running again.*/+/**+ * Deletes what the Team account could write, as an administrator (audit W5): renamed first where Windows allows, then through handles+ * opened relative to each parent and never through a link. Compiled by Windows PowerShell's Add-Type (Microsoft's csc.exe), so it is+ * C# 5. Not walked by path as Remove-Tree does: a Team process could swap a checked folder for a junction, and the administrator+ * would delete what is behind it.+ */+const TEAM_REMOVE_HELPER = String.raw`using System;+using System.Collections.Generic;+using System.Runtime.InteropServices;+using System.Text;+using Microsoft.Win32.SafeHandles;++public static class HarnessTeamRemove {+ const uint DELETE = 0x00010000, FILE_LIST_DIRECTORY = 0x1, FILE_READ_ATTRIBUTES = 0x80, FILE_WRITE_ATTRIBUTES = 0x100, SYNCHRONIZE = 0x00100000;+ const uint WALK = DELETE | FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | SYNCHRONIZE, BARE = DELETE | FILE_READ_ATTRIBUTES | SYNCHRONIZE;+ const uint SHARE_ALL = 7, OPEN_EXISTING = 3, FILE_FLAG_BACKUP_SEMANTICS = 0x02000000, FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000;+ const uint OBJ_CASE_INSENSITIVE = 0x40, FILE_SYNCHRONOUS_IO_NONALERT = 0x20, FILE_OPEN_FOR_BACKUP_INTENT = 0x4000, FILE_OPEN_REPARSE_POINT = 0x00200000;+ const uint ATTR_DIRECTORY = 0x10, ATTR_REPARSE = 0x400, ATTR_NORMAL = 0x80;+ const int INFO_BASIC = 0, INFO_DISPOSITION = 4, INFO_FULL_DIRECTORY = 14, ERROR_NO_MORE_FILES = 18, MAX_DEPTH = 512;++ [StructLayout(LayoutKind.Sequential)] struct UNICODE_STRING { public ushort Length; public ushort MaximumLength; public IntPtr Buffer; }+ [StructLayout(LayoutKind.Sequential)] struct OBJECT_ATTRIBUTES { public int Length; public IntPtr RootDirectory; public IntPtr ObjectName; public uint Attributes; public IntPtr SecurityDescriptor; public IntPtr SecurityQualityOfService; }+ [StructLayout(LayoutKind.Sequential)] struct IO_STATUS_BLOCK { public IntPtr Status; public IntPtr Information; }++ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]+ static extern SafeFileHandle CreateFileW(string name, uint access, uint share, IntPtr security, uint disposition, uint flags, IntPtr template);+ [DllImport("ntdll.dll")]+ static extern int NtOpenFile(out SafeFileHandle handle, uint access, ref OBJECT_ATTRIBUTES attributes, out IO_STATUS_BLOCK status, uint share, uint options);+ [DllImport("kernel32.dll", SetLastError = true)]+ static extern bool GetFileInformationByHandleEx(SafeFileHandle handle, int kind, byte[] buffer, uint size);+ [DllImport("kernel32.dll", SetLastError = true)]+ static extern bool SetFileInformationByHandle(SafeFileHandle handle, int kind, byte[] buffer, uint size);++ // What could not be deleted, deepest first. A link is deleted as itself and nothing behind it is touched: every child opens+ // relative to its parent's open handle and without following a link, so swapping a folder for a junction changes nothing.+ public static string[] Delete(string path) {+ List<string> left = new List<string>();+ string native = path.Length > 2 && path[1] == ':' ? "\\\\?\\" + path : path;+ SafeFileHandle top = CreateFileW(native, WALK, SHARE_ALL, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, IntPtr.Zero);+ if (top.IsInvalid) top = CreateFileW(native, BARE, SHARE_ALL, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, IntPtr.Zero);+ if (top.IsInvalid) { left.Add(path); return left.ToArray(); }+ using (top) { Finish(top, path, 0, left); }+ return left.ToArray();+ }++ static void Finish(SafeFileHandle item, string at, int depth, List<string> left) {+ uint attributes;+ if (!Attributes(item, out attributes)) { left.Add(at); return; }+ if ((attributes & ATTR_DIRECTORY) != 0 && (attributes & ATTR_REPARSE) == 0) {+ if (depth >= MAX_DEPTH) { left.Add(at); return; }+ Empty(item, at, depth, left);+ }+ if (!MarkDeleted(item)) left.Add(at);+ }++ static void Empty(SafeFileHandle folder, string at, int depth, List<string> left) {+ List<string> names = new List<string>();+ byte[] buffer = new byte[64 * 1024];+ while (true) {+ if (!GetFileInformationByHandleEx(folder, INFO_FULL_DIRECTORY, buffer, (uint)buffer.Length)) {+ if (Marshal.GetLastWin32Error() != ERROR_NO_MORE_FILES) left.Add(at);+ break;+ }+ for (int offset = 0; ; ) {+ int next = BitConverter.ToInt32(buffer, offset), length = BitConverter.ToInt32(buffer, offset + 60);+ string name = Encoding.Unicode.GetString(buffer, offset + 68, length);+ if (name != "." && name != "..") names.Add(name);+ if (next == 0) break;+ offset += next;+ }+ }+ foreach (string name in names) {+ string child = at + "\\" + name;+ SafeFileHandle item = OpenChild(folder, name, WALK);+ if (item.IsInvalid) item = OpenChild(folder, name, BARE);+ if (item.IsInvalid) { left.Add(child); continue; }+ using (item) { Finish(item, child, depth + 1, left); }+ }+ }++ static SafeFileHandle OpenChild(SafeFileHandle folder, string name, uint access) {+ IntPtr text = Marshal.StringToHGlobalUni(name), unicode = IntPtr.Zero;+ bool added = false;+ try {+ folder.DangerousAddRef(ref added);+ UNICODE_STRING label = new UNICODE_STRING();+ label.Length = (ushort)(name.Length * 2);+ label.MaximumLength = label.Length;+ label.Buffer = text;+ unicode = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UNICODE_STRING)));+ Marshal.StructureToPtr(label, unicode, false);+ OBJECT_ATTRIBUTES attributes = new OBJECT_ATTRIBUTES();+ attributes.Length = Marshal.SizeOf(typeof(OBJECT_ATTRIBUTES));+ attributes.RootDirectory = folder.DangerousGetHandle();+ attributes.ObjectName = unicode;+ attributes.Attributes = OBJ_CASE_INSENSITIVE;+ SafeFileHandle item;+ IO_STATUS_BLOCK status;+ int result = NtOpenFile(out item, access, ref attributes, out status, SHARE_ALL, FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_FOR_BACKUP_INTENT | FILE_OPEN_REPARSE_POINT);+ if (result >= 0) return item;+ if (item != null) item.Dispose();+ return new SafeFileHandle(IntPtr.Zero, true);+ } finally {+ if (added) folder.DangerousRelease();+ if (unicode != IntPtr.Zero) Marshal.FreeHGlobal(unicode);+ Marshal.FreeHGlobal(text);+ }+ }++ static bool Attributes(SafeFileHandle item, out uint attributes) {+ byte[] basic = new byte[40];+ attributes = 0;+ if (!GetFileInformationByHandleEx(item, INFO_BASIC, basic, 40)) return false;+ attributes = BitConverter.ToUInt32(basic, 32);+ return true;+ }++ // A read-only file refuses deletion until that is cleared.+ static bool MarkDeleted(SafeFileHandle item) {+ byte[] yes = new byte[] { 1 };+ if (SetFileInformationByHandle(item, INFO_DISPOSITION, yes, 1)) return true;+ uint attributes;+ if (!Attributes(item, out attributes)) return false;+ byte[] basic = new byte[40];+ BitConverter.GetBytes(ATTR_NORMAL).CopyTo(basic, 32);+ return SetFileInformationByHandle(item, INFO_BASIC, basic, 40) && SetFileInformationByHandle(item, INFO_DISPOSITION, yes, 1);+ }+}`++/** The PowerShell around that helper, needing $REPARSE-free Item-At and a `die` from the prelude. Run for real on Windows in windowsTeamRemove.real.spec.ts. */+export const windowsRemoveHelperLines = (): string[] => [+ // What the Team account named reaches the administrator's console from here too (security review of #2579).+ WINDOWS_CLEAN_LINE,+ `$HELPER = ${hereString(TEAM_REMOVE_HELPER)}`,+ 'function Load-Helper { Add-Type -TypeDefinition $HELPER -Language CSharp -ErrorAction Stop }',+ 'function Remove-Held([string]$path, $left = $null) {',+ ' if (-not (Item-At $path)) { return }',+ ' $at = $path',+ " $moved = Join-Path (Split-Path -Parent $path) ('.harness-removing-' + [guid]::NewGuid().ToString('N'))",+ ' try { [IO.Directory]::Move($path, $moved); $at = $moved } catch { }',+ ' $failed = @([HarnessTeamRemove]::Delete($at))',+ ' if ($failed.Count -eq 0) { return }',+ ' if ($null -eq $left) { throw "could not delete $(Clean-Line $failed[0]) and $($failed.Count - 1) more" }',+ ' foreach ($one in $failed) { [void]$left.Add($one) }',+ '}',+ // A removal that stopped partway left its renamed folders: only this script makes those names, in folders others cannot write.+ "function Remove-Renamed([string]$parent) { if (Item-At $parent) { foreach ($old in @(Get-ChildItem -LiteralPath $parent -Force -Filter '.harness-removing-*')) { Remove-Held $old.FullName } } }",+ // By the Task Scheduler service and the exact name, as setup deletes its own: the ScheduledTasks commands read -TaskName as a+ // wildcard, so a Team task named [G]oogleUpdate could match the real GoogleUpdate (security review 2 of #2579).+ 'function Task-Folder($own) {',+ ' if (-not $script:taskService) { $script:taskService = New-Object -ComObject Schedule.Service; $script:taskService.Connect() }',+ " $folder = ([string]$own.TaskPath).TrimEnd('\\')",+ " $script:taskService.GetFolder($(if ($folder) { $folder } else { '\\' }))",+ '}',+ 'function Delete-Task($own) { try { (Task-Folder $own).DeleteTask($own.TaskName, 0) } catch { } }',+ 'function Task-There($own) { try { [void](Task-Folder $own).GetTask($own.TaskName); $true } catch { $false } }',+ // Tasks the account registered for itself: any of them could start it again while it goes. By name or SID, as Windows shows either.+ 'function Team-Tasks {',+ ' @(Get-ScheduledTask -ErrorAction SilentlyContinue | Where-Object {',+ ' $user = [string]$_.Principal.UserId',+ " $parts = $user -split '\\\\'",+ ' $user -and ($_.TaskPath -ne $TASK_PATH -or $_.TaskName -ne $TASK_NAME) -and (($teamSid -and $user -eq $teamSid) -or ($parts[-1] -eq $TEAM -and ($parts.Count -eq 1 -or $parts[0] -eq $env:COMPUTERNAME)))',+ ' })',+ '}',+]++/** Removes control and format characters, as privacy.ts statusText does, from what the Team account wrote. Cut after that. */+export const WINDOWS_CLEAN_LINE = "function Clean-Line([string]$text) { $clean = [regex]::Replace($text, '[\\p{Cc}\\p{Cf}\\p{Cs}\\p{Zl}\\p{Zp}]', ''); if ($clean.Length -gt 2000) { $clean.Substring(0, 2000) } else { $clean } }"+export function buildWindowsRemoveScript(input: RemoveScriptInput): string {const user = checkWindowsUser(input.user, 'team account')const home = checkWindowsPath(input.home, 'team home')@@ -728,6 +899,9 @@ export function buildWindowsRemoveScript(input: RemoveScriptInput): string {' }','}','',+ ...windowsRemoveHelperLines(),+ `try { Load-Helper } catch { die "could not prepare the safe delete ($($_.Exception.Message)); nothing was removed: the Harness Team account and its daemon run as before" ${WINDOWS_REMOVE_REFUSED} }`,+ '','# 1. The team daemon\'s task stops and is disabled, so it starts nothing while the account goes.','$task = Get-ScheduledTask -TaskPath $TASK_PATH -TaskName $TASK_NAME -ErrorAction SilentlyContinue','if ($task) {',@@ -735,6 +909,21 @@ export function buildWindowsRemoveScript(input: RemoveScriptInput): string {' Stop-ScheduledTask -TaskPath $TASK_PATH -TaskName $TASK_NAME','}','',+ // Run again after the kill: a process alive at the first look can register a task before it dies (security review of #2579).+ '$script:seenTasks = @()',+ '$script:heldTasks = @()',+ 'function Hold-Tasks {',+ ' foreach ($own in @(Team-Tasks)) {',+ ' if ($script:seenTasks | Where-Object { $_.TaskPath -eq $own.TaskPath -and $_.TaskName -eq $own.TaskName }) { continue }',+ ' $script:seenTasks += $own',+ " if ($own.State -ne 'Disabled') { $script:heldTasks += $own }",+ ' Disable-ScheduledTask -InputObject $own -ErrorAction SilentlyContinue | Out-Null',+ ' Stop-ScheduledTask -InputObject $own -ErrorAction SilentlyContinue',+ ' }',+ '}',+ 'function Restore-Tasks { foreach ($own in $script:heldTasks) { Enable-ScheduledTask -InputObject $own -ErrorAction SilentlyContinue | Out-Null } }',+ 'Hold-Tasks',+ '','# 2. Every process running as the team account: its daemon, its terminal host, teammates\' agents.','function Team-Processes {',' if (-not $teamSid) { return @() }',@@ -742,6 +931,8 @@ export function buildWindowsRemoveScript(input: RemoveScriptInput): string {'}','foreach ($process in @(Team-Processes)) { Stop-Process -Id $process.ProcessId -Force -ErrorAction SilentlyContinue }','Start-Sleep -Seconds 1',+ 'Hold-Tasks',+ 'foreach ($process in @(Team-Processes)) { Stop-Process -Id $process.ProcessId -Force -ErrorAction SilentlyContinue }','','# 3. The profile. When something of the account still runs and holds it, the task runs again and nothing was removed.',// Windows keeps a profile's registry loaded after its account's last process has gone, and for good: on@@ -760,6 +951,7 @@ export function buildWindowsRemoveScript(input: RemoveScriptInput): string {' }',' $leftHive = [bool]$why -and $held -and @(Team-Processes).Count -eq 0',' if ($why -and -not $leftHive) {',+ ' Restore-Tasks',' if ($task) { Enable-ScheduledTask -TaskPath $TASK_PATH -TaskName $TASK_NAME | Out-Null; Start-ScheduledTask -TaskPath $TASK_PATH -TaskName $TASK_NAME }',` die "could not remove the profile $TEAM_HOME ($why). Nothing was removed: the Harness Team account and its daemon run as before" ${WINDOWS_REMOVE_REFUSED}`,' }',@@ -769,25 +961,35 @@ export function buildWindowsRemoveScript(input: RemoveScriptInput): string {'# 4. The account.','if ($account) {',' try { Remove-LocalUser -Name $TEAM } catch {',+ ' Restore-Tasks',' if ($task) { Enable-ScheduledTask -TaskPath $TASK_PATH -TaskName $TASK_NAME | Out-Null; Start-ScheduledTask -TaskPath $TASK_PATH -TaskName $TASK_NAME }',` die "could not delete the account $TEAM ($($_.Exception.Message)). Its profile was removed; harness team setup makes it again" ${WINDOWS_REMOVE_REFUSED}`,' }',' say "deleted the account $TEAM"','}','',+ // A task that started in the moment before the last look may have left a process with no account.+ 'foreach ($process in @(Team-Processes)) { Stop-Process -Id $process.ProcessId -Force -ErrorAction SilentlyContinue }',+ '','# 5. What it left: its task\'s definition, its batch logon right, a profile folder Windows did not take, what setup','# made and the sentinel.','if ($task) { Unregister-ScheduledTask -TaskPath $TASK_PATH -TaskName $TASK_NAME -Confirm:$false }',+ // The ones found while the account was there too: its name may not match once it has gone.+ 'foreach ($own in @($script:seenTasks + @(Team-Tasks))) { Delete-Task $own }',+ '$stayed = @(@($script:seenTasks) + @(Team-Tasks) | Where-Object { Task-There $_ })',+ 'if ($stayed.Count -gt 0) { say "could not remove $($stayed.Count) task(s) the team account registered: $(($stayed | ForEach-Object { Clean-Line $_.TaskName }) -join \', \')" }',`if ($teamSid) { [void](New-Stage ${SDDL.private}); Set-BatchLogon $teamSid $false }`,"try { $scheduler = New-Object -ComObject Schedule.Service; $scheduler.Connect(); $scheduler.GetFolder('\\').DeleteFolder($TASK_PATH.Trim('\\'), 0) } catch { }",// A folder Windows left behind when it removed the profile record, which named this folder as the team account's.- 'if ($teamProfile.Count -eq 1 -and -not $leftHive -and (Item-At $TEAM_HOME)) { Remove-Tree $TEAM_HOME }',+ 'if ($teamProfile.Count -eq 1 -and -not $leftHive -and (Item-At $TEAM_HOME)) { Remove-Held $TEAM_HOME }',+ 'Remove-Renamed (Split-Path -Parent $TEAM_HOME)',+ 'Remove-Renamed $SHARED',// The profile Windows would not delete: its record, then every file it lets go of now, and the ones it holds (the// registry files) at the next restart, through the Session Manager's pending deletions as MoveFileEx records them.'if ($leftHive) {',' Remove-Item -LiteralPath "$PROFILE_LIST\\$teamSid" -Recurse -Force -ErrorAction SilentlyContinue',' $left = New-Object System.Collections.ArrayList',- ' Remove-Tree $TEAM_HOME $left',+ ' Remove-Held $TEAM_HOME $left',' if ($left.Count -gt 0) {',' $existing = (Get-ItemProperty -LiteralPath $SESSION_MANAGER -Name PendingFileRenameOperations -ErrorAction SilentlyContinue).PendingFileRenameOperations',' $pending = if ($existing) { @($existing) } else { @() }',@@ -796,9 +998,9 @@ export function buildWindowsRemoveScript(input: RemoveScriptInput): string {' say "Windows still holds the registry of ${TEAM}; the rest of $TEAM_HOME ($($left.Count) items) is removed at the next restart"',' } else { say "removed the profile $TEAM_HOME" }','}',- 'Remove-Tree $STATUS_DIR',+ 'Remove-Held $STATUS_DIR','Remove-Tree $CONFIG',- "if (Item-At $SHARED) { foreach ($relay in @(Get-ChildItem -LiteralPath $SHARED -Force -Filter 'team-relay-*')) { Remove-Tree $relay.FullName } }",+ "if (Item-At $SHARED) { foreach ($relay in @(Get-ChildItem -LiteralPath $SHARED -Force -Filter 'team-relay-*')) { Remove-Held $relay.FullName } }",'$sentinel = Item-At $SENTINEL','if ($sentinel -and -not $sentinel.PSIsContainer) { [IO.File]::Delete($SENTINEL) }',// The shared folder, only when setup made it and nothing else has been put in it since.diff --git a/cli/src/team/windowsTeamRemove.real.spec.ts b/cli/src/team/windowsTeamRemove.real.spec.tsnew file mode 100644index 000000000..3f3fb2e95--- /dev/null+++ b/cli/src/team/windowsTeamRemove.real.spec.ts@@ -0,0 +1,135 @@+import { execFileSync, spawnSync } from 'node:child_process'+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { readTeamStatus, readTeamStatusOffThread } from './privacy.js'+import { buildWindowsRemoveScript, buildWindowsSetupScript, windowsRemoveHelperLines } from './windowsScript.js'++/**+ * Audit W4, W5 and W7 on real Windows, in Windows PowerShell 5.1 as the elevated scripts run: the C# helper compiled by Add-Type,+ * real junctions and a real task. The Windows workflow runs it (.github/workflows/windows.yml). It removes only its own throwaway+ * folder and its own task; nothing here creates an account or changes an ACL.+ */+const OWNER_HOME = 'C:\\Users\\someone', NODE_DIR = `${OWNER_HOME}\\.harness\\runtime\\node-v22.23.2-win32-x64`++describe.runIf(process.platform === 'win32')('the Team account\'s removal on Windows', { timeout: 120_000 }, () => {+ let root: string, script: string+ const powershell = (body: string) => {+ writeFileSync(script, ['$ErrorActionPreference = \'Stop\'', "function Item-At([string]$path) { Get-Item -LiteralPath $path -Force -ErrorAction SilentlyContinue }",+ '$TEAM = $env:USERNAME', '$teamSid = $null', "$TASK_PATH = '\\Harness\\'", "$TASK_NAME = 'not-this-one'", ...windowsRemoveHelperLines(), 'Load-Helper', body].join('\r\n'))+ const run = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', script], { encoding: 'utf8' })+ if (run.status !== 0) throw new Error(`exit ${run.status}: ${run.stdout}\n${run.stderr}`)+ return run.stdout+ }+ const junction = (link: string, target: string) => execFileSync('cmd.exe', ['/d', '/c', 'mklink', '/J', link, target], { stdio: 'ignore' })++ beforeAll(() => { root = realpathSync(mkdtempSync(join(tmpdir(), 'team-remove-'))); script = join(root, 'run.ps1') })+ afterAll(() => rmSync(root, { recursive: true, force: true }))++ it('both scripts parse in Windows PowerShell 5.1', () => {+ const setup = join(root, 'setup.ps1'), remove = join(root, 'remove.ps1')+ writeFileSync(setup, buildWindowsSetupScript({ user: 'harnessteam', realName: 'Harness Team', home: 'C:\\Users\\harnessteam', owner: 'someone', ownerHome: OWNER_HOME,+ ownerSid: 'S-1-5-21-1111111111-2222222222-3333333333-1001', stageDir: `${OWNER_HOME}\\AppData\\Local\\Temp\\harness-team-x1`, nodeRuntimeDir: NODE_DIR, tmuxRuntimeDir: null,+ cliDir: `${OWNER_HOME}\\.harness\\cli\\0.4.97`, ownerNode: `${NODE_DIR}\\node.exe`, ownerCli: `${OWNER_HOME}\\.harness\\cli\\0.4.97\\cli.js`, mintEnv: {}, signIn: 'missing' }))+ writeFileSync(remove, buildWindowsRemoveScript({ user: 'harnessteam', home: 'C:\\Users\\harnessteam', ownerHome: OWNER_HOME }))+ for (const file of [setup, remove]) {+ const errors = powershell(`$errors = $null; [void][System.Management.Automation.Language.Parser]::ParseFile('${file}', [ref]$null, [ref]$errors); $errors.Count`)+ expect(errors.trim(), file).toBe('0')+ }+ })++ it('deletes a tree with a read-only file, and leaves what a junction in it points at', () => {+ const outside = join(root, 'outside'), tree = join(root, 'tree'), deep = join(tree, 'a', 'b')+ mkdirSync(outside); writeFileSync(join(outside, 'kept'), 'kept')+ mkdirSync(deep, { recursive: true }); writeFileSync(join(deep, 'file'), 'x')+ writeFileSync(join(deep, 'locked'), 'x'); chmodSync(join(deep, 'locked'), 0o444)+ junction(join(deep, 'link'), outside)+ expect(powershell(`@([HarnessTeamRemove]::Delete('${tree}')).Count`).trim()).toBe('0')+ expect(existsSync(tree)).toBe(false)+ expect(readFileSync(join(outside, 'kept'), 'utf8')).toBe('kept')+ })++ it('removes a junction in the folder\'s own place as itself', () => {+ const outside = join(root, 'outside-2'), link = join(root, 'top-link')+ mkdirSync(outside); writeFileSync(join(outside, 'kept'), 'kept')+ junction(link, outside)+ powershell(`Remove-Held '${link}'`)+ expect(existsSync(link)).toBe(false)+ expect(existsSync(join(outside, 'kept'))).toBe(true)+ })++ it('renames first, and leaves no renamed folder behind', () => {+ const parent = join(root, 'parent'), tree = join(parent, 'status')+ mkdirSync(tree, { recursive: true }); writeFileSync(join(tree, 'status.json'), '{}')+ powershell(`Remove-Held '${tree}'`)+ expect(execFileSync('cmd.exe', ['/d', '/c', 'dir', '/a', '/b', parent], { encoding: 'utf8' }).trim()).toBe('')+ })++ it('takes a renamed folder a stopped removal left, and nothing else there', () => {+ const parent = join(root, 'parent-2'), old = join(parent, '.harness-removing-abc'), other = join(parent, 'keep-me')+ mkdirSync(old, { recursive: true }); mkdirSync(other); writeFileSync(join(old, 'status.json'), '{}')+ powershell(`Remove-Renamed '${parent}'`)+ expect(existsSync(old)).toBe(false)+ expect(existsSync(other)).toBe(true)+ })++ it('reports what it cannot delete: a file held open without sharing', () => {+ const tree = join(root, 'held')+ mkdirSync(tree); writeFileSync(join(tree, 'open'), 'x')+ const said = powershell(`$open = [IO.File]::Open('${join(tree, 'open')}', 'Open', 'Read', 'None'); $failed = @([HarnessTeamRemove]::Delete('${tree}')); $open.Close(); $failed -join '|'`)+ expect(said).toContain('open')+ })++ it('stops at a depth it can handle rather than crash the removal', () => {+ let deep = join(root, 'deep')+ const top = deep+ // Longer than a plain path can name: made from inside, as a process can.+ const made = powershell(`$at = '\\\\?\\${top}'; [void][IO.Directory]::CreateDirectory($at); for ($i = 0; $i -lt 60; $i++) { $at = "$at\\${'d'.repeat(100)}"; [void][IO.Directory]::CreateDirectory($at) }; @([HarnessTeamRemove]::Delete('${top}')).Count`)+ expect(made.trim()).toBe('0')+ deep = top+ expect(existsSync(deep)).toBe(false)+ })++ it('finds a task the account registered, and not its own daemon\'s', () => {+ const name = `HarnessW5Test-${process.pid}`+ const said = powershell(`+ $action = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument '/c exit 0'+ $task = Register-ScheduledTask -TaskName '${name}' -Action $action -Force+ try {+ $found = @(Team-Tasks | Where-Object { $_.TaskName -eq '${name}' }).Count+ $TEAM = 'somebody-else'+ $other = @(Team-Tasks | Where-Object { $_.TaskName -eq '${name}' }).Count+ "$found $other"+ } finally { Unregister-ScheduledTask -TaskName '${name}' -Confirm:$false }`)+ expect(said.trim()).toBe('1 0')+ })++ it('acts on a task named like a wildcard alone, and leaves the task it would match', () => {+ const plain = `HarnessW5Abc${process.pid}`, bracket = `[H]arnessW5Abc${process.pid}`+ const said = powershell(`+ $action = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument '/c exit 0'+ [void](Register-ScheduledTask -TaskName '${plain}' -Action $action -Force)+ $team = Register-ScheduledTask -TaskName '${bracket}' -Action $action -Force+ try {+ Disable-ScheduledTask -InputObject $team -ErrorAction SilentlyContinue | Out-Null+ $state = (Get-ScheduledTask | Where-Object { $_.TaskName -ceq '${plain}' }).State+ $there = Task-There $team+ Delete-Task $team+ "$state $there $(Task-There $team) $(@(Get-ScheduledTask | Where-Object { $_.TaskName -ceq '${plain}' }).Count)"+ } finally { (New-Object -ComObject Schedule.Service | ForEach-Object { $_.Connect(); $_.GetFolder('\\').DeleteTask('${plain}', 0) }) }`)+ expect(said.trim()).toBe('Ready True False 1')+ })++ it('removes escape codes, bells and format characters from a line (W7)', () => {+ const said = powershell(`Clean-Line ([string][char]27 + '[31mred' + [char]7 + [char]0x202e + ' text')`)+ expect(said.trim()).toBe('[31mred text')+ })++ it('reads the status file in a child (W4)', async () => {+ const file = join(root, 'status.json')+ writeFileSync(file, JSON.stringify({ version: 1, privacy: { passed: true, checkedAt: 3 } }))+ expect(readTeamStatus(file)).toEqual({ version: 1, privacy: { passed: true, checkedAt: 3 } })+ expect(await readTeamStatusOffThread(file)).toEqual({ version: 1, privacy: { passed: true, checkedAt: 3 } })+ })+})diff --git a/docs/plans/2026-11-02-team-windows-w4-w5-w7-plan.md b/docs/plans/2026-11-02-team-windows-w4-w5-w7-plan.mdnew file mode 100644index 000000000..0c6f2f7aa--- /dev/null+++ b/docs/plans/2026-11-02-team-windows-w4-w5-w7-plan.md@@ -0,0 +1,108 @@+# Team account on Windows: W4, W5 and W7 Implementation Plan++> Brought to the writing-plans format after the code was written: that rule arrived while this task was running (Ken, 2026-11-02). Steps below are marked as they happened.++**Goal:** The Team account can no longer stall the owner's Swarm service, redirect the elevated removal's deletes, or print escape codes to the administrator's console.++**Architecture:** Status reads on Windows run in a short-lived child process with a deadline. Removal deletes what the Team account could write through handles opened relative to their parent, from a small C# helper compiled before anything is removed. Setup cleans each line the Team account wrote before printing it.++**Tech Stack:** TypeScript, vitest, Windows PowerShell 5.1 (`Add-Type`, C# 5), the manual Windows workflow.++**Spec:** `docs/security/2026-11-02-team-account-windows.md` on PR #2568, findings W4, W5 and W7.++## Global Constraints++- Nothing here may stop the owner's Swarm service, whatever the Team account does to its own files.+- An elevated script deletes nothing through a link, and changes nothing if it cannot prepare to delete safely.+- Windows PowerShell 5.1 and C# 5: what `Add-Type` compiles there.+- Nothing unsigned is started; the child is the managed Node, the compiler Microsoft's `csc.exe`.+- Other platforms' behavior does not change.+- Two independent security reviews before merge (cleanup, deletes data).++## Review Focus++1. A status file held open for good: the owner's service keeps running, each read ends at its deadline, and children do not pile up. Pinned by the FIFO tests in `privacy.spec.ts`.+2. A folder swapped for a junction during removal: what the junction points at survives. Pinned by the junction cases in `windowsTeamRemove.real.spec.ts`; the moment of the swap itself is not interleaved in a test, so it is argued from handle-relative opens.+3. A removal that stops partway, then runs again: its renamed folders go too. Pinned by `windowsScript.spec.ts` and `windowsTeamRemove.real.spec.ts` (`Remove-Renamed`).+4. A machine where `Add-Type` is blocked: removal stops with nothing removed and the daemon running. Pinned by `windowsScript.spec.ts`; the blocked state is not produced on a real machine.+5. A very deep tree the Team account built: no crash, and what is left is named. Pinned by the depth case in `windowsTeamRemove.real.spec.ts` for a long path; the 512-level limit itself is not reached in a test.++---++## Decisions++- **W4, a child process rather than a worker or the thread pool.** A worker stuck in a synchronous open cannot be stopped and would hold up the daemon's exit; an async read stuck in the thread pool holds a pool thread, which every file operation shares. A child can be killed. The daemon's read waits on it without blocking and allows one child at a time, so a stuck one never piles up. `harness team status` and setup use the same child synchronously with the same deadline.+- **W5, handle-relative deletes.** Each child opens relative to its parent's open handle, without following a link, and a link is deleted as itself. The rename into a new random name comes first and is best effort: Windows refuses it while it holds a profile's registry.+- **W5, the helper compiles before step 1.** A computer where `Add-Type` cannot run stops with nothing removed, rather than falling back to deleting by path.+- **W5, the Team account's own tasks** are disabled with the daemon's task, enabled again if removal stops, and deleted once the account is gone.+- **W7** cleans lines where they are read, so every print and error that uses them gets clean text.++## Design++- **Growth:** nothing is stored. Each read's child exits or is killed.+- **Concurrency:** one status child at a time. A read during a stuck child answers "no status", as an unreadable file already does.+- **Read cost:** one short child process a minute, on Windows computers with a Team account only.+- **Scale:** N/A because there is one reader per computer.+- **Compatibility:** other platforms keep today's read. Scripts run once and are not versioned.+- **Migration and rollback:** none; the code can be reverted.+- **Audience:** Windows ACLs enforce it, as before. No server is involved.+- **Identity:** tasks are matched by the Team account's SID or name, never the owner's.+- **Failure:** a read past its deadline is logged and is no status. A compile failure stops removal before anything changes. What cannot be deleted is reported, as today.+- **Platforms:** the changes apply to Windows; the status read is proven on macOS with a FIFO, and the rest by `windowsTeamRemove.real.spec.ts` on Windows.++## Tasks++### Task 1: W4, the status read++**Files:**+- Modify: `cli/src/team/privacy.ts`, `cli/src/team/refresh.ts`, `cli/src/superTabs/service.ts`+- Test: `cli/src/team/privacy.spec.ts`, `cli/src/team/refresh.spec.ts`++**Interfaces:**+- Consumes: nothing from other tasks.+- Produces: `readTeamStatusOffThread(path, options?) -> Promise<TeamStatus | null>`; `readStatusFile(path, platform?, deadlineMs?) -> string`.++- [x] **Step 1: Write the failing tests:** a FIFO stands in for the oplock, as an open waits on either.+- [x] **Step 2: Run them to verify they fail:** `npx vitest run src/team/privacy.spec.ts src/team/refresh.spec.ts`, 13 failed.+- [x] **Step 3: Implement** the child, with one running at a time, and wire the daemon to it.+- [x] **Step 4: Run them to verify they pass.**++### Task 2: W7, setup's output++**Files:**+- Modify: `cli/src/team/windowsScript.ts`+- Test: `cli/src/team/windowsScript.spec.ts`++**Interfaces:**+- Produces: `WINDOWS_CLEAN_LINE`, PowerShell's `Clean-Line`.++- [x] **Step 1: Write the failing test.**+- [x] **Step 2: Run it to verify it fails:** `npx vitest run src/team/windowsScript.spec.ts`.+- [x] **Step 3: Implement** `Clean-Line`, applied where `As-Team` reads its lines.+- [x] **Step 4: Run it to verify it passes.**++### Task 3: W5, removal++**Files:**+- Modify: `cli/src/team/windowsScript.ts`+- Test: `cli/src/team/windowsScript.spec.ts`++**Interfaces:**+- Produces: `windowsRemoveHelperLines() -> string[]`; PowerShell's `Remove-Held`, `Remove-Renamed`, `Team-Tasks`, `Restore-Tasks`.++- [x] **Step 1: Write the failing tests.**+- [x] **Step 2: Run them to verify they fail:** 8 failed in `windowsScript.spec.ts`.+- [x] **Step 3: Implement** the helper, the rename, and the task handling.+- [x] **Step 4: Run them to verify they pass.**++### Task 4: Real Windows++**Files:**+- Create: `cli/src/team/windowsTeamRemove.real.spec.ts`+- Modify: `.github/workflows/windows.yml`++**Interfaces:**+- Consumes: `windowsRemoveHelperLines`, `WINDOWS_CLEAN_LINE`, `readTeamStatusOffThread`.++- [x] **Step 1: Run the Windows workflow:** real junctions, a read-only file, a real task, escape codes, both architectures. The helper compiled and 8 of 9 cases passed; one failed on this spec's own fixture.+- [ ] **Step 2: Fix that fixture and run it once more.**