Skip to content

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.

Harness Team account is listed in Users & Groups, and a removal macOS refuses changes nothing (#1699)

Dee33209d56a72f
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 1be9b32ef..ecc4a4192 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -160,7 +160,8 @@ Machine:
harness team setup on a Mac: a separate account, Harness Team, whose own daemon runs teammates' Swarm
agents so they cannot read your files (one administrator password; again repairs it)
harness team status whether that account exists and runs, its sign-in and privacy check, and what it made
- harness team remove delete that account, its home folder and its daemon
+ harness team remove delete that account, its home folder and its daemon (in Terminal: sudo, then macOS
+ asks to let Terminal administer your computer)
harness team on|off a computer used only for agents: sign it in for team work only, or back as your own
harness tui all of Harness in this terminal: swarms, panes, every machine (⌥O ⌥P ⌥N)
harness new [agent] [--machine <name>] [folder|name] [-- task]
diff --git a/cli/src/lib/guestHelperInstall.spec.ts b/cli/src/lib/guestHelperInstall.spec.ts
index 2b3053930..0112a2c71 100644
--- a/cli/src/lib/guestHelperInstall.spec.ts
+++ b/cli/src/lib/guestHelperInstall.spec.ts
@@ -131,6 +131,15 @@ describe('installing the helper', () => {
.toEqual({ ok: false, code: 'FAILED', message: 'Sharing could not be set up on this computer.' })
})
+ it('finds the script\'s reason after earlier lines, which osascript ends with CR', async () => {
+ // As macOS hands `do shell script`'s stderr back (seen in the VM rig, 24 Oct 2026): every line but the last ends in CR.
+ const stderr = '0:120: execution error: cp: /usr/local/lib/harness/x: Operation not permitted\r'
+ + 'harness: /usr/local is not owned by root (6)\n'
+ const failed = vi.fn<GuestRunner>(async () => ({ code: 1, stdout: '', stderr }))
+ expect(await installGuestHelper({ owner: 'ann', runner: failed, platform: 'darwin', nodeRuntimeDir: null, hookScript: null }))
+ .toEqual({ ok: false, code: 'FAILED', message: '/usr/local is not owned by root (6)' })
+ })
+
it('uses pkexec on a Linux desktop and sudo in a terminal', async () => {
const runner = vi.fn<GuestRunner>(async () => ok)
expect(await installGuestHelper({ owner: 'ann', runner, platform: 'linux', graphical: true, nodeRuntimeDir: null, hookScript: null })).toEqual({ ok: true })
diff --git a/cli/src/lib/guestHelperInstall.ts b/cli/src/lib/guestHelperInstall.ts
index 5d3cb7e4a..1bcc6becc 100644
--- a/cli/src/lib/guestHelperInstall.ts
+++ b/cli/src/lib/guestHelperInstall.ts
@@ -169,7 +169,9 @@ export async function installGuestHelper(options: GuestHelperInstallOptions = {}
}
}
if (result.code !== 0) {
- const said = result.stderr.trim().split('\n').pop()?.replace(/^.*harness: /, '') ?? ''
+ // osascript's `do shell script` ends the script's stderr lines with CR, not LF: split on both, or a reason after an
+ // earlier line is never found, and the CR left in it makes a terminal print the line over itself.
+ const said = result.stderr.trim().split(/[\r\n]+/).pop()?.replace(/^.*harness: /, '') ?? ''
return { ok: false, code: 'FAILED', message: said || 'Sharing could not be set up on this computer.' }
}
return { ok: true }
diff --git a/cli/src/team/admin.spec.ts b/cli/src/team/admin.spec.ts
index 89bbd46f8..62ba3f62a 100644
--- a/cli/src/team/admin.spec.ts
+++ b/cli/src/team/admin.spec.ts
@@ -14,8 +14,8 @@ function fixture(answer: { code: number | null; stdout?: string; stderr?: string
const stage = join(parent, 'stage')
const seen: { script?: string; files: Record<string, { text: string; mode: number }> } = { files: {} }
// Never osascript: the fake reads what was staged, as root would, and answers.
- const runner = vi.fn<GuestRunner>(async (_command, args) => {
- const path = /quoted form of "([^"]+)"/.exec(args[1]!)![1]!
+ const runner = vi.fn<GuestRunner>(async (command, args) => {
+ const path = command === 'sudo' ? args.at(-1)! : /quoted form of "([^"]+)"/.exec(args[1]!)![1]!
seen.script = readFileSync(path, 'utf8')
for (const name of ['team.json', 'team.plist']) {
const file = join(stage, name)
@@ -47,7 +47,7 @@ describe('adminRunner', () => {
expect(await fixture({ code: 1, stderr: '0:180: execution error: User canceled. (-128)' }).run(() => ({ script: '' }), 'p'))
.toEqual({ ok: false, code: 'CANCELLED', message: 'The administrator prompt was cancelled.' })
expect(await fixture({ code: 1, stderr: '0:180: execution error: harness: launchd would not start the team daemon (8)' }).run(() => ({ script: '' }), 'p'))
- .toEqual({ ok: false, code: 'FAILED', message: 'launchd would not start the team daemon' })
+ .toEqual({ ok: false, code: 'FAILED', message: 'launchd would not start the team daemon', status: 8 })
expect(await fixture({ code: 2, stderr: '' }).run(() => ({ script: '' }), 'p'))
.toEqual({ ok: false, code: 'FAILED', message: 'The script stopped (exit 2).' })
})
@@ -57,7 +57,27 @@ describe('adminRunner', () => {
const stderr = '0:296: execution error: ✗ Harness would not give a team sign-in code: Invalid or expired token\r'
+ 'harness: could not get a sign-in code from your Harness sign-in (7)\n'
expect(await fixture({ code: 1, stderr }).run(() => ({ script: '' }), 'p'))
- .toEqual({ ok: false, code: 'FAILED', message: 'could not get a sign-in code from your Harness sign-in' })
+ .toEqual({ ok: false, code: 'FAILED', message: 'could not get a sign-in code from your Harness sign-in', status: 7 })
+ })
+
+ it('runs the script with sudo in the terminal when asked, with the prompt\'s sentence, and the password every time', async () => {
+ const f = fixture({ code: 0, stdout: 'harness: team computer abc\n' })
+ expect(await f.run((dir) => ({ script: `#!/bin/sh\necho ${dir}\n` }), 'Harness wants to remove 100% of it.', 'sudo'))
+ .toEqual({ ok: true, stdout: 'harness: team computer abc\n' })
+ const [command, args] = f.runner.mock.calls[0]!
+ expect(command).toBe('sudo')
+ expect(args).toEqual(['-k', '-p', 'Harness wants to remove 100%% of it.\nPassword for %u: ', '/bin/sh', join(f.stage, 'run.sh')])
+ expect(existsSync(f.stage)).toBe(false)
+ })
+
+ it('with sudo, tells a password sudo never got from a script that stopped, and keeps the script\'s exit status', async () => {
+ expect(await fixture({ code: 1, stderr: 'Sorry, try again.\nsudo: 3 incorrect password attempts\n' }).run(() => ({ script: '' }), 'p', 'sudo'))
+ .toEqual({ ok: false, code: 'CANCELLED', message: 'sudo did not get an administrator password.' })
+ const refused = fixture({ code: 9, stderr: 'harness: could not delete the account harnessteam: macOS did not allow it (eDSPermissionError). Nothing was removed\n' })
+ expect(await refused.run(() => ({ script: '' }), 'p', 'sudo')).toEqual({ ok: false, code: 'FAILED', status: 9,
+ message: 'could not delete the account harnessteam: macOS did not allow it (eDSPermissionError). Nothing was removed' })
+ expect(await fixture({ code: 3, stderr: '' }).run(() => ({ script: '' }), 'p', 'sudo'))
+ .toEqual({ ok: false, code: 'FAILED', message: 'The script stopped (exit 3).', status: 3 })
})
it('removes the stage when building the script throws', async () => {
diff --git a/cli/src/team/admin.ts b/cli/src/team/admin.ts
index 1c9f38d0e..524056d60 100644
--- a/cli/src/team/admin.ts
+++ b/cli/src/team/admin.ts
@@ -1,9 +1,14 @@
/**
* Runs a privileged team script once as root, behind the system's own administrator prompt (password or Touch ID),
- * as the guest helper's install does (lib/guestHelperInstall.ts). The script and the files it installs are staged
- * in a folder private to this account (mkdtemp is 0700), so nobody can swap one in between, and removed after.
+ * as the guest helper's install does (lib/guestHelperInstall.ts), or with sudo in the terminal the command runs in. The
+ * script and the files it installs are staged in a folder private to this account (mkdtemp is 0700), so nobody can swap
+ * one in between, and removed after.
*
- * Everything that touches the system goes through [AdminDeps]; the specs never run osascript.
+ * Why sudo at all: macOS 26 deletes an account only for an app the person allowed to administer the computer, and it
+ * cannot ask that for the administrator prompt's process (authtrampoline), so it refuses it. With sudo in a terminal the
+ * terminal app is the one asking, and macOS asks the person once: "Terminal would like to administer your computer".
+ *
+ * Everything that touches the system goes through [AdminDeps]; the specs never run osascript or sudo.
*/
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
@@ -13,7 +18,8 @@ import { adminAppleScript } from '../lib/guestHelperInstall.js'
export type AdminResult =
| { ok: true; stdout: string }
- | { ok: false; code: 'CANCELLED' | 'FAILED'; message: string }
+ /** [status]: the script's own exit status, when it stopped with one (`do shell script` ends its error with it). */
+ | { ok: false; code: 'CANCELLED' | 'FAILED'; message: string; status?: number }
export interface AdminScript {
script: string
@@ -21,8 +27,11 @@ export interface AdminScript {
files?: Record<string, string>
}
+/** How root is asked for: the administrator prompt (a dialog), or sudo in this terminal, which asks for the password there. */
+export type AdminVia = 'prompt' | 'sudo'
+
/** Builds the script once the staging folder exists (the script names it), then runs it as root. */
-export type RunAdmin = (build: (stageDir: string) => AdminScript, prompt: string) => Promise<AdminResult>
+export type RunAdmin = (build: (stageDir: string) => AdminScript, prompt: string, via?: AdminVia) => Promise<AdminResult>
export interface AdminDeps {
runner?: GuestRunner
@@ -34,7 +43,7 @@ export function adminRunner(deps: AdminDeps = {}): RunAdmin {
const runner = deps.runner ?? runGuestCommand
const makeStage = deps.makeStage ?? (() => mkdtempSync(join(tmpdir(), 'harness-team-')))
const removeStage = deps.removeStage ?? ((dir: string) => rmSync(dir, { recursive: true, force: true }))
- return async (build, prompt) => {
+ return async (build, prompt, via = 'prompt') => {
const stageDir = makeStage()
try {
chmodSync(stageDir, 0o700)
@@ -42,6 +51,20 @@ export function adminRunner(deps: AdminDeps = {}): RunAdmin {
for (const [name, content] of Object.entries(files)) writeFileSync(join(stageDir, name), content, { mode: 0o600 })
const path = join(stageDir, 'run.sh')
writeFileSync(path, script, { mode: 0o700 })
+ if (via === 'sudo') {
+ // sudo asks on the terminal itself (/dev/tty), so the script's output is still collected here. `-k`: the password
+ // every time, as the dialog asks for it, never a few minutes' leftover sudo from something else.
+ const ask = `${prompt.replaceAll('%', '%%')}\nPassword for %u: `
+ const result = await runner('sudo', ['-k', '-p', ask, '/bin/sh', path], { timeoutMs: 15 * 60_000 })
+ if (result.code === 0) return { ok: true, stdout: result.stdout }
+ const lines = result.stderr.trim().split(/[\r\n]+/)
+ const last = lines.pop() ?? ''
+ if (!/^harness: /.test(last) && /incorrect password|password is required|terminal is required|no tty present/i.test(result.stderr)) {
+ return { ok: false, code: 'CANCELLED', message: 'sudo did not get an administrator password.' }
+ }
+ return { ok: false, code: 'FAILED', message: last.replace(/^.*harness: /, '') || `The script stopped (exit ${result.code}).`,
+ ...(result.code !== null ? { status: result.code } : {}) }
+ }
const result = await runner('osascript', ['-e', adminAppleScript(path, prompt)], { timeoutMs: 15 * 60_000 })
// -128 is the prompt's Cancel.
if (result.code !== 0 && /-128|User canceled/i.test(result.stderr)) {
@@ -50,8 +73,10 @@ export function adminRunner(deps: AdminDeps = {}): RunAdmin {
if (result.code !== 0) {
// `do shell script` hands the script's stderr back with its lines ended by CR, not LF: split on both, or a reason
// after an earlier line is never found, and the CR left in it makes a terminal print the line over itself.
- const said = result.stderr.trim().split(/[\r\n]+/).pop()?.replace(/^.*harness: /, '').replace(/\s*\(\d+\)$/, '') ?? ''
- return { ok: false, code: 'FAILED', message: said || `The script stopped (exit ${result.code}).` }
+ const last = result.stderr.trim().split(/[\r\n]+/).pop() ?? ''
+ const status = /\((\d+)\)$/.exec(last)?.[1]
+ const said = last.replace(/^.*harness: /, '').replace(/\s*\(\d+\)$/, '')
+ return { ok: false, code: 'FAILED', message: said || `The script stopped (exit ${result.code}).`, ...(status ? { status: Number(status) } : {}) }
}
return { ok: true, stdout: result.stdout }
} finally {
diff --git a/cli/src/team/command.spec.ts b/cli/src/team/command.spec.ts
index c1f1aaae7..4cc35041b 100644
--- a/cli/src/team/command.spec.ts
+++ b/cli/src/team/command.spec.ts
@@ -4,7 +4,7 @@
import { describe, expect, it, vi } from 'vitest'
import type { AuthSession } from '../lib/authSession.js'
import type { AdminScript, RunAdmin } from './admin.js'
-import { teamCommand, type TeamCommandDeps } from './command.js'
+import { REPAIR_PROMPT, SETUP_PROMPT, teamCommand, type TeamCommandDeps } from './command.js'
import type { TeamConfig } from './config.js'
import type { PrivacyResult, TeamStatus } from './privacy.js'
import type { TeamEngines } from './engines.js'
@@ -27,10 +27,12 @@ function fake(over: Partial<TeamCommandDeps> & { adminResult?: Awaited<ReturnTyp
const out: string[] = [], err: string[] = []
const built: AdminScript[] = []
const prompts: string[] = []
+ const vias: Array<string | undefined> = []
const status = new Map<string, TeamStatus>()
- const admin = vi.fn<RunAdmin>(async (build, prompt) => {
+ const admin = vi.fn<RunAdmin>(async (build, prompt, via) => {
built.push(build('/private/var/folders/aa/T/harness-team-stage'))
prompts.push(prompt)
+ vias.push(via)
return over.adminResult ?? { ok: true, stdout: 'harness: handed a sign-in to the team account\n' }
})
const startedAt = now
@@ -46,7 +48,8 @@ function fake(over: Partial<TeamCommandDeps> & { adminResult?: Awaited<ReturnTyp
env: {}, interactive: false, ask: vi.fn(async () => 'y'), now: () => now, sleep: vi.fn(async (ms: number) => { now += ms }),
session: () => session, writeSession: vi.fn((s: AuthSession) => { session = s }), clearSession: vi.fn(() => { session = null }),
auth: vi.fn(async () => ({ session: session!, headers: { authorization: 'Bearer x' } })), post: post as never,
- get: vi.fn(async () => ({ user: { id: 'user-placeholder-1' } })) as never, machineKey: () => ({ priv: new Uint8Array(32).fill(9) }),
+ get: vi.fn(async (path: string) => path === '/api/machines' ? { machines: MACHINES } : { user: { id: 'user-placeholder-1' } }) as never,
+ delete: vi.fn(async () => ({ deleted: true })) as never, machineKey: () => ({ priv: new Uint8Array(32).fill(9) }),
computerId: () => 't'.repeat(32), autonomousEnv: 'prod',
installed: () => ({ cliDir: `${OWNER_HOME}/.harness/cli`, cliJs: `${OWNER_HOME}/.harness/cli/cli.js`,
node: `${OWNER_HOME}/.harness/runtime/node-v1/bin/node`, nodeRuntimeDir: `${OWNER_HOME}/.harness/runtime/node-v1`, tmuxRuntimeDir: null }),
@@ -60,9 +63,18 @@ function fake(over: Partial<TeamCommandDeps> & { adminResult?: Awaited<ReturnTyp
stopDaemon: vi.fn(async () => true), startDaemon: vi.fn(async () => {}),
...over,
}
- return { deps, out, err, built, prompts, post, admin, status, session: () => session, setSession: (s: AuthSession | null) => { session = s } }
+ return { deps, out, err, built, prompts, vias, post, admin, status, session: () => session, setSession: (s: AuthSession | null) => { session = s } }
}
+/** The owner's machines as the backend lists them, computer ids lower case without dashes: this computer, the team
+ * account's, and a dedicated Mac mini's. */
+const TEAM_COMPUTER = 'ebe7fc88-cd44-491f-aa61-9963fa0dfd82'
+const MACHINES = [
+ { machineId: 'm1', computerId: 'c'.repeat(32), sessionKind: 'computer' },
+ { machineId: 'm-team', computerId: TEAM_COMPUTER.replace(/-/g, ''), sessionKind: 'team' },
+ { machineId: 'm-mini', computerId: 'a'.repeat(32), sessionKind: 'team' },
+]
+
const reported = (startedAt: number): TeamStatus => ({ version: 1, signIn: { state: 'signed-in', at: startedAt + 3_000 }, privacy: { passed: true, checkedAt: startedAt + 3_000 } })
describe('harness team', () => {
@@ -98,6 +110,22 @@ describe('harness team setup', () => {
expect(text).toContain('engines ? not reported yet')
})
+ it('asks to create the account on a Mac without one, and to repair it on a Mac that has it', async () => {
+ const first = fake({ statusAfter: reported })
+ await teamCommand(['setup'], first.deps)
+ expect(first.prompts[0]).toBe(SETUP_PROMPT)
+ expect(first.out[0]).toContain('Harness will set up a separate account')
+ for (const over of [{ readConfig: () => config }, { accountExists: vi.fn(async () => true) }]) {
+ const again = fake({ statusAfter: reported, ...over })
+ await teamCommand(['setup'], again.deps)
+ expect(again.prompts[0]).toBe(REPAIR_PROMPT)
+ expect(again.prompts[0]).toContain('repair the Harness Team account')
+ expect(again.out[0]).toContain('Harness will repair the Harness Team account')
+ }
+ // What setup says it made is what it makes now: a password nobody knows, and listed.
+ expect(first.out.join('\n')).toContain('a standard user with a random password nobody knows, listed in Users & Groups')
+ })
+
it('shows the team account\'s engines as its daemon reported them in this run, and how to sign them in', async () => {
const f = fake({ statusAfter: (t) => ({ ...reported(t), engines: { checkedAt: t + 3_000, claude: { installed: true, signedIn: false }, codex: { installed: true, signedIn: false } } }) })
expect(await teamCommand(['setup'], f.deps)).toBe(0)
@@ -245,15 +273,89 @@ describe('harness team status', () => {
})
describe('harness team remove', () => {
- it('runs one privileged removal with what the config names', async () => {
- const f = fake({ readConfig: () => ({ ...config, env: { AUTONOMOUS_ENV: 'stag' } }) })
+ // The team daemon's computer id as its file holds it, with dashes; the backend lists it without (MACHINES).
+ const removed = { ok: true as const, stdout: `harness: deleted the account harnessteam\nharness: team computer ${TEAM_COMPUTER}\nharness: removed the Harness Team account, its home folder and its daemon\n` }
+ const refused = { ok: false as const, code: 'FAILED' as const, status: 9,
+ message: 'could not delete the account harnessteam: macOS did not allow it (eDSPermissionError). Nothing was removed: the Harness Team account and its daemon run as before' }
+
+ it('runs one privileged removal with what the config names, behind the prompt when not in a terminal', async () => {
+ const f = fake({ readConfig: () => ({ ...config, env: { AUTONOMOUS_ENV: 'stag' } }), adminResult: removed })
expect(await teamCommand(['remove'], f.deps)).toBe(0)
expect(f.prompts[0]).toContain('remove the Harness Team account')
- expect(f.built[0]!.script).toContain(`TEAM_CLI='${config.cli}'`)
- expect(f.built[0]!.script).toContain("'AUTONOMOUS_ENV=stag'")
+ expect(f.vias[0]).toBe('prompt')
+ expect(f.built[0]!.script).toContain("TEAM_HOME='/Users/harnessteam'")
+ expect(f.built[0]!.script).toContain(`SENTINEL='${OWNER_HOME}/.harness-team-privacy'`)
expect(f.out.join('\n')).toContain('Your home folder stays private')
})
+ it('in a terminal, runs it with sudo there, so macOS can ask to let the terminal administer the Mac', async () => {
+ const f = fake({ readConfig: () => config, interactive: true, adminResult: removed })
+ expect(await teamCommand(['remove'], f.deps)).toBe(0)
+ expect(f.vias[0]).toBe('sudo')
+ expect(f.out[0]).toContain('sudo asks for your password here; macOS may then ask to let this terminal administer your computer')
+ const cancelled = fake({ readConfig: () => config, interactive: true, adminResult: { ok: false, code: 'CANCELLED', message: '' } })
+ expect(await teamCommand(['remove'], cancelled.deps)).toBe(1)
+ expect(cancelled.err[0]).toBe('✗ Nothing was removed: sudo did not get an administrator password.')
+ })
+
+ it('takes the team account\'s computer off the owner\'s account once the account is gone, which signs it out', async () => {
+ const f = fake({ readConfig: () => config, adminResult: removed })
+ expect(await teamCommand(['remove'], f.deps)).toBe(0)
+ // Only the team machine with that computer id: not this computer's, not another team machine.
+ expect(f.deps.delete).toHaveBeenCalledTimes(1)
+ expect(f.deps.delete).toHaveBeenCalledWith('/api/machines/m-team', { authorization: 'Bearer x' })
+ expect(f.out.join('\n')).toContain('✓ Took its computer off your Harness account, which signs it out.')
+ expect(f.post).not.toHaveBeenCalled()
+ const json = fake({ readConfig: () => config, adminResult: removed })
+ await teamCommand(['remove', '--json'], json.deps)
+ expect(JSON.parse(json.out.at(-1)!)).toEqual({ ok: true, removed: true, computer: { removed: 1 } })
+ })
+
+ it('never takes off this computer\'s own machine, or anything when no computer was named', async () => {
+ const own = fake({ readConfig: () => config, adminResult: { ok: true, stdout: `harness: team computer ${'c'.repeat(32)}\n` } })
+ expect(await teamCommand(['remove'], own.deps)).toBe(0)
+ expect(own.deps.delete).not.toHaveBeenCalled()
+ const unnamed = fake({ readConfig: () => config, adminResult: { ok: true, stdout: 'harness: removed the Harness Team account, its home folder and its daemon\n' } })
+ expect(await teamCommand(['remove'], unnamed.deps)).toBe(0)
+ expect(unnamed.deps.get).not.toHaveBeenCalled()
+ expect(unnamed.deps.delete).not.toHaveBeenCalled()
+ expect(unnamed.out.join('\n')).toContain('If its computer, "Mac-placeholder · Team", is still on your Harness account, remove it there: harness machines')
+ })
+
+ it('says how to finish when the computer cannot be taken off: signed out here, or the backend failing', async () => {
+ const signedOut = fake({ readConfig: () => config, adminResult: removed, session: () => null })
+ expect(await teamCommand(['remove'], signedOut.deps)).toBe(0)
+ expect(signedOut.out.join('\n')).toContain('! Its computer is still on your Harness account (this computer is not signed in to Harness). '
+ + 'Remove "Mac-placeholder · Team": harness machines')
+ const failing = fake({ readConfig: () => config, adminResult: removed, delete: vi.fn(async () => { throw new Error('backend unavailable') }) as never })
+ expect(await teamCommand(['remove'], failing.deps)).toBe(0)
+ expect(failing.out.join('\n')).toContain('(backend unavailable)')
+ })
+
+ it('when macOS keeps the account, says that nothing was removed and exactly what to do', async () => {
+ const f = fake({ readConfig: () => config, adminResult: refused })
+ expect(await teamCommand(['remove'], f.deps)).toBe(1)
+ const text = f.err.join('\n')
+ expect(f.err[0]).toBe('✗ macOS kept the Harness Team account: could not delete the account harnessteam: macOS did not allow it (eDSPermissionError). '
+ + 'Nothing was removed: the Harness Team account and its daemon run as before.')
+ expect(text).toContain('run harness team remove in Terminal')
+ expect(text).toContain('macOS asks to let Terminal')
+ expect(text).toContain('delete "Harness Team" in System Settings > Users & Groups (ⓘ, Delete User…, Delete the home folder)')
+ // Nothing on the backend: the account still runs, signed in.
+ expect(f.deps.get).not.toHaveBeenCalled()
+ expect(f.deps.delete).not.toHaveBeenCalled()
+ expect(f.post).not.toHaveBeenCalled()
+ const terminal = fake({ readConfig: () => config, interactive: true, adminResult: refused, env: { __CFBundleIdentifier: 'com.apple.Terminal' } })
+ expect(await teamCommand(['remove'], terminal.deps)).toBe(1)
+ expect(terminal.err.join('\n')).toContain('it asks again after: tccutil reset SystemPolicySysAdminFiles com.apple.Terminal')
+ const odd = fake({ readConfig: () => config, interactive: true, adminResult: refused, env: { __CFBundleIdentifier: 'x; rm -rf ~' } })
+ await teamCommand(['remove'], odd.deps)
+ expect(odd.err.join('\n')).toContain('it asks again after: tccutil reset SystemPolicySysAdminFiles\n')
+ const json = fake({ readConfig: () => config, adminResult: refused })
+ await teamCommand(['remove', '--json'], json.deps)
+ expect(JSON.parse(json.out[0]!)).toMatchObject({ ok: false, code: 'DELETE_REFUSED', next: expect.arrayContaining([expect.stringContaining('Users & Groups')]) })
+ })
+
it('has nothing to do without an account, and refuses off a Mac or as root', async () => {
const none = fake({ exists: () => false })
expect(await teamCommand(['remove', '--json'], none.deps)).toBe(0)
@@ -263,6 +365,7 @@ describe('harness team remove', () => {
expect(await teamCommand(['remove'], fake({ uid: () => 0 }).deps)).toBe(1)
const cancelled = fake({ adminResult: { ok: false, code: 'CANCELLED', message: '' } })
expect(await teamCommand(['remove'], cancelled.deps)).toBe(1)
+ expect(cancelled.err[0]).toBe('✗ Nothing was removed: the administrator prompt was cancelled.')
const failed = fake({ adminResult: { ok: false, code: 'FAILED', message: 'dscl refused' } })
expect(await teamCommand(['remove'], failed.deps)).toBe(1)
expect(failed.err[0]).toContain('dscl refused')
@@ -447,15 +550,6 @@ describe('internal verbs', () => {
expect(owner.deps.writeStatus).not.toHaveBeenCalled()
expect(owner.deps.privacy).not.toHaveBeenCalled()
})
-
- it('__signout revokes and clears the team account\'s session', async () => {
- const f = inTeam()
- f.setSession({ ...computer, kind: 'team', refreshToken: 'hnr_team' })
- expect(await teamCommand(['__signout'], f.deps)).toBe(0)
- expect(f.post).toHaveBeenCalledWith('/api/auth/revoke', { refreshToken: 'hnr_team' })
- expect(f.session()).toBeNull()
- expect(f.status.get(STATUS)?.signIn).toMatchObject({ state: 'signed-out' })
- })
})
describe('parseLaunchctlPrint', () => {
diff --git a/cli/src/team/command.ts b/cli/src/team/command.ts
index b76856b8b..ab6823d7c 100644
--- a/cli/src/team/command.ts
+++ b/cli/src/team/command.ts
@@ -8,7 +8,6 @@
* Internal verbs, run by the scripts and the team daemon's job, not by people:
* __handoff (as the owner, from setup's script) print a fresh team sign-in code
* __start <file> (as the team account, before its daemon) redeem a handed-over code, run the privacy check
- * __signout (as the team account, from remove's script) sign its session out of Harness
*
* Nothing here falls back to the owner: a team account that is missing, signed out or not private is reported, and
* team work does not run as the owner instead.
@@ -17,13 +16,14 @@ import type { AuthSession } from '../lib/authSession.js'
import type { RunAdmin } from './admin.js'
import { teamConfigJson, type TeamConfig } from './config.js'
import { engineLines, type TeamEngines } from './engines.js'
-import { mintTeamConversion, mintTeamHandoff, redeemTeamHandoff, revokeHarnessRefresh, teamSession, TeamSignInError, type Get, type Post } from './handoff.js'
+import { mintTeamConversion, mintTeamHandoff, redeemTeamHandoff, revokeHarnessRefresh, teamSession, TeamSignInError, type Delete, type Get, type Post } from './handoff.js'
import {
- SENTINEL_NAME, TEAM_CONFIG_FILE, TEAM_HOME, TEAM_LABEL, TEAM_PLIST, TEAM_PORT, TEAM_REAL_NAME, TEAM_STATUS_DIR, TEAM_STATUS_FILE,
+ SENTINEL_NAME, TEAM_CONFIG_FILE, TEAM_HOME, TEAM_LABEL, TEAM_PLIST, TEAM_PORT, TEAM_REAL_NAME, TEAM_SHARED_DIR, TEAM_SHARED_MARK,
+ TEAM_STATUS_DIR, TEAM_STATUS_FILE,
TEAM_USER, TeamInputError, carriedBackendEnv, checkPath, checkUser, teamPaths,
} from './layout.js'
import type { PrivacyResult, TeamStatus } from './privacy.js'
-import { buildRemoveScript, buildSetupScript, teamLaunchdPlist } from './script.js'
+import { REMOVE_REFUSED, TEAM_COMPUTER_LINE, buildRemoveScript, buildSetupScript, teamLaunchdPlist } from './script.js'
export const TEAM_USAGE = [
'Usage: harness team <setup | status | remove | on | off> [--json]',
@@ -33,13 +33,17 @@ export const TEAM_USAGE = [
' for an administrator password once. It installs the account\'s own Claude Code and Codex, which you sign in',
' once in a terminal on its machine. Running it again repairs it (--sign-in-again: a new sign-in for it)',
' status whether the account exists and runs, its sign-in, privacy check and engines, and everything setup made',
- ' remove delete the account, its home folder and its daemon (administrator password); your home stays private',
+ ' remove delete the account, its home folder and its daemon; your home stays private. Run it in Terminal: sudo',
+ ' asks for your password, and macOS asks once to let Terminal administer your computer, which it needs',
' on for a computer used only for agents (a Mac mini, a Linux or Windows box): sign it in for team work',
' only. It then runs Swarm agents and reaches none of your other computers (--yes skips the question)',
' off sign this computer out of team work, then sign it in as your own computer again',
].join('\n')
export const SETUP_PROMPT = 'Harness wants to create a separate account, Harness Team, for Swarm work on this Mac, so teammates\' agents cannot read your files.'
+/** The same script on a Mac that has the account: it repairs what is there. (The dialog's title, "osascript", is the
+ * process that asks, and osascript cannot change it.) */
+export const REPAIR_PROMPT = 'Harness wants to repair the Harness Team account, which runs Swarm work on this Mac so teammates\' agents cannot read your files.'
export const REMOVE_PROMPT = 'Harness wants to remove the Harness Team account, its home folder and its daemon from this Mac.'
/** How long setup waits for the team daemon to sign in and report its privacy check. */
@@ -79,6 +83,7 @@ export interface TeamCommandDeps {
auth(): Promise<{ session: AuthSession; headers: Record<string, string> }>
post: Post
get: Get
+ delete: Delete
/** This computer's machine key on the account's device key log (lib/e2ee/store.ts), never made here; null when it has
* none. `team on` signs with it to show the backend it is this computer. */
machineKey(): { priv: Uint8Array } | null
@@ -129,7 +134,6 @@ export async function teamCommand(argv: string[], deps: TeamCommandDeps): Promis
case 'off': return await teamOff(deps, json)
case '__handoff': return await handoff(deps)
case '__start': return await jobStart(deps, words[1])
- case '__signout': return await signOut(deps)
default:
deps.err(`Unknown command: harness team ${verb}\n\n${TEAM_USAGE}`)
return 2
@@ -150,7 +154,7 @@ function fail(deps: TeamCommandDeps, json: boolean, code: string, message: strin
function madeLines(ownerHome: string): string[] {
const team = teamPaths()
return [
- ` account ${TEAM_REAL_NAME} (${TEAM_USER}): a standard user with no usable password, shown in Users & Groups`,
+ ` account ${TEAM_REAL_NAME} (${TEAM_USER}): a standard user with a random password nobody knows, listed in Users & Groups`,
` home ${TEAM_HOME}`,
` daemon ${TEAM_LABEL}, a LaunchDaemon at ${TEAM_PLIST}, running as ${TEAM_USER} on port ${TEAM_PORT}`,
` log ${team.log} (inside the account's home)`,
@@ -163,10 +167,11 @@ function madeLines(ownerHome: string): string[] {
function byHandLines(ownerHome: string): string[] {
return [
- ' To remove it by hand:',
- ` sudo launchctl bootout system/${TEAM_LABEL}; sudo rm ${TEAM_PLIST}`,
- ` sudo dscl . -delete /Users/${TEAM_USER}; sudo rm -rf ${TEAM_HOME}`,
- ` sudo rm -rf '${TEAM_CONFIG_FILE}' '${TEAM_STATUS_DIR}'; rm ${ownerHome}/${SENTINEL_NAME}`,
+ ' To remove it by hand, in Terminal (macOS asks to let Terminal administer your computer for the first line):',
+ ` sudo dscl . -delete /Users/${TEAM_USER}`,
+ ` sudo launchctl bootout system/${TEAM_LABEL}; sudo rm ${TEAM_PLIST}; sudo rm -rf ${TEAM_HOME}`,
+ ` sudo rm -rf '${TEAM_CONFIG_FILE}' '${TEAM_STATUS_DIR}' '${TEAM_SHARED_MARK}'; rm ${ownerHome}/${SENTINEL_NAME}`,
+ ` sudo rmdir '${TEAM_SHARED_DIR}' (only when it is empty)`,
]
}
@@ -201,8 +206,11 @@ async function setup(deps: TeamCommandDeps, json: boolean, signInAgain: boolean)
statusFile: TEAM_STATUS_FILE, node: teamNode, cli: team.cliJs, env: carried, createdAt: new Date(deps.now()).toISOString(),
}
const plist = teamLaunchdPlist({ user: TEAM_USER, home: TEAM_HOME, node: teamNode, cli: team.cliJs, port: TEAM_PORT, env: carried })
+ const repair = deps.readConfig() !== null || await deps.accountExists(TEAM_USER)
if (!json) {
- deps.out('Harness will set up a separate account for Swarm work on this Mac. macOS asks for an administrator password once.')
+ deps.out(repair
+ ? 'Harness will repair the Harness Team account on this Mac. macOS asks for an administrator password once.'
+ : 'Harness will set up a separate account for Swarm work on this Mac. macOS asks for an administrator password once.')
for (const line of madeLines(ownerHome)) deps.out(line)
}
const startedAt = deps.now()
@@ -213,7 +221,7 @@ async function setup(deps: TeamCommandDeps, json: boolean, signInAgain: boolean)
ownerNode: installed.node, ownerCli: installed.cliJs, mintEnv, signIn: signInAgain ? 'always' : 'missing',
}),
files: { 'team.json': teamConfigJson(config), 'team.plist': plist },
- }), SETUP_PROMPT)
+ }), repair ? REPAIR_PROMPT : SETUP_PROMPT)
if (!result.ok) {
if (result.code === 'CANCELLED') return fail(deps, json, 'CANCELLED', 'Nothing was changed: the administrator prompt was cancelled.')
return fail(deps, json, 'SETUP_FAILED', `The Harness Team account was not finished: ${sentence(result.message)} Run \`harness team setup\` again; it repairs what is there.`)
@@ -306,9 +314,56 @@ async function status(deps: TeamCommandDeps, json: boolean): Promise<number> {
return 0
}
+/** A terminal app's bundle id as macOS gives it to what the app starts, for the one command that asks again. */
+const BUNDLE_ID = /^[A-Za-z0-9][A-Za-z0-9.-]{0,127}$/
+
+/** What to do when macOS keeps the account ([REMOVE_REFUSED]): nothing was removed, and the account runs as before. */
+function refusedLines(deps: TeamCommandDeps, inTerminal: boolean): string[] {
+ const usersAndGroups = `delete "${TEAM_REAL_NAME}" in System Settings > Users & Groups (ⓘ, Delete User…, Delete the home folder), then run harness team remove again for the rest`
+ if (!inTerminal) {
+ return [
+ ' macOS 26 deletes an account only for an app you allow to administer this Mac, and it cannot ask that for this prompt. Either:',
+ ' · run harness team remove in Terminal: it asks for your password there, then macOS asks to let Terminal',
+ ' administer your computer. Choose Allow.',
+ ` · or ${usersAndGroups}.`,
+ ]
+ }
+ const app = deps.env.__CFBundleIdentifier?.trim()
+ const reset = `tccutil reset SystemPolicySysAdminFiles${app && BUNDLE_ID.test(app) ? ` ${app}` : ''}`
+ return [
+ ' macOS deletes an account only for an app you allow to administer this Mac. If you chose Don\'t Allow when it asked,',
+ ` it asks again after: ${reset}`,
+ ` Or ${usersAndGroups}.`,
+ ]
+}
+
+interface MachineRow { machineId: string; computerId?: string | null; sessionKind?: string | null }
+
+/** A computer id as the backend keeps it (backend lib/deviceAuth.ts `normalizeComputerId`): lower case, no dashes. */
+const computerKey = (id: string | null | undefined): string => (id ?? '').trim().toLowerCase().replace(/-/g, '')
+
+/**
+ * The team account's computer, off the owner's Harness account: the backend ends the team sign-in bound to it with it.
+ * Only after the account is gone: a removal macOS refuses must leave the account signed in and running. Only a team
+ * machine with that computer id, never this computer's own.
+ */
+async function forgetTeamComputer(deps: TeamCommandDeps, computerId: string): Promise<{ removed: number } | { error: string }> {
+ if (!deps.session()) return { error: 'this computer is not signed in to Harness' }
+ try {
+ const { session, headers } = await deps.auth()
+ const { machines = [] } = await deps.get<{ machines?: MachineRow[] }>('/api/machines', headers)
+ const key = computerKey(computerId)
+ const ours = machines.filter((m) => key !== '' && computerKey(m.computerId) === key && m.sessionKind === 'team' && m.machineId !== session.machineId)
+ for (const machine of ours) await deps.delete(`/api/machines/${encodeURIComponent(machine.machineId)}`, headers)
+ return { removed: ours.length }
+ } catch (error) {
+ return { error: (error as Error).message }
+ }
+}
+
async function remove(deps: TeamCommandDeps, json: boolean): Promise<number> {
if (deps.platform !== 'darwin') return fail(deps, json, 'UNSUPPORTED', 'The Harness Team account is made on a Mac; this computer has none. To stop team work here: harness team off.')
- if (deps.uid() === 0) return fail(deps, json, 'RUN_AS_YOURSELF', 'Run this as yourself, not with sudo: macOS asks for an administrator password itself.')
+ if (deps.uid() === 0) return fail(deps, json, 'RUN_AS_YOURSELF', 'Run this as yourself, not with sudo: Harness asks for an administrator password itself.')
const config = deps.readConfig()
const ownerHome = checkPath(config?.ownerHome ?? deps.home(), 'home folder')
if (!config && !await deps.accountExists(TEAM_USER) && !deps.exists(TEAM_PLIST) && !deps.exists(TEAM_HOME)) {
@@ -316,21 +371,40 @@ async function remove(deps: TeamCommandDeps, json: boolean): Promise<number> {
else deps.out('No Harness Team account on this Mac; nothing to remove.')
return 0
}
+ // In a terminal, with sudo there: macOS then asks to let the terminal app administer the Mac, which deleting an account
+ // needs (./admin.ts). Elsewhere (Desktop, a script), the administrator prompt, which macOS 26 refuses it.
+ const inTerminal = deps.interactive
+ if (inTerminal && !json) deps.out('Harness will remove the Harness Team account. sudo asks for your password here; macOS may then ask to let this terminal administer your computer.')
const result = await deps.admin(() => ({
- script: buildRemoveScript({ user: config?.user ?? TEAM_USER, home: config?.home ?? TEAM_HOME, ownerHome,
- teamNode: config?.node ?? null, teamCli: config?.cli ?? null, env: config?.env ?? {} }),
- }), REMOVE_PROMPT)
+ script: buildRemoveScript({ user: config?.user ?? TEAM_USER, home: config?.home ?? TEAM_HOME, ownerHome }),
+ }), REMOVE_PROMPT, inTerminal ? 'sudo' : 'prompt')
if (!result.ok) {
- if (result.code === 'CANCELLED') return fail(deps, json, 'CANCELLED', 'Nothing was removed: the administrator prompt was cancelled.')
+ if (result.code === 'CANCELLED') {
+ return fail(deps, json, 'CANCELLED', `Nothing was removed: ${inTerminal ? 'sudo did not get an administrator password' : 'the administrator prompt was cancelled'}.`)
+ }
+ if (result.status === REMOVE_REFUSED) {
+ const next = refusedLines(deps, inTerminal)
+ if (json) return fail(deps, json, 'DELETE_REFUSED', sentence(result.message), { next: next.map((line) => line.trim()) })
+ fail(deps, json, 'DELETE_REFUSED', `macOS kept the Harness Team account: ${sentence(result.message)}`)
+ for (const line of next) deps.err(line)
+ return 1
+ }
return fail(deps, json, 'REMOVE_FAILED', `The Harness Team account was not fully removed: ${sentence(result.message)} Run \`harness team remove\` again.`)
}
try { deps.setupDecision?.decline() } catch { /* only Desktop's offer reads it */ }
- if (json) deps.out(JSON.stringify({ ok: true, removed: true }))
- else {
- deps.out(`✓ Removed the Harness Team account (${TEAM_USER}), ${TEAM_HOME} and the daemon ${TEAM_LABEL}.`)
- deps.out(` Your home folder stays private (mode 700). Its computer stays in your list until you remove it: harness machines`)
- deps.out(' Harness will not make it again on its own when you join a Swarm; harness team setup makes it again.')
+ const computerId = TEAM_COMPUTER_LINE.exec(result.stdout)?.[1] ?? null
+ const forgotten = computerId ? await forgetTeamComputer(deps, computerId) : null
+ if (json) {
+ deps.out(JSON.stringify({ ok: true, removed: true, computer: forgotten }))
+ return 0
}
+ deps.out(`✓ Removed the Harness Team account (${TEAM_USER}), ${TEAM_HOME} and the daemon ${TEAM_LABEL}.`)
+ const teamMachine = `"${deps.hostname().slice(0, 60)} · Team"`
+ if (forgotten && 'removed' in forgotten && forgotten.removed > 0) deps.out('✓ Took its computer off your Harness account, which signs it out.')
+ else if (forgotten && 'error' in forgotten) deps.out(`! Its computer is still on your Harness account (${forgotten.error}). Remove ${teamMachine}: harness machines`)
+ else if (!computerId) deps.out(` If its computer, ${teamMachine}, is still on your Harness account, remove it there: harness machines`)
+ deps.out(' Your home folder stays private (mode 700).')
+ deps.out(' Harness will not make it again on its own when you join a Swarm; harness team setup makes it again.')
return 0
}
@@ -465,15 +539,3 @@ async function jobStart(deps: TeamCommandDeps, file: string | undefined): Promis
}
return 0
}
-
-/** `team __signout`: run as the team account by remove's script, before the account is deleted. */
-async function signOut(deps: TeamCommandDeps): Promise<number> {
- const session = deps.session()
- if (session) await revokeHarnessRefresh(deps.post, session.refreshToken)
- deps.clearSession()
- const config = deps.readConfig()
- if (config && config.user === deps.user()) {
- try { deps.writeStatus(config.statusFile, { signIn: { state: 'signed-out', at: deps.now() } }) } catch { /* removed next */ }
- }
- return 0
-}
diff --git a/cli/src/team/deps.ts b/cli/src/team/deps.ts
index ae6f2eff4..9afad3049 100644
--- a/cli/src/team/deps.ts
+++ b/cli/src/team/deps.ts
@@ -57,6 +57,7 @@ export function teamCommandDeps(options: {
auth: controlPlaneAuth,
post: (path, body, headers) => postJson(path, body, headers ?? {}),
get: (path, headers) => requestJson('GET', path, undefined, headers ?? {}),
+ delete: (path, headers) => requestJson('DELETE', path, undefined, headers ?? {}),
machineKey: () => peekIdentity(),
computerId,
autonomousEnv: env.AUTONOMOUS_ENV,
diff --git a/cli/src/team/handoff.ts b/cli/src/team/handoff.ts
index 78067571b..1a2e21673 100644
--- a/cli/src/team/handoff.ts
+++ b/cli/src/team/handoff.ts
@@ -21,6 +21,7 @@ import { HANDOFF_CODE } from './layout.js'
export type Post = <T>(path: string, body: unknown, headers?: Record<string, string>) => Promise<T>
export type Get = <T>(path: string, headers?: Record<string, string>) => Promise<T>
+export type Delete = <T>(path: string, headers?: Record<string, string>) => Promise<T>
type SignedIn = { session: AuthSession; headers: Record<string, string> }
export class TeamSignInError extends Error {
diff --git a/cli/src/team/layout.ts b/cli/src/team/layout.ts
index 598cb18bc..210780c38 100644
--- a/cli/src/team/layout.ts
+++ b/cli/src/team/layout.ts
@@ -3,9 +3,10 @@
* privileged script (docs/plans/2026-10-24-swarm-team-account.md, Task 2).
*
* The team account is a separate, standard macOS user that runs a second Harness daemon for Swarm work, so a
- * teammate's agent on this Mac cannot read the owner's files. It is visible in System Settings > Users & Groups
+ * teammate's agent on this Mac cannot read the owner's files. It is listed in System Settings > Users & Groups
* and named "Harness Team" on purpose: a hidden user with a LaunchDaemon is the persistence pattern endpoint
* security tools and careful engineers treat as malware, and anyone auditing the Mac should find it at a glance.
+ * macOS lists an account only when it has a password, so it gets a random one that nobody knows (./script.ts).
*/
import { isAbsolute, normalize } from 'node:path'
@@ -20,6 +21,9 @@ export const TEAM_PLIST = `/Library/LaunchDaemons/${TEAM_LABEL}.plist`
/** Root-owned: what setup made, read by the team daemon. Root's so a process in the team account cannot point its
* own privacy check somewhere else. */
export const TEAM_SHARED_DIR = '/Library/Application Support/Harness'
+/** Left in that folder by a setup that made it, so removal takes the folder away once it is empty, and never one made
+ * by anything else. */
+export const TEAM_SHARED_MARK = `${TEAM_SHARED_DIR}/.made-by-harness-team-setup`
export const TEAM_CONFIG_FILE = `${TEAM_SHARED_DIR}/team.json`
/** The team account's: where its daemon reports sign-in and the privacy check, for the owner's `harness team status`. */
export const TEAM_STATUS_DIR = `${TEAM_SHARED_DIR}/Team`
@@ -44,6 +48,8 @@ export function teamPaths(home: string = TEAM_HOME) {
runtime: `${harness}/runtime`,
auth: `${harness}/auth`,
session: `${harness}/auth/session.json`,
+ /** Its daemon's computer id, at the product root as every daemon keeps it (config/env.ts). */
+ computerId: `${harness}/computer-id`,
bin: `${home}/.local/bin`,
/** The single-use sign-in code setup hands over; the team daemon redeems it on its next start and deletes it. */
handoff: `${harness}/team-handoff`,
diff --git a/cli/src/team/script.spec.ts b/cli/src/team/script.spec.ts
index d9491a3b0..1e38796c5 100644
--- a/cli/src/team/script.spec.ts
+++ b/cli/src/team/script.spec.ts
@@ -9,8 +9,8 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import {
- SENTINEL_TEXT, TEAM_COPY, TEAM_ENGINES_INSTALL, TEAM_JOB_WRAPPER, WRITE_PRIVATE, WRITE_PUBLIC, buildRemoveScript, buildSetupScript, sh, teamLaunchdPlist,
- type SetupScriptInput,
+ REMOVE_REFUSED, SENTINEL_TEXT, TEAM_COMPUTER_LINE, TEAM_COPY, TEAM_ENGINES_INSTALL, TEAM_JOB_WRAPPER, TEAM_PASSWORD, WRITE_PRIVATE, WRITE_PUBLIC,
+ buildRemoveScript, buildSetupScript, sh, teamLaunchdPlist, type SetupScriptInput,
} from './script.js'
const OWNER_HOME = '/Users/owner-placeholder'
@@ -71,10 +71,15 @@ describe('setup script', () => {
expect(script.split(OWNER_HOME).length - 1).toBe(6)
})
- it('makes a visible, standard account with an unusable password, and never an administrator', () => {
+ it('makes a listed, standard account with a random password, and never an administrator', () => {
const script = buildSetupScript(input())
expect(script).toContain('dscl . -create "/Users/$TEAM" RealName "$TEAM_NAME"')
- expect(script).toContain("dscl . -create \"/Users/$TEAM\" Password '*'")
+ // `*` only while a new record is made, before its UniqueID: the random password replaces it at once.
+ expect(script.split("dscl . -create \"/Users/$TEAM\" Password '*'")).toHaveLength(2)
+ expect(at(script, " dscl . -create \"/Users/$TEAM\" Password '*'")).toBeLessThan(at(script, ' dscl . -create "/Users/$TEAM" UniqueID "$uid"'))
+ expect(at(script, TEAM_PASSWORD)).toBeLessThan(at(script, 'team_uid=$(id -u "$TEAM")'))
+ // Never on a command line: no `dscl . -passwd`, no sysadminctl, no password argument.
+ expect(script).not.toMatch(/-passwd|sysadminctl|-password/)
expect(script).toContain('dscl . -create "/Users/$TEAM" PrimaryGroupID 20')
expect(script).not.toMatch(/IsHidden 1/)
expect(script).toContain('dscl . -delete "/Users/$TEAM" IsHidden')
@@ -127,6 +132,13 @@ describe('setup script', () => {
parses(script)
})
+ it('marks the shared folder as its own only when it made it', () => {
+ const script = buildSetupScript(input())
+ expect(script).toContain('if [ ! -d "$SHARED" ]; then mkdir "$SHARED"; chown 0:0 "$SHARED"; chmod 755 "$SHARED"; made_shared=1; fi')
+ expect(at(script, 'owned_by_root "$SHARED"')).toBeLessThan(at(script, '[ -z "$made_shared" ] || : > "$SHARED_MARK"'))
+ expect(script).toContain("SHARED_MARK='/Library/Application Support/Harness/.made-by-harness-team-setup'")
+ })
+
it('copies a managed tmux only when there is one', () => {
expect(buildSetupScript(input())).toContain("TMUX_NAME=''")
const script = buildSetupScript(input({ tmuxRuntimeDir: `${OWNER_HOME}/.harness/runtime/tmux-3.5a-darwin-arm64` }))
@@ -229,6 +241,58 @@ describe('the team account\'s copy of the runtime', () => {
})
})
+describe('the team account\'s password', () => {
+ /** TEAM_PASSWORD with a stand-in dscl on PATH that records every call (its arguments, and what it read) and keeps the
+ * account's state in a folder. Nothing touches a real account. */
+ function run(state: { password?: boolean; refuses?: boolean } = {}) {
+ const root = temp()
+ const bin = join(root, 'bin'), log = join(root, 'calls')
+ mkdirSync(bin)
+ if (state.password) writeFileSync(join(root, 'has-password'), '')
+ writeFileSync(join(bin, 'dscl'), [
+ '#!/bin/sh',
+ `printf 'argv:%s\\n' "$*" >> '${log}'`,
+ 'if [ "$#" = 1 ]; then',
+ ` input=$(cat); printf 'stdin:%s\\n' "$input" >> '${log}'`,
+ ` ${state.refuses ? 'exit 0' : `case $input in "passwd /Users/harnessteam "*) : > '${root}/has-password' ;; esac`}`,
+ ' exit 0',
+ 'fi',
+ `[ -e '${root}/has-password' ] && echo 'AuthenticationAuthority: ;ShadowHash;HASHLIST:<SALTED-SHA512-PBKDF2>'`,
+ 'exit 0',
+ ].join('\n'), { mode: 0o755 })
+ const result = spawnSync('/bin/sh', ['-c', `set -eu\ndie() { printf 'harness: %s\\n' "$1" >&2; exit "$2"; }\nTEAM=harnessteam\n${TEAM_PASSWORD}\necho done`],
+ { encoding: 'utf8', env: { PATH: `${bin}:/usr/bin:/bin` } })
+ const calls = existsSync(log) ? readFileSync(log, 'utf8').trim().split('\n') : []
+ return { result, calls }
+ }
+
+ it('is random, 40 letters and digits, and reaches dscl only on its input, never as an argument', () => {
+ const { result, calls } = run()
+ expect(result.stderr).toBe('')
+ expect(result.stdout).toBe('done\n')
+ const stdin = calls.filter((c) => c.startsWith('stdin:'))
+ expect(stdin).toHaveLength(1)
+ const password = /^stdin:passwd \/Users\/harnessteam ([A-Za-z0-9]{40})$/.exec(stdin[0]!)?.[1]
+ expect(password).toBeDefined()
+ // What `ps` would show: the arguments of every call. The password is in none of them.
+ for (const call of calls.filter((c) => c.startsWith('argv:'))) expect(call).not.toContain(password)
+ expect(calls).toContain('argv:.')
+ expect(run().calls.find((c) => c.startsWith('stdin:'))).not.toBe(stdin[0])
+ })
+
+ it('is left as it is on a repair run', () => {
+ const { result, calls } = run({ password: true })
+ expect(result.stdout).toBe('done\n')
+ expect(calls).toEqual(['argv:. -read /Users/harnessteam AuthenticationAuthority'])
+ })
+
+ it('stops setup, saying why, when macOS does not take it', () => {
+ const { result } = run({ refuses: true })
+ expect(result.status).toBe(4)
+ expect(result.stderr).toBe('harness: macOS did not take a password for the account harnessteam, so Users & Groups would not list it\n')
+ })
+})
+
describe('the team daemon\'s job', () => {
const plistInput = { user: 'harnessteam', home: '/Users/harnessteam', node: '/Users/harnessteam/.harness/runtime/node-v1/bin/node',
cli: '/Users/harnessteam/.harness/cli/cli.js', port: 18493, env: { BACKEND_WS_URL: 'wss://backend.example.test/a&b' } }
@@ -281,19 +345,20 @@ describe('the team daemon\'s job', () => {
})
describe('remove script', () => {
- const removeInput = { user: 'harnessteam', home: '/Users/harnessteam', ownerHome: OWNER_HOME,
- teamNode: '/Users/harnessteam/.harness/runtime/node-v1/bin/node', teamCli: '/Users/harnessteam/.harness/cli/cli.js',
- env: { AUTONOMOUS_ENV: 'stag' } }
+ const removeInput = { user: 'harnessteam', home: '/Users/harnessteam', ownerHome: OWNER_HOME }
- it('parses, signs the account out as itself first, then removes the job, the account and its files', () => {
+ it('parses, and deletes the account before anything it cannot undo', () => {
const script = buildRemoveScript(removeInput)
parses(script)
+ // Where every daemon keeps its computer id (config/env.ts): the product root, not the data folder.
+ expect(script).toContain("COMPUTER_ID='/Users/harnessteam/.harness/computer-id'")
const order = [
- 'team __signout', 'launchctl bootout "system/$LABEL"', 'rm -f "$PLIST"', 'pkill -KILL -u "$TEAM"', 'dscl . -delete "/Users/$TEAM"',
- 'rm -rf "$TEAM_HOME" "$STATUS_DIR"', 'rm -f "$CONFIG" "$SENTINEL"',
+ 'launchctl bootout "system/$LABEL"', 'dscl . -delete "/Users/$TEAM"', 'pkill -KILL -u "$team_uid"', 'rm -f "$PLIST"',
+ 'rm -rf "$TEAM_HOME" "$STATUS_DIR"', 'rm -f "$CONFIG" "$SENTINEL"', 'rmdir "$SHARED"',
].map((needle) => at(script, needle))
expect([...order].sort((a, b) => a - b)).toEqual(order)
- expect(script).toContain('/usr/bin/sudo -n -H -u "$TEAM" /usr/bin/env \'AUTONOMOUS_ENV=stag\' "$TEAM_NODE" "$TEAM_CLI" team __signout')
+ // The team account is no longer signed out from here: that cannot be undone, and the deletion may yet be refused.
+ expect(script).not.toContain('__signout')
// The owner's home folder stays private: nothing here changes its mode.
expect(script).not.toMatch(/chmod/)
})
@@ -302,15 +367,176 @@ describe('remove script', () => {
const script = buildRemoveScript(removeInput)
expect(script).toContain('is not the Harness Team account (its home is $existing); nothing was removed')
expect(script).toContain('belongs to $holder; nothing was removed')
- })
-
- it('skips the sign-out when the config does not name the team account\'s CLI', () => {
- const script = buildRemoveScript({ ...removeInput, teamNode: null, teamCli: null, env: {} })
- expect(script).toContain("TEAM_NODE=''")
- parses(script)
expect(() => buildRemoveScript({ ...removeInput, user: 'root' })).toThrow()
expect(() => buildRemoveScript({ ...removeInput, home: '/Users/a b/../c' })).toThrow()
})
+
+ /**
+ * The whole removal script, run for real against a temporary folder: every path it names is moved into it, and every
+ * system command it calls (dscl, launchctl, pkill, id, stat, sudo, sleep) is a stand-in shell function, defined before
+ * the script's first line runs, that records the call and keeps the account's state in files. Nothing touches a real
+ * account, job or folder outside the temporary one.
+ */
+ function sandbox(over: { account?: boolean; refuse?: boolean; bootstrapFails?: boolean; mark?: boolean; otherShared?: boolean; keptHome?: boolean
+ otherOwner?: boolean } = {}) {
+ const root = temp()
+ const state = join(root, 'state'), log = join(root, 'calls')
+ mkdirSync(state)
+ const p = {
+ TEAM_HOME: join(root, 'Users', 'harnessteam'), PLIST: join(root, 'LaunchDaemons', 'ai.autonomous.harness.team.plist'),
+ SHARED: join(root, 'Application Support', 'Harness'), SENTINEL: join(root, 'Users', 'owner', '.harness-team-privacy'),
+ }
+ const paths = { ...p, CONFIG: join(p.SHARED, 'team.json'), STATUS_DIR: join(p.SHARED, 'Team'),
+ SHARED_MARK: join(p.SHARED, '.made-by-harness-team-setup'), COMPUTER_ID: join(p.TEAM_HOME, '.harness', 'computer-id'),
+ DELETED_HOME: `${p.TEAM_HOME} (Deleted)` }
+ // Users & Groups, told to keep the home folder of an account it deletes, renames it.
+ mkdirSync(over.keptHome ? join(paths.DELETED_HOME, '.harness') : join(p.TEAM_HOME, '.harness', 'cli', 'data'), { recursive: true })
+ if (over.keptHome) mkdirSync(join(p.TEAM_HOME, '.harness', 'cli', 'data'), { recursive: true })
+ mkdirSync(join(root, 'LaunchDaemons'))
+ mkdirSync(paths.STATUS_DIR, { recursive: true })
+ mkdirSync(join(root, 'Users', 'owner'))
+ writeFileSync(over.keptHome ? join(paths.DELETED_HOME, '.harness', 'computer-id') : paths.COMPUTER_ID, 'team-computer-1\n')
+ writeFileSync(p.PLIST, '<plist/>')
+ writeFileSync(paths.CONFIG, '{}')
+ writeFileSync(join(paths.STATUS_DIR, 'status.json'), '{}')
+ writeFileSync(p.SENTINEL, 'x')
+ if (over.mark !== false) writeFileSync(paths.SHARED_MARK, '')
+ if (over.otherShared) writeFileSync(join(p.SHARED, 'other.json'), '{}')
+ if (over.account !== false) writeFileSync(join(state, 'account'), '')
+ writeFileSync(join(state, 'loaded'), '')
+ const stub = (name: string, body: string) => `${name}() { printf '%s %s\\n' ${name} "$*" >> ${sh(log)}; ${body}\n}`
+ const prelude = [
+ // The home's owner by number, and that number's name: the team account's, nobody's once it is deleted, or someone else's.
+ stub('id', [
+ 'case "$*" in',
+ " '-u') echo 0 ;;",
+ " '-u harnessteam') echo 600 ;;",
+ ` '-un 600') if [ -e ${sh(`${state}/account`)} ]; then echo harnessteam; else return 1; fi ;;`,
+ " '-un 701') echo someone ;;",
+ ' *) return 1 ;;',
+ 'esac',
+ ].join('\n')),
+ stub('stat', `[ "$1 $2" = '-f %u' ] && echo ${over.otherOwner ? 701 : 600}`),
+ stub('head', 'command head "$@"'),
+ stub('dscl', [
+ 'case "$*" in',
+ ` *-read*UniqueID*) [ -e ${sh(`${state}/account`)} ] && echo 'UniqueID: 600' ;;`,
+ ` *-read*NFSHomeDirectory*) [ -e ${sh(`${state}/account`)} ] && echo ${sh(`NFSHomeDirectory: ${p.TEAM_HOME}`)} ;;`,
+ ` *-delete*) ${over.refuse
+ ? "echo '<main> delete status: eDSPermissionError' >&2; echo '<dscl_cmd> DS Error: -14120 (eDSPermissionError)' >&2; return 40"
+ : `rm ${sh(`${state}/account`)}`} ;;`,
+ 'esac',
+ ].join('\n')),
+ stub('launchctl', [
+ 'case "$1" in',
+ ` bootout) rm -f ${sh(`${state}/loaded`)} ;;`,
+ ` bootstrap) ${over.bootstrapFails ? 'return 5' : `: > ${sh(`${state}/loaded`)}`} ;;`,
+ ` print) [ -e ${sh(`${state}/loaded`)} ] ;;`,
+ 'esac',
+ ].join('\n')),
+ stub('sudo', 'while [ "$#" -gt 0 ]; do case "$1" in -n) shift ;; -u) shift 2 ;; *) break ;; esac; done; "$@"'),
+ stub('pkill', ':'),
+ stub('sleep', ':'),
+ ].join('\n')
+ let script = buildRemoveScript(removeInput)
+ for (const [name, value] of Object.entries(paths)) {
+ expect(script, name).toMatch(new RegExp(`^${name}=`, 'm'))
+ script = script.replace(new RegExp(`^${name}=.*$`, 'm'), `${name}=${sh(value)}`)
+ }
+ // The stand-ins are found by name: the script's absolute /usr/bin/sudo and /bin/cat would pass them by.
+ script = script.replaceAll('/usr/bin/sudo', 'sudo').replaceAll('/bin/cat', 'cat').replace('\ncd /\n', `\ncd /\n${prelude}\n`)
+ // Nothing left that names a real place: every path is in the temporary folder.
+ expect(script).not.toMatch(/'\/(Users|Library)\//)
+ const file = join(root, 'remove.sh')
+ writeFileSync(file, script)
+ const result = spawnSync('/bin/sh', [file], { encoding: 'utf8', env: { PATH: '/usr/bin:/bin' } })
+ const calls = existsSync(log) ? readFileSync(log, 'utf8').trim().split('\n') : []
+ return { result, calls, paths, state, gone: (path: string) => !existsSync(path) }
+ }
+
+ it('removes the account, its daemon and everything setup made, and names its computer for the owner to take off', () => {
+ const s = sandbox()
+ expect(s.result.stderr).toBe('')
+ expect(s.result.status).toBe(0)
+ expect(TEAM_COMPUTER_LINE.exec(s.result.stdout)?.[1]).toBe('team-computer-1')
+ expect(s.result.stdout).toContain('harness: removed the Harness Team account, its home folder and its daemon')
+ for (const path of [s.paths.TEAM_HOME, s.paths.PLIST, s.paths.CONFIG, s.paths.STATUS_DIR, s.paths.SENTINEL, s.paths.SHARED]) expect(s.gone(path), path).toBe(true)
+ const deleted = s.calls.indexOf('dscl . -delete /Users/harnessteam')
+ expect(deleted).toBeGreaterThan(s.calls.indexOf('launchctl bootout system/ai.autonomous.harness.team'))
+ expect(s.calls.indexOf('pkill -KILL -u 600')).toBeGreaterThan(deleted)
+ expect(s.calls.some((c) => c.startsWith('launchctl bootstrap'))).toBe(false)
+ // Its computer id was read as the team account, not by root.
+ expect(s.calls).toContain(`sudo -n -u harnessteam cat ${s.paths.COMPUTER_ID}`)
+ })
+
+ it('when macOS refuses the deletion, changes nothing and starts the team daemon again', () => {
+ const s = sandbox({ refuse: true })
+ expect(s.result.status).toBe(REMOVE_REFUSED)
+ expect(s.result.stderr).toBe('harness: could not delete the account harnessteam: macOS did not allow it (eDSPermissionError). '
+ + 'Nothing was removed: the Harness Team account and its daemon run as before\n')
+ for (const path of [s.paths.TEAM_HOME, s.paths.PLIST, s.paths.CONFIG, s.paths.STATUS_DIR, s.paths.SENTINEL, s.paths.SHARED_MARK, s.paths.COMPUTER_ID]) {
+ expect(s.gone(path), path).toBe(false)
+ }
+ expect(s.calls).toContain(`launchctl bootstrap system ${s.paths.PLIST}`)
+ expect(existsSync(join(s.state, 'loaded'))).toBe(true)
+ expect(existsSync(join(s.state, 'account'))).toBe(true)
+ expect(s.calls.some((c) => c.startsWith('pkill'))).toBe(false)
+ expect(s.result.stdout).not.toMatch(TEAM_COMPUTER_LINE)
+ })
+
+ it('says so when the team daemon does not start again after a refusal', () => {
+ const s = sandbox({ refuse: true, bootstrapFails: true })
+ expect(s.result.status).toBe(REMOVE_REFUSED)
+ expect(s.result.stderr).toContain('Nothing was removed, but the team daemon did not start again: harness team setup starts it')
+ expect(s.gone(s.paths.PLIST)).toBe(false)
+ })
+
+ it('finishes after the account was deleted elsewhere (Users & Groups), stopping what still runs under its old id', () => {
+ const s = sandbox({ account: false })
+ expect(s.result.status).toBe(0)
+ expect(s.calls.some((c) => c.startsWith('dscl . -delete'))).toBe(false)
+ expect(s.calls).toContain('pkill -KILL -u 600')
+ for (const path of [s.paths.TEAM_HOME, s.paths.PLIST, s.paths.CONFIG, s.paths.SHARED]) expect(s.gone(path), path).toBe(true)
+ // Its computer id, from the home it left, owned by its old id.
+ expect(TEAM_COMPUTER_LINE.exec(s.result.stdout)?.[1]).toBe('team-computer-1')
+ })
+
+ it('never reads a computer id through a link, or from a file its old id does not own', () => {
+ const script = buildRemoveScript(removeInput)
+ expect(script).toContain('[ ! -L "$left" ] && [ ! -L "$left/.harness" ] && [ ! -L "$f" ] && [ -f "$f" ] || continue')
+ expect(script).toContain('[ "$(stat -f %u "$f")" = "$team_uid" ] || continue')
+ })
+
+ it('also removes the home folder Users & Groups kept, renamed, when the account was deleted there, and names its computer', () => {
+ const s = sandbox({ account: false, keptHome: true })
+ expect(s.result.status).toBe(0)
+ expect(s.gone(s.paths.DELETED_HOME)).toBe(true)
+ expect(s.gone(s.paths.TEAM_HOME)).toBe(true)
+ expect(s.calls).toContain('pkill -KILL -u 600')
+ // Read from the home it left, after its processes were stopped.
+ expect(TEAM_COMPUTER_LINE.exec(s.result.stdout)?.[1]).toBe('team-computer-1')
+ expect(s.calls.indexOf(`head -n 1 ${s.paths.DELETED_HOME}/.harness/computer-id`)).toBeGreaterThan(s.calls.indexOf('pkill -KILL -u 600'))
+ expect(buildRemoveScript(removeInput)).toContain("DELETED_HOME='/Users/harnessteam (Deleted)'")
+ })
+
+ it('leaves a home folder that belongs to another account, and everything else, alone', () => {
+ const s = sandbox({ account: false, otherOwner: true })
+ expect(s.result.status).toBe(4)
+ expect(s.result.stderr).toBe(`harness: ${s.paths.TEAM_HOME} belongs to someone; nothing was removed\n`)
+ for (const path of [s.paths.TEAM_HOME, s.paths.PLIST, s.paths.CONFIG]) expect(s.gone(path), path).toBe(false)
+ expect(s.calls.some((c) => c.startsWith('launchctl') || c.startsWith('pkill'))).toBe(false)
+ })
+
+ it('removes the shared folder only when setup made it and nothing else is in it', () => {
+ const notMade = sandbox({ mark: false })
+ expect(notMade.result.status).toBe(0)
+ expect(notMade.gone(notMade.paths.SHARED)).toBe(false)
+ const shared = sandbox({ otherShared: true })
+ expect(shared.result.status).toBe(0)
+ expect(shared.gone(shared.paths.SHARED)).toBe(false)
+ expect(shared.gone(shared.paths.SHARED_MARK)).toBe(false)
+ expect(shared.gone(shared.paths.CONFIG)).toBe(true)
+ })
})
describe('real permission bits on a temporary folder', () => {
diff --git a/cli/src/team/script.ts b/cli/src/team/script.ts
index 3e25e27b6..5da6d015d 100644
--- a/cli/src/team/script.ts
+++ b/cli/src/team/script.ts
@@ -14,7 +14,7 @@
*/
import { TEAM_ENGINES } from './engines.js'
import {
- SENTINEL_NAME, TEAM_CONFIG_FILE, TEAM_LABEL, TEAM_PLIST, TEAM_SHARED_DIR, TEAM_STATUS_DIR,
+ SENTINEL_NAME, TEAM_CONFIG_FILE, TEAM_LABEL, TEAM_PLIST, TEAM_SHARED_DIR, TEAM_SHARED_MARK, TEAM_STATUS_DIR,
checkName, checkPath, checkPort, checkUser, teamPaths,
} from './layout.js'
@@ -201,6 +201,24 @@ export const TEAM_ENGINES_INSTALL = [
'done',
].join('\n')
+/**
+ * The team account's password. macOS lists only an account with one: macOS 26 hides an account whose password is `*`
+ * from Users & Groups. A random one, made here and forgotten: never printed, logged or stored, and never a process's
+ * argument, where `ps` shows it to every account. `printf` is the shell's own, and dscl reads the command from its
+ * input. Once: a repair run keeps the password there, and gives one to an account made before this (`*`). Set by root,
+ * so the account gets no secure token. Run inside the setup script, with $TEAM and die().
+ */
+export const TEAM_PASSWORD = [
+ 'if ! dscl . -read "/Users/$TEAM" AuthenticationAuthority 2>/dev/null | grep -q ";ShadowHash;"; then',
+ ` pw=$(LC_ALL=C tr -dc 'A-Za-z0-9' </dev/urandom | head -c 40)`,
+ ' [ "${#pw}" -eq 40 ] || die "could not make a password for the account $TEAM" 4',
+ ` printf 'passwd /Users/%s %s\\n' "$TEAM" "$pw" | dscl . >/dev/null 2>&1 || true`,
+ ' pw=',
+ ' dscl . -read "/Users/$TEAM" AuthenticationAuthority 2>/dev/null | grep -q ";ShadowHash;" \\',
+ ' || die "macOS did not take a password for the account $TEAM, so Users & Groups would not list it" 4',
+ 'fi',
+].join('\n')
+
/** Stdin to a file, as whoever runs it: the next name first, then a rename, so a reader never sees half of it. */
export const WRITE_PRIVATE = 'umask 077 && cat > "$1.next" && mv -f "$1.next" "$1"'
export const WRITE_PUBLIC = 'umask 022 && cat > "$1.next" && chmod 644 "$1.next" && mv -f "$1.next" "$1"'
@@ -249,6 +267,7 @@ export function buildSetupScript(input: SetupScriptInput): string {
`OWNER_NODE=${sh(ownerNode)}`,
`OWNER_CLI=${sh(ownerCli)}`,
`SHARED=${sh(TEAM_SHARED_DIR)}`,
+ `SHARED_MARK=${sh(TEAM_SHARED_MARK)}`,
`CONFIG=${sh(TEAM_CONFIG_FILE)}`,
`STATUS_DIR=${sh(TEAM_STATUS_DIR)}`,
`LABEL=${sh(TEAM_LABEL)}`,
@@ -285,8 +304,8 @@ export function buildSetupScript(input: SetupScriptInput): string {
'[ -f "$CLI_SRC/cli.js" ] || die "no installed Harness CLI at $CLI_SRC"',
'[ -x "$NODE_SRC/bin/node" ] || die "no Harness Node runtime at $NODE_SRC"',
'',
- '# 1. The account: a standard user named Harness Team, visible in System Settings > Users & Groups, whose',
- '# password is unusable, so nobody can sign in to it. An account by this name that is not ours is left alone.',
+ '# 1. The account: a standard user named Harness Team, listed in System Settings > Users & Groups. Its password is',
+ '# random and nobody knows it, so nobody can sign in to it. An account by this name that is not ours is left alone.',
'if dscl . -read "/Users/$TEAM" UniqueID >/dev/null 2>&1; then',
" existing=$(dscl . -read \"/Users/$TEAM\" NFSHomeDirectory 2>/dev/null | awk '{print $2}')",
' [ "$existing" = "$TEAM_HOME" ] || die "an account named $TEAM already exists and is not the Harness Team account; nothing was changed" 4',
@@ -294,13 +313,15 @@ export function buildSetupScript(input: SetupScriptInput): string {
' say "creating the account $TEAM_NAME ($TEAM)"',
' uid=$(free_id)',
' dscl . -create "/Users/$TEAM"',
+ // No way in while the record is being made: the random password below replaces this.
+ " dscl . -create \"/Users/$TEAM\" Password '*'",
' dscl . -create "/Users/$TEAM" UniqueID "$uid"',
' dscl . -create "/Users/$TEAM" NFSHomeDirectory "$TEAM_HOME"',
'fi',
'dscl . -create "/Users/$TEAM" RealName "$TEAM_NAME"',
'dscl . -create "/Users/$TEAM" PrimaryGroupID 20',
'dscl . -create "/Users/$TEAM" UserShell /bin/zsh',
- "dscl . -create \"/Users/$TEAM\" Password '*'",
+ TEAM_PASSWORD,
// Visible on purpose (see layout.ts): an earlier hidden setup is made visible again.
'dscl . -delete "/Users/$TEAM" IsHidden >/dev/null 2>&1 || true',
'if dseditgroup -o checkmember -m "$TEAM" admin >/dev/null 2>&1; then dseditgroup -o edit -d "$TEAM" -t user admin; fi',
@@ -343,8 +364,11 @@ export function buildSetupScript(input: SetupScriptInput): string {
`as_team /bin/sh -c ${sh(TEAM_ENGINES_INSTALL)} sh "$TEAM_HOME" "$NODE_NAME" ${TEAM_ENGINES.map((e) => sh(e.packageName)).join(' ')} || true`,
'',
'# 6. What setup made (root\'s), and the team account\'s status folder, which the owner can read.',
- 'if [ ! -d "$SHARED" ]; then mkdir -p "$SHARED"; chown 0:0 "$SHARED"; chmod 755 "$SHARED"; fi',
+ // A folder setup made says so, so that removal takes it away again once it is empty, and never one made by anything else.
+ 'made_shared=',
+ 'if [ ! -d "$SHARED" ]; then mkdir "$SHARED"; chown 0:0 "$SHARED"; chmod 755 "$SHARED"; made_shared=1; fi',
'owned_by_root "$SHARED"',
+ '[ -z "$made_shared" ] || : > "$SHARED_MARK"',
'install -o 0 -g 0 -m 0644 "$STAGE/team.json" "$CONFIG"',
'[ ! -L "$STATUS_DIR" ] || die "$STATUS_DIR is a symbolic link" 6',
'[ -d "$STATUS_DIR" ] || mkdir "$STATUS_DIR"',
@@ -394,24 +418,29 @@ export interface RemoveScriptInput {
user: string
home: string
ownerHome: string
- /** The team account's Node and CLI (from its config), run as that account to sign it out; null when unknown. */
- teamNode: string | null
- teamCli: string | null
- /** The backend settings the team daemon runs with, for that sign-out. */
- env?: Record<string, string>
}
+/** The exit status of a removal that deleted nothing because macOS kept the account: the team daemon runs again. */
+export const REMOVE_REFUSED = 9
+
+/** What the removal says last on success when it read the team account's computer id: `harness team remove` then takes
+ * that computer off the owner's Harness account, which ends its team sign-in (./command.ts). */
+export const TEAM_COMPUTER_LINE = /^harness: team computer ([A-Za-z0-9_-]{1,128})$/m
+
export function buildRemoveScript(input: RemoveScriptInput): string {
const user = checkUser(input.user, 'team account')
const home = checkPath(input.home, 'team home')
const ownerHome = checkPath(input.ownerHome, 'owner home')
- const teamNode = input.teamNode === null ? '' : checkPath(input.teamNode, 'team Node')
- const teamCli = input.teamCli === null ? '' : checkPath(input.teamCli, 'team CLI')
- const env = Object.entries(checkEnv(input.env ?? {})).map(([name, value]) => sh(`${name}=${value}`)).join(' ')
+ const paths = teamPaths(home)
return [
'#!/bin/sh',
- '# Harness Team account removal (cli/src/team/script.ts), run once as root behind the macOS administrator prompt.',
- '# It leaves the owner\'s home folder private, as setup made it.',
+ '# Harness Team account removal (cli/src/team/script.ts), run once as root: behind the macOS administrator prompt, or',
+ '# with sudo in a terminal. It leaves the owner\'s home folder private, as setup made it.',
+ '#',
+ '# The account goes first, before anything that cannot be undone. macOS 26 deletes an account only for an app the',
+ '# person allowed to administer the computer (Privacy & Security\'s "administer your computer"). It cannot ask that',
+ '# for the administrator prompt\'s own process, or for a LaunchDaemon, and refuses them (eDSPermissionError); it',
+ '# asks it for a terminal app. When it refuses, the team daemon runs again and nothing else has changed.',
'set -eu',
'cd /',
`die() { printf 'harness: %s\\n' "$1" >&2; exit "\${2:-1}"; }`,
@@ -422,38 +451,90 @@ export function buildRemoveScript(input: RemoveScriptInput): string {
`PLIST=${sh(TEAM_PLIST)}`,
`CONFIG=${sh(TEAM_CONFIG_FILE)}`,
`STATUS_DIR=${sh(TEAM_STATUS_DIR)}`,
+ `SHARED=${sh(TEAM_SHARED_DIR)}`,
+ `SHARED_MARK=${sh(TEAM_SHARED_MARK)}`,
`SENTINEL=${sh(`${ownerHome}/${SENTINEL_NAME}`)}`,
- `TEAM_NODE=${sh(teamNode)}`,
- `TEAM_CLI=${sh(teamCli)}`,
+ `COMPUTER_ID=${sh(paths.computerId)}`,
+ // What Users & Groups leaves when the account is deleted there with "Don't change the home folder".
+ `DELETED_HOME=${sh(`${home} (Deleted)`)}`,
'[ "$(id -u)" = 0 ] || die "run as root"',
'exists=',
+ 'team_uid=',
'if dscl . -read "/Users/$TEAM" UniqueID >/dev/null 2>&1; then',
' exists=1',
" existing=$(dscl . -read \"/Users/$TEAM\" NFSHomeDirectory 2>/dev/null | awk '{print $2}')",
' [ "$existing" = "$TEAM_HOME" ] || die "the account $TEAM is not the Harness Team account (its home is $existing); nothing was removed" 4',
+ ' team_uid=$(id -u "$TEAM")',
'fi',
- 'if [ -e "$TEAM_HOME" ] && [ ! -L "$TEAM_HOME" ]; then',
- // A home left by a team account deleted earlier is owned by a bare user id; anyone else's is not ours to delete.
- ' holder=$(stat -f %Su "$TEAM_HOME")',
+ // A home left by a team account deleted earlier (in Users & Groups, say) is owned by a bare user id; anyone else's is
+ // not ours to delete. That id has no account, so whatever still runs under it was the team account's. By number:
+ // `stat -f %Su` prints such an owner as "(600)" on macOS 26.
+ 'for left in "$TEAM_HOME" "$DELETED_HOME"; do',
+ ' [ -e "$left" ] && [ ! -L "$left" ] || continue',
+ ' holder_uid=$(stat -f %u "$left")',
+ ' holder=$(id -un "$holder_uid" 2>/dev/null) || holder=',
' case $holder in',
' "$TEAM"|root) ;;',
- ' *[!0-9]*) die "$TEAM_HOME belongs to $holder; nothing was removed" 4 ;;',
+ ' \'\') [ -n "$team_uid" ] || team_uid=$holder_uid ;;',
+ ' *) die "$left belongs to $holder; nothing was removed" 4 ;;',
' esac',
+ 'done',
+ // Read as the team account, never followed as root, and only in the form a computer id has.
+ 'computer=',
+ 'if [ -n "$exists" ]; then',
+ ' computer=$(/usr/bin/sudo -n -u "$TEAM" /bin/cat "$COMPUTER_ID" 2>/dev/null | head -n 1) || computer=',
+ ' case $computer in \'\'|*[!A-Za-z0-9_-]*) computer= ;; esac',
+ ' [ "${#computer}" -le 128 ] || computer=',
'fi',
- '# Sign the team account out of Harness while it still can, as that account and with its own CLI.',
- 'if [ -n "$exists" ] && [ -n "$TEAM_NODE" ] && [ -x "$TEAM_NODE" ] && [ -f "$TEAM_CLI" ]; then',
- ` /usr/bin/sudo -n -H -u "$TEAM" /usr/bin/env ${env ? `${env} ` : ''}"$TEAM_NODE" "$TEAM_CLI" team __signout >/dev/null 2>&1 \\`,
- ' || say "could not sign the team account out of Harness; that sign-in lapses after 90 days unused"',
- 'fi',
+ '',
+ '# 1. The team daemon stops, so it starts nothing while the account goes. Its agents keep running in tmux.',
'launchctl bootout "system/$LABEL" >/dev/null 2>&1 || true',
- 'rm -f "$PLIST"',
+ '',
+ '# 2. The account. When macOS keeps it, the daemon starts again, as setup starts it, and nothing else was changed.',
'if [ -n "$exists" ]; then',
- ' pkill -KILL -u "$TEAM" >/dev/null 2>&1 || true',
- ' sleep 1',
- ' dscl . -delete "/Users/$TEAM"',
+ ' if ! why=$(dscl . -delete "/Users/$TEAM" 2>&1); then',
+ ' why=$(printf \'%s\\n\' "$why" | tail -n 1)',
+ ' again=no',
+ ' if [ -f "$PLIST" ]; then',
+ ' tries=0',
+ ' until launchctl bootstrap system "$PLIST" >/dev/null 2>&1; do',
+ ' tries=$((tries + 1)); [ "$tries" -lt 5 ] || break',
+ ' launchctl bootout "system/$LABEL" >/dev/null 2>&1 || true; sleep 1',
+ ' done',
+ ' launchctl print "system/$LABEL" >/dev/null 2>&1 && again=yes',
+ ' fi',
+ ' case $why in *eDSPermissionError*) why="macOS did not allow it (eDSPermissionError)" ;; esac',
+ ` [ "$again" = yes ] || die "could not delete the account $TEAM: $why. Nothing was removed, but the team daemon did not start again: harness team setup starts it" ${REMOVE_REFUSED}`,
+ ` die "could not delete the account $TEAM: $why. Nothing was removed: the Harness Team account and its daemon run as before" ${REMOVE_REFUSED}`,
+ ' fi',
+ ' say "deleted the account $TEAM"',
+ 'fi',
+ '',
+ '# 3. What it left: its processes, its daemon\'s definition, its home, what setup made and the privacy sentinel.',
+ 'if [ -n "$team_uid" ] && [ "$team_uid" -gt 500 ]; then pkill -KILL -u "$team_uid" >/dev/null 2>&1 || true; sleep 1; fi',
+ // An account deleted elsewhere cannot be asked for its computer id: read it from the home it left, now that nothing
+ // runs under its id, only from a plain file that id owns, never through a link.
+ 'if [ -z "$exists" ] && [ -n "$team_uid" ]; then',
+ ' for left in "$TEAM_HOME" "$DELETED_HOME"; do',
+ ' f="$left/.harness/computer-id"',
+ ' [ ! -L "$left" ] && [ ! -L "$left/.harness" ] && [ ! -L "$f" ] && [ -f "$f" ] || continue',
+ ' [ "$(stat -f %u "$f")" = "$team_uid" ] || continue',
+ ' computer=$(head -n 1 "$f") || computer=',
+ ' case $computer in \'\'|*[!A-Za-z0-9_-]*) computer= ;; esac',
+ ' [ "${#computer}" -le 128 ] || computer=',
+ ' [ -z "$computer" ] || break',
+ ' done',
'fi',
+ 'rm -f "$PLIST"',
'rm -rf "$TEAM_HOME" "$STATUS_DIR"',
+ '[ ! -e "$DELETED_HOME" ] || [ -L "$DELETED_HOME" ] || rm -rf "$DELETED_HOME"',
'rm -f "$CONFIG" "$SENTINEL"',
+ // The shared folder, only when setup made it and nothing else has been put in it since.
+ `if [ -f "$SHARED_MARK" ] && [ ! -L "$SHARED" ] && [ -z "$(ls -A "$SHARED" | grep -vx ${sh(basename(TEAM_SHARED_MARK))} || true)" ]; then`,
+ ' rm -f "$SHARED_MARK"',
+ ' rmdir "$SHARED" 2>/dev/null || true',
+ 'fi',
+ '[ -z "$computer" ] || say "team computer $computer"',
'say "removed the Harness Team account, its home folder and its daemon"',
'',
].join('\n')
diff --git a/docs/plans/2026-10-24-swarm-team-account.md b/docs/plans/2026-10-24-swarm-team-account.md
index 78e4da59a..8d2a375fb 100644
--- a/docs/plans/2026-10-24-swarm-team-account.md
+++ b/docs/plans/2026-10-24-swarm-team-account.md
@@ -156,3 +156,49 @@ VMs; team accounts on Windows and Linux (dedicated machines use `harness team on
**Not exercised.** A real owner sign-in, and minting and redeeming against production. A real owner today takes the stand-in's path: the code is minted without `kind`, and the redeemed session has no `kind`, so it is revoked. Also not exercised: a team daemon signing in through setup; Desktop's automatic setup (join, contribute, startup); the 5-minute recheck while serving a Swarm (kickstart was used instead); finishing engine sign-in (a device code needs a person); and a Swarm start landing in the team account.
Tests: `npx vitest run src/team src/superTabs/machines.spec.ts src/superTabs/service.spec.ts`: 209 passed. `npm run typecheck` is clean.
+
+## Validation, second VM run (24 Oct 2026)
+
+Fixes for open bugs 5, 6 and 7, checked in another fresh VM from the same image (macOS 26.6.2, build 25G83). The CLI was bundled from this branch and installed by the real installer from a local manifest. The owner sign-in and the backend were the loopback stand-ins of the first run; the stand-in also answered `GET /api/machines` and `DELETE /api/machines/:id`, and redeemed codes as `kind: "team"`, so the team account was signed in (`hta_`/`htr_`) throughout. Nothing ran on a developer's own Mac.
+
+**What changed.**
+- *Bug 5.* Setup gives the account a 40-character random password, made in the root script from `/dev/urandom` and handed to dscl on its input (`printf 'passwd …' | dscl .`; `printf` is the shell's own), never printed, logged, stored or on a command line. Only when the account has no `ShadowHash` authority, so a repair run keeps it and an account made by the first version gets one. Root sets it, so the account has no secure token.
+- *Bug 6.* Removal deletes the account first, after only stopping the daemon. When macOS refuses, it starts the daemon again and exits 9 with nothing else changed. In a terminal, `harness team remove` runs the script with sudo there instead of the dialog. The team sign-in now ends from the owner's side after the account is gone: the script names the team computer, and the owner's CLI deletes that team machine from the account, which signs its session out (#1691). The script no longer runs `team __signout`.
+- *Bug 7.* Setup marks `/Library/Application Support/Harness` when it creates it; removal deletes it only when marked and empty. A folder made by the first version is left in place.
+- A repair run's dialog says "Harness wants to repair the Harness Team account…". The dialog's title stays "osascript": osascript cannot change it.
+- `lib/guestHelperInstall.ts` splits osascript's stderr on CR and LF, as `team/admin.ts` does.
+
+**What macOS 26 lets delete an account.** Each was run as root through the real administrator prompt on throwaway accounts, except where noted.
+
+| Mechanism | Result |
+|---|---|
+| `dscl . -delete /Users/x` | ✗ `DS Error: -14120 (eDSPermissionError)` |
+| `sysadminctl -deleteUser x` | ✗ record kept, `### Error:-14120`, but exit 0, after it had already killed the account's processes and deleted its home (`-keepHome` "is not available on this system") |
+| one-shot LaunchDaemon (`launchctl bootstrap`) running `dscl . -delete` | ✗ -14120 |
+| the same job running `sysadminctl -deleteUser` | ✗ as above |
+| `launchctl submit … dscl . -delete` | ✗ -14120 |
+| `sudo dscl . -delete` in Terminal | macOS asks "Terminal would like to administer your computer". Don't Allow: -14120; Allow: ✓ |
+| System Settings > Users & Groups > Delete User | ✓ |
+| setting a password (`dscl` from input, `dscl . -passwd`), deleting an attribute | ✓ through the prompt |
+
+The unified log gives the reason. opendirectoryd has sandboxd ask TCC for `kTCCServiceSystemPolicyAllFiles`, then `kTCCServiceSystemPolicySysAdminFiles`, for the responsible process. Behind the prompt that process is `authtrampoline`, and TCC answers "Platform binary prompting is 'Deny'", so no prompt appears. A Terminal decision lives in the person's TCC database, and `tccutil reset SystemPolicySysAdminFiles com.apple.Terminal` makes macOS ask again. Over ssh, the first run's delete worked because `sshd-keygen-wrapper` has Full Disk Access (Remote Login's).
+
+| Step | Result |
+|---|---|
+| Setup through the real prompt | ✓ create dialog, exit 0, `✓ The Harness Team account is signed in.`, `✓ Private`. A `ps` sampler during setup (2.1 million lines) saw the root `dscl .` with no other argument and no 40-character token anywhere |
+| Listed in Users & Groups | ✓ "Harness Team · Standard" (it was hidden in the first run). `Password: ********`, `;ShadowHash;HASHLIST:<SALTED-SHA512-PBKDF2,SRP-RFC5054-4096-SHA512-PBKDF2>`, `Secure token is DISABLED`, not in `admin` |
+| Login window | ✓ lists Harness Team. A guessed password is refused (`Authentication failed … ODErrorCredentialsInvalid` for its GeneratedUID); `dscl /Local/Default -authonly harnessteam ''` and a guess give `eDSAuthFailed` |
+| Privacy check | ✓ `Private ✓`; `cat`/`ls` of the sentinel, `/Users/admin`, `~/.gitconfig` and `~/code` as `harnessteam` each give `Permission denied` |
+| Repair run | ✓ repair dialog. Before/after snapshot: same uid 600, same password (`ShadowHashData` SHA-256 `895034f17cc5a78b`), same session file, same plist; only the job's pid changed |
+| Removal through the prompt (not a terminal) | ✗ as expected, safely: `✗ macOS kept the Harness Team account: could not delete the account harnessteam: macOS did not allow it (eDSPermissionError). Nothing was removed: the Harness Team account and its daemon run as before.`, then both ways to finish. Afterwards: account, password, session file, plist and shared folder unchanged, daemon running again (`privacy check passed` 8 s later), `sign-in ✓`; the stand-in saw no revoke, no machine call |
+| Removal in Terminal | ✓ `sudo` asked for the password with the dialog's sentence, macOS asked to let Terminal administer the computer, Allow: `✓ Removed …`, `✓ Took its computer off your Harness account, which signs it out.` The stand-in logged `GET /api/machines` and `DELETE /api/machines/<the team machine>` only, never the owner's |
+| Removal in Terminal, Don't Allow | ✓ nothing removed and the daemon runs again; the message gives `tccutil reset SystemPolicySysAdminFiles com.apple.Terminal` |
+| Users & Groups, then `harness team remove` again | ✓ with "Don't change the home folder" (macOS renames it `/Users/harnessteam (Deleted)`, owned by uid 600) the removal stops the account's leftover processes, deletes that folder and the rest, and takes its computer off the account |
+| Nothing left behind | ✓ no account, home, plist, job, uid-600 process, sentinel, staging folder or `/Library/Application Support/Harness`; `status`: `No Harness Team account on this computer.` |
+| `/Users/admin` | ✓ `drwx------` after every removal |
+
+Three bugs found here were fixed and checked again in the VM. The team computer id is read from `~/.harness/computer-id`, not the data folder. A home left by an account deleted elsewhere is judged by uid, because `stat -f %Su` prints such an owner as `(600)` on macOS 26; the first version's check refused it. The removal also handles the `(Deleted)` folder Users & Groups leaves. Setup, the Users & Groups fallback and removal in Terminal were run again with that bundle. One more fix came after the VM was deleted. The backend keeps a computer id lower case and without dashes (`normalizeComputerId`), while the stand-in listed the id as the team account's file holds it. The CLI now compares both in the backend's form; a spec covers it, and the VM did not run it.
+
+**Not exercised.** Removal through the prompt with the deletion allowed (macOS 26 has no way). `harness team remove` from a terminal other than Terminal.app, or inside a Harness pane, where the responsible process is the daemon's Node. A real owner sign-in, production minting, redeeming and machine deletion: the stand-ins answered, so the team session ending with its machine rests on #1691's backend tests. Desktop's automatic setup. A team account made by the first version, repaired to get a password. The guest helper's install: its parsing fix has a spec only. In the VM image `admin` has passwordless sudo; that file was moved aside to see sudo's prompt, then put back. Rig: tart's VNC server crashed the VM five times on connect; `vmn-start` brought it back each time.
+
+Tests: `npx vitest run src/team src/lib/guestHelperInstall.spec.ts src/superTabs/machines.spec.ts src/superTabs/service.spec.ts src/services/guestLaunches.spec.ts src/services/sharedMachines.spec.ts src/cliCommand.spec.ts src/architecture.spec.ts`: 318 passed. `npm run typecheck` is clean. No coverage gate covers `src/team` or `src/lib/guestHelperInstall.ts`.