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
CLI: a Harness Team account on a Mac for Swarm work, with a privacy check (#1688)
Dee9e98fda7cf13
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 430450af8..c5499f4a8 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -157,6 +157,11 @@ Machine:harness service uninstall undo that: the daemon goes back to \`harness start\`harness service status what launchd, systemd or Task Scheduler has registered, and whether it runs (--json)harness logs export zip the last 7 days of logs (app, CLI, dial, daemon) to the Desktop+ 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 on|off a computer used only for agents: sign it in for team work only, or back as your ownharness tui all of Harness in this terminal: swarms, panes, every machine (⌥O ⌥P ⌥N)harness new [agent] [--machine <name>] [folder|name] [-- task]make a harness from a shell: \`harness new\` is claude here; see \`harness new -h\`@@ -365,12 +370,14 @@ async function authStatusCommand(json: boolean): Promise<void> {autonomousEnv: latest?.autonomousEnv,expiresAt: latest?.expiresAt,method: latest?.method ?? 'sso',+ // A Harness Team sign-in (team/): this computer runs its own Swarm agents and reaches no other computer.+ ...(latest?.kind ? { kind: latest.kind } : {}),// Read-only: a machine that has not signed in yet has no key, and asking must not make one....(fingerprintNow ? { fingerprint: fingerprintNow } : {}),}if (json) console.log(JSON.stringify(payload))else {- console.log(`\n ${payload.loggedIn ? '✓ Signed in' : '✗ Not signed in'}${payload.machineId ? ` (machine ${payload.machineId})` : ''}${payload.loggedIn && payload.method === 'qr' ? ' — by your phone' : ''}\n`)+ console.log(`\n ${payload.loggedIn ? '✓ Signed in' : '✗ Not signed in'}${payload.machineId ? ` (machine ${payload.machineId})` : ''}${payload.loggedIn && payload.kind === 'team' ? ' — for team work only (harness team off undoes it)' : payload.loggedIn && payload.method === 'qr' ? ' — by your phone' : ''}\n`)// A session a phone approved is Harness's own, and billing's Autonomous service does not take it.// Say so where the person looks, not only when billing refuses. Grid is not named: it learns who// holds a Harness-issued sign-in from the Harness backend (autonomous-grid ADR 0046), and naming@@ -2935,6 +2942,21 @@ switch (cmd) {serviceCommand(rest, serviceCommandDeps({ relaunch: () => launch(false), tildify })).then((code) => { process.exitCode = code }).catch(onError)break+ case 'team':+ // Loaded only here (team/deps.ts). The daemon is stopped before a sign-in changes under it and started again on the+ // new one; `launch` prints its status block and exits, so it is always the last step.+ Promise.all([import('./team/command.js'), import('./team/deps.js')])+ .then(([{ teamCommand }, { teamCommandDeps }]) => teamCommand(rest, teamCommandDeps({+ stopDaemon: async () => (await stopDaemonOrExit()).pid !== null,+ startDaemon: () => launch(false),+ signIn: async (restart) => {+ const outcome = await loginCommand(false, false, false, { method: 'ask' })+ if (outcome.signedIn) await restartDaemonForIdentity(restart)+ else if (restart) await launch(false)+ },+ })))+ .then((code) => { process.exitCode = code }).catch(onError)+ breakcase 'reset':resetCommand().catch(onError)breakdiff --git a/cli/src/lib/authSession.spec.ts b/cli/src/lib/authSession.spec.tsindex 74cd24793..5d532f4dc 100644--- a/cli/src/lib/authSession.spec.ts+++ b/cli/src/lib/authSession.spec.ts@@ -136,6 +136,16 @@ describe('AuthSessionManager', () => {expect(readAuthSession()).not.toHaveProperty('clientId')})+ // A Harness Team sign-in (cli/src/team/) keeps its kind through every rewrite; any other kind reads as a computer's.+ it('keeps a team sign-in\'s kind, and reads no other', async () => {+ writeAuthSession({ ...baseSession(), kind: 'team' })+ expect(readAuthSession()?.kind).toBe('team')+ new AuthSessionManager('http://backend.invalid').updateMachineId('machine-2')+ expect(readAuthSession()).toMatchObject({ kind: 'team', machineId: 'machine-2' })+ await writeFile(AUTH_SESSION_FILE, JSON.stringify({ ...baseSession(), kind: 'admin' }))+ expect(readAuthSession()).not.toHaveProperty('kind')+ })+// `process.exit` skips `finally`: a daemon that exited mid-refresh left the lock for the next// `harness auth status` to wait out (30s), which is how long the desktop app waits for it.it('drops the refresh lock when the process exits while holding it, and only then', async () => {diff --git a/cli/src/lib/authSession.ts b/cli/src/lib/authSession.tsindex 6f6a24385..9f2e638c0 100644--- a/cli/src/lib/authSession.ts+++ b/cli/src/lib/authSession.ts@@ -15,6 +15,9 @@ export interface AuthSession {* billing's Autonomous service does not take; grid does, through the Harness backend —* autonomous-grid ADR 0046); absent or `sso` — the browser. */method?: 'sso' | 'qr'+ /** `team`: a Harness Team sign-in (cli/src/team/), which runs this computer's own daemon and its Swarm agents and+ * reaches none of the account's other computers. Absent: a computer's ordinary sign-in. */+ kind?: 'team'/** The auth-service client these tokens were issued to, as the backend's exchange reported it.* A refresh has to name the same one. Absent is the backend's configured client. */clientId?: SsoClientId@@ -71,6 +74,7 @@ function parse(raw: string): AuthSession | null {computerId: value.computerId,...(typeof value.machineId === 'string' && value.machineId ? { machineId: value.machineId } : {}),...(value.method === 'qr' || value.method === 'sso' ? { method: value.method } : {}),+ ...(value.kind === 'team' ? { kind: 'team' as const } : {}),...(knownSsoClientId(value.clientId) ? { clientId: knownSsoClientId(value.clientId) } : {}),updatedAt: typeof value.updatedAt === 'number' ? value.updatedAt : 0,...(typeof value.signInEpoch === 'string' && value.signInEpoch ? { signInEpoch: value.signInEpoch } : {}),diff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.tsindex ecf6e8d7c..48c00c113 100644--- a/cli/src/superTabs/machines.spec.ts+++ b/cli/src/superTabs/machines.spec.ts@@ -8,8 +8,9 @@ import { fakeCore } from '../testing/fakeCore.js'import { apisOn, ContributedMachines, liveOn, offered, refusedOn, servedOn, sharedWith, swarmWorktreesFile } from './machines.js'import { SuperTabHostError } from './host.js'import { startAgent } from './start.js'+import type { PrivacyObservation } from '../team/privacy.js'-function fixture(env: NodeJS.ProcessEnv = {}) {+function fixture(env: NodeJS.ProcessEnv = {}, privacy: () => PrivacyObservation | null = () => null) {let now = 1000const core = fakeCore({ dataDir: '/isolated-pool-fixture', agents: {byAgent: vi.fn(id => id === 'running' ? { agentId: id } as never : undefined),@@ -25,7 +26,7 @@ function fixture(env: NodeJS.ProcessEnv = {}) {const start = vi.fn(async () => ({ ok: true }))const prepare = vi.fn(async () => {})const log = vi.fn()- const machine = new ContributedMachines(core, 'host', { backend, open, capabilities, start, prepare, log, env, now: () => now } as never)+ const machine = new ContributedMachines(core, 'host', { backend, open, capabilities, start, prepare, log, env, privacy, now: () => now } as never)return { machine, pool, core, backend, open, request, close, capabilities, start, prepare, log, advance: () => { now += 16000 }, step: (ms: number) => { now += ms } }}@@ -283,6 +284,109 @@ describe('contributed machine executor', () => {expect(read[0]!.name).toHaveLength(200)})+ // The Harness Team account (cli/src/team/): its daemon reports its privacy check with the reading, and refuses new+ // work while it fails, besides routing (Task 3) not sending it any.+ describe('Harness Team privacy', () => {+ const passed: PrivacyObservation = { mode: 'account', passed: true, checkedAt: 900 }+ const exposed: PrivacyObservation = { mode: 'account', passed: false, item: 'gitconfig', detail: 'The team account could read ~/.gitconfig.', checkedAt: 900 }+ const posts = (f: ReturnType<typeof fixture>) => f.backend.mock.calls.filter(c => c[1] === 'POST' && String(c[2]).includes('/machines/')).map(c => c[3] as Record<string, unknown>)++ it('sends the check with the reading, and nothing from the owner\'s own daemon', async () => {+ const team = fixture({}, () => passed)+ await team.machine.tick()+ expect(posts(team)[0]).toMatchObject({ privacy: passed })+ expect(team.start).toHaveBeenCalledOnce()+ const owner = fixture()+ await owner.machine.tick()+ expect(posts(owner)[0]).not.toHaveProperty('privacy')+ const dedicated = fixture({}, () => ({ mode: 'dedicated' }))+ await dedicated.machine.tick()+ expect(posts(dedicated)[0]).toMatchObject({ privacy: { mode: 'dedicated' } })+ expect(dedicated.start).toHaveBeenCalledOnce()+ })++ it('refuses a new start while the team account is not private, and never starts it anywhere else', async () => {+ const f = fixture({}, () => exposed)+ await f.machine.tick()+ expect(f.start).not.toHaveBeenCalled()+ const refusal = f.backend.mock.calls.find(c => String(c[2]).endsWith('/starts/tab/start'))![3] as { operationId: string; command: Record<string, unknown> }+ expect(refusal.operationId).toBe('privacy-failed-start')+ expect(refusal.command).toMatchObject({ type: 'agent.startFailed', startId: 'start' })+ expect(String(refusal.command.error)).toContain('not private (gitconfig)')+ // One already dispatched is reconciled as before: refusing it could orphan what it launched.+ f.pool.starts[0]!.dispatched = true+ f.advance(); await f.machine.tick()+ expect(f.start).toHaveBeenCalledOnce()+ })++ it('sends a changed result at once, without waiting for the next beat', async () => {+ let current: PrivacyObservation = passed+ const f = fixture({}, () => current)+ await f.machine.tick()+ f.step(6_000); await f.machine.tick()+ expect(posts(f)).toHaveLength(1)+ current = exposed+ f.step(6_000); await f.machine.tick()+ expect(posts(f)).toHaveLength(2)+ expect(posts(f)[1]).toMatchObject({ privacy: { passed: false, item: 'gitconfig' } })+ })++ it('reports a check that throws as unchecked, and refuses on it', async () => {+ const f = fixture({}, () => { throw new Error('config unreadable') })+ await f.machine.tick()+ expect(posts(f)[0]).toMatchObject({ privacy: { mode: 'account', passed: false, item: 'unchecked' } })+ expect(f.start).not.toHaveBeenCalled()+ })++ it('drops only the privacy field for a backend from before it, for ten minutes, keeping the local-model fields', async () => {+ const f = fixture({}, () => passed)+ f.capabilities.mockResolvedValue({ ok: true, resources: { cpuPercent: 20, memoryTotalBytes: 1000, memoryUsedBytes: 200, projectDiskFreeBytes: 1000 },+ tools: { git: true }, toolProbeErrors: { flutter: 'timed out' } } as never)+ const original = f.backend.getMockImplementation()!+ f.backend.mockImplementation(async (core, method, path, body) => {+ if (method === 'POST' && (body as Record<string, unknown>)?.privacy) throw new SuperTabHostError('VALIDATION_ERROR', 'Unrecognized key: privacy', 400)+ return original(core, method, path, body)+ })+ await f.machine.tick()+ expect(posts(f)).toHaveLength(2)+ expect(posts(f)[1]).not.toHaveProperty('privacy')+ expect(posts(f)[1]).toHaveProperty('toolProbeErrors')+ f.advance(); await f.machine.tick()+ expect(posts(f)).toHaveLength(3)+ expect(posts(f)[2]).not.toHaveProperty('privacy')+ f.step(10 * 60_000); await f.machine.tick()+ expect(posts(f).at(-2)).toHaveProperty('privacy')+ expect(posts(f).at(-1)).not.toHaveProperty('privacy')+ })++ it('falls back to the oldest reading when the backend refuses the other new fields too', async () => {+ const f = fixture({}, () => passed)+ f.capabilities.mockResolvedValue({ ok: true, resources: { cpuPercent: 20, memoryTotalBytes: 1000, memoryUsedBytes: 200, projectDiskFreeBytes: 1000 },+ tools: { git: true }, toolProbeErrors: { flutter: 'timed out' } } as never)+ const original = f.backend.getMockImplementation()!+ f.backend.mockImplementation(async (core, method, path, body) => {+ const sent = body as Record<string, unknown>+ if (method === 'POST' && (sent?.privacy || sent?.toolProbeErrors)) throw new SuperTabHostError('VALIDATION_ERROR', 'Unrecognized key', 400)+ return original(core, method, path, body)+ })+ await f.machine.tick()+ expect(posts(f)).toHaveLength(3)+ expect(posts(f)[2]).not.toHaveProperty('privacy')+ expect(posts(f)[2]).not.toHaveProperty('toolProbeErrors')+ })++ it('does not retry a refusal that is not about the fields', async () => {+ const f = fixture({}, () => passed)+ const original = f.backend.getMockImplementation()!+ f.backend.mockImplementation(async (core, method, path, body) => {+ if (method === 'POST' && String(path).includes('/machines/')) throw new SuperTabHostError('FORBIDDEN', 'no', 403)+ return original(core, method, path, body)+ })+ await expect(f.machine.tick()).resolves.toBeUndefined()+ expect(posts(f)).toHaveLength(1)+ })+ })+it('binds stopped native proof to the current slot reservation generation', async () => {const f = fixture()Object.assign(f.pool, { reservations: [{ harnessId: 'stopped', generation: 'new-contribution' }] })diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.tsindex 320162202..63f698602 100644--- a/cli/src/superTabs/machines.ts+++ b/cli/src/superTabs/machines.ts@@ -13,6 +13,8 @@ import { createSwarmCloneTrustRepair, swarmCloneRoots } from './cloneTrust.js'import { git } from '../lib/worktreeSweep.js'import { projectsRoot } from '../lib/projectFolder.js'import { worktreeFolderName } from '../lib/agentNames.js'+import { teamPrivacyObserver } from '../team/observer.js'+import type { PrivacyObservation } from '../team/privacy.js'const finite = (v: unknown) => typeof v === 'number' && Number.isFinite(v) ? v : nullconst list = (v: unknown) => Array.isArray(v) ? v.map(object) : []@@ -20,6 +22,9 @@ const list = (v: unknown) => Array.isArray(v) ? v.map(object) : []// include tools from pending starts. An uncommon tool first named during routing remains unverified and is refused.const COMMON_TOOLS = ['git', 'node', 'npm', 'flutter', 'gh', 'cargo', 'python3']const VERIFIED_TOOL_TTL_MS = 10 * 60_000+/** After a backend refuses the privacy field (one from before the Harness Team account), how long the reading goes+ * without it before the field is offered again: a backend deployed meanwhile is heard from within this long. */+const PRIVACY_REFUSED_MS = 10 * 60_000const UNVERIFIED_TOOL_TTL_MS = 60_000/** How often the executor asks the backend what its tabs want of it (a start waiting, a pause) and compares what it@@ -89,6 +94,15 @@ export class ContributedMachines {private readonly cleaning = new Map<string, Promise<void>>()/** Per removal whose cleanup or acknowledgement failed, how often and when it may run again. */private readonly cleanupRetries = new Map<string, { failures: number; at: number }>()+ /** Until when the reading leaves out its privacy field, which the backend refused. */+ private privacyRefusedUntil = 0+ /** This pass's privacy reading, read once a pass (the check itself runs at most every five minutes). */+ private privacy(): PrivacyObservation | null {+ try { return (this.deps.privacy ?? teamPrivacyObserver)() } catch (error) {+ // A check that could not run is not a pass: a team account reports it unchecked, never private.+ return { mode: 'account', passed: false, item: 'unchecked', detail: `The privacy check did not run: ${error instanceof Error ? error.message : String(error)}`, checkedAt: this.deps.now() }+ }+ }/** The grids this machine reads, at most once a minute: every Swarm's reading shares it. */private gridModelsRead: { at: number; answer: unknown } | null = nullprivate async gridModels(local: { request: (type: string, payload: Record<string, unknown>, timeoutMs: number) => Promise<unknown> }): Promise<unknown> {@@ -101,7 +115,9 @@ export class ContributedMachines {}constructor(private readonly core: CoreApi, private readonly machineId: string,private readonly deps: { backend: typeof backend; open: typeof openDaemon; capabilities: typeof readCapabilities;- start: typeof startAgent; now: () => number; prepare?: typeof prepareSwarmProject; log?: (message: string) => void; env?: NodeJS.ProcessEnv } =+ start: typeof startAgent; now: () => number; prepare?: typeof prepareSwarmProject; log?: (message: string) => void; env?: NodeJS.ProcessEnv+ /** The Harness Team account's privacy check (team/privacy.ts): null for the owner's own daemon. */+ privacy?: () => PrivacyObservation | null } ={ backend, open: openDaemon, capabilities: readCapabilities, start: startAgent, now: Date.now }) {}stop() { this.stopped = true }/** DESKTOP-0TFH0OJ, 2026-10-23: every Claude start there was refused (CLI 0.4.57 took an API-key Claude for one not@@ -129,6 +145,7 @@ export class ContributedMachines {const pendingIds = new Set(pools.flatMap(row => list(row.starts).map(start => start.id)))for (const id of this.waiting.keys()) if (!pendingIds.has(id)) this.waiting.delete(id)for (const tab of this.published.keys()) if (!pools.some(row => row.tabId === tab)) this.published.delete(tab)+ const privacy = this.privacy()// The local daemon is reached only for a reading to send, never for a pass that has nothing to say.let local: Awaited<ReturnType<typeof openDaemon>> | null = nulllet usage: Record<string, unknown> | null = null@@ -148,7 +165,9 @@ export class ContributedMachines {return Array.isArray(wanted) ? wanted.filter((name): name is string => typeof name === 'string' && /^[A-Za-z0-9_.+-]{1,80}$/.test(name)) : []})])].slice(0, 20)const signature = JSON.stringify([row.reservations, pool.generation, [...running].sort(), [...stopped].sort(), row.paused === true || pool.paused === true,- pending.map(start => start.id).sort()])+ pending.map(start => start.id).sort(),+ // A privacy result that changes (a home folder opened again) is sent at once, not on the next beat.+ privacy ? [privacy.mode, 'passed' in privacy ? privacy.passed : null, 'item' in privacy ? privacy.item : null] : null])const last = this.published.get(String(row.tabId))if (!last || last.signature !== signature || began - last.at >= MACHINE_HEARTBEAT_MS) {local ??= await this.deps.open(where)@@ -199,6 +218,7 @@ export class ContributedMachines {await local.request('grid_swarm_offers', { grid: row.localGrid }, 10_000).catch(() => ({}))),].slice(0, MAX_LOCAL_MODELS) : nullconst observation = { generation: pool.generation, tools: reportedTools, ...(localModels ? { localModels } : {}),+ ...(privacy && began >= this.privacyRefusedUntil ? { privacy } : {}),...(refusedModels.length ? { refusedModels } : {}),...(Object.keys(toolProbeErrors).length ? { toolProbeErrors } : {}),resources: { cpuPercent: finite(resources.cpuPercent), memoryUsedBytes: finite(resources.memoryUsedBytes), memoryTotalBytes: finite(resources.memoryTotalBytes),@@ -215,12 +235,22 @@ export class ContributedMachines {&& identifier(r.harnessId) && identifier(r.generation)).map(r => ({ harnessId: r.harnessId, generation: r.generation })) } : {}) }try {const path = `/api/super-tabs/${row.tabId}/machines/${this.machineId}`- try { await this.deps.backend(this.core, 'POST', path, observation) }- catch (error) {- if (!(error instanceof SuperTabHostError) || error.status !== 400 || error.code !== 'VALIDATION_ERROR' || !('toolProbeErrors' in observation || 'localModels' in observation || 'refusedModels' in observation)) throw error- // Older backends reject the additive fields. Their boolean-only view still safely refuses an unverified tool.- const { toolProbeErrors: _probeErrors, localModels: _served, refusedModels: _refused, ...legacy } = observation- await this.deps.backend(this.core, 'POST', path, legacy)+ const refused = (error: unknown) => error instanceof SuperTabHostError && error.status === 400 && error.code === 'VALIDATION_ERROR'+ // Older backends reject the additive fields. The privacy field is the newest, so it goes alone first: a backend+ // that takes everything else keeps the local models it reads. Their boolean-only view still safely refuses an+ // unverified tool, and a reading without privacy is never one a Team machine passes on.+ const { privacy: _privacy, ...withoutPrivacy } = observation+ const { toolProbeErrors: _probeErrors, localModels: _served, refusedModels: _refused, ...legacy } = withoutPrivacy+ const attempts = [observation, ...('privacy' in observation ? [withoutPrivacy] : []),+ ...('toolProbeErrors' in observation || 'localModels' in observation || 'refusedModels' in observation ? [legacy] : [])]+ for (const [index, attempt] of attempts.entries()) {+ try {+ await this.deps.backend(this.core, 'POST', path, attempt)+ break+ } catch (error) {+ if (!refused(error) || index === attempts.length - 1) throw error+ if (attempt === observation && 'privacy' in observation) this.privacyRefusedUntil = began + PRIVACY_REFUSED_MS+ }}this.published.set(String(row.tabId), { at: began, signature })} catch (error) { this.failed = true; throw error }@@ -241,6 +271,14 @@ export class ContributedMachines {input.action === 'startStatus' ? 'GET' : 'POST', path,input.action === 'startStatus' ? undefined : { operationId: input.operationId, command: input.command }) })try {+ // The Harness Team account is not private (its owner's home folder opened again, say): a new start is refused+ // here as well as by routing, and never moved to the owner's account instead.+ if (privacy?.mode === 'account' && !privacy.passed && !start.dispatched) {+ await scoped({ action: 'command', operationId: `privacy-failed-${start.id}`,+ command: { type: 'agent.startFailed', startId: start.id,+ error: `This computer's Harness Team account is not private (${privacy.item}): ${privacy.detail} Its owner can run \`harness team setup\` to repair it.` } })+ continue+ }if (pool.scope === 'swarm' && !start.dispatched) {try { await (this.deps.prepare ?? prepareSwarmProject)(this.core, row, start) }catch (error) {diff --git a/cli/src/team/admin.spec.ts b/cli/src/team/admin.spec.tsnew file mode 100644index 000000000..f6b6aead3--- /dev/null+++ b/cli/src/team/admin.spec.ts@@ -0,0 +1,61 @@+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { GuestRunner } from '../lib/guestAccounts.js'+import { adminRunner } from './admin.js'++const cleanup: string[] = []+afterEach(() => { for (const dir of cleanup.splice(0)) rmSync(dir, { recursive: true, force: true }) })++function fixture(answer: { code: number | null; stdout?: string; stderr?: string }) {+ const parent = mkdtempSync(join(tmpdir(), 'team-admin-'))+ cleanup.push(parent)+ 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]!+ seen.script = readFileSync(path, 'utf8')+ for (const name of ['team.json', 'team.plist']) {+ const file = join(stage, name)+ if (existsSync(file)) seen.files[name] = { text: readFileSync(file, 'utf8'), mode: statSync(file).mode & 0o777 }+ }+ return { code: answer.code, stdout: answer.stdout ?? '', stderr: answer.stderr ?? '' }+ })+ const run = adminRunner({ runner, makeStage: () => { mkdirSync(stage); return stage } })+ return { run, runner, stage, seen }+}++describe('adminRunner', () => {+ it('stages the script and its files privately, runs it behind the administrator prompt, and removes the stage', async () => {+ const f = fixture({ code: 0, stdout: 'harness: done\n' })+ const result = await f.run((dir) => ({ script: `#!/bin/sh\necho ${dir}\n`, files: { 'team.json': '{}', 'team.plist': '<plist/>' } }), 'Harness wants "this".')+ expect(result).toEqual({ ok: true, stdout: 'harness: done\n' })+ expect(f.runner).toHaveBeenCalledTimes(1)+ const [command, args] = f.runner.mock.calls[0]!+ expect(command).toBe('osascript')+ expect(args[0]).toBe('-e')+ expect(args[1]).toContain('with administrator privileges')+ expect(args[1]).toContain('with prompt "Harness wants \\"this\\"."')+ expect(f.seen.script).toBe(`#!/bin/sh\necho ${f.stage}\n`)+ expect(f.seen.files['team.json']).toEqual({ text: '{}', mode: 0o600 })+ expect(existsSync(f.stage)).toBe(false)+ })++ it('tells a cancelled prompt from a script that stopped, in the script\'s own words', async () => {+ 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' })+ expect(await fixture({ code: 2, stderr: '' }).run(() => ({ script: '' }), 'p'))+ .toEqual({ ok: false, code: 'FAILED', message: 'The script stopped (exit 2).' })+ })++ it('removes the stage when building the script throws', async () => {+ const f = fixture({ code: 0 })+ await expect(f.run(() => { throw new Error('bad input') }, 'p')).rejects.toThrow('bad input')+ expect(existsSync(f.stage)).toBe(false)+ expect(f.runner).not.toHaveBeenCalled()+ })+})diff --git a/cli/src/team/admin.ts b/cli/src/team/admin.tsnew file mode 100644index 000000000..a1da4b58f--- /dev/null+++ b/cli/src/team/admin.ts@@ -0,0 +1,59 @@+/**+ * 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.+ *+ * Everything that touches the system goes through [AdminDeps]; the specs never run osascript.+ */+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { runGuestCommand, type GuestRunner } from '../lib/guestAccounts.js'+import { adminAppleScript } from '../lib/guestHelperInstall.js'++export type AdminResult =+ | { ok: true; stdout: string }+ | { ok: false; code: 'CANCELLED' | 'FAILED'; message: string }++export interface AdminScript {+ script: string+ /** Files the script installs from the staging folder, by name. */+ files?: Record<string, string>+}++/** 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 interface AdminDeps {+ runner?: GuestRunner+ makeStage?: () => string+ removeStage?: (dir: string) => void+}++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) => {+ const stageDir = makeStage()+ try {+ chmodSync(stageDir, 0o700)+ const { script, files = {} } = build(stageDir)+ 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 })+ 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)) {+ return { ok: false, code: 'CANCELLED', message: 'The administrator prompt was cancelled.' }+ }+ if (result.code !== 0) {+ const said = result.stderr.trim().split('\n').pop()?.replace(/^.*harness: /, '').replace(/\s*\(\d+\)$/, '') ?? ''+ return { ok: false, code: 'FAILED', message: said || `The script stopped (exit ${result.code}).` }+ }+ return { ok: true, stdout: result.stdout }+ } finally {+ removeStage(stageDir)+ }+ }+}diff --git a/cli/src/team/command.spec.ts b/cli/src/team/command.spec.tsnew file mode 100644index 000000000..9de335670--- /dev/null+++ b/cli/src/team/command.spec.ts@@ -0,0 +1,360 @@+/**+ * `harness team` against fake deps: no administrator prompt, account, launchd, daemon or backend is touched.+ */+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 type { TeamConfig } from './config.js'+import type { PrivacyResult, TeamStatus } from './privacy.js'+import { parseLaunchctlPrint } from './deps.js'++const OWNER_HOME = '/Users/owner-placeholder'+const CODE = `hnh_${'b'.repeat(43)}`+const STATUS = '/Library/Application Support/Harness/Team/status.json'+const computer: AuthSession = { version: 1, accessToken: 'access-placeholder', refreshToken: 'hnr_old', autonomousEnv: 'prod', computerId: 'c'.repeat(32), machineId: 'm1', updatedAt: 1 }+const config: TeamConfig = {+ version: 1, user: 'harnessteam', realName: 'Harness Team', home: '/Users/harnessteam', owner: 'owner-placeholder', ownerHome: OWNER_HOME,+ sentinel: `${OWNER_HOME}/.harness-team-privacy`, port: 18493, label: 'ai.autonomous.harness.team',+ plist: '/Library/LaunchDaemons/ai.autonomous.harness.team.plist', statusFile: STATUS,+ node: '/Users/harnessteam/.harness/runtime/node-v1/bin/node', cli: '/Users/harnessteam/.harness/cli/cli.js', env: {}, createdAt: 'x',+}++function fake(over: Partial<TeamCommandDeps> & { adminResult?: Awaited<ReturnType<RunAdmin>>; statusAfter?: (startedAt: number) => TeamStatus | null } = {}) {+ let now = 1_000_000+ let session: AuthSession | null = computer+ const out: string[] = [], err: string[] = []+ const built: AdminScript[] = []+ const prompts: string[] = []+ const status = new Map<string, TeamStatus>()+ const admin = vi.fn<RunAdmin>(async (build, prompt) => {+ built.push(build('/private/var/folders/aa/T/harness-team-stage'))+ prompts.push(prompt)+ return over.adminResult ?? { ok: true, stdout: 'harness: handed a sign-in to the team account\n' }+ })+ const startedAt = now+ const post = vi.fn(async (path: string, _body: unknown, _headers?: Record<string, string>): Promise<unknown> => {+ if (path === '/api/auth/handoff') return { code: CODE, expiresIn: 90 }+ if (path === '/api/auth/handoff/redeem') return { token: 'hna_team', refreshToken: 'hnr_team', expiresIn: 3600, kind: 'team' }+ return {}+ })+ const deps: TeamCommandDeps = {+ platform: 'darwin',+ out: (line) => out.push(line), err: (line) => err.push(line),+ user: () => 'owner-placeholder', home: () => OWNER_HOME, uid: () => 501, hostname: () => 'Mac-placeholder',+ 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,+ 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 }),+ exists: () => true, mode: () => 0o700, admin,+ readConfig: () => null,+ readStatus: (path) => over.statusAfter ? over.statusAfter(startedAt) : status.get(path) ?? null,+ writeStatus: vi.fn((path: string, update: Partial<TeamStatus>) => { status.set(path, { ...(status.get(path) ?? { version: 1 }), ...update, version: 1 }) }),+ accountExists: vi.fn(async () => false), jobState: vi.fn(async () => ({ loaded: true, pid: 4242, state: 'running' })),+ takeHandoff: vi.fn(() => CODE), privacy: vi.fn((): PrivacyResult => ({ passed: true, checkedAt: now })),+ 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 } }+}++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', () => {+ it('prints its help, and refuses an unknown verb', async () => {+ const f = fake()+ expect(await teamCommand([], f.deps)).toBe(0)+ expect(f.out[0]).toContain('Usage: harness team <setup | status | remove | on | off>')+ expect(await teamCommand(['frobnicate'], f.deps)).toBe(2)+ })+})++describe('harness team setup', () => {+ it('says what it will make, runs one privileged script, and waits for the team daemon to sign in and pass its check', async () => {+ const f = fake({ statusAfter: reported, env: { BACKEND_WS_URL: 'wss://backend.example.test', HARNESS_AUTH_DIR: '/tmp/auth' } })+ expect(await teamCommand(['setup'], f.deps)).toBe(0)+ expect(f.admin).toHaveBeenCalledTimes(1)+ expect(f.prompts[0]).toContain('Harness Team')+ const { script, files } = f.built[0]!+ expect(script).toContain("OWNER='owner-placeholder'")+ expect(script).toContain("STAGE='/private/var/folders/aa/T/harness-team-stage'")+ expect(script).toContain("'HARNESS_AUTH_DIR=/tmp/auth'")+ const written = JSON.parse(files!['team.json']!) as TeamConfig+ expect(written).toMatchObject({ user: 'harnessteam', ownerHome: OWNER_HOME, port: 18493, node: '/Users/harnessteam/.harness/runtime/node-v1/bin/node',+ env: { BACKEND_WS_URL: 'wss://backend.example.test' } })+ expect(files!['team.plist']).toContain('<string>wss://backend.example.test</string>')+ expect(files!['team.plist']).not.toContain('HARNESS_AUTH_DIR')+ const text = f.out.join('\n')+ expect(text).toContain('Harness Team (harnessteam)')+ expect(text).toContain('/Library/LaunchDaemons/ai.autonomous.harness.team.plist')+ expect(text).toContain('✓ The Harness Team account is signed in.')+ expect(text).toContain('✓ Private')+ })++ it('reports a failed privacy check or sign-in, and returns failure', async () => {+ const f = fake({ statusAfter: (t) => ({ version: 1, signIn: { state: 'failed', at: t + 1, detail: 'code refused' },+ privacy: { passed: false, item: 'gitconfig', detail: 'The team account could read ~/.gitconfig.', checkedAt: t + 1 } }) })+ expect(await teamCommand(['setup'], f.deps)).toBe(1)+ expect(f.err.join('\n')).toContain('did not sign in: code refused')+ expect(f.err.join('\n')).toContain('Not private (gitconfig)')+ })++ it('says when the daemon has not reported in time, ignoring an older report', async () => {+ const f = fake({ statusAfter: (t) => ({ version: 1, privacy: { passed: true, checkedAt: t - 10 } }) })+ expect(await teamCommand(['setup'], f.deps)).toBe(0)+ expect(f.out.join('\n')).toContain('has not reported its privacy check yet')+ expect(f.out.join('\n')).toContain('has not signed in yet')+ })++ it('does not wait for a sign-in the script did not hand over, and asks again with --sign-in-again', async () => {+ const f = fake({ adminResult: { ok: true, stdout: '' }, statusAfter: (t) => ({ version: 1, privacy: { passed: true, checkedAt: t + 1 } }) })+ expect(await teamCommand(['setup', '--json'], f.deps)).toBe(0)+ expect(JSON.parse(f.out.at(-1)!)).toMatchObject({ ok: true, user: 'harnessteam', label: 'ai.autonomous.harness.team', privacy: { passed: true } })+ expect(f.built[0]!.script).toContain("SIGN_IN='missing'")+ const again = fake({ statusAfter: reported })+ await teamCommand(['setup', '--sign-in-again'], again.deps)+ expect(again.built[0]!.script).toContain("SIGN_IN='always'")+ })++ it('changes nothing when the prompt is cancelled, and says how to finish a script that stopped', async () => {+ const cancelled = fake({ adminResult: { ok: false, code: 'CANCELLED', message: 'x' } })+ expect(await teamCommand(['setup'], cancelled.deps)).toBe(1)+ expect(cancelled.err[0]).toContain('Nothing was changed')+ const stopped = fake({ adminResult: { ok: false, code: 'FAILED', message: 'launchd would not start the team daemon' } })+ expect(await teamCommand(['setup', '--json'], stopped.deps)).toBe(1)+ expect(JSON.parse(stopped.out.at(-1)!)).toMatchObject({ ok: false, code: 'SETUP_FAILED' })+ })++ it('refuses where it cannot help, before any prompt', async () => {+ const cases: Array<[Partial<TeamCommandDeps>, string]> = [+ [{ platform: 'linux' }, 'harness team on'],+ [{ uid: () => 0 }, 'not with sudo'],+ [{ session: () => null }, 'Sign this computer in first'],+ [{ session: () => ({ ...computer, kind: 'team' }) }, 'already runs team work only'],+ [{ user: () => 'harnessteam' }, 'not the Harness Team account'],+ [{ exists: () => false }, 'not installed'],+ [{ env: { BACKEND_WS_URL: 'wss://x/$(id)' } }, 'BACKEND_WS_URL'],+ [{ home: () => "/Users/o'brien" }, 'plain absolute path'],+ ]+ for (const [over, says] of cases) {+ const f = fake(over)+ expect(await teamCommand(['setup'], f.deps), says).toBe(1)+ expect(f.err.join('\n'), says).toContain(says)+ expect(f.admin).not.toHaveBeenCalled()+ }+ })+})++describe('harness team status', () => {+ it('lists the account, the daemon, the sign-in, the privacy check and everything setup made', async () => {+ const f = fake({ readConfig: () => config, accountExists: vi.fn(async () => true) })+ f.status.set(STATUS, { version: 1, signIn: { state: 'signed-in', at: 1_000_000 - 30_000 }, privacy: { passed: true, checkedAt: 1_000_000 - 120_000 } })+ expect(await teamCommand(['status'], f.deps)).toBe(0)+ const text = f.out.join('\n')+ for (const needle of ['Harness Team (harnessteam)', '● exists', '● running (pid 4242)', '✓ signed in (30s ago)', 'Private ✓ (checked 2m ago)',+ `${OWNER_HOME} · mode 700 ✓`, '/Users/harnessteam', 'ai.autonomous.harness.team, a LaunchDaemon at /Library/LaunchDaemons/ai.autonomous.harness.team.plist',+ '/Library/Application Support/Harness/team.json', 'sudo dscl . -delete /Users/harnessteam', 'harness team remove']) {+ expect(text, needle).toContain(needle)+ }+ })++ it('shows what is wrong: a failed check, an open home, a stopped daemon', async () => {+ const f = fake({ readConfig: () => config, accountExists: vi.fn(async () => true), mode: () => 0o750,+ jobState: vi.fn(async () => ({ loaded: false, pid: null, state: null })), exists: (p) => p !== config.plist })+ f.status.set(STATUS, { version: 1, privacy: { passed: false, item: 'sentinel', detail: 'The team account could read it.', checkedAt: 1_000_000 - 7_200_000 } })+ await teamCommand(['status'], f.deps)+ const text = f.out.join('\n')+ expect(text).toContain('○ not installed')+ expect(text).toContain('? not reported yet')+ expect(text).toContain('✗ sentinel: The team account could read it. (checked 2h ago)')+ expect(text).toContain('mode 750 ✗ should be 700')+ })++ it('answers in JSON, and says plainly when there is no team account or the computer is dedicated', async () => {+ const f = fake({ readConfig: () => config, accountExists: vi.fn(async () => true) })+ await teamCommand(['status', '--json'], f.deps)+ expect(JSON.parse(f.out[0]!)).toMatchObject({ account: true, user: 'harnessteam', label: 'ai.autonomous.harness.team', job: { pid: 4242 }, ownerHomeMode: '700', privacy: null })+ const none = fake()+ await teamCommand(['status'], none.deps)+ expect(none.out[0]).toContain('No Harness Team account on this computer. harness team setup makes one.')+ const linux = fake({ platform: 'linux', session: () => ({ ...computer, kind: 'team' }) })+ await teamCommand(['status'], linux.deps)+ expect(linux.out[0]).toContain('runs team work only')+ const linuxJson = fake({ platform: 'linux' })+ await teamCommand(['status', '--json'], linuxJson.deps)+ expect(JSON.parse(linuxJson.out[0]!)).toEqual({ account: false, dedicated: false })+ })+})++describe('harness team remove', () => {+ it('runs one privileged removal with what the config names', async () => {+ const f = fake({ readConfig: () => ({ ...config, env: { AUTONOMOUS_ENV: 'stag' } }) })+ 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.out.join('\n')).toContain('Your home folder stays private')+ })++ 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)+ expect(JSON.parse(none.out[0]!)).toEqual({ ok: true, removed: false })+ expect(none.admin).not.toHaveBeenCalled()+ expect(await teamCommand(['remove'], fake({ platform: 'win32' }).deps)).toBe(1)+ 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)+ 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')+ })+})++describe('harness team on and off', () => {+ it('on: mints a team sign-in with this computer\'s, redeems it here, and swaps the daemon onto it', async () => {+ const f = fake({ platform: 'linux' })+ expect(await teamCommand(['on', '--yes'], f.deps)).toBe(0)+ expect(f.post).toHaveBeenCalledWith('/api/auth/handoff', { kind: 'team' }, { authorization: 'Bearer x' })+ expect(f.post).toHaveBeenCalledWith('/api/auth/handoff/redeem', { code: CODE, label: 'Mac-placeholder · Team', computerId: computer.computerId })+ expect(f.session()).toMatchObject({ kind: 'team', accessToken: 'hna_team', computerId: computer.computerId, machineId: 'm1' })+ expect(f.post).toHaveBeenCalledWith('/api/auth/revoke', { refreshToken: 'hnr_old' })+ expect(f.deps.stopDaemon).toHaveBeenCalled()+ expect(f.deps.startDaemon).toHaveBeenCalled()+ })++ it('on: asks first at a terminal, needs --yes otherwise, and leaves a Mac with a team account alone', async () => {+ const ask = fake({ interactive: true, ask: vi.fn(async () => 'n') })+ expect(await teamCommand(['on'], ask.deps)).toBe(1)+ expect(ask.post).not.toHaveBeenCalled()+ const yes = fake({ interactive: true })+ expect(await teamCommand(['on'], yes.deps)).toBe(0)+ expect(await teamCommand(['on'], fake().deps)).toBe(1)+ const mac = fake({ readConfig: () => config })+ expect(await teamCommand(['on', '--yes'], mac.deps)).toBe(1)+ expect(mac.err[0]).toContain('has a Harness Team account')+ expect(await teamCommand(['on', '--yes'], fake({ session: () => null }).deps)).toBe(1)+ const already = fake({ session: () => ({ ...computer, kind: 'team' }) })+ expect(await teamCommand(['on', '--json'], already.deps)).toBe(0)+ expect(JSON.parse(already.out[0]!)).toEqual({ ok: true, changed: false })+ })++ it('on: changes nothing when the backend will not hand out a team sign-in, or makes something else', async () => {+ const f = fake({ post: (async () => { throw Object.assign(new Error('Add a phone from a computer'), { status: 403 }) }) as never })+ expect(await teamCommand(['on', '--yes'], f.deps)).toBe(1)+ expect(f.session()).toBe(computer)+ expect(f.deps.stopDaemon).not.toHaveBeenCalled()+ expect(f.err[0]).toContain('Nothing was changed on this computer.')+ // A backend from before team sessions: the redeem makes a phone's session, which is signed out again.+ const old = fake()+ old.post.mockImplementation(async (path: string) => path === '/api/auth/handoff' ? { code: CODE, expiresIn: 90 }+ : path === '/api/auth/handoff/redeem' ? { token: 'hna_phone', refreshToken: 'hnr_phone', expiresIn: 3600 } : {})+ expect(await teamCommand(['on', '--yes', '--json'], old.deps)).toBe(1)+ expect(JSON.parse(old.out.at(-1)!)).toMatchObject({ ok: false, code: 'NOT_TEAM' })+ expect(old.post).toHaveBeenCalledWith('/api/auth/revoke', { refreshToken: 'hnr_phone' })+ expect(old.session()).toBe(computer)+ expect(old.deps.stopDaemon).not.toHaveBeenCalled()+ })++ it('off: signs the team session out, then the ordinary sign-in at a terminal, or says how', async () => {+ const signIn = vi.fn(async () => {})+ const f = fake({ interactive: true, signIn })+ f.setSession({ ...computer, kind: 'team', refreshToken: 'hnr_team' })+ expect(await teamCommand(['off'], f.deps)).toBe(0)+ expect(f.post).toHaveBeenCalledWith('/api/auth/revoke', { refreshToken: 'hnr_team' })+ expect(f.session()).toBeNull()+ expect(signIn).toHaveBeenCalledWith(true)+ const quiet = fake()+ quiet.setSession({ ...computer, kind: 'team' })+ expect(await teamCommand(['off'], quiet.deps)).toBe(0)+ expect(quiet.out.join('\n')).toContain('harness login')+ expect(quiet.deps.startDaemon).toHaveBeenCalled()+ const json = fake()+ json.setSession({ ...computer, kind: 'team' })+ expect(await teamCommand(['off', '--json'], json.deps)).toBe(0)+ expect(JSON.parse(json.out[0]!)).toMatchObject({ ok: true, changed: true, next: 'harness login' })+ const notTeam = fake()+ expect(await teamCommand(['off'], notTeam.deps)).toBe(0)+ expect(notTeam.out[0]).toContain('nothing to change')+ })+})++describe('internal verbs', () => {+ it('__handoff prints the code and nothing else', async () => {+ const f = fake()+ expect(await teamCommand(['__handoff'], f.deps)).toBe(0)+ expect(f.out).toEqual([CODE])+ const team = fake()+ team.setSession({ ...computer, kind: 'team' })+ expect(await teamCommand(['__handoff'], team.deps)).toBe(1)+ expect(team.out).toEqual([])+ })++ const inTeam = (over: Partial<TeamCommandDeps> = {}) => {+ const f = fake({ user: () => 'harnessteam', readConfig: () => config, ...over })+ f.setSession(null)+ return f+ }++ it('__start redeems the handed-over code for this computer, stores a team session and reports it with the check', async () => {+ const f = inTeam()+ expect(await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], f.deps)).toBe(0)+ expect(f.deps.takeHandoff).toHaveBeenCalledWith('/Users/harnessteam/.harness/team-handoff')+ expect(f.post).toHaveBeenCalledWith('/api/auth/handoff/redeem', { code: CODE, label: 'Mac-placeholder · Team', computerId: 't'.repeat(32) })+ expect(f.session()).toMatchObject({ kind: 'team', computerId: 't'.repeat(32), refreshToken: 'hnr_team' })+ expect(f.status.get(STATUS)).toMatchObject({ signIn: { state: 'signed-in' }, privacy: { passed: true } })+ expect(f.out.join('\n')).toContain('[team] signed in for team work')+ })++ it('__start stores nothing when the backend makes a session that is not a team one', async () => {+ const f = inTeam()+ f.post.mockImplementation(async (path: string) => path === '/api/auth/handoff/redeem' ? { token: 'hna_phone', refreshToken: 'hnr_phone' } : {})+ expect(await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], f.deps)).toBe(0)+ expect(f.session()).toBeNull()+ expect(f.status.get(STATUS)?.signIn).toMatchObject({ state: 'failed', detail: expect.stringContaining('does not make team sign-ins yet') })+ })++ it('__start reports a refused code and an unsafe file, and still exits 0 so the daemon starts', async () => {+ const refused = inTeam({ post: (async () => { throw Object.assign(new Error('expired'), { status: 401 }) }) as never })+ expect(await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], refused.deps)).toBe(0)+ expect(refused.session()).toBeNull()+ expect(refused.status.get(STATUS)?.signIn).toMatchObject({ state: 'failed' })+ const unsafe = inTeam({ takeHandoff: () => { throw new Error('not this account\'s private file') } })+ expect(await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], unsafe.deps)).toBe(0)+ expect(unsafe.status.get(STATUS)?.signIn).toMatchObject({ state: 'failed', detail: 'not this account\'s private file' })+ })++ it('__start leaves an existing sign-in alone, runs the check with no code, and writes nothing outside the team account', async () => {+ const signed = inTeam()+ signed.setSession({ ...computer, kind: 'team' })+ await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], signed.deps)+ expect(signed.post).not.toHaveBeenCalled()+ expect(signed.out.join('\n')).toContain('was not used')+ const failing = inTeam({ takeHandoff: () => null, privacy: () => ({ passed: false, item: 'ssh', detail: 'could read ~/.ssh', checkedAt: 1 }) })+ await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], failing.deps)+ expect(failing.out.join('\n')).toContain('privacy check FAILED (ssh)')+ const owner = fake({ readConfig: () => config })+ await teamCommand(['__start'], owner.deps)+ 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', () => {+ it('reads the pid and state, and a job launchd does not know as not loaded', () => {+ expect(parseLaunchctlPrint(0, 'system/ai.autonomous.harness.team = {\n\tstate = running\n\tpid = 812\n}')).toEqual({ loaded: true, pid: 812, state: 'running' })+ expect(parseLaunchctlPrint(0, '\tstate = not running\n')).toEqual({ loaded: true, pid: null, state: 'not running' })+ expect(parseLaunchctlPrint(113, 'Could not find service')).toEqual({ loaded: false, pid: null, state: null })+ })+})diff --git a/cli/src/team/command.ts b/cli/src/team/command.tsnew file mode 100644index 000000000..53b4383dc--- /dev/null+++ b/cli/src/team/command.ts@@ -0,0 +1,445 @@+/**+ * `harness team setup | status | remove | on | off` (docs/plans/2026-10-24-swarm-team-account.md, Task 2).+ *+ * On a Mac, Swarm work from teammates runs in the Harness Team account: a separate standard user with its own Harness+ * daemon, which cannot read the owner's files. A computer used only for agents (a Mac mini, a Linux or Windows box)+ * needs no second user: `harness team on` signs that computer in for team work only.+ *+ * 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.+ */+import type { AuthSession } from '../lib/authSession.js'+import type { RunAdmin } from './admin.js'+import { teamConfigJson, type TeamConfig } from './config.js'+import { mintTeamHandoff, redeemTeamHandoff, revokeHarnessRefresh, teamSession, TeamSignInError, 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,+ TEAM_USER, TeamInputError, carriedBackendEnv, checkPath, checkUser, teamPaths,+} from './layout.js'+import type { PrivacyResult, TeamStatus } from './privacy.js'+import { buildRemoveScript, buildSetupScript, teamLaunchdPlist } from './script.js'++export const TEAM_USAGE = [+ 'Usage: harness team <setup | status | remove | on | off> [--json]',+ '',+ ' setup make the Harness Team account on this Mac for Swarm work: a separate standard user, "Harness Team"',+ ` (${TEAM_USER}), whose own Harness daemon runs teammates' agents so they cannot read your files. macOS asks`,+ ' for an administrator password once. Running it again repairs it (--sign-in-again: a new sign-in for it)',+ ' status whether the account exists and runs, its sign-in and privacy check, and everything setup made',+ ' remove delete the account, its home folder and its daemon (administrator password); your home stays private',+ ' 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.'+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. */+export const SETUP_REPORT_WAIT_MS = 90_000++export interface Installed {+ /** The owner's installed CLI folder and its cli.js. */+ cliDir: string+ cliJs: string+ /** The managed Node the installed CLI runs on, and its runtime folder (null without a managed runtime). */+ node: string+ nodeRuntimeDir: string | null+ tmuxRuntimeDir: string | null+}++export interface JobState { loaded: boolean; pid: number | null; state: string | null }++export interface TeamCommandDeps {+ platform: NodeJS.Platform+ out(line: string): void+ err(line: string): void+ /** This process's account, home and uid. */+ user(): string+ home(): string+ uid(): number+ hostname(): string+ env: NodeJS.ProcessEnv+ interactive: boolean+ ask(question: string): Promise<string>+ now(): number+ sleep(ms: number): Promise<void>++ session(): AuthSession | null+ writeSession(session: AuthSession): void+ clearSession(): void+ /** Bearer headers for this computer's sign-in, refreshed when stale (lib/controlPlane.ts). */+ auth(): Promise<{ session: AuthSession; headers: Record<string, string> }>+ post: Post+ computerId(): string+ autonomousEnv: 'prod' | 'stag'++ installed(): Installed+ exists(path: string): boolean+ /** A path's permission bits, or null when it cannot be read. */+ mode(path: string): number | null+ admin: RunAdmin+ readConfig(): TeamConfig | null+ readStatus(path: string): TeamStatus | null+ writeStatus(path: string, update: Partial<Omit<TeamStatus, 'version'>>): void+ accountExists(user: string): Promise<boolean>+ jobState(label: string): Promise<JobState>++ /** The team account's side: its handed-over code, and the privacy check. */+ takeHandoff(path: string): string | null+ privacy(config: TeamConfig): PrivacyResult++ /** This computer's daemon: stopped (true when one was running), started again (prints its status and may exit),+ * and the ordinary sign-in, for `team off` (which starts the daemon again when [restart]). */+ stopDaemon(): Promise<boolean>+ startDaemon(): Promise<void>+ signIn?(restart: boolean): Promise<void>+}++export async function teamCommand(argv: string[], deps: TeamCommandDeps): Promise<number> {+ const words = argv.filter((arg) => !arg.startsWith('-'))+ const flags = argv.filter((arg) => arg.startsWith('-'))+ const json = flags.includes('--json')+ const verb = words[0]+ if (verb === undefined || verb === 'help' || flags.includes('-h') || flags.includes('--help')) {+ deps.out(TEAM_USAGE)+ return 0+ }+ try {+ switch (verb) {+ case 'setup': return await setup(deps, json, flags.includes('--sign-in-again'))+ case 'status': return await status(deps, json)+ case 'remove': return await remove(deps, json)+ case 'on': return await teamOn(deps, json, flags.includes('--yes'))+ 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+ }+ } catch (error) {+ if (!(error instanceof TeamInputError) && !(error instanceof TeamSignInError)) throw error+ return fail(deps, json, error instanceof TeamSignInError ? error.code : 'INVALID_INPUT', error.message)+ }+}++function fail(deps: TeamCommandDeps, json: boolean, code: string, message: string, extra: Record<string, unknown> = {}): number {+ if (json) deps.out(JSON.stringify({ ok: false, code, message, ...extra }))+ else deps.err(`✗ ${message}`)+ return 1+}++/** What setup makes, said plainly so anyone can audit it or take it off the Mac by hand. */+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`,+ ` 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)`,+ ` setup ${TEAM_CONFIG_FILE} and ${TEAM_STATUS_DIR}/`,+ ` check ${ownerHome}/${SENTINEL_NAME}, a file the account must not be able to read`,+ ` your home ${ownerHome}, made private (mode 700)`,+ ]+}++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}`,+ ]+}++const notMac = 'The Harness Team account is made on a Mac. On a computer used only for agents, run `harness team on`.'++async function setup(deps: TeamCommandDeps, json: boolean, signInAgain: boolean): Promise<number> {+ if (deps.platform !== 'darwin') return fail(deps, json, 'UNSUPPORTED', notMac)+ 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.')+ const session = deps.session()+ if (!session) return fail(deps, json, 'NOT_SIGNED_IN', 'Sign this computer in first (harness login): the team account is signed in from your sign-in.')+ if (session.kind === 'team') return fail(deps, json, 'TEAM_SESSION', 'This computer already runs team work only (harness team on): it needs no Harness Team account.')+ const owner = checkUser(deps.user(), 'owner account')+ const ownerHome = checkPath(deps.home(), 'home folder')+ if (owner === TEAM_USER) return fail(deps, json, 'RUN_AS_YOURSELF', 'Run this from your own account, not the Harness Team account.')+ const installed = deps.installed()+ if (!deps.exists(installed.cliJs) || !installed.nodeRuntimeDir) {+ return fail(deps, json, 'NOT_INSTALLED', 'Harness is not installed for this account (no ~/.harness/cli/cli.js and Node runtime to copy). Install it, then run this again.')+ }+ const carried = carriedBackendEnv(deps.env)+ const mintEnv: Record<string, string> = { ...carried }+ if (deps.env.HARNESS_AUTH_DIR?.trim()) mintEnv.HARNESS_AUTH_DIR = checkPath(deps.env.HARNESS_AUTH_DIR.trim(), 'HARNESS_AUTH_DIR')+ delete mintEnv.ADAPTER_UPDATE_DISABLE+ const team = teamPaths()+ const nodeName = installed.nodeRuntimeDir.slice(installed.nodeRuntimeDir.lastIndexOf('/') + 1)+ const teamNode = `${team.runtime}/${nodeName}/bin/node`+ const config: TeamConfig = {+ version: 1, user: TEAM_USER, realName: TEAM_REAL_NAME, home: TEAM_HOME, owner, ownerHome,+ sentinel: `${ownerHome}/${SENTINEL_NAME}`, port: TEAM_PORT, label: TEAM_LABEL, plist: TEAM_PLIST,+ 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 })+ if (!json) {+ deps.out('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()+ const result = await deps.admin((stageDir) => ({+ script: buildSetupScript({+ user: TEAM_USER, realName: TEAM_REAL_NAME, home: TEAM_HOME, owner, ownerHome, stageDir,+ nodeRuntimeDir: installed.nodeRuntimeDir!, tmuxRuntimeDir: installed.tmuxRuntimeDir, cliDir: installed.cliDir,+ ownerNode: installed.node, ownerCli: installed.cliJs, mintEnv, signIn: signInAgain ? 'always' : 'missing',+ }),+ files: { 'team.json': teamConfigJson(config), 'team.plist': plist },+ }), 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: ${result.message} Run \`harness team setup\` again; it repairs what is there.`)+ }+ const handedOver = /handed a sign-in to the team account/.test(result.stdout)+ if (!json) deps.out(handedOver ? 'Waiting for the team daemon to sign in and check its privacy…' : 'Waiting for the team daemon to check its privacy…')+ // The daemon reports through its status file (./privacy.ts): the sign-in when it redeemed one, the check every start.+ let report: TeamStatus | null = null+ // From now, not from before the prompt: a person may take longer than this to answer it.+ const deadline = deps.now() + SETUP_REPORT_WAIT_MS+ for (;;) {+ report = deps.readStatus(TEAM_STATUS_FILE)+ const checked = (report?.privacy?.checkedAt ?? 0) >= startedAt+ const signed = !handedOver || (report?.signIn?.at ?? 0) >= startedAt+ if ((checked && signed) || deps.now() >= deadline) break+ await deps.sleep(1_000)+ }+ const privacy = report?.privacy && report.privacy.checkedAt >= startedAt ? report.privacy : null+ const signIn = report?.signIn && (!handedOver || report.signIn.at >= startedAt) ? report.signIn : null+ if (json) {+ const ok = privacy?.passed === true && (!handedOver || signIn?.state === 'signed-in')+ deps.out(JSON.stringify({ ok, user: TEAM_USER, home: TEAM_HOME, label: TEAM_LABEL, plist: TEAM_PLIST, privacy, signIn }))+ return ok ? 0 : 1+ }+ let code = 0+ if (handedOver && signIn?.state === 'signed-in') deps.out('✓ The Harness Team account is signed in.')+ else if (handedOver && signIn) { deps.err(`✗ The team account did not sign in: ${signIn.detail ?? signIn.state}`); code = 1 }+ else if (handedOver) deps.out('! The team daemon has not signed in yet: harness team status')+ if (privacy?.passed) deps.out('✓ Private: the team account cannot read your files.')+ else if (privacy) { deps.err(`✗ Not private (${privacy.item}): ${privacy.detail}`); code = 1 }+ else deps.out('! The team daemon has not reported its privacy check yet: harness team status')+ deps.out(' status: harness team status · undo: harness team remove')+ return code+}++function ago(now: number, at: number): string {+ const seconds = Math.max(0, Math.round((now - at) / 1000))+ if (seconds < 90) return `${seconds}s ago`+ if (seconds < 90 * 60) return `${Math.round(seconds / 60)}m ago`+ return `${Math.round(seconds / 3600)}h ago`+}++async function status(deps: TeamCommandDeps, json: boolean): Promise<number> {+ const session = deps.session()+ const dedicated = session?.kind === 'team'+ const config = deps.platform === 'darwin' ? deps.readConfig() : null+ const exists = deps.platform === 'darwin' ? await deps.accountExists(config?.user ?? TEAM_USER) : false+ if (!config && !exists) {+ if (json) deps.out(JSON.stringify({ account: false, dedicated }))+ else if (dedicated) deps.out('This computer runs team work only (harness team on): Swarm agents run here, and it reaches none of your other computers.\n undo: harness team off')+ else deps.out(`No Harness Team account on this computer.${deps.platform === 'darwin' ? ' harness team setup makes one.' : ' On a computer used only for agents: harness team on.'}`)+ return 0+ }+ const user = config?.user ?? TEAM_USER+ const home = config?.home ?? TEAM_HOME+ const ownerHome = config?.ownerHome ?? deps.home()+ const job = await deps.jobState(config?.label ?? TEAM_LABEL)+ const report = deps.readStatus(config?.statusFile ?? TEAM_STATUS_FILE)+ const homeMode = deps.mode(ownerHome)+ const plistPresent = deps.exists(config?.plist ?? TEAM_PLIST)+ if (json) {+ deps.out(JSON.stringify({+ account: exists, user, realName: config?.realName ?? TEAM_REAL_NAME, home, homePresent: deps.exists(home),+ label: config?.label ?? TEAM_LABEL, plist: config?.plist ?? TEAM_PLIST, plistPresent, job, port: config?.port ?? TEAM_PORT,+ config: config ? TEAM_CONFIG_FILE : null, ownerHomeMode: homeMode === null ? null : homeMode.toString(8),+ signIn: report?.signIn ?? null, privacy: report?.privacy ?? null, dedicated,+ }))+ return 0+ }+ const now = deps.now()+ deps.out(`Harness Team account · ${config?.realName ?? TEAM_REAL_NAME} (${user})`)+ deps.out(` account ${exists ? '● exists' : '○ missing · harness team setup makes it again'}`)+ deps.out(` daemon ${job.pid !== null ? `● running (pid ${job.pid})` : job.loaded ? `◍ loaded, not running${job.state ? ` (${job.state})` : ''}` : plistPresent ? '○ installed, not loaded · harness team setup starts it' : '○ not installed · harness team setup installs it'}`)+ const signIn = report?.signIn+ deps.out(` sign-in ${!signIn ? '? not reported yet' : signIn.state === 'signed-in' ? `✓ signed in (${ago(now, signIn.at)})` : `✗ ${signIn.state}${signIn.detail ? `: ${signIn.detail}` : ''}`}`)+ const privacy = report?.privacy+ deps.out(` privacy ${!privacy ? '? not checked yet' : privacy.passed ? `Private ✓ (checked ${ago(now, privacy.checkedAt)})` : `✗ ${privacy.item}: ${privacy.detail} (checked ${ago(now, privacy.checkedAt)})`}`)+ deps.out(` your home ${ownerHome} · mode ${homeMode === null ? 'unknown' : homeMode.toString(8)}${homeMode === 0o700 ? ' ✓' : ' ✗ should be 700: harness team setup makes it private again'}`)+ deps.out('')+ deps.out(' What setup made:')+ for (const line of madeLines(ownerHome)) deps.out(` ${line}`)+ deps.out('')+ deps.out(' undo: harness team remove')+ for (const line of byHandLines(ownerHome)) deps.out(line)+ return 0+}++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.')+ 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)) {+ if (json) deps.out(JSON.stringify({ ok: true, removed: false }))+ else deps.out('No Harness Team account on this Mac; nothing to remove.')+ return 0+ }+ 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)+ if (!result.ok) {+ if (result.code === 'CANCELLED') return fail(deps, json, 'CANCELLED', 'Nothing was removed: the administrator prompt was cancelled.')+ return fail(deps, json, 'REMOVE_FAILED', `The Harness Team account was not fully removed: ${result.message} Run \`harness team remove\` again.`)+ }+ 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`)+ }+ return 0+}++async function teamOn(deps: TeamCommandDeps, json: boolean, yes: boolean): Promise<number> {+ const session = deps.session()+ if (!session) return fail(deps, json, 'NOT_SIGNED_IN', 'Sign this computer in first (harness login), then run harness team on.')+ if (session.kind === 'team') {+ if (json) deps.out(JSON.stringify({ ok: true, changed: false }))+ else deps.out('This computer already runs team work only. undo: harness team off')+ return 0+ }+ if (deps.platform === 'darwin' && deps.readConfig()) {+ return fail(deps, json, 'TEAM_ACCOUNT', 'This Mac has a Harness Team account, which runs its team work. `harness team on` is for a computer used only for agents.')+ }+ if (!yes) {+ if (!deps.interactive || json) return fail(deps, json, 'CONFIRM', 'Add --yes to sign this computer in for team work only.')+ deps.out('This computer will run Swarm agents for your team and will no longer reach your other computers.')+ deps.out('Use it only on a computer used for agents alone: they can read everything this account can.')+ const answer = (await deps.ask('Sign this computer in for team work only? [y/N] ')).trim()+ if (!/^y(es)?$/i.test(answer)) return fail(deps, json, 'CANCELLED', 'Nothing was changed.')+ }+ const label = `${deps.hostname().slice(0, 60)} · Team`+ let tokens: Awaited<ReturnType<typeof redeemTeamHandoff>>+ try {+ const { code } = await mintTeamHandoff(() => deps.auth(), deps.post)+ tokens = await redeemTeamHandoff(code, label, session.computerId, { post: deps.post, sleep: deps.sleep, now: deps.now })+ } catch (error) {+ if (error instanceof TeamSignInError) throw new TeamSignInError(`${error.message} Nothing was changed on this computer.`, error.code)+ throw error+ }+ // The daemon holds the computer's sign-in in memory: it stops before the file changes, and comes back on the new one.+ const wasRunning = await deps.stopDaemon()+ const previous = deps.session() ?? session+ deps.writeSession(teamSession(tokens, session.computerId, deps.autonomousEnv, deps.now(),+ session.machineId ? { machineId: session.machineId } : {}))+ await revokeHarnessRefresh(deps.post, previous.refreshToken)+ if (json) deps.out(JSON.stringify({ ok: true, changed: true }))+ else deps.out('✓ This computer now runs team work only. undo: harness team off')+ if (wasRunning) await deps.startDaemon()+ return 0+}++async function teamOff(deps: TeamCommandDeps, json: boolean): Promise<number> {+ const session = deps.session()+ if (session?.kind !== 'team') {+ if (json) deps.out(JSON.stringify({ ok: true, changed: false }))+ else deps.out('This computer does not run team work only; nothing to change.')+ return 0+ }+ const wasRunning = await deps.stopDaemon()+ await revokeHarnessRefresh(deps.post, session.refreshToken)+ deps.clearSession()+ if (json) {+ deps.out(JSON.stringify({ ok: true, changed: true, next: 'harness login' }))+ if (wasRunning) await deps.startDaemon()+ return 0+ }+ deps.out('✓ Signed this computer out of team work.')+ // A team sign-in cannot hand out a computer's one (Task 1): signing in again is the ordinary sign-in.+ if (deps.interactive && deps.signIn) {+ await deps.signIn(wasRunning)+ return 0+ }+ deps.out(' Sign it in as your own computer: harness login')+ if (wasRunning) await deps.startDaemon()+ return 0+}++/** `team __handoff`: run as the owner by setup's script, the moment the code is handed over. Prints only the code. */+async function handoff(deps: TeamCommandDeps): Promise<number> {+ const { code } = await mintTeamHandoff(() => deps.auth(), deps.post)+ deps.out(code)+ return 0+}++/**+ * `team __start <file>`: run by the team daemon's job, as the team account, before its master starts. Its lines go+ * to the daemon's log. Always exits 0: the daemon starts either way, signed out if the sign-in failed, and reports+ * the privacy check it failed. Team work never runs as the owner instead.+ */+async function jobStart(deps: TeamCommandDeps, file: string | undefined): Promise<number> {+ const config = deps.readConfig()+ const mine = config && config.user === deps.user() ? config : null+ const statusFile = mine?.statusFile ?? TEAM_STATUS_FILE+ const log = (line: string) => deps.out(`${new Date(deps.now()).toISOString()} [team] ${line}`)+ const report = (update: Partial<Omit<TeamStatus, 'version'>>) => {+ if (!mine) return+ try { deps.writeStatus(statusFile, update) } catch (error) { log(`could not write ${statusFile}: ${(error as Error).message}`) }+ }+ if (file) {+ let code: string | null = null+ try {+ code = deps.takeHandoff(checkPath(file, 'sign-in file'))+ } catch (error) {+ log((error as Error).message)+ report({ signIn: { state: 'failed', at: deps.now(), detail: (error as Error).message } })+ }+ if (code && deps.session()) {+ log('already signed in; the handed-over sign-in code was not used')+ report({ signIn: { state: 'signed-in', at: deps.now() } })+ } else if (code) {+ const label = `${deps.hostname().slice(0, 60)} · Team`+ try {+ const computerId = deps.computerId()+ const tokens = await redeemTeamHandoff(code, label, computerId, { post: deps.post, sleep: deps.sleep, now: deps.now })+ deps.writeSession(teamSession(tokens, computerId, deps.autonomousEnv, deps.now()))+ log('signed in for team work')+ report({ signIn: { state: 'signed-in', at: deps.now() } })+ } catch (error) {+ log(`sign-in failed: ${(error as Error).message}`)+ report({ signIn: { state: 'failed', at: deps.now(), detail: (error as Error).message } })+ }+ }+ }+ if (mine) {+ const privacy = deps.privacy(mine)+ log(privacy.passed ? 'privacy check passed' : `privacy check FAILED (${privacy.item}): ${privacy.detail}`)+ report({ privacy })+ }+ 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/config.ts b/cli/src/team/config.tsnew file mode 100644index 000000000..e543d0723--- /dev/null+++ b/cli/src/team/config.ts@@ -0,0 +1,69 @@+/**+ * What setup made, written root-owned to /Library/Application Support/Harness/team.json and read by the team+ * daemon (its privacy check) and by the owner's `harness team status`. Nothing in it is secret: names and paths.+ */+import { readFileSync } from 'node:fs'+import { TEAM_CONFIG_FILE, carriedBackendEnv, checkPath, checkPort, checkUser } from './layout.js'++export interface TeamConfig {+ version: 1+ /** The team account's short name, and its home. */+ user: string+ realName: string+ home: string+ /** The Mac's owner, whose files the team account must not reach, and their home. */+ owner: string+ ownerHome: string+ /** The world-readable file in the owner's home that only the home folder's mode protects. */+ sentinel: string+ port: number+ label: string+ plist: string+ statusFile: string+ /** The team account's Node and CLI, which `harness team remove` runs as that account to sign it out. */+ node: string+ cli: string+ /** The backend settings carried from the owner's environment (./layout.ts `carriedBackendEnv`), which the team+ * daemon runs with and `harness team remove` signs it out against. */+ env: Record<string, string>+ createdAt: string+}++export function teamConfigJson(config: TeamConfig): string {+ return `${JSON.stringify(config, null, 2)}\n`+}++/** The config at [path], every field checked; null when there is none or it is not one setup wrote. */+export function readTeamConfig(path: string = TEAM_CONFIG_FILE, read: (path: string) => string = (p) => readFileSync(p, 'utf8')): TeamConfig | null {+ let raw: unknown+ try { raw = JSON.parse(read(path)) } catch { return null }+ if (!raw || typeof raw !== 'object') return null+ const value = raw as Record<string, unknown>+ try {+ const text = (key: string): string => {+ const v = value[key]+ if (typeof v !== 'string' || !v) throw new Error(key)+ return v+ }+ if (value.version !== 1 || typeof value.port !== 'number') return null+ return {+ version: 1,+ user: checkUser(text('user')),+ realName: text('realName').slice(0, 80),+ home: checkPath(text('home')),+ owner: checkUser(text('owner')),+ ownerHome: checkPath(text('ownerHome')),+ sentinel: checkPath(text('sentinel')),+ port: checkPort(value.port),+ label: text('label'),+ plist: checkPath(text('plist')),+ statusFile: checkPath(text('statusFile')),+ node: checkPath(text('node')),+ cli: checkPath(text('cli')),+ env: carriedBackendEnv(value.env && typeof value.env === 'object' ? value.env as NodeJS.ProcessEnv : {}),+ createdAt: text('createdAt'),+ }+ } catch {+ return null+ }+}diff --git a/cli/src/team/deps.ts b/cli/src/team/deps.tsnew file mode 100644index 000000000..ac81f85a4--- /dev/null+++ b/cli/src/team/deps.ts@@ -0,0 +1,85 @@+/** This computer's side of `harness team` (./command.ts): every module it needs, loaded only when it runs. */+import { existsSync, statSync } from 'node:fs'+import { homedir, hostname, userInfo } from 'node:os'+import { dirname, join } from 'node:path'+import { createInterface } from 'node:readline'+import { env } from '../config/env.js'+import { clearAuthSession, readAuthSession, writeAuthSession } from '../lib/authSession.js'+import { controlPlaneAuth, postJson } from '../lib/controlPlane.js'+import { computerId } from '../lib/daemonState.js'+import { runGuestCommand, type GuestRunner } from '../lib/guestAccounts.js'+import { managedNodeRuntimeDir } from '../lib/guestHelperInstall.js'+import { managedNodePath } from '../lib/nodeRuntime.js'+import { managedTmuxPath } from '../lib/tmuxOnPath.js'+import { adminRunner } from './admin.js'+import type { JobState, TeamCommandDeps } from './command.js'+import { readTeamConfig } from './config.js'+import { realPrivacyDeps, readTeamStatus, runPrivacyCheck, writeTeamStatus } from './privacy.js'+import { takeHandoffFile } from './handoff.js'++/** What `launchctl print system/<label>` says of a job; not loaded when launchd does not know it. Readable without root. */+export function parseLaunchctlPrint(code: number | null, stdout: string): JobState {+ if (code !== 0) return { loaded: false, pid: null, state: null }+ const pid = /^\s*pid = (\d+)\s*$/m.exec(stdout)+ const state = /^\s*state = (.+?)\s*$/m.exec(stdout)+ return { loaded: true, pid: pid ? Number(pid[1]) : null, state: state ? state[1]! : null }+}++export function teamCommandDeps(options: {+ stopDaemon: () => Promise<boolean>+ startDaemon: () => Promise<void>+ signIn?: (restart: boolean) => Promise<void>+ runner?: GuestRunner+}): TeamCommandDeps {+ const runner = options.runner ?? runGuestCommand+ return {+ platform: process.platform,+ out: (line) => console.log(line),+ err: (line) => console.error(line),+ user: () => userInfo().username,+ home: () => homedir(),+ uid: () => process.getuid?.() ?? -1,+ hostname: () => hostname(),+ env: process.env,+ interactive: process.stdin.isTTY === true && process.stdout.isTTY === true,+ ask: (question) => new Promise((resolve) => {+ const rl = createInterface({ input: process.stdin, output: process.stdout })+ rl.question(question, (answer) => { rl.close(); resolve(answer) })+ }),+ now: () => Date.now(),+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),+ session: readAuthSession,+ writeSession: writeAuthSession,+ clearSession: clearAuthSession,+ auth: controlPlaneAuth,+ post: (path, body, headers) => postJson(path, body, headers ?? {}),+ computerId,+ autonomousEnv: env.AUTONOMOUS_ENV,+ installed: () => {+ const tmux = managedTmuxPath()+ return {+ cliDir: env.ADAPTER_CLI_DIR,+ cliJs: join(env.ADAPTER_CLI_DIR, 'cli.js'),+ node: managedNodePath(),+ nodeRuntimeDir: managedNodeRuntimeDir(),+ tmuxRuntimeDir: tmux ? dirname(dirname(tmux)) : null,+ }+ },+ exists: existsSync,+ mode: (path) => { try { return statSync(path).mode & 0o777 } catch { return null } },+ admin: adminRunner({ runner }),+ readConfig: () => readTeamConfig(),+ readStatus: (path) => readTeamStatus(path),+ writeStatus: writeTeamStatus,+ accountExists: async (user) => (await runner('id', ['-u', user], { timeoutMs: 10_000 })).code === 0,+ jobState: async (label) => {+ const result = await runner('launchctl', ['print', `system/${label}`], { timeoutMs: 10_000 })+ return parseLaunchctlPrint(result.code, result.stdout)+ },+ takeHandoff: (path) => takeHandoffFile(path),+ privacy: (config) => runPrivacyCheck(config, realPrivacyDeps),+ stopDaemon: options.stopDaemon,+ startDaemon: options.startDaemon,+ ...(options.signIn ? { signIn: options.signIn } : {}),+ }+}diff --git a/cli/src/team/handoff.spec.ts b/cli/src/team/handoff.spec.tsnew file mode 100644index 000000000..bde65e931--- /dev/null+++ b/cli/src/team/handoff.spec.ts@@ -0,0 +1,131 @@+import { chmodSync, existsSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { AuthSession } from '../lib/authSession.js'+import { mintTeamHandoff, redeemTeamHandoff, revokeHarnessRefresh, takeHandoffFile, teamSession, TeamSignInError } from './handoff.js'++const CODE = `hnh_${'a'.repeat(43)}`+const computer: AuthSession = { version: 1, accessToken: 'access-placeholder', autonomousEnv: 'prod', computerId: 'c'.repeat(32), updatedAt: 1 }+const headers = { authorization: 'Bearer access-placeholder', 'x-autonomous-env': 'prod' }++const cleanup: string[] = []+afterEach(() => { for (const dir of cleanup.splice(0)) rmSync(dir, { recursive: true, force: true }) })+function temp(): string {+ const dir = mkdtempSync(join(tmpdir(), 'team-handoff-'))+ cleanup.push(dir)+ return dir+}++describe('mintTeamHandoff', () => {+ it('asks for a team code with this computer\'s sign-in', async () => {+ const post = vi.fn(async () => ({ code: CODE, expiresIn: 90 }))+ await expect(mintTeamHandoff(async () => ({ session: computer, headers }), post as never)).resolves.toEqual({ code: CODE, expiresIn: 90 })+ expect(post).toHaveBeenCalledWith('/api/auth/handoff', { kind: 'team' }, headers)+ })++ it('refuses a team sign-in, a signed-out computer and an answer without a code', async () => {+ const post = vi.fn(async () => ({ code: CODE }))+ await expect(mintTeamHandoff(async () => ({ session: { ...computer, kind: 'team' }, headers }), post as never)).rejects.toMatchObject({ code: 'TEAM_SESSION' })+ expect(post).not.toHaveBeenCalled()+ await expect(mintTeamHandoff(async () => { throw new Error('Not signed in.') }, post as never)).rejects.toMatchObject({ code: 'NOT_SIGNED_IN' })+ await expect(mintTeamHandoff(async () => ({ session: computer, headers }), (async () => ({ code: 'x; rm -rf /' })) as never)).rejects.toMatchObject({ code: 'BACKEND' })+ await expect(mintTeamHandoff(async () => ({ session: computer, headers }), (async () => { throw new Error('403') }) as never)).rejects.toMatchObject({ code: 'BACKEND' })+ expect((await mintTeamHandoff(async () => ({ session: computer, headers }), post as never)).expiresIn).toBe(90)+ })+})++describe('redeemTeamHandoff', () => {+ it('redeems for this computer id, with its label', async () => {+ const post = vi.fn(async () => ({ token: 'hna_t', refreshToken: 'hnr_r', expiresIn: 3600, kind: 'team' }))+ await expect(redeemTeamHandoff(CODE, 'Mac · Team', 'id', { post: post as never })).resolves.toMatchObject({ token: 'hna_t' })+ expect(post).toHaveBeenCalledWith('/api/auth/handoff/redeem', { code: CODE, label: 'Mac · Team', computerId: 'id' })+ })++ it('takes a refused code as final, and tries an unreachable backend again until the code would run out', async () => {+ const refused = vi.fn(async () => { throw Object.assign(new Error('That code has expired.'), { status: 401 }) })+ await expect(redeemTeamHandoff(CODE, 'l', 'id', { post: refused as never })).rejects.toMatchObject({ code: 'EXPIRED' })+ expect(refused).toHaveBeenCalledTimes(1)+ let now = 0+ const sleep = vi.fn(async (ms: number) => { now += ms })+ const flaky = vi.fn().mockRejectedValueOnce(new Error('ECONNRESET')).mockResolvedValueOnce({ token: 'hna_t', kind: 'team' })+ await expect(redeemTeamHandoff(CODE, 'l', 'id', { post: flaky as never, sleep, now: () => now })).resolves.toEqual({ token: 'hna_t', kind: 'team' })+ const down = vi.fn(async () => { throw Object.assign(new Error('Service unavailable'), { status: 503 }) })+ await expect(redeemTeamHandoff(CODE, 'l', 'id', { post: down as never, sleep, now: () => now, retryForMs: 30_000 })).rejects.toMatchObject({ code: 'BACKEND' })+ expect(down.mock.calls.length).toBeGreaterThan(2)+ })++ // A backend from before team sessions ignores {kind:"team"} and makes a phone's session, which reaches every+ // computer on the account. Anything but a session it calls a team one is signed out again and refused.+ it('fails closed on a session the backend does not call a team one, signing it out again', async () => {+ const post = vi.fn(async (path: string) => path.endsWith('/redeem') ? { token: 'hna_t', refreshToken: 'hnr_phone', expiresIn: 3600 } : {})+ await expect(redeemTeamHandoff(CODE, 'l', 'id', { post: post as never })).rejects.toMatchObject({ code: 'NOT_TEAM' })+ expect(post).toHaveBeenCalledWith('/api/auth/revoke', { refreshToken: 'hnr_phone' })+ const viewer = vi.fn(async (path: string) => path.endsWith('/redeem') ? { token: 'hna_t', refreshToken: 'hnr_phone', kind: 'viewer' } : {})+ await expect(redeemTeamHandoff(CODE, 'l', 'id', { post: viewer as never })).rejects.toMatchObject({ code: 'NOT_TEAM' })+ await expect(mintTeamHandoff(async () => ({ session: computer, headers }), (async () => ({ code: CODE, kind: 'viewer' })) as never))+ .rejects.toMatchObject({ code: 'BACKEND' })+ })++ it('refuses a malformed code and an answer without a session', async () => {+ await expect(redeemTeamHandoff('short', 'l', 'id', { post: vi.fn() as never })).rejects.toBeInstanceOf(TeamSignInError)+ await expect(redeemTeamHandoff(CODE, 'l', 'id', { post: (async () => ({})) as never })).rejects.toMatchObject({ code: 'BACKEND' })+ })+})++describe('team session and revoke', () => {+ it('marks the stored session as a team one, keeping what it is given', () => {+ expect(teamSession({ token: 'hna_t', refreshToken: 'hnr_r', expiresIn: 10 }, 'id', 'stag', 1_000, { machineId: 'm' })).toEqual({+ version: 1, accessToken: 'hna_t', refreshToken: 'hnr_r', expiresAt: 11_000, autonomousEnv: 'stag', computerId: 'id', machineId: 'm', kind: 'team', updatedAt: 1_000,+ })+ expect(teamSession({ token: 'hna_t', autonomousEnv: 'prod' }, 'id', 'stag', 1)).toMatchObject({ autonomousEnv: 'prod', kind: 'team' })+ })++ it('revokes only a Harness-issued session, and never fails', async () => {+ const post = vi.fn(async () => ({}))+ expect(await revokeHarnessRefresh(post as never, 'hnr_x')).toBe(true)+ expect(post).toHaveBeenCalledWith('/api/auth/revoke', { refreshToken: 'hnr_x' })+ expect(await revokeHarnessRefresh(post as never, 'eyJ.sso')).toBe(false)+ expect(await revokeHarnessRefresh(post as never, undefined)).toBe(false)+ expect(await revokeHarnessRefresh((async () => { throw new Error('down') }) as never, 'hnr_x')).toBe(false)+ })+})++describe('takeHandoffFile', () => {+ it('reads this account\'s private file once and deletes it', () => {+ const file = join(temp(), 'team-handoff')+ writeFileSync(file, `${CODE}\n`, { mode: 0o600 })+ expect(takeHandoffFile(file)).toBe(CODE)+ expect(existsSync(file)).toBe(false)+ expect(takeHandoffFile(file)).toBeNull()+ })++ it('deletes unread a file others can read, a link, or one holding something else', () => {+ const dir = temp()+ const open = join(dir, 'open')+ writeFileSync(open, CODE, { mode: 0o600 })+ chmodSync(open, 0o644)+ expect(() => takeHandoffFile(open)).toThrow(/deleted unread/)+ expect(existsSync(open)).toBe(false)+ const target = join(dir, 'target'), link = join(dir, 'link')+ writeFileSync(target, CODE, { mode: 0o600 })+ symlinkSync(target, link)+ expect(() => takeHandoffFile(link)).toThrow(TeamSignInError)+ expect(existsSync(link)).toBe(false)+ expect(existsSync(target)).toBe(true)+ const junk = join(dir, 'junk')+ writeFileSync(junk, '$(id)', { mode: 0o600 })+ expect(() => takeHandoffFile(junk)).toThrow(/did not hold a sign-in code/)+ expect(existsSync(junk)).toBe(false)+ })++ it('refuses a file another account owns', () => {+ const deps = {+ open: () => 3, fstat: () => ({ isFile: () => true, uid: 501, mode: 0o100600, size: 10 }), read: vi.fn(() => 0),+ close: vi.fn(), unlink: vi.fn(), euid: () => 502,+ }+ expect(() => takeHandoffFile('/x', deps)).toThrow(/not this account's private file/)+ expect(deps.read).not.toHaveBeenCalled()+ expect(deps.unlink).toHaveBeenCalledWith('/x')+ })+})diff --git a/cli/src/team/handoff.ts b/cli/src/team/handoff.tsnew file mode 100644index 000000000..93eeab5ee--- /dev/null+++ b/cli/src/team/handoff.ts@@ -0,0 +1,180 @@+/**+ * Signing a team daemon in (docs/plans/2026-10-24-swarm-team-account.md, Tasks 1 and 2).+ *+ * The owner's signed-in computer mints a single-use team handoff code (`POST /api/auth/handoff {kind:"team"}`,+ * about 90 seconds); the team daemon redeems it for a team session bound to its own computer id+ * (`POST /api/auth/handoff/redeem {code,label,computerId}`). A team session runs its own computer and the Swarm+ * agents there, and reaches none of the account's other computers: the backend enforces that, not this file.+ *+ * In the Harness Team account the code travels in a file only that account can read (owner the team account, mode+ * 600), written by setup just before the job starts; the daemon reads it, deletes it, then redeems it.+ */+import { constants, fstatSync, openSync, readSync, closeSync, unlinkSync } from 'node:fs'+import type { AuthSession } from '../lib/authSession.js'+import { HANDOFF_CODE } from './layout.js'++export type Post = <T>(path: string, body: unknown, headers?: Record<string, string>) => Promise<T>++export class TeamSignInError extends Error {+ constructor(message: string, readonly code: 'NOT_SIGNED_IN' | 'TEAM_SESSION' | 'EXPIRED' | 'BACKEND' | 'NOT_TEAM' | 'UNSAFE_FILE') {+ super(message)+ this.name = 'TeamSignInError'+ }+}++/** A team handoff code from this computer's own sign-in. Refused for a team sign-in: it may not hand one out. */+export async function mintTeamHandoff(+ auth: () => Promise<{ session: AuthSession; headers: Record<string, string> }>, post: Post,+): Promise<{ code: string; expiresIn: number }> {+ let signedIn: { session: AuthSession; headers: Record<string, string> }+ try {+ signedIn = await auth()+ } catch (error) {+ throw new TeamSignInError(`This computer is not signed in: ${(error as Error).message}`, 'NOT_SIGNED_IN')+ }+ if (signedIn.session.kind === 'team') {+ throw new TeamSignInError('This computer runs team work only, and a team sign-in cannot hand out another.', 'TEAM_SESSION')+ }+ let minted: { code?: unknown; expiresIn?: unknown }+ try {+ minted = await post('/api/auth/handoff', { kind: 'team' }, signedIn.headers)+ } catch (error) {+ throw new TeamSignInError(`Harness would not give a team sign-in code: ${(error as Error).message}`, 'BACKEND')+ }+ if (typeof minted?.code !== 'string' || !HANDOFF_CODE.test(minted.code)) {+ throw new TeamSignInError('Harness answered without a team sign-in code.', 'BACKEND')+ }+ if ((minted as { kind?: unknown }).kind !== undefined && (minted as { kind?: unknown }).kind !== 'team') {+ throw new TeamSignInError('Harness answered with a sign-in code that is not a team one.', 'BACKEND')+ }+ return { code: minted.code, expiresIn: typeof minted.expiresIn === 'number' ? minted.expiresIn : 90 }+}++export interface TeamTokens {+ token: string+ refreshToken?: string+ expiresIn?: number+ autonomousEnv?: 'prod' | 'stag'+ /** What the backend made. Required to be `team`: see `redeemTeamHandoff`. */+ kind?: string+}++export interface RedeemDeps {+ post: Post+ sleep?: (ms: number) => Promise<void>+ now?: () => number+ /** How long to keep trying a backend that does not answer: the code lives about 90 seconds. */+ retryForMs?: number+}++/**+ * Redeem [code] for a team session for [computerId]. A refused code is final; an unreachable backend is tried+ * again until the code would have run out.+ *+ * Fails closed on what it gets back. A backend from before team sessions ignores `{kind:"team"}` when the code is+ * minted, and redeeming that code makes a phone's session, which reaches every computer on the account: far more+ * than a team session may. So the answer must say it is a team session (`kind: "team"`); anything else is signed+ * out again at once and refused.+ */+export async function redeemTeamHandoff(code: string, label: string, computerId: string, deps: RedeemDeps): Promise<TeamTokens> {+ if (!HANDOFF_CODE.test(code)) throw new TeamSignInError('The team sign-in code is not in the form Harness expects.', 'EXPIRED')+ const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))+ const now = deps.now ?? Date.now+ const deadline = now() + (deps.retryForMs ?? 60_000)+ for (let attempt = 0; ; attempt++) {+ try {+ const tokens = await deps.post<TeamTokens>('/api/auth/handoff/redeem', { code, label: label.slice(0, 80), computerId })+ if (typeof tokens?.token !== 'string' || !tokens.token) throw new TeamSignInError('Harness answered without a session.', 'BACKEND')+ if (tokens.kind !== 'team') {+ await revokeHarnessRefresh(deps.post, tokens.refreshToken)+ throw new TeamSignInError('This Harness backend does not make team sign-ins yet, so nothing was signed in.', 'NOT_TEAM')+ }+ return tokens+ } catch (error) {+ if (error instanceof TeamSignInError) throw error+ const status = (error as { status?: number }).status+ if (status !== undefined && status >= 400 && status < 500) {+ throw new TeamSignInError(`Harness refused the team sign-in code (${(error as Error).message}).`, 'EXPIRED')+ }+ if (now() >= deadline) throw new TeamSignInError(`Harness could not be reached to sign in: ${(error as Error).message}`, 'BACKEND')+ await sleep(Math.min(10_000, 1_000 * 2 ** attempt))+ }+ }+}++/** The session file for a team sign-in: the same shape `harness login` writes, marked `kind: team`. */+export function teamSession(tokens: TeamTokens, computerId: string, fallbackEnv: 'prod' | 'stag', now: number, extra: Partial<AuthSession> = {}): AuthSession {+ // `kind` is what the session file says, always team here; the backend's word for it is checked on redeem.+ return {+ version: 1,+ accessToken: tokens.token,+ ...(tokens.refreshToken ? { refreshToken: tokens.refreshToken } : {}),+ ...(tokens.expiresIn ? { expiresAt: now + tokens.expiresIn * 1000 } : {}),+ autonomousEnv: tokens.autonomousEnv ?? fallbackEnv,+ computerId,+ ...extra,+ kind: 'team',+ updatedAt: now,+ }+}++/** Sign a Harness-issued session out on the backend. Best effort: an Autonomous sign-in is not ours to revoke. */+export async function revokeHarnessRefresh(post: Post, refreshToken: string | undefined): Promise<boolean> {+ if (!refreshToken?.startsWith('hnr_')) return false+ try {+ await post('/api/auth/revoke', { refreshToken })+ return true+ } catch {+ return false+ }+}++export interface HandoffFileDeps {+ open(path: string): number+ fstat(fd: number): { isFile(): boolean; uid: number; mode: number; size: number }+ read(fd: number, buffer: Buffer): number+ close(fd: number): void+ unlink(path: string): void+ euid(): number+}++export const realHandoffFileDeps: HandoffFileDeps = {+ // Never through a link, and without blocking on a FIFO someone left in its place.+ open: (path) => openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK),+ fstat: (fd) => fstatSync(fd),+ read: (fd, buffer) => readSync(fd, buffer, 0, buffer.length, 0),+ close: (fd) => closeSync(fd),+ unlink: (path) => unlinkSync(path),+ euid: () => process.geteuid?.() ?? -1,+}++/**+ * The code in [path], read once and deleted, or null when there is none. The file must be this account's own, a+ * plain file, and readable by nobody else; anything else is deleted unread and refused.+ */+export function takeHandoffFile(path: string, deps: HandoffFileDeps = realHandoffFileDeps): string | null {+ let fd: number+ try {+ fd = deps.open(path)+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null+ try { deps.unlink(path) } catch { /* nothing more to do */ }+ throw new TeamSignInError(`The team sign-in file could not be opened safely (${(error as NodeJS.ErrnoException).code ?? 'error'}); it was deleted.`, 'UNSAFE_FILE')+ }+ let text = ''+ let safe = false+ try {+ const stat = deps.fstat(fd)+ safe = stat.isFile() && stat.uid === deps.euid() && (stat.mode & 0o077) === 0 && stat.size <= 4096+ if (safe) {+ const buffer = Buffer.alloc(4096)+ text = buffer.subarray(0, deps.read(fd, buffer)).toString('utf8').trim()+ }+ } finally {+ deps.close(fd)+ try { deps.unlink(path) } catch { /* already gone */ }+ }+ if (!safe) throw new TeamSignInError('The team sign-in file was not this account\'s private file; it was deleted unread.', 'UNSAFE_FILE')+ if (!HANDOFF_CODE.test(text)) throw new TeamSignInError('The team sign-in file did not hold a sign-in code; it was deleted.', 'UNSAFE_FILE')+ return text+}diff --git a/cli/src/team/layout.ts b/cli/src/team/layout.tsnew file mode 100644index 000000000..598cb18bc--- /dev/null+++ b/cli/src/team/layout.ts@@ -0,0 +1,122 @@+/**+ * Where the Harness Team account lives on a Mac, and the checks every value passes before it goes into the+ * 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+ * 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.+ */+import { isAbsolute, normalize } from 'node:path'++export const TEAM_USER = 'harnessteam'+export const TEAM_REAL_NAME = 'Harness Team'+export const TEAM_HOME = `/Users/${TEAM_USER}`+/** The team daemon's control port. Not 18473 (the owner's daemon) or 18474 (a dev daemon beside it): the team+ * daemon runs as its own OS user and would find another port anyway, but a fixed one is easier to audit. */+export const TEAM_PORT = 18493+export const TEAM_LABEL = 'ai.autonomous.harness.team'+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'+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`+export const TEAM_STATUS_FILE = `${TEAM_STATUS_DIR}/status.json`+/** A file in the owner's home, readable by everyone, so only the home folder's own mode keeps it from the team+ * account. Directly in the home: ~/Library is 700 on its own, so a sentinel there would pass even with the home+ * folder open. */+export const SENTINEL_NAME = '.harness-team-privacy'++/** The team account's own files, all inside its home. */+export function teamPaths(home: string = TEAM_HOME) {+ const harness = `${home}/.harness`+ const cli = `${harness}/cli`+ const data = `${cli}/data`+ return {+ home,+ harness,+ cli,+ cliJs: `${cli}/cli.js`,+ data,+ log: `${data}/harness.log`,+ runtime: `${harness}/runtime`,+ auth: `${harness}/auth`,+ session: `${harness}/auth/session.json`,+ 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`,+ }+}++const USER = /^[a-z_][a-z0-9_.-]{0,31}$/+const SAFE_PATH = /^\/[A-Za-z0-9._@+ /-]{0,1023}$/+const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/+const WS_URL = /^wss?:\/\/[A-Za-z0-9.-]{1,253}(:\d{1,5})?(\/[A-Za-z0-9._~/-]{0,200})?$/+const HTTP_URL = /^https?:\/\/[A-Za-z0-9.-]{1,253}(:\d{1,5})?(\/[A-Za-z0-9._~/-]{0,200})?$/++export class TeamInputError extends Error {+ constructor(message: string) {+ super(message)+ this.name = 'TeamInputError'+ }+}++/** A macOS short name: letters, digits and `_.-`, as `dscl` takes them. Never root. */+export function checkUser(user: string, what = 'account'): string {+ if (!USER.test(user) || user === 'root') throw new TeamInputError(`not a usable ${what} name: ${JSON.stringify(user)}`)+ return user+}++/** An absolute path of plain characters, normalized, with no `..`: it goes into a script run as root. */+export function checkPath(path: string, what = 'path'): string {+ if (!isAbsolute(path) || !SAFE_PATH.test(path) || normalize(path) !== path || path.split('/').includes('..')+ || (path.length > 1 && path.endsWith('/'))) {+ throw new TeamInputError(`the ${what} must be a plain absolute path: ${JSON.stringify(path)}`)+ }+ return path+}++/** One path segment (a runtime folder's name). */+export function checkName(name: string, what = 'name'): string {+ if (!NAME.test(name) || name === '.' || name === '..') throw new TeamInputError(`not a usable ${what}: ${JSON.stringify(name)}`)+ return name+}++/** A port the team daemon can bind that is neither the owner's daemon's nor a dev daemon's. */+export function checkPort(port: number): number {+ if (!Number.isInteger(port) || port < 1024 || port > 65535 || port === 18473 || port === 18474) {+ throw new TeamInputError(`not a usable port for the team daemon: ${port}`)+ }+ return port+}++/**+ * The settings that choose which backend the team daemon signs in to, carried from the owner's environment when+ * set (a staging backend in the fresh-Mac VM rig), each checked. Anything else stays the team account's default.+ */+export function carriedBackendEnv(source: NodeJS.ProcessEnv): Record<string, string> {+ const carried: Record<string, string> = {}+ const ws = source.BACKEND_WS_URL?.trim()+ if (ws) {+ if (!WS_URL.test(ws)) throw new TeamInputError(`BACKEND_WS_URL is not a plain ws:// or wss:// address: ${JSON.stringify(ws)}`)+ carried.BACKEND_WS_URL = ws+ }+ const web = source.WEB_URL?.trim()+ if (web) {+ if (!HTTP_URL.test(web)) throw new TeamInputError(`WEB_URL is not a plain http:// or https:// address: ${JSON.stringify(web)}`)+ carried.WEB_URL = web+ }+ const autonomous = source.AUTONOMOUS_ENV?.trim()+ if (autonomous) {+ if (autonomous !== 'prod' && autonomous !== 'stag') throw new TeamInputError(`AUTONOMOUS_ENV must be prod or stag: ${JSON.stringify(autonomous)}`)+ carried.AUTONOMOUS_ENV = autonomous+ }+ const updates = source.ADAPTER_UPDATE_DISABLE?.trim()+ if (updates === 'true' || updates === '1') carried.ADAPTER_UPDATE_DISABLE = 'true'+ return carried+}++/** A handoff code as the shell checks it too: plain token characters only. */+export const HANDOFF_CODE = /^[A-Za-z0-9_-]{16,256}$/diff --git a/cli/src/team/observer.ts b/cli/src/team/observer.tsnew file mode 100644index 000000000..34f56fb78--- /dev/null+++ b/cli/src/team/observer.ts@@ -0,0 +1,19 @@+/** The privacy reading this process sends with its machine's Super Tab observation (superTabs/machines.ts). */+import { userInfo } from 'node:os'+import { readAuthSession } from '../lib/authSession.js'+import { readTeamConfig } from './config.js'+import { TeamPrivacyObserver, runPrivacyCheck, writeTeamStatus, type PrivacyObservation } from './privacy.js'++let observer: TeamPrivacyObserver | null = null++export function teamPrivacyObserver(): PrivacyObservation | null {+ observer ??= new TeamPrivacyObserver({+ config: () => readTeamConfig(),+ user: () => userInfo().username,+ teamSession: () => readAuthSession()?.kind === 'team',+ check: (config) => runPrivacyCheck(config),+ writeStatus: writeTeamStatus,+ now: () => Date.now(),+ })+ return observer.observe()+}diff --git a/cli/src/team/privacy.spec.ts b/cli/src/team/privacy.spec.tsnew file mode 100644index 000000000..92738c177--- /dev/null+++ b/cli/src/team/privacy.spec.ts@@ -0,0 +1,179 @@+import { chmodSync, mkdirSync, mkdtempSync, rmSync, 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, privacyProbes, readTeamStatus, realPrivacyDeps, runPrivacyCheck, writeTeamStatus,+ type PrivacyDeps, type PrivacyResult,+} from './privacy.js'++const OWNER_HOME = '/Users/owner-placeholder'+const config = { ownerHome: OWNER_HOME, sentinel: `${OWNER_HOME}/.harness-team-privacy` }+const errno = (code: string) => Object.assign(new Error(code), { code })+const refusedEverywhere = (over: Partial<PrivacyDeps> = {}): PrivacyDeps => ({+ open: () => { throw errno('EACCES') }, list: () => { throw errno('EACCES') }, groups: () => [20], now: () => 5, ...over,+})++const cleanup: string[] = []+afterEach(() => {+ for (const dir of cleanup.splice(0)) {+ try { chmodSync(dir, 0o700) } catch { /* gone */ }+ rmSync(dir, { recursive: true, force: true })+ }+})++describe('privacy check', () => {+ it('passes only when every probe is refused', () => {+ expect(runPrivacyCheck(config, refusedEverywhere())).toEqual({ passed: true, checkedAt: 5 })+ expect(runPrivacyCheck(config, refusedEverywhere({ list: () => { throw errno('EPERM') } }))).toEqual({ passed: true, checkedAt: 5 })+ })++ it('tries the sentinel, the home listing, ~/.gitconfig, ~/.ssh, project folders, the Keychain, Chrome and Safari', () => {+ const tried: string[] = []+ runPrivacyCheck(config, refusedEverywhere({+ open: (p) => { tried.push(`open ${p}`); throw errno('EACCES') }, list: (p) => { tried.push(`list ${p}`); throw errno('EACCES') },+ }))+ expect(tried).toEqual([+ `open ${OWNER_HOME}/.harness-team-privacy`, `list ${OWNER_HOME}`, `open ${OWNER_HOME}/.gitconfig`, `list ${OWNER_HOME}/.ssh`,+ ...['code', 'Code', 'Developer', 'Projects', 'projects', 'src', 'Documents'].map((name) => `list ${OWNER_HOME}/${name}`),+ `list ${OWNER_HOME}/Library/Keychains`, `list ${OWNER_HOME}/Library/Application Support/Google/Chrome`, `list ${OWNER_HOME}/Library/Safari`,+ ])+ expect(privacyProbes(config).map((p) => p.item)).toEqual(['sentinel', 'home-listing', 'gitconfig', 'ssh', 'projects', 'keychain', 'chrome', 'safari'])+ })++ it('reports the first item it could read, without the owner\'s path', () => {+ const result = runPrivacyCheck(config, refusedEverywhere({ list: (p) => { if (p.endsWith('/Developer')) return; throw errno('EACCES') } }))+ expect(result).toMatchObject({ passed: false, item: 'projects', detail: 'The team account could read your project folders (~/code and the like).' })+ const sentinel = runPrivacyCheck(config, refusedEverywhere({ open: () => {} }))+ expect(sentinel).toMatchObject({ passed: false, item: 'sentinel' })+ for (const r of [result, sentinel]) expect(JSON.stringify(r)).not.toContain(OWNER_HOME)+ })++ it('fails on any answer but a refusal: a missing file means the folder above it was searchable', () => {+ const result = runPrivacyCheck(config, refusedEverywhere({ open: (p) => { throw errno(p.endsWith('.gitconfig') ? 'ENOENT' : 'EACCES') } }))+ expect(result).toMatchObject({ passed: false, item: 'gitconfig' })+ expect((result as { detail: string }).detail).toContain('ENOENT')+ })++ it('fails an administrator team account', () => {+ expect(runPrivacyCheck(config, refusedEverywhere({ groups: () => [20, 80] }))).toMatchObject({ passed: false, item: 'standard-user' })+ })++ it('reads real permission bits: a closed home passes, an open one fails at its first readable item', () => {+ // As the folder's owner the owner bits decide, so they stand in for "another account" here. Root reads anything.+ if (process.getuid?.() === 0) return+ const home = mkdtempSync(join(tmpdir(), 'team-owner-home-'))+ cleanup.push(home)+ writeFileSync(join(home, '.harness-team-privacy'), 'sentinel', { mode: 0o644 })+ writeFileSync(join(home, '.gitconfig'), '[user]', { mode: 0o644 })+ for (const dir of ['code', '.ssh', 'Library/Keychains', 'Library/Safari', 'Library/Application Support/Google/Chrome']) mkdirSync(join(home, dir), { recursive: true })+ const real = { ...realPrivacyDeps, groups: () => [] }+ const target = { ownerHome: home, sentinel: join(home, '.harness-team-privacy') }+ chmodSync(home, 0o000)+ expect(runPrivacyCheck(target, real)).toMatchObject({ passed: true })+ chmodSync(home, 0o700)+ expect(runPrivacyCheck(target, real)).toMatchObject({ passed: false, item: 'sentinel' })+ // Searchable but not listable, its sentinel closed: the listing is refused, ~/.gitconfig is not.+ chmodSync(join(home, '.harness-team-privacy'), 0o000)+ chmodSync(home, 0o100)+ expect(runPrivacyCheck(target, real)).toMatchObject({ passed: false, item: 'gitconfig' })+ })+})++describe('status file', () => {+ it('merges each report into the file, readable by others, through a rename', () => {+ const dir = mkdtempSync(join(tmpdir(), 'team-status-'))+ cleanup.push(dir)+ const file = join(dir, 'Team', 'status.json')+ expect(readTeamStatus(file)).toBeNull()+ writeTeamStatus(file, { signIn: { state: 'signed-in', at: 1 } })+ writeTeamStatus(file, { privacy: { passed: false, item: 'ssh', detail: 'x', checkedAt: 2 } })+ expect(readTeamStatus(file)).toEqual({ version: 1, signIn: { state: 'signed-in', at: 1 }, privacy: { passed: false, item: 'ssh', detail: 'x', checkedAt: 2 } })+ expect(statSync(file).mode & 0o777).toBe(0o644)+ })++ it('drops what it does not recognise', () => {+ expect(readTeamStatus('/x', () => 'not json')).toBeNull()+ expect(readTeamStatus('/x', () => '{"version":2}')).toBeNull()+ expect(readTeamStatus('/x', () => JSON.stringify({ version: 1, signIn: { state: 'odd', at: 1 }, privacy: { passed: false, item: 'other', detail: 'x', checkedAt: 1 } })))+ .toEqual({ version: 1 })+ expect(readTeamStatus('/x', () => JSON.stringify({ version: 1, privacy: { passed: true, checkedAt: 3 }, signIn: { state: 'failed', at: 2, detail: 'expired' } })))+ .toEqual({ version: 1, privacy: { passed: true, checkedAt: 3 }, signIn: { state: 'failed', at: 2, detail: 'expired' } })+ })+})++const teamConfig: TeamConfig = {+ version: 1, user: 'harnessteam', realName: 'Harness Team', home: '/Users/harnessteam', owner: 'owner-placeholder', ownerHome: OWNER_HOME,+ sentinel: `${OWNER_HOME}/.harness-team-privacy`, port: 18493, label: 'ai.autonomous.harness.team',+ plist: '/Library/LaunchDaemons/ai.autonomous.harness.team.plist', statusFile: '/Library/Application Support/Harness/Team/status.json',+ node: '/Users/harnessteam/.harness/runtime/node-v1/bin/node', cli: '/Users/harnessteam/.harness/cli/cli.js', env: { AUTONOMOUS_ENV: 'stag' },+ createdAt: '2026-10-24T00:00:00.000Z',+}++describe('team config', () => {+ it('reads back what setup writes, and nothing it did not', () => {+ expect(readTeamConfig('/x', () => teamConfigJson(teamConfig))).toEqual(teamConfig)+ expect(readTeamConfig('/x', () => { throw errno('ENOENT') })).toBeNull()+ expect(readTeamConfig('/x', () => JSON.stringify({ ...teamConfig, version: 2 }))).toBeNull()+ expect(readTeamConfig('/x', () => JSON.stringify({ ...teamConfig, ownerHome: '/Users/../etc' }))).toBeNull()+ expect(readTeamConfig('/x', () => JSON.stringify({ ...teamConfig, port: 18473 }))).toBeNull()+ expect(readTeamConfig('/x', () => JSON.stringify({ ...teamConfig, user: '' }))).toBeNull()+ expect(readTeamConfig('/x', () => JSON.stringify({ ...teamConfig, env: { BACKEND_WS_URL: 'javascript:x' } }))).toBeNull()+ })+})++describe('privacy observer', () => {+ function observer(over: { user?: string; config?: TeamConfig | null; team?: boolean; result?: PrivacyResult | (() => PrivacyResult) } = {}) {+ let now = 1_000+ const given = over.result+ const check = vi.fn((): PrivacyResult => typeof given === 'function' ? given() : given ?? { passed: true, checkedAt: now })+ const writeStatus = vi.fn()+ const o = new TeamPrivacyObserver({+ config: () => over.config === undefined ? teamConfig : over.config, user: () => over.user ?? 'harnessteam',+ teamSession: () => over.team ?? false, check, writeStatus, now: () => now,+ })+ return { o, check, writeStatus, step: (ms: number) => { now += ms } }+ }++ it('checks in the team account, at most every five minutes, and reports it for the owner', () => {+ const f = observer()+ expect(f.o.observe()).toEqual({ mode: 'account', passed: true, checkedAt: 1_000 })+ f.step(PRIVACY_RECHECK_MS - 1)+ f.o.observe()+ expect(f.check).toHaveBeenCalledTimes(1)+ f.step(1)+ f.o.observe()+ expect(f.check).toHaveBeenCalledTimes(2)+ expect(f.writeStatus).toHaveBeenLastCalledWith(teamConfig.statusFile, { privacy: { passed: true, checkedAt: 1_000 + PRIVACY_RECHECK_MS } })+ })++ it('reports a check that throws as unchecked, never as private', () => {+ const f = observer({ result: () => { throw new Error('boom') } })+ expect(f.o.observe()).toMatchObject({ mode: 'account', passed: false, item: 'unchecked' })+ })++ it('keeps reporting when the status file cannot be written', () => {+ const f = observer()+ f.writeStatus.mockImplementation(() => { throw new Error('read-only') })+ expect(f.o.observe()).toMatchObject({ mode: 'account', passed: true })+ })++ it('reports a dedicated computer, and nothing for the owner\'s own daemon', () => {+ expect(observer({ user: 'owner-placeholder', team: true }).o.observe()).toEqual({ mode: 'dedicated' })+ expect(observer({ config: null, team: true }).o.observe()).toEqual({ mode: 'dedicated' })+ const owner = observer({ user: 'owner-placeholder' })+ expect(owner.o.observe()).toBeNull()+ expect(owner.check).not.toHaveBeenCalled()+ })++ it('writes its status through the real file helpers', () => {+ const dir = mkdtempSync(join(tmpdir(), 'team-observer-'))+ cleanup.push(dir)+ const file = join(dir, 'status.json')+ const o = new TeamPrivacyObserver({ config: () => ({ ...teamConfig, statusFile: file }), user: () => 'harnessteam', teamSession: () => false,+ check: () => ({ passed: true, checkedAt: 7 }), writeStatus: writeTeamStatus, now: () => 7 })+ o.observe()+ expect(JSON.parse(readFileSync(file, 'utf8'))).toEqual({ version: 1, privacy: { passed: true, checkedAt: 7 } })+ })+})diff --git a/cli/src/team/privacy.ts b/cli/src/team/privacy.tsnew file mode 100644index 000000000..61925b624--- /dev/null+++ b/cli/src/team/privacy.ts@@ -0,0 +1,188 @@+/**+ * The Harness Team account's privacy check (docs/plans/2026-10-24-swarm-team-account.md, Task 2), run by the team+ * daemon itself, as the team account: as its job starts (`harness team __start`) and while it serves a Swarm+ * (superTabs/machines.ts, at most every PRIVACY_RECHECK_MS).+ *+ * A second account alone is not private. On macOS every local account is in the group staff, a home folder is+ * `drwxr-x---` with that group by default, and `~/code` (755) or `~/.gitconfig` (644) inside it are readable by any+ * other account on the Mac. Setup makes the owner's home 700; this proves it, from the side that matters, every+ * 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 { closeSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, writeFileSync } from 'node:fs'+import { dirname } from 'node:path'+import type { TeamConfig } from './config.js'++export type PrivacyItem =+ | 'sentinel' | 'home-listing' | 'gitconfig' | 'ssh' | 'projects' | 'keychain' | 'chrome' | 'safari' | 'standard-user'++export type PrivacyResult =+ | { passed: true; checkedAt: number }+ | { passed: false; item: PrivacyItem | 'unchecked'; detail: string; checkedAt: number }++interface Probe { item: PrivacyItem; what: string; kind: 'read' | 'list'; paths: string[] }++/** The folders people keep projects in: listing any of them must be refused. */+const PROJECT_FOLDERS = ['code', 'Code', 'Developer', 'Projects', 'projects', 'src', 'Documents']++/** What the check tries, in order. `what` is shown to people and sent with the machine's reading, so it names a+ * place by `~`, never by the owner's absolute path (which carries their account name). */+export function privacyProbes(config: Pick<TeamConfig, 'ownerHome' | 'sentinel'>): Probe[] {+ const home = config.ownerHome+ return [+ { item: 'sentinel', what: 'the privacy sentinel in your home folder', kind: 'read', paths: [config.sentinel] },+ { item: 'home-listing', what: 'the list of files in your home folder', kind: 'list', paths: [home] },+ { item: 'gitconfig', what: '~/.gitconfig', kind: 'read', paths: [`${home}/.gitconfig`] },+ { item: 'ssh', what: '~/.ssh', kind: 'list', paths: [`${home}/.ssh`] },+ { item: 'projects', what: 'your project folders (~/code and the like)', kind: 'list', paths: PROJECT_FOLDERS.map((name) => `${home}/${name}`) },+ { item: 'keychain', what: 'your login Keychain folder', kind: 'list', paths: [`${home}/Library/Keychains`] },+ { item: 'chrome', what: 'Chrome\'s profile folder', kind: 'list', paths: [`${home}/Library/Application Support/Google/Chrome`] },+ { item: 'safari', what: 'Safari\'s folder', kind: 'list', paths: [`${home}/Library/Safari`] },+ ]+}++export interface PrivacyDeps {+ /** Opens and closes [path] for reading; throws as the system does. */+ open(path: string): void+ /** Lists [path]; throws as the system does. */+ list(path: string): void+ /** This process's group ids. */+ groups(): number[]+ now(): number+}++export const realPrivacyDeps: PrivacyDeps = {+ open: (path) => closeSync(openSync(path, 'r')),+ list: (path) => { readdirSync(path) },+ groups: () => process.getgroups?.() ?? [],+ now: () => Date.now(),+}++/** The group macOS administrators are in. */+const ADMIN_GID = 80++const refused = (error: unknown): boolean => {+ const code = (error as NodeJS.ErrnoException | null)?.code+ return code === 'EACCES' || code === 'EPERM'+}++export function runPrivacyCheck(config: Pick<TeamConfig, 'ownerHome' | 'sentinel'>, deps: PrivacyDeps = realPrivacyDeps): PrivacyResult {+ const checkedAt = deps.now()+ for (const probe of privacyProbes(config)) {+ for (const path of probe.paths) {+ try {+ if (probe.kind === 'read') deps.open(path)+ else deps.list(path)+ } catch (error) {+ if (refused(error)) continue+ const code = (error as NodeJS.ErrnoException | null)?.code ?? 'an error'+ // ENOENT under a home folder at 700 cannot happen: the folder would have refused the search first.+ return { passed: false, item: probe.item, checkedAt,+ detail: `The team account was not refused ${probe.what} (it got ${code}), so your home folder is not private.` }+ }+ return { passed: false, item: probe.item, checkedAt, detail: `The team account could read ${probe.what}.` }+ }+ }+ if (deps.groups().includes(ADMIN_GID)) {+ return { passed: false, item: 'standard-user', checkedAt, detail: 'The team account is an administrator; it must be a standard user.' }+ }+ return { passed: true, checkedAt }+}++/** What the team daemon reports for the owner's `harness team status`, in the team account's status folder. */+export interface TeamStatus {+ version: 1+ signIn?: { state: 'signed-in' | 'failed' | 'signed-out'; at: number; detail?: string }+ privacy?: PrivacyResult+}++const ITEMS = new Set<string>(['sentinel', 'home-listing', 'gitconfig', 'ssh', 'projects', 'keychain', 'chrome', 'safari', 'standard-user', 'unchecked'])++function privacyOf(value: unknown): PrivacyResult | undefined {+ if (!value || typeof value !== 'object') return undefined+ const v = value as Record<string, unknown>+ if (typeof v.checkedAt !== 'number' || !Number.isFinite(v.checkedAt)) return undefined+ if (v.passed === true) return { passed: true, checkedAt: v.checkedAt }+ if (v.passed === false && typeof v.item === 'string' && ITEMS.has(v.item) && typeof v.detail === 'string') {+ return { passed: false, item: v.item as PrivacyItem, detail: v.detail.slice(0, 300), checkedAt: v.checkedAt }+ }+ return undefined+}++export function readTeamStatus(path: string, read: (path: string) => string = (p) => readFileSync(p, 'utf8')): TeamStatus | null {+ let raw: unknown+ try { raw = JSON.parse(read(path)) } catch { return null }+ if (!raw || typeof raw !== 'object' || (raw as { version?: unknown }).version !== 1) return null+ const value = raw as Record<string, unknown>+ const status: TeamStatus = { version: 1 }+ const signIn = value.signIn as Record<string, unknown> | undefined+ if (signIn && typeof signIn === 'object' && ['signed-in', 'failed', 'signed-out'].includes(String(signIn.state)) && typeof signIn.at === 'number') {+ status.signIn = { state: signIn.state as 'signed-in', at: signIn.at, ...(typeof signIn.detail === 'string' ? { detail: signIn.detail.slice(0, 300) } : {}) }+ }+ const privacy = privacyOf(value.privacy)+ if (privacy) status.privacy = privacy+ return status+}++/** Merge [update] into the status file, through a temporary file and a rename: the owner's reader never sees half. */+export function writeTeamStatus(path: string, update: Partial<Omit<TeamStatus, 'version'>>): void {+ const next: TeamStatus = { ...(readTeamStatus(path) ?? { version: 1 }), ...update, version: 1 }+ mkdirSync(dirname(path), { recursive: true })+ const temp = `${path}.${process.pid}.next`+ writeFileSync(temp, `${JSON.stringify(next)}\n`, { mode: 0o644 })+ renameSync(temp, path)+}++/** How often a team daemon serving a Swarm checks again: a home folder opened again shows within this long. */+export const PRIVACY_RECHECK_MS = 5 * 60_000++/**+ * The privacy field of the machine's Super Tab reading (superTabs/machines.ts), which routing reads (Task 3):+ * - `account`: this daemon runs in the Harness Team account; `passed`, or the first item that failed.+ * - `dedicated`: the whole computer is for agents (`harness team on`), with no owner's files on it to protect.+ * The owner's own daemon reports nothing.+ */+export type PrivacyObservation =+ | { mode: 'account'; passed: true; checkedAt: number }+ | { mode: 'account'; passed: false; item: PrivacyItem | 'unchecked'; detail: string; checkedAt: number }+ | { mode: 'dedicated' }++export interface PrivacyObserverDeps {+ config(): TeamConfig | null+ /** The account this process runs as. */+ user(): string+ /** This computer's stored sign-in is a team session. */+ teamSession(): boolean+ check(config: TeamConfig): PrivacyResult+ writeStatus(path: string, update: Partial<Omit<TeamStatus, 'version'>>): void+ now(): number+}++export class TeamPrivacyObserver {+ private last: PrivacyResult | null = null+ constructor(private readonly deps: PrivacyObserverDeps) {}++ /** This daemon runs in the Harness Team account that setup made. */+ inTeamAccount(): TeamConfig | null {+ const config = this.deps.config()+ return config && config.user === this.deps.user() ? config : null+ }++ observe(): PrivacyObservation | null {+ const config = this.inTeamAccount()+ if (config) {+ const now = this.deps.now()+ if (!this.last || now - this.last.checkedAt >= PRIVACY_RECHECK_MS || now < this.last.checkedAt) {+ try {+ this.last = this.deps.check(config)+ } catch (error) {+ this.last = { passed: false, item: 'unchecked', checkedAt: now, detail: `The privacy check did not run: ${(error as Error).message}` }+ }+ // The owner's status line is a convenience; the reading is what routing trusts.+ try { this.deps.writeStatus(config.statusFile, { privacy: this.last }) } catch { /* reported next time */ }+ }+ return { mode: 'account', ...this.last }+ }+ return this.deps.teamSession() ? { mode: 'dedicated' } : null+ }+}diff --git a/cli/src/team/script.spec.ts b/cli/src/team/script.spec.tsnew file mode 100644index 000000000..c938f67ad--- /dev/null+++ b/cli/src/team/script.spec.ts@@ -0,0 +1,281 @@+/**+ * The privileged scripts are tested as text, and their pieces that run as an ordinary account are run here against+ * temporary folders. Nothing in this file creates a user, changes a permission outside a temporary folder, or calls+ * osascript, launchctl, dscl or sudo: the whole scripts are only parsed (`sh -n`), never run.+ */+import { execFileSync, spawnSync } from 'node:child_process'+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, rmSync, statSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+import {+ SENTINEL_TEXT, TEAM_COPY, TEAM_JOB_WRAPPER, WRITE_PRIVATE, WRITE_PUBLIC, buildRemoveScript, buildSetupScript, sh, teamLaunchdPlist,+ type SetupScriptInput,+} from './script.js'++const OWNER_HOME = '/Users/owner-placeholder'+const NODE_DIR = `${OWNER_HOME}/.harness/runtime/node-v22.23.2-darwin-arm64`+const input = (over: Partial<SetupScriptInput> = {}): SetupScriptInput => ({+ user: 'harnessteam', realName: 'Harness Team', home: '/Users/harnessteam', owner: 'owner-placeholder', ownerHome: OWNER_HOME,+ stageDir: '/private/var/folders/aa/T/harness-team-x1', nodeRuntimeDir: NODE_DIR, tmuxRuntimeDir: null,+ cliDir: `${OWNER_HOME}/.harness/cli`, ownerNode: `${NODE_DIR}/bin/node`, ownerCli: `${OWNER_HOME}/.harness/cli/cli.js`,+ mintEnv: {}, signIn: 'missing', ...over,+})++const cleanup: string[] = []+afterEach(() => {+ for (const dir of cleanup.splice(0)) {+ try { execFileSync('chmod', ['-R', 'u+rwx', dir]) } catch { /* gone */ }+ rmSync(dir, { recursive: true, force: true })+ }+})+function temp(): string {+ const dir = mkdtempSync(join(tmpdir(), 'team-script-'))+ cleanup.push(dir)+ return dir+}+/** Parses a script without running a line of it. */+function parses(script: string): void {+ const file = join(temp(), 'script.sh')+ writeFileSync(file, script)+ const result = spawnSync('/bin/sh', ['-n', file], { encoding: 'utf8' })+ expect(result.stderr).toBe('')+ expect(result.status).toBe(0)+}+const at = (script: string, needle: string): number => {+ const index = script.indexOf(needle)+ expect(index, needle).toBeGreaterThanOrEqual(0)+ return index+}++describe('sh', () => {+ it('single-quotes every word, a quote inside included', () => {+ expect(sh('a b')).toBe("'a b'")+ expect(sh("it's")).toBe("'it'\\''s'")+ expect(execFileSync('/bin/sh', ['-c', `printf '%s' ${sh("x'; touch /nope; '$(id)`")}`], { encoding: 'utf8' })).toBe("x'; touch /nope; '$(id)`")+ })+})++describe('setup script', () => {+ it('parses, and names every value once, single-quoted', () => {+ const script = buildSetupScript(input({ mintEnv: { BACKEND_WS_URL: 'wss://backend.example.test', HARNESS_AUTH_DIR: '/tmp/auth dir' } }))+ parses(script)+ expect(script).toContain("TEAM='harnessteam'")+ expect(script).toContain("TEAM_NAME='Harness Team'")+ expect(script).toContain(`OWNER_HOME='${OWNER_HOME}'`)+ expect(script).toContain("PLIST='/Library/LaunchDaemons/ai.autonomous.harness.team.plist'")+ expect(script).toContain("CONFIG='/Library/Application Support/Harness/team.json'")+ expect(script).toContain(`SENTINEL='${OWNER_HOME}/.harness-team-privacy'`)+ expect(script).toContain("'BACKEND_WS_URL=wss://backend.example.test' 'HARNESS_AUTH_DIR=/tmp/auth dir' \"$OWNER_NODE\" \"$OWNER_CLI\" team __handoff")+ // The owner's paths appear only in their assignments: every use goes through the quoted variable.+ expect(script.split(OWNER_HOME).length - 1).toBe(6)+ })++ it('makes a visible, standard account with an unusable 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 '*'")+ expect(script).toContain('dscl . -create "/Users/$TEAM" PrimaryGroupID 20')+ expect(script).not.toMatch(/IsHidden 1/)+ expect(script).toContain('dscl . -delete "/Users/$TEAM" IsHidden')+ expect(script).toContain('dseditgroup -o edit -d "$TEAM" -t user admin')+ expect(script).not.toMatch(/-a "\$TEAM" -t user admin|GroupMembership "\$TEAM"/)+ // An account by that name that is not ours is refused, not taken over.+ expect(script).toContain('already exists and is not the Harness Team account')+ })++ it('runs its steps in order: account, homes, stop, runtime, config, sign-in, daemon', () => {+ const script = buildSetupScript(input())+ const order = [+ 'owned_by_root "$dir"', 'dscl . -create "/Users/$TEAM"', 'chmod 700 "$TEAM_HOME"', 'chmod 700 "$OWNER_HOME"',+ 'as_owner /bin/sh -c', 'launchctl bootout "system/$LABEL"', 'mktemp -d /private/var/tmp/harness-team.XXXXXX', 'as_team /bin/sh -c',+ 'install -o 0 -g 0 -m 0644 "$STAGE/team.json" "$CONFIG"', 'team __handoff', 'as_team /bin/sh -c \'umask 077',+ 'install -o 0 -g 0 -m 0644 "$STAGE/team.plist" "$PLIST"', 'launchctl bootstrap system "$PLIST"',+ ].map((needle) => at(script, needle))+ expect([...order].sort((a, b) => a - b)).toEqual(order)+ })++ it('never writes inside the team home as root: the team account copies and writes its own files', () => {+ const script = buildSetupScript(input())+ for (const line of script.split('\n')) {+ if (/^\s*(cp|mv|ln|printf|cat|install)\b/.test(line) && !line.includes('| as_team') && !line.includes('| as_owner')) {+ expect(line, line).not.toMatch(/TEAM_HOME|HANDOFF|TEAM_SESSION/)+ }+ }+ expect(script).toContain('printf \'%s\\n\' "$code" | as_team /bin/sh -c')+ expect(script).toContain(`| as_owner /bin/sh -c ${sh(WRITE_PUBLIC)} sh "$SENTINEL"`)+ })++ it('hands over a sign-in only when the team account has none, unless asked again', () => {+ expect(buildSetupScript(input())).toContain("SIGN_IN='missing'")+ expect(buildSetupScript(input({ signIn: 'always' }))).toContain("SIGN_IN='always'")+ expect(buildSetupScript(input())).toContain('if [ "$SIGN_IN" = always ] || [ ! -s "$TEAM_SESSION" ]; then')+ })++ 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` }))+ expect(script).toContain("TMUX_NAME='tmux-3.5a-darwin-arm64'")+ parses(script)+ })++ it('refuses a value that is not plain, before anything is written', () => {+ const bad: Array<Partial<SetupScriptInput>> = [+ { user: "harness'team" }, { user: 'root' }, { user: 'Harness Team' }, { owner: 'owner;id' }, { owner: 'harnessteam' },+ { ownerHome: "/Users/a'b" }, { ownerHome: '/Users/a$(id)' }, { ownerHome: '/Users/../etc' }, { ownerHome: 'Users/rel' },+ { ownerHome: '/Users/a\nb' }, { ownerHome: '/Users/harnessteam' }, { home: `${OWNER_HOME}/team` },+ { stageDir: '/tmp/`id`' }, { nodeRuntimeDir: '/x/node"v' }, { realName: 'Harness "Team"' },+ { mintEnv: { 'BAD-NAME': 'x' } }, { mintEnv: { BACKEND_WS_URL: 'wss://x\n' } },+ ]+ for (const over of bad) expect(() => buildSetupScript(input(over)), JSON.stringify(over)).toThrow()+ })+})++describe('the team account\'s copy of the runtime', () => {+ it('lays the runtime, the CLI and the harness launcher into the home it is given, privately', () => {+ const root = temp()+ const stage = join(root, 'stage'), home = join(root, 'home')+ mkdirSync(join(stage, 'node', 'bin'), { recursive: true })+ mkdirSync(join(stage, 'cli'), { recursive: true })+ mkdirSync(home)+ writeFileSync(join(stage, 'node', 'bin', 'node'), '#!/bin/sh\necho node "$@"\n', { mode: 0o755 })+ writeFileSync(join(stage, 'cli', 'cli.js'), '// cli')+ writeFileSync(join(stage, 'cli', 'package.json'), '{"type":"module"}')+ // A second run replaces what the first laid down.+ for (let run = 0; run < 2; run++) execFileSync('/bin/sh', ['-c', TEAM_COPY, 'sh', stage, home, 'node-v1', ''])+ const runtime = join(home, '.harness', 'runtime')+ expect(readFileSync(join(runtime, 'current-node'), 'utf8')).toBe(`${runtime}/node-v1/bin/node\n`)+ expect(existsSync(join(runtime, 'node-v1.next'))).toBe(false)+ expect(readFileSync(join(home, '.harness', 'cli', 'cli.js'), 'utf8')).toBe('// cli')+ expect(existsSync(join(home, '.harness', 'cli', 'notify.mjs'))).toBe(false)+ expect(statSync(join(home, '.harness')).mode & 0o777).toBe(0o700)+ expect(statSync(join(home, '.harness', 'auth')).mode & 0o777).toBe(0o700)+ const launcher = join(home, '.local', 'bin', 'harness')+ expect(readFileSync(launcher, 'utf8')).toBe(`#!/bin/sh\nexec "${runtime}/node-v1/bin/node" "${home}/.harness/cli/cli.js" "$@"\n`)+ expect(execFileSync(launcher, ['status'], { encoding: 'utf8' })).toBe(`node ${home}/.harness/cli/cli.js status\n`)+ })++ it('links a managed tmux when one is staged', () => {+ const root = temp()+ const stage = join(root, 'stage'), home = join(root, 'home')+ mkdirSync(join(stage, 'node', 'bin'), { recursive: true })+ mkdirSync(join(stage, 'tmux', 'bin'), { recursive: true })+ mkdirSync(join(stage, 'cli'), { recursive: true })+ mkdirSync(home)+ writeFileSync(join(stage, 'tmux', 'bin', 'tmux'), '#!/bin/sh\n', { mode: 0o755 })+ execFileSync('/bin/sh', ['-c', TEAM_COPY, 'sh', stage, home, 'node-v1', 'tmux-3'])+ const runtime = join(home, '.harness', 'runtime')+ expect(readFileSync(join(runtime, 'current-tmux'), 'utf8')).toBe(`${runtime}/tmux-3/bin/tmux\n`)+ expect(readlinkSync(join(home, '.local', 'bin', 'tmux'))).toBe(`${runtime}/tmux-3/bin/tmux`)+ })++ it('writes the sign-in file readable by its owner alone, and the sentinel readable by everyone', () => {+ const dir = temp()+ execFileSync('/bin/sh', ['-c', WRITE_PRIVATE, 'sh', join(dir, 'handoff')], { input: 'code\n' })+ expect(readFileSync(join(dir, 'handoff'), 'utf8')).toBe('code\n')+ expect(statSync(join(dir, 'handoff')).mode & 0o777).toBe(0o600)+ execFileSync('/bin/sh', ['-c', WRITE_PUBLIC, 'sh', join(dir, 'sentinel')], { input: `${SENTINEL_TEXT}\n` })+ expect(statSync(join(dir, 'sentinel')).mode & 0o777).toBe(0o644)+ expect(existsSync(join(dir, 'sentinel.next'))).toBe(false)+ })+})++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' } }++ it('runs the team daemon as the team account, on its own port and data folder, and never as a platform agent', () => {+ const plist = teamLaunchdPlist(plistInput)+ expect(plist).toContain('<key>Label</key>\n\t<string>ai.autonomous.harness.team</string>')+ expect(plist).toContain('<key>UserName</key>\n\t<string>harnessteam</string>')+ expect(plist).toContain('<key>PORT</key>\n\t\t<string>18493</string>')+ expect(plist).toContain('<key>ADAPTER_DATA_DIR</key>\n\t\t<string>/Users/harnessteam/.harness/cli/data</string>')+ expect(plist).toContain('<key>HOME</key>\n\t\t<string>/Users/harnessteam</string>')+ expect(plist).toContain('<string>wss://backend.example.test/a&b</string>')+ expect(plist).toContain('<string>/Users/harnessteam/.harness/team-handoff</string>')+ // The log is opened by the job as the team account, never by launchd, which may open it as root.+ expect(plist).not.toContain('StandardOutPath')+ expect(plist).not.toContain('StandardErrorPath')+ expect(plist).not.toContain('HARNESSD_PLATFORM')+ expect(plist).toContain('<string>Standard</string>')+ if (existsSync('/usr/bin/plutil')) {+ const file = join(temp(), 'team.plist')+ writeFileSync(file, plist)+ expect(execFileSync('/usr/bin/plutil', ['-lint', file], { encoding: 'utf8' })).toContain('OK')+ }+ })++ it('refuses a port the owner\'s or a dev daemon uses, and a value it cannot carry', () => {+ expect(() => teamLaunchdPlist({ ...plistInput, port: 18473 })).toThrow()+ expect(() => teamLaunchdPlist({ ...plistInput, port: 18474 })).toThrow()+ expect(() => teamLaunchdPlist({ ...plistInput, env: { 'A B': 'x' } })).toThrow()+ expect(() => teamLaunchdPlist({ ...plistInput, node: 'relative/node' })).toThrow()+ })++ it('redeems and checks before the daemon, then becomes the daemon, logging both as the team account', () => {+ const dir = temp()+ const node = join(dir, 'node')+ writeFileSync(node, '#!/bin/sh\necho "ran: $*"\n', { mode: 0o755 })+ const log = join(dir, 'harness.log')+ execFileSync('/bin/sh', ['-c', TEAM_JOB_WRAPPER, 'harness-team', node, '/x/cli.js', '/x/team-handoff', log])+ expect(readFileSync(log, 'utf8')).toBe('ran: /x/cli.js team __start /x/team-handoff\nran: /x/cli.js __harnessd\n')+ })++ it('starts the daemon even when the start step fails', () => {+ const dir = temp()+ const node = join(dir, 'node')+ writeFileSync(node, '#!/bin/sh\n[ "$2" = team ] && exit 3\necho "daemon"\n', { mode: 0o755 })+ const log = join(dir, 'harness.log')+ execFileSync('/bin/sh', ['-c', TEAM_JOB_WRAPPER, 'harness-team', node, '/x/cli.js', '/x/h', log])+ expect(readFileSync(log, 'utf8')).toBe('daemon\n')+ })+})++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' } }++ it('parses, signs the account out as itself first, then removes the job, the account and its files', () => {+ const script = buildRemoveScript(removeInput)+ parses(script)+ 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"',+ ].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 owner's home folder stays private: nothing here changes its mode.+ expect(script).not.toMatch(/chmod/)+ })++ it('leaves an account or a home that is not the Harness Team account\'s alone', () => {+ 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()+ })+})++describe('real permission bits on a temporary folder', () => {+ it('the staged runtime folder is readable by others but changeable by its owner alone', () => {+ // What `chmod -R a+rX,go-w` gives the staging folder the team account reads from.+ const dir = temp()+ mkdirSync(join(dir, 'bin'))+ writeFileSync(join(dir, 'bin', 'node'), '', { mode: 0o700 })+ writeFileSync(join(dir, 'cli.js'), '', { mode: 0o600 })+ chmodSync(dir, 0o700)+ execFileSync('chmod', ['-R', 'a+rX,go-w', dir])+ // An executable stays one for the team account; a plain file only becomes readable.+ expect(statSync(join(dir, 'bin', 'node')).mode & 0o777).toBe(0o755)+ expect(statSync(join(dir, 'cli.js')).mode & 0o777).toBe(0o644)+ expect(statSync(join(dir, 'bin')).mode & 0o777).toBe(0o755)+ })+})diff --git a/cli/src/team/script.ts b/cli/src/team/script.tsnew file mode 100644index 000000000..932faa334--- /dev/null+++ b/cli/src/team/script.ts@@ -0,0 +1,421 @@+/**+ * The privileged scripts behind `harness team setup` and `harness team remove`, and the LaunchDaemon that runs the+ * team daemon (docs/plans/2026-10-24-swarm-team-account.md, Task 2). Each is built here as text, checked by its+ * spec, and run once as root behind the macOS administrator prompt (./admin.ts).+ *+ * Rules every line follows:+ * - Every value is checked against a strict pattern first (./layout.ts) and goes into the script single-quoted.+ * Nothing a person typed reaches the shell unquoted, and nothing reaches it that the pattern did not allow.+ * - Root never writes inside the team account's home. That account may run a teammate's agent, which could plant a+ * symbolic link where root is about to write and turn the write into one anywhere on disk. Root makes the home+ * folder itself (its parent, /Users, is root's) and stages files in a folder only root can change; the team+ * account copies them in itself (`as_team`). Likewise the sentinel in the owner's home is written as the owner.+ * - Every step checks what is there, so a second run repairs a first one that stopped part-way.+ */+import {+ SENTINEL_NAME, TEAM_CONFIG_FILE, TEAM_LABEL, TEAM_PLIST, TEAM_SHARED_DIR, TEAM_STATUS_DIR,+ checkName, checkPath, checkPort, checkUser, teamPaths,+} from './layout.js'++/** POSIX single quotes: the one quoting with no special characters inside. */+export function sh(word: string): string {+ return `'${word.replaceAll("'", `'\\''`)}'`+}++const xml = (text: string): string =>+ text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''')++const ENV_NAME = /^[A-Z_][A-Z0-9_]{0,63}$/+// eslint-disable-next-line no-control-regex+const CONTROL = /[\u0000-\u001f\u007f]/++function checkEnv(env: Record<string, string>): Record<string, string> {+ for (const [name, value] of Object.entries(env)) {+ if (!ENV_NAME.test(name) || CONTROL.test(value) || value.length > 1024) {+ throw new Error(`the team daemon cannot carry ${JSON.stringify(name)}=${JSON.stringify(value)}`)+ }+ }+ return env+}++/** What `team __start` is run with before the master, as the team account: redeem a handed-over sign-in code if+ * there is one, run the privacy check, then the daemon. Positional, so no path is ever part of the shell source. */+export const TEAM_JOB_WRAPPER = '"$1" "$2" team __start "$3" >>"$4" 2>&1; exec "$1" "$2" __harnessd >>"$4" 2>&1'++export interface TeamPlistInput {+ label?: string+ user: string+ home: string+ /** The team account's own Node and CLI. */+ node: string+ cli: string+ port: number+ /** Backend settings carried from the owner's environment (./layout.ts `carriedBackendEnv`). */+ env: Record<string, string>+}++/**+ * The LaunchDaemon: launchd runs the team daemon as the team account from boot, and again if it crashes.+ *+ * No StandardOutPath: launchd may open it as root, inside a home the team account controls. The wrapper opens the+ * log itself, as the team account. No HARNESSD_PLATFORM either: that names the owner's own launchd agent+ * (harnessd/platform.ts), which `harness stop` inside the team account would otherwise try to stop.+ */+export function teamLaunchdPlist(input: TeamPlistInput): string {+ const user = checkUser(input.user)+ const home = checkPath(input.home, 'team home')+ const node = checkPath(input.node, 'team Node')+ const cli = checkPath(input.cli, 'team CLI')+ const port = checkPort(input.port)+ const paths = teamPaths(home)+ const environment = {+ HOME: home, USER: user, LOGNAME: user, SHELL: '/bin/zsh', LANG: 'en_US.UTF-8',+ PATH: `${paths.bin}:/usr/bin:/bin:/usr/sbin:/sbin`,+ ADAPTER_DATA_DIR: paths.data, PORT: String(port),+ ...checkEnv(input.env),+ }+ const vars = Object.entries(environment).map(([name, value]) => `\t\t<key>${xml(name)}</key>\n\t\t<string>${xml(value)}</string>`).join('\n')+ const args = ['/bin/sh', '-c', TEAM_JOB_WRAPPER, 'harness-team', node, cli, paths.handoff, paths.log]+ return `<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<!-- The Harness Team account's daemon: Swarm work on this Mac runs as the separate user "${xml(user)}", which cannot+ read the owner's files. Written by "harness team setup"; "harness team status" shows it, "harness team remove"+ removes it with the account. -->+<plist version="1.0">+<dict>+ <key>Label</key>+ <string>${xml(input.label ?? TEAM_LABEL)}</string>+ <key>UserName</key>+ <string>${xml(user)}</string>+ <key>GroupName</key>+ <string>staff</string>+ <key>InitGroups</key>+ <true/>+ <key>ProgramArguments</key>+ <array>+${args.map((arg) => `\t\t<string>${xml(arg)}</string>`).join('\n')}+ </array>+ <key>EnvironmentVariables</key>+ <dict>+${vars}+ </dict>+ <key>WorkingDirectory</key>+ <string>${xml(home)}</string>+ <key>RunAtLoad</key>+ <true/>+ <!-- Again after a crash, not after a clean exit: a clean exit is a stop someone asked for, or a sign-in that ended. -->+ <key>KeepAlive</key>+ <dict>+ <key>SuccessfulExit</key>+ <false/>+ <key>Crashed</key>+ <true/>+ </dict>+ <key>ThrottleInterval</key>+ <integer>10</integer>+ <key>ExitTimeOut</key>+ <integer>10</integer>+ <!-- The agents live in tmux and outlive the daemon, as they do for the owner's. -->+ <key>AbandonProcessGroup</key>+ <true/>+ <!-- Not Interactive like the owner's own daemon: the person at this Mac comes first. -->+ <key>ProcessType</key>+ <string>Standard</string>+</dict>+</plist>+`+}++export interface SetupScriptInput {+ user: string+ realName: string+ home: string+ owner: string+ ownerHome: string+ /** The owner's private staging folder, holding `team.json` and `team.plist`. */+ stageDir: string+ /** The owner's managed Node runtime folder (`~/.harness/runtime/node-…`), copied for the team account. */+ nodeRuntimeDir: string+ /** The owner's managed tmux folder, when the installer put one under ~/.harness/runtime; else Homebrew's serves. */+ tmuxRuntimeDir: string | null+ /** The owner's installed CLI folder (`~/.harness/cli`): cli.js, notify.mjs, package.json. */+ cliDir: string+ /** The owner's Node and CLI, run as the owner to mint the team sign-in code at the moment it is handed over. */+ ownerNode: string+ ownerCli: string+ /** Settings for that run: which backend, which sign-in folder. */+ mintEnv: Record<string, string>+ /** `missing`: hand over a sign-in only when the team account has none. `always`: a new one regardless. */+ signIn: 'missing' | 'always'+}++const basename = (path: string): string => path.slice(path.lastIndexOf('/') + 1)++/** The team account copies the staged runtime into its own home: run as that account, never as root. */+export const TEAM_COPY = [+ 'set -eu',+ 'umask 077',+ 'stage=$1; home=$2; node_name=$3; tmux_name=$4',+ 'rt="$home/.harness/runtime"; cli="$home/.harness/cli"; bin="$home/.local/bin"',+ 'mkdir -p "$rt" "$cli/data" "$home/.harness/auth" "$bin"',+ 'chmod 700 "$home/.harness" "$cli/data" "$home/.harness/auth"',+ 'put_dir() { rm -rf "$2.next"; cp -R "$1" "$2.next"; rm -rf "$2"; mv "$2.next" "$2"; }',+ 'put_dir "$stage/node" "$rt/$node_name"',+ `printf '%s\\n' "$rt/$node_name/bin/node" > "$rt/current-node.next" && mv -f "$rt/current-node.next" "$rt/current-node"`,+ 'if [ -n "$tmux_name" ]; then',+ ' put_dir "$stage/tmux" "$rt/$tmux_name"',+ ` printf '%s\\n' "$rt/$tmux_name/bin/tmux" > "$rt/current-tmux.next" && mv -f "$rt/current-tmux.next" "$rt/current-tmux"`,+ ' ln -sfn "$rt/$tmux_name/bin/tmux" "$bin/tmux"',+ 'fi',+ 'for f in cli.js notify.mjs package.json; do',+ ' [ ! -e "$stage/cli/$f" ] || { cp "$stage/cli/$f" "$cli/.$f.next" && mv -f "$cli/.$f.next" "$cli/$f"; }',+ 'done',+ // The same launcher the installer writes, so `harness` works in the team account's own terminals.+ `printf '#!/bin/sh\\nexec "%s" "%s" "$@"\\n' "$rt/$node_name/bin/node" "$cli/cli.js" > "$bin/harness.next"`,+ 'chmod 755 "$bin/harness.next" && mv -f "$bin/harness.next" "$bin/harness"',+].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"'++export const SENTINEL_TEXT = 'Harness Team privacy check. The Harness Team account on this Mac must not be able to read this file:'+ + ' if it can, your home folder is not private. It is removed with the account (harness team remove).'++export function buildSetupScript(input: SetupScriptInput): string {+ const user = checkUser(input.user, 'team account')+ const owner = checkUser(input.owner, 'owner account')+ if (user === owner) throw new Error('the team account must be a different account from the owner')+ if (!/^[A-Za-z0-9 ]{1,40}$/.test(input.realName)) throw new Error(`not a usable full name: ${JSON.stringify(input.realName)}`)+ const home = checkPath(input.home, 'team home')+ const ownerHome = checkPath(input.ownerHome, 'owner home')+ if (home === ownerHome || home.startsWith(`${ownerHome}/`) || ownerHome.startsWith(`${home}/`)) throw new Error('the team home and the owner home must be apart')+ const stage = checkPath(input.stageDir, 'staging folder')+ const nodeDir = checkPath(input.nodeRuntimeDir, 'Node runtime')+ const nodeName = checkName(basename(nodeDir), 'Node runtime folder')+ const tmuxDir = input.tmuxRuntimeDir === null ? null : checkPath(input.tmuxRuntimeDir, 'tmux runtime')+ const tmuxName = tmuxDir === null ? '' : checkName(basename(tmuxDir), 'tmux runtime folder')+ const cliDir = checkPath(input.cliDir, 'installed CLI')+ const ownerNode = checkPath(input.ownerNode, 'owner Node')+ const ownerCli = checkPath(input.ownerCli, 'owner CLI')+ const mintEnv = Object.entries(checkEnv(input.mintEnv)).map(([name, value]) => sh(`${name}=${value}`)).join(' ')+ const paths = teamPaths(home)+ const lines = [+ '#!/bin/sh',+ '# Harness Team account setup (cli/src/team/script.ts), run once as root behind the macOS administrator prompt.',+ '# Running it again repairs what is there; `harness team remove` undoes it.',+ 'set -eu',+ 'umask 022',+ 'cd /',+ `die() { printf 'harness: %s\\n' "$1" >&2; exit "\${2:-1}"; }`,+ `say() { printf 'harness: %s\\n' "$1"; }`,+ `TEAM=${sh(user)}`,+ `TEAM_NAME=${sh(input.realName)}`,+ `TEAM_HOME=${sh(home)}`,+ `OWNER=${sh(owner)}`,+ `OWNER_HOME=${sh(ownerHome)}`,+ `STAGE=${sh(stage)}`,+ `NODE_SRC=${sh(nodeDir)}`,+ `NODE_NAME=${sh(nodeName)}`,+ `TMUX_SRC=${sh(tmuxDir ?? '')}`,+ `TMUX_NAME=${sh(tmuxName)}`,+ `CLI_SRC=${sh(cliDir)}`,+ `OWNER_NODE=${sh(ownerNode)}`,+ `OWNER_CLI=${sh(ownerCli)}`,+ `SHARED=${sh(TEAM_SHARED_DIR)}`,+ `CONFIG=${sh(TEAM_CONFIG_FILE)}`,+ `STATUS_DIR=${sh(TEAM_STATUS_DIR)}`,+ `LABEL=${sh(TEAM_LABEL)}`,+ `PLIST=${sh(TEAM_PLIST)}`,+ `SENTINEL=${sh(`${ownerHome}/${SENTINEL_NAME}`)}`,+ `HANDOFF=${sh(paths.handoff)}`,+ `TEAM_SESSION=${sh(paths.session)}`,+ `SIGN_IN=${sh(input.signIn)}`,+ 'as_team() { /usr/bin/sudo -n -H -u "$TEAM" "$@"; }',+ 'as_owner() { /usr/bin/sudo -n -H -u "$OWNER" "$@"; }',+ // A folder root relies on must be root's alone, and not a link: another account could swap what it holds.+ 'owned_by_root() {',+ ' [ -e "$1" ] || return 0',+ ' [ ! -L "$1" ] || die "$1 is a symbolic link" 6',+ ' [ "$(stat -f %u "$1")" = 0 ] || die "$1 is not owned by root" 6',+ ' mode=$(stat -f %Lp "$1")',+ ' [ $((0$mode & 022)) -eq 0 ] || die "$1 can be written by others" 6',+ '}',+ '# The first free user id at or above 600, as the guest helper picks one.',+ 'free_id() {',+ " used=$(dscl . -list /Users UniqueID | awk '{print $2}')",+ ' candidate=600',+ ' while printf \'%s\\n\' "$used" | grep -qx "$candidate"; do candidate=$((candidate + 1)); done',+ " printf '%s' \"$candidate\"",+ '}',+ '',+ '[ "$(id -u)" = 0 ] || die "run as root"',+ '[ "$(uname -s)" = Darwin ] || die "the Harness Team account is for macOS"',+ 'for dir in / /Users /Library "/Library/Application Support" /Library/LaunchDaemons; do owned_by_root "$dir"; done',+ 'owner_uid=$(id -u "$OWNER") || die "no such account: $OWNER"',+ '[ "$owner_uid" != 0 ] || die "the owner cannot be root"',+ '[ -d "$OWNER_HOME" ] && [ ! -L "$OWNER_HOME" ] || die "$OWNER_HOME is not a folder"',+ '[ "$(stat -f %u "$OWNER_HOME")" = "$owner_uid" ] || die "$OWNER_HOME does not belong to $OWNER"',+ '[ -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.',+ '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',+ 'else',+ ' say "creating the account $TEAM_NAME ($TEAM)"',+ ' uid=$(free_id)',+ ' dscl . -create "/Users/$TEAM"',+ ' 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 '*'",+ // 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',+ 'team_uid=$(id -u "$TEAM")',+ '',+ '# 2. Its home folder, private to it.',+ '[ ! -L "$TEAM_HOME" ] || die "$TEAM_HOME is a symbolic link" 4',+ 'if [ ! -d "$TEAM_HOME" ]; then',+ ' createhomedir -c -u "$TEAM" >/dev/null 2>&1 || true',+ ' [ -d "$TEAM_HOME" ] || mkdir "$TEAM_HOME"',+ 'fi',+ 'home_uid=$(stat -f %u "$TEAM_HOME")',+ '[ "$home_uid" = "$team_uid" ] || [ "$home_uid" = 0 ] || die "$TEAM_HOME belongs to another account" 4',+ 'chown "$TEAM:staff" "$TEAM_HOME"',+ 'chmod 700 "$TEAM_HOME"',+ '',+ '# 3. The owner\'s home folder, private: every account on a Mac is in the group staff, and a home folder is',+ '# readable by that group by default. The sentinel inside is readable by everyone on purpose, so the',+ '# privacy check proves the folder\'s own mode keeps it out.',+ 'say "making $OWNER_HOME private (mode 700)"',+ 'chmod 700 "$OWNER_HOME"',+ `printf '%s\\n' ${sh(SENTINEL_TEXT)} | as_owner /bin/sh -c ${sh(WRITE_PUBLIC)} sh "$SENTINEL"`,+ '',+ '# 4. The team daemon stops while its files are replaced. Its agents keep running in tmux.',+ 'launchctl bootout "system/$LABEL" >/dev/null 2>&1 || true',+ '',+ '# 5. The Harness runtime, staged where only root can change it, then copied in by the team account itself.',+ 'RT=$(mktemp -d /private/var/tmp/harness-team.XXXXXX)',+ 'trap \'rm -rf "$RT"\' EXIT',+ 'mkdir "$RT/node" "$RT/cli"',+ 'for part in bin lib include; do [ ! -e "$NODE_SRC/$part" ] || cp -R "$NODE_SRC/$part" "$RT/node/"; done',+ 'for f in cli.js notify.mjs package.json; do [ ! -e "$CLI_SRC/$f" ] || cp "$CLI_SRC/$f" "$RT/cli/"; done',+ 'if [ -n "$TMUX_NAME" ]; then cp -R "$TMUX_SRC" "$RT/tmux"; fi',+ 'chmod -R a+rX,go-w "$RT"',+ 'chmod 755 "$RT"',+ `as_team /bin/sh -c ${sh(TEAM_COPY)} sh "$RT" "$TEAM_HOME" "$NODE_NAME" "$TMUX_NAME"`,+ '',+ '# 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',+ 'owned_by_root "$SHARED"',+ '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"',+ 'chown "$TEAM:staff" "$STATUS_DIR"',+ 'chmod 755 "$STATUS_DIR"',+ '',+ '# 7. Sign-in: a single-use code minted from the owner\'s own sign-in now, so its 90 seconds start here, and',+ '# written where only the team account can read it. The team daemon redeems it as it starts and deletes it.',+ 'if [ "$SIGN_IN" = always ] || [ ! -s "$TEAM_SESSION" ]; then',+ ` minted=$(as_owner /usr/bin/env ${mintEnv ? `${mintEnv} ` : ''}"$OWNER_NODE" "$OWNER_CLI" team __handoff) || die "could not get a sign-in code from your Harness sign-in" 7`,+ // Its last line: a warning the CLI printed first must not become part of the code.+ ' code=$(printf \'%s\\n\' "$minted" | tail -n 1)',+ // The shell's own check of what ./layout.ts HANDOFF_CODE allows: token characters, 16 to 256 of them.+ ' case $code in \'\'|*[!A-Za-z0-9_-]*) die "the sign-in code was not in the form Harness expects" 7 ;; esac',+ ' [ "${#code}" -ge 16 ] && [ "${#code}" -le 256 ] || die "the sign-in code was not in the form Harness expects" 7',+ ` printf '%s\\n' "$code" | as_team /bin/sh -c ${sh(WRITE_PRIVATE)} sh "$HANDOFF"`,+ ' say "handed a sign-in to the team account"',+ 'fi',+ '',+ '# 8. The LaunchDaemon, root\'s, which runs the team daemon as the team account from boot.',+ 'install -o 0 -g 0 -m 0644 "$STAGE/team.plist" "$PLIST"',+ 'plutil -lint "$PLIST" >/dev/null || die "the team daemon\'s definition is not valid" 8',+ 'launchctl enable "system/$LABEL" >/dev/null 2>&1 || true',+ 'tries=0',+ 'until launchctl bootstrap system "$PLIST" >/dev/null 2>&1; do',+ ' tries=$((tries + 1))',+ ' [ "$tries" -lt 5 ] || die "launchd would not start the team daemon" 8',+ ' launchctl bootout "system/$LABEL" >/dev/null 2>&1 || true',+ ' sleep 1',+ 'done',+ 'say "the team daemon runs as $TEAM ($LABEL)"',+ '',+ ]+ return lines.join('\n')+}++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>+}++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(' ')+ 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.',+ 'set -eu',+ 'cd /',+ `die() { printf 'harness: %s\\n' "$1" >&2; exit "\${2:-1}"; }`,+ `say() { printf 'harness: %s\\n' "$1"; }`,+ `TEAM=${sh(user)}`,+ `TEAM_HOME=${sh(home)}`,+ `LABEL=${sh(TEAM_LABEL)}`,+ `PLIST=${sh(TEAM_PLIST)}`,+ `CONFIG=${sh(TEAM_CONFIG_FILE)}`,+ `STATUS_DIR=${sh(TEAM_STATUS_DIR)}`,+ `SENTINEL=${sh(`${ownerHome}/${SENTINEL_NAME}`)}`,+ `TEAM_NODE=${sh(teamNode)}`,+ `TEAM_CLI=${sh(teamCli)}`,+ '[ "$(id -u)" = 0 ] || die "run as root"',+ 'exists=',+ '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',+ '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")',+ ' case $holder in',+ ' "$TEAM"|root) ;;',+ ' *[!0-9]*) die "$TEAM_HOME belongs to $holder; nothing was removed" 4 ;;',+ ' esac',+ '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',+ 'launchctl bootout "system/$LABEL" >/dev/null 2>&1 || true',+ 'rm -f "$PLIST"',+ 'if [ -n "$exists" ]; then',+ ' pkill -KILL -u "$TEAM" >/dev/null 2>&1 || true',+ ' sleep 1',+ ' dscl . -delete "/Users/$TEAM"',+ 'fi',+ 'rm -rf "$TEAM_HOME" "$STATUS_DIR"',+ 'rm -f "$CONFIG" "$SENTINEL"',+ 'say "removed the Harness Team account, its home folder and its daemon"',+ '',+ ].join('\n')+}