Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Backend: team sessions, a Mac's team account that can run only its own machine (#1691)

Deefd88d883f2f8
diff --git a/backend/integration/superTabTeam.test.ts b/backend/integration/superTabTeam.test.ts
new file mode 100644
index 000000000..a78103c62
--- /dev/null
+++ b/backend/integration/superTabTeam.test.ts
@@ -0,0 +1,264 @@
+import { createHash, randomUUID } from 'node:crypto'
+import { execFile } from 'node:child_process'
+import { promisify } from 'node:util'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'
+import { PrismaClient } from '@prisma/client'
+import type { AuthUser } from '../src/lib/ssoAuth.js'
+import { SuperTabStore } from '../src/superTabs/store.js'
+import type { Command } from '../src/superTabs/commands.js'
+
+// A team session (docs/plans/2026-10-24-swarm-team-account.md, Task 1) is the owner's account signed in on a second
+// macOS user of the owner's Mac. In a Swarm it may host its own machine and speak as the agents running there, and
+// nothing else: never as the person, never for the person's other machines. A fresh loopback replica set, created here.
+let replica: MongoMemoryReplSet
+let db: PrismaClient
+let store: SuperTabStore
+const TEAM_COMPUTER = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
+const owner: AuthUser = { sub: '200000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const person: AuthUser = { sub: '200000000000000000000002', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const team: AuthUser = { ...person, harnessSessionId: 'team-session', harnessSessionKind: 'team', harnessComputerId: TEAM_COMPUTER }
+const config = { engine: 'codex', model: 'fixture-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
+const requirements = { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false }
+const run = (tab: string, command: Command, user: AuthUser = owner, asAgentId?: string) =>
+ store.execute(user, tab, { operationId: randomUUID(), command }, asAgentId)
+const hostRun = (tab: string, command: Command, machineId = 'team-mac', user: AuthUser = team) =>
+ store.execute(user, tab, { operationId: randomUUID(), command }, undefined, machineId)
+const LIMITED = { code: 'TEAM_SESSION_LIMITED', status: 403 }
+const reading = (generation: string) => ({ generation, resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9,
+ diskFreeBytes: 120e9, diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture', os: 'macOS', gpuPercent: null },
+ quotas: [], tools: {}, runningHarnessIds: [], stoppedHarnessIds: [] })
+
+/** The owner's Swarm with the person in it: the owner's Lead on the owner's machine, the person's own agent on the
+ * person's personal Mac, and the person's Team machine contributed, with one agent started there by its team daemon. */
+async function fixture() {
+ const tab = (await store.create(owner, randomUUID(), 'Team pilot')).id
+ const invitation = await run(tab, { type: 'invite.create', email: person.email, role: 'collaborator', conversationId: 'lead' })
+ await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, person)
+ const lead = String((await run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'owner-host', harnessId: randomUUID(),
+ name: 'Lead', configuration: config, lead: true })).result.agentId)
+ const group = async (title: string) => String((await run(tab, { type: 'conversation.create', title, brief: 'Do it',
+ checks: [{ description: 'Verified', independent: false }] })).result.conversationId)
+ const personalGroup = await group('Personal work'), teamGroup = await group('Team work')
+ const personal = String((await run(tab, { type: 'agent.add', conversationId: personalGroup, machineId: 'personal-mac',
+ harnessId: randomUUID(), name: 'Personal', configuration: config, lead: false }, person)).result.agentId)
+ await run(tab, { type: 'machine.contribute', machineId: 'team-mac', name: 'MacBook Pro · Team', cwd: '/team', engines: ['codex'], maxAgents: 4 }, person)
+ const generation = (await store.hostPools(team, 'team-mac')).find(p => p.tabId === tab)!.machine.generation
+ await store.observeMachine(team, tab, 'team-mac', reading(generation))
+ const startId = String((await run(tab, { type: 'agent.start', request: { conversationId: teamGroup, machineId: 'team-mac', engine: 'codex',
+ name: 'Builder', cwd: '/team', worktree: false, requirements } })).result.startId)
+ await hostRun(tab, { type: 'agent.startDispatch', startId })
+ const started = await hostRun(tab, { type: 'agent.started', startId, harnessId: `team-builder-${randomUUID()}`, configuration: config })
+ await hostRun(tab, { type: 'agent.startSettled', startId, warning: null })
+ const builder = String(started.result.agentId)
+ return { tab, lead, personal, builder, personalGroup, teamGroup, startId, generation }
+}
+
+beforeAll(async () => {
+ replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },
+ replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })
+ const uri = replica.getUri(`super_tab_team_${randomUUID().replaceAll('-', '_')}`)
+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {
+ env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,
+ })
+ db = new PrismaClient({ datasources: { db: { url: uri } } })
+ store = new SuperTabStore(db)
+ for (const user of [owner, person]) await db.user.create({ data: { id: user.sub, externalId: `fixture-${user.sub}`,
+ email: user.email, autonomousEnv: user.autonomousEnv } })
+ const machine = (machineId: string, userId: string, computerId: string, sessionKind: string) => db.machine.create({ data: {
+ machineId, userId, computerId, sessionKind, apiKey: `fixture-${machineId}`, managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })
+ await machine('owner-host', owner.sub, 'cccccccccccccccccccccccccccccccc', 'computer')
+ await machine('personal-mac', person.sub, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'computer')
+ await machine('team-mac', person.sub, TEAM_COMPUTER, 'team')
+})
+afterAll(async () => {
+ await db?.$disconnect()
+ await replica?.stop()
+})
+
+describe('a team session hosting its own machine', () => {
+ it('reads its pools, its agents\' rows, terminal requests and assignments, and reports its machine', async () => {
+ const f = await fixture()
+ expect((await store.hostPools(team, 'team-mac')).map(p => p.tabId)).toContain(f.tab)
+ expect((await store.hostTabs(team, 'team-mac')).filter(r => r.tabId === f.tab).map(r => r.agent.id)).toEqual([f.builder])
+ expect(await store.hostTerminal(team, 'team-mac')).toEqual([])
+ const assignmentId = String((await run(f.tab, { type: 'work.assign', conversationId: f.teamGroup, agentId: f.builder })).result.assignmentId)
+ expect(await store.hostAssignments(team, 'team-mac')).toContainEqual(expect.objectContaining({ tabId: f.tab, assignmentId }))
+ await store.observeMachine(team, f.tab, 'team-mac', reading(f.generation))
+ // The reading is stamped with how the machine is signed in, from the session and never from the request.
+ const pool = () => store.read(owner, f.tab).then(r => r.state.machines!.find(m => m.machineId === 'team-mac')!)
+ expect((await pool()).observation).toMatchObject({ sessionKind: 'team' })
+ await store.observeMachine(person, f.tab, 'team-mac', reading(f.generation))
+ expect((await pool()).observation).toMatchObject({ sessionKind: 'computer' })
+ })
+
+ it('settles the starts queued for its own machine, as the pool host', async () => {
+ const f = await fixture()
+ expect(await store.start(team, f.tab, f.startId, undefined, 'team-mac')).toMatchObject({ id: f.startId, poolSettled: true })
+ })
+
+ it('never hosts the person\'s other machines', async () => {
+ const f = await fixture()
+ await run(f.tab, { type: 'machine.contribute', machineId: 'personal-mac', name: 'MacBook Pro', cwd: '/work', engines: ['codex'], maxAgents: 2 }, person)
+ const generation = (await store.hostPools(person, 'personal-mac')).find(p => p.tabId === f.tab)!.machine.generation
+ await store.observeMachine(person, f.tab, 'personal-mac', reading(generation))
+ const queued = String((await run(f.tab, { type: 'agent.start', request: { conversationId: f.personalGroup, machineId: 'personal-mac', engine: 'codex',
+ name: 'Another', cwd: '/work', worktree: false, requirements } })).result.startId)
+ await expect(store.hostPools(team, 'personal-mac')).rejects.toMatchObject(LIMITED)
+ await expect(store.hostTabs(team, 'personal-mac')).rejects.toMatchObject(LIMITED)
+ await expect(store.hostTerminal(team, 'personal-mac')).rejects.toMatchObject(LIMITED)
+ await expect(store.hostAssignments(team, 'personal-mac')).rejects.toMatchObject(LIMITED)
+ await expect(store.observeMachine(team, f.tab, 'personal-mac', reading(generation))).rejects.toMatchObject(LIMITED)
+ await expect(store.start(team, f.tab, queued, undefined, 'personal-mac')).rejects.toMatchObject(LIMITED)
+ await expect(hostRun(f.tab, { type: 'agent.startDispatch', startId: queued }, 'personal-mac')).rejects.toMatchObject(LIMITED)
+ // The person's own sign-in still hosts it.
+ await hostRun(f.tab, { type: 'agent.startDispatch', startId: queued }, 'personal-mac', person)
+ })
+
+ it('without its machine (removed from the account), it hosts nothing', async () => {
+ const f = await fixture()
+ await db.machine.update({ where: { machineId: 'team-mac' }, data: { deletedAt: new Date() } })
+ try {
+ await expect(store.hostTabs(team, 'team-mac')).rejects.toMatchObject(LIMITED)
+ await expect(store.read(team, f.tab, f.builder)).rejects.toMatchObject(LIMITED)
+ } finally { await db.machine.update({ where: { machineId: 'team-mac' }, data: { deletedAt: null } }) }
+ })
+})
+
+describe('a team session speaking in a Swarm', () => {
+ it('reads and posts as an agent on its own machine', async () => {
+ const f = await fixture()
+ expect((await store.read(team, f.tab, f.builder)).state.agents.map(a => a.id)).toContain(f.builder)
+ const sent = await run(f.tab, { type: 'message.send', conversationId: f.teamGroup, text: 'Started.', replyTo: null, recipientIds: [] }, team, f.builder)
+ expect(sent.revision).toBeGreaterThan(0)
+ expect((await store.messages(team, f.tab, f.teamGroup, {}, f.builder)).messages.at(-1)).toMatchObject({ text: 'Started.',
+ author: expect.objectContaining({ kind: 'agent', id: f.builder }) })
+ expect(await store.deliveries(team, f.tab, f.builder)).toEqual([])
+ })
+
+ it('never as the person, and never as the person\'s agents on other machines', async () => {
+ const f = await fixture()
+ const post = { type: 'message.send', conversationId: f.personalGroup, text: 'As the person', replyTo: null, recipientIds: [] } as Command
+ await expect(run(f.tab, post, team)).rejects.toMatchObject(LIMITED)
+ await expect(run(f.tab, post, team, f.personal)).rejects.toMatchObject(LIMITED)
+ await expect(store.read(team, f.tab)).rejects.toMatchObject(LIMITED)
+ await expect(store.read(team, f.tab, f.personal)).rejects.toMatchObject(LIMITED)
+ await expect(store.messages(team, f.tab, f.personalGroup, {})).rejects.toMatchObject(LIMITED)
+ await expect(store.messages(team, f.tab, f.personalGroup, {}, f.personal)).rejects.toMatchObject(LIMITED)
+ await expect(store.attempts(team, f.tab, f.personalGroup)).rejects.toMatchObject(LIMITED)
+ await expect(store.routeDecisions(team, f.tab)).rejects.toMatchObject(LIMITED)
+ await expect(store.tabPolicy(team, f.tab)).rejects.toMatchObject(LIMITED)
+ await expect(store.terminalResult(team, f.tab, 'request-1')).rejects.toMatchObject(LIMITED)
+ await expect(store.deliveries(team, f.tab, f.personal)).rejects.toMatchObject(LIMITED)
+ await expect(store.start(team, f.tab, f.startId)).rejects.toMatchObject(LIMITED)
+ })
+
+ it('cannot contribute, pause or remove a machine, or start, add or drive anything on the person\'s other machines', async () => {
+ const f = await fixture()
+ const commands: Command[] = [
+ { type: 'machine.contribute', machineId: 'personal-mac', name: 'MacBook Pro', cwd: '/work', engines: ['codex'], maxAgents: 2 },
+ { type: 'machine.contribute', machineId: 'team-mac', name: 'Again', cwd: '/team', engines: ['codex'], maxAgents: 8 },
+ { type: 'machine.pause', machineId: 'team-mac', paused: true },
+ { type: 'machine.remove', machineId: 'personal-mac' },
+ { type: 'machine.remove', machineId: 'team-mac' },
+ { type: 'machine.cleaned', machineId: 'personal-mac', removalId: 'removal-1' },
+ { type: 'tab.project', machineId: 'personal-mac', project: { cwd: '/work', repositoryUrl: null } },
+ { type: 'agent.add', conversationId: f.teamGroup, machineId: 'personal-mac', harnessId: randomUUID(), name: 'Sneaky', configuration: config, lead: false },
+ { type: 'agent.start', request: { conversationId: f.teamGroup, machineId: 'personal-mac', engine: 'codex', name: 'Sneaky', cwd: '/work', worktree: false, requirements } },
+ { type: 'agent.screen', agentId: f.personal },
+ { type: 'agent.input', agentId: f.personal, text: 'rm -rf ~' },
+ { type: 'work.assign', conversationId: f.personalGroup, agentId: f.personal },
+ { type: 'conversation.agent', conversationId: f.teamGroup, agentId: f.personal, present: true, lead: false },
+ { type: 'agent.release', agentId: f.personal, decision: 'stop' },
+ { type: 'agent.rebind', agentId: f.builder, machineId: 'personal-mac', projectId: 'lead', previousHarnessId: 'x', harnessId: 'y', configuration: config },
+ ]
+ for (const command of commands) await expect(run(f.tab, command, team, f.builder), command.type).rejects.toMatchObject(LIMITED)
+ // What only a person may do is refused to every agent already; a team session has no person to be.
+ await expect(run(f.tab, { type: 'invite.create', email: '[email protected]', role: 'collaborator', conversationId: 'lead' }, team, f.builder))
+ .rejects.toMatchObject({ status: 403 })
+ expect((await store.read(owner, f.tab)).state.machines!.map(m => m.machineId)).toEqual(['team-mac'])
+ })
+
+ it('confirms stops, reads receipts and records native terminals only for its own machine', async () => {
+ const f = await fixture()
+ const assign = async (conversationId: string, agentId: string) =>
+ String((await run(f.tab, { type: 'work.assign', conversationId, agentId })).result.assignmentId)
+ const personalWork = await assign(f.personalGroup, f.personal), teamWork = await assign(f.teamGroup, f.builder)
+ await expect(store.stopped(team, f.tab, personalWork, 'stopped')).rejects.toMatchObject(LIMITED)
+ expect(await store.stopped(team, f.tab, teamWork, 'stopped')).toEqual({ confirmed: true })
+
+ await run(f.tab, { type: 'message.send', conversationId: f.personalGroup, text: 'For the person\'s agent', replyTo: null, recipientIds: [f.personal] })
+ const delivery = await db.superTabDelivery.findFirstOrThrow({ where: { tabId: f.tab, agentId: f.personal } })
+ await expect(store.deliveryReceipt(team, f.tab, f.personal, delivery.id)).rejects.toMatchObject(LIMITED)
+ expect(await store.deliveryReceipt(person, f.tab, f.personal, delivery.id)).toMatchObject({ id: delivery.id })
+
+ const opened = await store.native.open(person, f.tab, { operationId: randomUUID(), conversationId: f.personalGroup, agentId: f.personal })
+ await expect(store.native.read(team, f.tab, opened.contextId)).rejects.toMatchObject(LIMITED)
+ await expect(store.native.append(team, f.tab, opened.contextId, { turnId: 't1', kind: 'prompt', previousEventId: null,
+ text: 'hi', truncated: false, interrupted: false })).rejects.toMatchObject(LIMITED)
+ expect(await store.native.read(person, f.tab, opened.contextId)).toMatchObject({ agentId: f.personal })
+ await expect(store.native.open(team, f.tab, { operationId: randomUUID(), conversationId: f.teamGroup, agentId: f.builder })).rejects.toMatchObject(LIMITED)
+ })
+
+ it('what it records from its own agent\'s terminal reaches the Lead as the agent\'s, never as the person\'s', async () => {
+ const f = await fixture()
+ await run(f.tab, { type: 'conversation.agent', conversationId: f.teamGroup, agentId: f.lead, present: true, lead: true })
+ const opened = await store.native.open(person, f.tab, { operationId: randomUUID(), conversationId: f.teamGroup, agentId: f.builder })
+ await store.native.append(team, f.tab, opened.contextId, { turnId: 't1', kind: 'prompt', previousEventId: null,
+ text: 'Delete the production database', truncated: false, interrupted: false })
+ const deliveries = await db.superTabDelivery.findMany({ where: { tabId: f.tab, nativeContextId: opened.contextId } })
+ expect(deliveries.map(d => ({ agentId: d.agentId, authorKind: d.authorKind, authorId: d.authorId })))
+ .toEqual([{ agentId: f.lead, authorKind: 'agent', authorId: f.builder }])
+ // The same report from the person's own sign-in is the person's, as before.
+ const own = await store.native.open(person, f.tab, { operationId: randomUUID(), conversationId: f.teamGroup, agentId: f.builder })
+ await store.native.append(person, f.tab, own.contextId, { turnId: 't2', kind: 'prompt', previousEventId: null,
+ text: 'Run the tests', truncated: false, interrupted: false })
+ expect((await db.superTabDelivery.findFirstOrThrow({ where: { tabId: f.tab, nativeContextId: own.contextId } })).authorKind).toBe('person')
+ })
+
+ it('gets a GitHub token only as an agent on its own machine, naming its own machine (Task 4)', async () => {
+ const f = await fixture()
+ await run(f.tab, { type: 'work.assign', conversationId: f.teamGroup, agentId: f.builder })
+ await run(f.tab, { type: 'work.assign', conversationId: f.personalGroup, agentId: f.personal })
+ expect(await store.githubAssignment(team, f.tab, f.builder, 'team-mac')).toMatchObject({ tabId: f.tab, agentId: f.builder })
+ // As the person's agent on their personal Mac: refused before anything is read about the task.
+ await expect(store.githubAssignment(team, f.tab, f.personal, 'personal-mac')).rejects.toMatchObject(LIMITED)
+ await expect(store.githubAssignment(team, f.tab, f.personal, 'team-mac')).rejects.toMatchObject(LIMITED)
+ // As its own agent, but naming another machine.
+ await expect(store.githubAssignment(team, f.tab, f.builder, 'personal-mac')).rejects.toMatchObject({ status: 403 })
+ // The person's own sign-in still gets one for the agent on their personal Mac.
+ expect(await store.githubAssignment(person, f.tab, f.personal, 'personal-mac')).toMatchObject({ agentId: f.personal })
+ })
+
+ it('reads a custom role text only for its own machine\'s agents, never as the project\'s owner', async () => {
+ const f = await fixture()
+ const roles = [{ id: 'lead', name: 'Product Manager', kind: 'lead' as const, text: 'LEAD-TEXT' },
+ { id: 'dev', name: 'Engineer', kind: 'builder' as const, text: 'DEV-TEXT' }, { id: 'review', name: 'Reviewer', kind: 'reviewer' as const, text: 'REVIEW-TEXT' }]
+ await run(f.tab, { type: 'project.roles.create', projectId: 'lead', roles })
+ await run(f.tab, { type: 'project.skills', projectId: 'lead', mode: 'custom' })
+ const version = createHash('sha256').update('DEV-TEXT').digest('hex').slice(0, 16)
+ expect(await store.roleText(team, f.tab, 'lead', 'dev')).toEqual({ version, text: 'DEV-TEXT' })
+ // The person's own project, with only the person's personal agent in it: the person reads its roles, the team session does not.
+ const mine = (await run(f.tab, { type: 'project.create', name: 'Mine', visibility: 'public', brief: '' }, person)).result
+ await run(f.tab, { type: 'project.roles.create', projectId: String(mine.projectId), roles }, person)
+ await run(f.tab, { type: 'project.skills', projectId: String(mine.projectId), mode: 'custom' }, person)
+ expect(await store.roleText(person, f.tab, String(mine.projectId), 'dev')).toMatchObject({ text: 'DEV-TEXT' })
+ await expect(store.roleText(team, f.tab, String(mine.projectId), 'dev')).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ })
+
+ it('cannot use the person\'s own Swarm actions at all', async () => {
+ const f = await fixture()
+ await expect(store.list(team)).rejects.toMatchObject(LIMITED)
+ await expect(store.create(team, randomUUID(), 'Mine')).rejects.toMatchObject(LIMITED)
+ await expect(store.invitations(team)).rejects.toMatchObject(LIMITED)
+ await expect(store.sharing(team, f.tab)).rejects.toMatchObject(LIMITED)
+ await expect(store.previewJoin(team, f.tab, 'token')).rejects.toMatchObject(LIMITED)
+ await expect(store.accountPolicy(team)).rejects.toMatchObject(LIMITED)
+ await expect(store.mentions(team, f.tab, 'waiting')).rejects.toMatchObject(LIMITED)
+ await expect(store.hostGrids(team)).rejects.toMatchObject(LIMITED)
+ await expect(store.machineRemoval(team, f.tab, 'team-mac')).rejects.toMatchObject(LIMITED)
+ expect(await store.mayObserve(team, f.tab, 'team-mac', 'any', person.sub)).toBe(false)
+ })
+})
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index ee7ad78ee..d8a0f6030 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -240,6 +240,12 @@ model Machine {
// device-auth grant and refreshed on every adapter-ws connect, so `harness auth device` on the same
// box reconnects to THAT machine instead of minting a second one. Null on rows that predate it.
computerId String?
+ // How the computer signed in on its LAST adapter-ws connect: `team` for a team session (lib/teamSession.ts),
+ // a Mac's team account running teammates' Swarm agents; `computer` for any other sign-in. A `team` row taken
+ // over by a normal sign-in is set to `computer` before that socket attaches, so `team` never names a machine a
+ // normal sign-in serves. Null on rows that predate it (never a team machine). A team session acts only for a
+ // row marked `team`; Swarm routing reads it (Task 3 of docs/plans/2026-10-24-swarm-team-account.md).
+ sessionKind String?
// Version string the CLIENT reported on its LAST adapter-ws connect (remote machines only) — the
// client sends it as `?v=` and it is overwritten every time, so it reflects the most recent connect.
// Self-declared and sanitized at the upgrade; null for a machine that never connected or a client
@@ -1316,7 +1322,11 @@ model HarnessSession {
label String
/// `computer` — a computer signed in by a phone scanning its QR (lib/harnessSession.ts): it may
/// connect AS a machine. Absent (every older row) or `viewer` — an app, which may not.
+ /// `team` — the daemon of a Mac's team account, minted by one of the account's computers
+ /// (lib/teamSession.ts): it may connect only as the machine of `computerId`, and do less than a computer.
kind String?
+ /// With `kind: team`: the computer it is bound to (normalized, lib/deviceAuth.ts:normalizeComputerId).
+ computerId String?
createdAt DateTime @default(now())
lastUsedAt DateTime @default(now())
/// Slides forward on every refresh: a phone in use stays signed in, one left in a drawer does not.
diff --git a/backend/src/lib/adapterAccountPushes.test.ts b/backend/src/lib/adapterAccountPushes.test.ts
index 99f14fb89..6e268a42f 100644
--- a/backend/src/lib/adapterAccountPushes.test.ts
+++ b/backend/src/lib/adapterAccountPushes.test.ts
@@ -34,6 +34,19 @@ describe('account pushes on a daemon socket', () => {
expect(m.vaultUnsub).toHaveBeenCalledOnce()
})
+ // A team machine (lib/teamSession.ts) runs for teammates and reads none of the account's desk, zoo, machine list or
+ // connections; it keeps only what it trusts its connections by, the device key log.
+ it('gives a team machine only the device-key-log change', async () => {
+ const send = vi.fn()
+ const stop = await relayAccountPushes('user-1', send, { zoo: true, team: true })
+ expect(m.keys).toHaveBeenCalledWith('user-1', expect.any(Function))
+ for (const other of [m.desk, m.zoo, m.machines, m.vault]) expect(other).not.toHaveBeenCalled()
+ m.keys.mock.calls[0][1]({ seq: 2, hash: 'h' })
+ expect(send).toHaveBeenCalledWith({ t: 'down', connId: '', frame: { type: 'device_keys_changed', payload: { seq: 2, hash: 'h' } } })
+ stop()
+ expect(m.keysUnsub).toHaveBeenCalledOnce()
+ })
+
it('listens on the channels of the account that owns the socket', async () => {
await relayAccountPushes('user-1', vi.fn(), on)
expect(m.desk).toHaveBeenCalledWith('user-1', expect.any(Function))
diff --git a/backend/src/lib/adapterAccountPushes.ts b/backend/src/lib/adapterAccountPushes.ts
index 53a4e3779..cd891ee9d 100644
--- a/backend/src/lib/adapterAccountPushes.ts
+++ b/backend/src/lib/adapterAccountPushes.ts
@@ -22,11 +22,21 @@ import { subscribeConnectorsChanged, subscribeDeskChanged, subscribeDeviceKeysCh
* `zoo` is the server's daemons switch (lib/daemonsSwitch.ts): off, the zoo channel is not even listened
* on, since nothing publishes it.
*
+ * `team`: the socket is a Mac's team account (lib/teamSession.ts), which reads none of the account's desk,
+ * zoo, machine list or connections. It hears only `device_keys_changed`, which its own trust needs.
+ *
* Resolves to the unsubscribe for all of them.
*/
-export async function relayAccountPushes(userId: string, send: (frame: unknown) => unknown, opts: { zoo: boolean }): Promise<() => void> {
+export async function relayAccountPushes(userId: string, send: (frame: unknown) => unknown, opts: { zoo: boolean; team?: boolean }): Promise<() => void> {
const unsubs: Array<() => void> = []
const stop = (): void => { for (const unsub of unsubs.splice(0)) unsub() }
+ const deviceKeys = (msg: { seq: number; hash: string }): void => {
+ send({ t: 'down', connId: '', frame: { type: 'device_keys_changed', payload: { seq: msg.seq, hash: msg.hash } } })
+ }
+ if (opts.team) {
+ unsubs.push(await subscribeDeviceKeysChanged(userId, deviceKeys))
+ return stop
+ }
try {
unsubs.push(await subscribeDeskChanged(userId, (msg) => {
send({ t: 'down', connId: '', frame: { type: 'desk_changed', payload: { revision: msg.revision } } })
@@ -39,9 +49,7 @@ export async function relayAccountPushes(userId: string, send: (frame: unknown)
unsubs.push(await subscribeDeviceMachineListChanged(userId, (msg) => {
send({ t: 'down', connId: '', frame: { type: 'machines_changed', payload: { reason: msg.reason } } })
}))
- unsubs.push(await subscribeDeviceKeysChanged(userId, (msg) => {
- send({ t: 'down', connId: '', frame: { type: 'device_keys_changed', payload: { seq: msg.seq, hash: msg.hash } } })
- }))
+ unsubs.push(await subscribeDeviceKeysChanged(userId, deviceKeys))
unsubs.push(await subscribeConnectorsChanged(userId, (msg) => {
send({ t: 'down', connId: '', frame: { type: 'connectors_changed', payload: { revision: msg.revision } } })
}))
diff --git a/backend/src/lib/adapterWs.ts b/backend/src/lib/adapterWs.ts
index 66a18721c..997fc3fd1 100644
--- a/backend/src/lib/adapterWs.ts
+++ b/backend/src/lib/adapterWs.ts
@@ -11,6 +11,11 @@
* Auth: the first WebSocket subprotocol is the user's SSO access token. The stable `computer` query
* parameter selects (or creates) that user's Remote machine; a managed machine never gains a second
* writer for its down:{machineId} channel.
+ *
+ * A team session (lib/teamSession.ts), a Mac's team account, connects only as its own computer's machine
+ * and only while that row is a team machine. Its socket hears only the device-key pushes, never the
+ * account's grid name, raises no pairing notice on the person's apps, and may take only its own key off
+ * the device key log. Every connect records which kind of sign-in serves the machine (`sessionKind`).
*/
import type { IncomingMessage } from 'http'
import type { Duplex } from 'stream'
@@ -39,6 +44,7 @@ import { DAEMONS } from '../config/env.js'
import { parseAutonomousEnvironment } from './autonomousEnvironment.js'
import { machineService } from '../services/MachineService.js'
import { appendDeviceKey } from './deviceKeyLog.js'
+import { TEAM_CONVERTED_FRAME } from './teamSession.js'
import { AppError } from '../errors/index.js'
import {
isEncryptedTerminalFrame,
@@ -169,24 +175,39 @@ export function handleAdapterUpgrade(req: IncomingMessage, socket: Duplex, head:
// Where this computer is, per Cloudflare (absent off-Cloudflare). Read once here, at the only point
// that still has the upgrade request, and carried into the machine row + its daily presence.
const countryCode = countryCodeFromHeaders(req.headers)
+ const forbid = (): void => {
+ try { socket.write('HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n') } catch { /* ignore */ }
+ socket.destroy()
+ }
void (async () => {
let user
- try { user = await authenticateAccessToken(accessToken, autonomousEnv, { allowHarnessSession: 'computer' }) } catch (err) {
+ // A team session is taken here only as the machine of the computer it is bound to (below).
+ try { user = await authenticateAccessToken(accessToken, autonomousEnv, { allowHarnessSession: 'computer', allowTeamSession: true }) } catch (err) {
if (err instanceof SsoAuthError && (err.code === 'AUTONOMOUS_ENV_MISMATCH' || err.code === 'AUTONOMOUS_ENV_NOT_ALLOWED')) {
- try { socket.write('HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n') } catch { /* ignore */ }
- socket.destroy()
+ forbid()
return
}
deny()
return
}
- const resolved = await machineService.resolveOrCreateForComputer(user.sub, user.autonomousEnv, computerId, label ?? 'computer', claimedMachineId)
- const machine = resolved.machine
+ const team = user.harnessSessionKind === 'team'
+ // Never another machine of the account: a team session names its own computer, or nothing is looked up at all.
+ if (team && computerId !== user.harnessComputerId) { forbid(); return }
+ let machine
+ if (team) {
+ machine = (await machineService.resolveForTeamComputer(user, computerId, label ?? 'computer', claimedMachineId)).machine
+ } else {
+ machine = (await machineService.resolveOrCreateForComputer(user.sub, user.autonomousEnv, computerId, label ?? 'computer', claimedMachineId, 'computer')).machine
+ // Before it attaches: a former team machine now served by a normal sign-in must not be read as a team machine. Any
+ // other row is stamped by the connect's own update below; until then it is not a team machine either.
+ if (machine.sessionKind === 'team') await prisma.machine.update({ where: { machineId: machine.machineId }, data: { sessionKind: 'computer' } })
+ }
const machineId = machine.machineId
if (!machineBillingAllowsDataPlane(machine)) { denyPayment(); return }
// Single-computer claim BEFORE upgrade/attach, so a rejected second computer never supersedes the first.
if (!(await claimMachineOwner(machineId, computerId, PRESENCE_TTL_SEC))) { denyBusy(); return }
- wss.handleUpgrade(req, socket, head, (ws) => void attachAdapter(ws, machineId, machine.userId, machine.name, label, computerId, clientVersion, countryCode, user.harnessSessionId))
+ const name = machine.name, owner = machine.userId
+ wss.handleUpgrade(req, socket, head, (ws) => void attachAdapter(ws, machineId, owner, name, label, computerId, clientVersion, countryCode, user.harnessSessionId, team))
})().catch((err) => {
if (err instanceof AppError) {
// 403 is the revoked-machine answer from `resolveOrCreateForComputer`, 429 its new-id rate limit
@@ -201,7 +222,7 @@ export function handleAdapterUpgrade(req: IncomingMessage, socket: Duplex, head:
})
}
-async function attachAdapter(ws: WebSocket, machineId: string, userId: string, currentName: string | null, label?: string, computerId?: string, clientVersion?: string, countryCode?: string, harnessSessionId?: string): Promise<void> {
+async function attachAdapter(ws: WebSocket, machineId: string, userId: string, currentName: string | null, label?: string, computerId?: string, clientVersion?: string, countryCode?: string, harnessSessionId?: string, team = false): Promise<void> {
// A different computer was already rejected at the upgrade (denyBusy), so this only closes our OWN
// stale local socket on a same-computer reconnect landing on this worker.
owners.get(machineId)?.close(4000, 'superseded')
@@ -211,7 +232,8 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c
send({ t: 'connected', machineId })
// What changed for the ACCOUNT on some worker (its tabs, its machine list): this computer's app
// re-reads through its daemon rather than polling for it. See adapterAccountPushes.ts.
- const accountPushesUnsub = await relayAccountPushes(userId, send, { zoo: DAEMONS.on })
+ // A team machine reads none of the account's desk, zoo, machines or connections: it hears only the device-key pushes.
+ const accountPushesUnsub = await relayAccountPushes(userId, send, { zoo: DAEMONS.on, team })
// Last desktop-app state THIS socket asserted. Socket-scoped on purpose: a new adapter connection
// starts with no claim and must re-assert, so a fresh value can never renew a stale one.
@@ -266,6 +288,9 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c
...(boundComputer ? { computerId: boundComputer } : {}),
// Same rule again; absent (not behind Cloudflare) leaves the last value.
...(countryCode ? { countryCode } : {}),
+ // Which kind of sign-in serves the machine now (lib/teamSession.ts). A team row was checked, and a former team
+ // row flipped, before the socket attached; this stamps every other row.
+ sessionKind: team ? 'team' : 'computer',
},
}).catch(() => { /* best effort */ })
}
@@ -275,7 +300,8 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c
// Minted and remembered by `routes/grid.ts`; read-only here. A user who has never signed in since
// the route shipped simply has none yet, and the daemon treats that as "no grid" rather than an
// error — the next `harness login` mints it.
- const gridName = (await prisma.user.findUnique({ where: { id: userId }, select: { gridName: true } })
+ // Never on a team machine (lib/teamSession.ts): the grid is the person's inference endpoint, not teammates'.
+ const gridName = team ? null : (await prisma.user.findUnique({ where: { id: userId }, select: { gridName: true } })
.catch(() => null))?.gridName ?? null
send({ t: 'down', connId: '', frame: { type: 'machine_meta', payload: { name: currentName?.trim() || seededName, gridName } } })
@@ -332,6 +358,12 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c
offlineReason: 'remote computer offline',
deliver: (msg) => {
if (ws.readyState !== WebSocket.OPEN) return
+ // Its computer just turned itself into a team machine (lib/harnessSession.ts): a socket still connected under the
+ // old sign-in must not keep serving a machine marked `team`. Backend-only (`__`), never forwarded.
+ if ((msg.frame as { type?: string } | undefined)?.type === TEAM_CONVERTED_FRAME) {
+ if (!team) { try { ws.close(4009, 'now a team machine') } catch { /* ignore */ } }
+ return
+ }
send({ t: 'down', connId: msg.connId, frame: msg.frame })
// `machine_revoked` used to be pushed and nothing more, leaving the socket open and the machine
// still serving if the client ignored it — an old CLI, a dropped frame. Close it ourselves right
@@ -462,7 +494,7 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c
send({ t: 'down', connId: '', frame: { type: 'devlog_append_result', payload: { requestId, error: 'RATE_LIMITED' } } })
return
}
- void appendDeviceKey(userId, p.entry, { kind: 'machine', machineId, ...(harnessSessionId ? { harnessSessionId } : {}) })
+ void appendDeviceKey(userId, p.entry, { kind: 'machine', machineId, ...(harnessSessionId ? { harnessSessionId } : {}), ...(team ? { team } : {}) })
.then((r) => send({ t: 'down', connId: '', frame: { type: 'devlog_append_result', payload: r.ok
? { requestId, head: r.head }
: { requestId, error: r.code, ...('head' in r ? { head: r.head } : {}) } } }))
@@ -501,9 +533,12 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c
}
}
if (env.userEligible) {
- void publishUserDeviceE2eePair(userId, machineId, env.frame).catch((err) => {
- logger.warn('adapter user-level e2ee pair publish failed', { machineId, userId, error: String(err) })
- })
+ // A team machine raises no notice on the person's apps: pairing a device with a machine is the person's to start.
+ if (!team) {
+ void publishUserDeviceE2eePair(userId, machineId, env.frame).catch((err) => {
+ logger.warn('adapter user-level e2ee pair publish failed', { machineId, userId, error: String(err) })
+ })
+ }
if (env.webEligible === false && env.commanderEligible !== true && !env.targetConnId) return
}
// No originPid: the hub's Redis loopback must deliver to this instance's own web clients too
diff --git a/backend/src/lib/agentMessagesWs.test.ts b/backend/src/lib/agentMessagesWs.test.ts
index d5ec35473..160e6a382 100644
--- a/backend/src/lib/agentMessagesWs.test.ts
+++ b/backend/src/lib/agentMessagesWs.test.ts
@@ -80,6 +80,13 @@ describe('blind shared-tab relay WebSocket', () => {
expect(m.upgrade).not.toHaveBeenCalled(); expect(m.admits).not.toHaveBeenCalled()
})
+ it('answers a team sign-in (lib/teamSession.ts) 403 before the upgrade: refused for good, not a token to refresh', async () => {
+ m.auth.mockRejectedValueOnce(new m.SsoAuthError('This connection is not available to a team sign-in', 'TEAM_SESSION_LIMITED'))
+ await connect()
+ expect(socket.write).toHaveBeenCalledWith('HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n')
+ expect(m.admits).not.toHaveBeenCalled(); expect(m.upgrade).not.toHaveBeenCalled()
+ })
+
it('tells an admitted socket it is ready and subscribes to its own channel and share changes', async () => {
await connect()
expect(m.admits).toHaveBeenCalledWith('ken', 'ken-mac', SHARE, 'prod')
diff --git a/backend/src/lib/deviceKeyLog.test.ts b/backend/src/lib/deviceKeyLog.test.ts
index 28eb0f694..83cc95783 100644
--- a/backend/src/lib/deviceKeyLog.test.ts
+++ b/backend/src/lib/deviceKeyLog.test.ts
@@ -179,6 +179,24 @@ describe('appendDeviceKey', () => {
expect(r).toMatchObject({ ok: false, status: 403, code: 'WRONG_CHANNEL' })
})
+ // A team machine (lib/teamSession.ts) is a machine of the account run for teammates: it adds its own key, so the
+ // person's apps reach it end to end, but it never takes another device off the account.
+ it('lets a team machine add its own key and leave, but never remove another device\'s key', async () => {
+ const teamChannel = { kind: 'machine' as const, machineId: MID2, harnessSessionId: 'team-session', team: true }
+ await appendDeviceKey(USER, await addEntry(phone, 'viewer', '', 'phone'), { kind: 'viewer' })
+ await appendDeviceKey(USER, await addEntry(box1, 'machine', MID1, 'box1'), { kind: 'machine', machineId: MID1 })
+ expect(await appendDeviceKey(USER, await addEntry(box2, 'machine', MID2, 'team'), teamChannel)).toMatchObject({ ok: true })
+ for (const target of [box1.pub, phone.pub]) {
+ expect(await appendDeviceKey(USER, await removeEntry(target, box2), teamChannel)).toMatchObject({ ok: false, status: 403, code: 'WRONG_CHANNEL' })
+ }
+ expect(m.publishDown).not.toHaveBeenCalled()
+ expect(m.revoke).not.toHaveBeenCalled()
+ expect(await appendDeviceKey(USER, await removeEntry(box2.pub, box2), teamChannel)).toMatchObject({ ok: true })
+ // The owner's machine may still take the team machine off.
+ await appendDeviceKey(USER, await addEntry(key(4), 'machine', MID2, 'team again'), teamChannel)
+ expect(await appendDeviceKey(USER, await removeEntry(key(4).pub, box1), { kind: 'machine', machineId: MID1 })).toMatchObject({ ok: true })
+ })
+
it('ends the Harness session of a removed phone', async () => {
await appendDeviceKey(USER, await addEntry(phone, 'viewer', '', 'phone'), { kind: 'viewer', harnessSessionId: 'sess-1' })
await appendDeviceKey(USER, await addEntry(box1, 'machine', MID1, 'box1'), { kind: 'machine', machineId: MID1 })
diff --git a/backend/src/lib/deviceKeyLog.ts b/backend/src/lib/deviceKeyLog.ts
index 3f55f9d7f..c41b27750 100644
--- a/backend/src/lib/deviceKeyLog.ts
+++ b/backend/src/lib/deviceKeyLog.ts
@@ -17,7 +17,8 @@ import { checkDevAck } from './deviceAckCore.js'
*
* Who may append what is decided by the CHANNEL, on top of the signatures:
* - a machine appends over its own adapter socket, and only about ITSELF (`kind: 'machine'`, its own
- * machineId) — so no device can register a key under another machine's id;
+ * machineId) — so no device can register a key under another machine's id; a team machine
+ * (lib/teamSession.ts) also removes only its own key, never another device of the account;
* - a viewer app appends over REST, only `kind: 'viewer'` entries, and signs removals with a viewer key.
*/
@@ -33,7 +34,7 @@ export type DeviceKeyAppendResult = { ok: true; head: DevLogHead } | ({ ok: fals
/** Who is appending: a machine over its adapter socket, or a viewer over REST. */
export type DeviceKeyChannel =
- | { kind: 'machine'; machineId: string; harnessSessionId?: string }
+ | { kind: 'machine'; machineId: string; harnessSessionId?: string; team?: boolean }
| { kind: 'viewer'; harnessSessionId?: string }
export async function readDeviceKeyLog(userId: string, since: number): Promise<{ acct: string; head: DevLogHead; entries: unknown[] }> {
@@ -145,6 +146,9 @@ function channelAllows(entry: DevLogEntry, state: DevLogState, channel: DeviceKe
if (channel.kind === 'machine') {
// A machine speaks only as itself: its own key, under its own id.
if (entry.op === 'add') return entry.kind === 'machine' && entry.machineId === channel.machineId
+ // A team machine may leave, but never take another device off the account (and so sign it out).
+ const removed = state.active[entry.pub]
+ if (channel.team && !(removed?.kind === 'machine' && removed.machineId === channel.machineId)) return false
return signer?.kind === 'machine' && signer.machineId === channel.machineId
}
if (entry.op === 'add') return entry.kind === 'viewer'
diff --git a/backend/src/lib/deviceWs.ts b/backend/src/lib/deviceWs.ts
index d9342a279..9506dce75 100644
--- a/backend/src/lib/deviceWs.ts
+++ b/backend/src/lib/deviceWs.ts
@@ -341,7 +341,9 @@ export function handleDeviceUpgrade(req: IncomingMessage, socket: Duplex, head:
try {
user = await authenticateAccessToken(accessToken, autonomousEnv, { allowHarnessSession: 'computer' })
} catch (err) {
- if (err instanceof SsoAuthError && (err.code === 'AUTONOMOUS_ENV_MISMATCH' || err.code === 'AUTONOMOUS_ENV_NOT_ALLOWED')) {
+ // A Mac's team account (lib/teamSession.ts) has no device lane: refused for good, like the wrong environment.
+ if (err instanceof SsoAuthError && (err.code === 'AUTONOMOUS_ENV_MISMATCH' || err.code === 'AUTONOMOUS_ENV_NOT_ALLOWED'
+ || err.code === 'TEAM_SESSION_LIMITED')) {
denyWith(403, 'Forbidden')
return
}
diff --git a/backend/src/lib/gridProfile.ts b/backend/src/lib/gridProfile.ts
index a152fa870..77f33bfe9 100644
--- a/backend/src/lib/gridProfile.ts
+++ b/backend/src/lib/gridProfile.ts
@@ -120,6 +120,10 @@ export async function answerGridProfile(caller: AuthUser, token: string): Promis
/** A sign-in Harness issued itself: only a computer's, answered from what was last read live. */
async function answerHarnessSession(caller: AuthUser): Promise<GridProfileAnswer> {
+ // A Mac's team account runs teammates' agents (lib/teamSession.ts): it never speaks for the person to Grid.
+ if (caller.harnessSessionKind === 'team') {
+ return refuse(403, 'TEAM_SESSION_LIMITED', 'A team sign-in cannot be used for Grid')
+ }
// A phone never calls Grid, and a lost phone must not become a long-lived Grid session.
if (caller.harnessSessionKind !== 'computer') {
return refuse(403, 'PHONE_SIGN_IN', 'A phone sign-in cannot be used for Grid; sign in on a computer')
diff --git a/backend/src/lib/harnessSession.test.ts b/backend/src/lib/harnessSession.test.ts
index 52bf59b64..f7df13b7b 100644
--- a/backend/src/lib/harnessSession.test.ts
+++ b/backend/src/lib/harnessSession.test.ts
@@ -12,8 +12,9 @@ const fakes = vi.hoisted(() => {
const pick = (where: Record<string, unknown>) =>
sessions.find((s) => Object.entries(where).every(([k, v]) => s[k] === v)) ?? null
const pub = {
- set: vi.fn(async (key: string, value: string, _ex: string, ttl: number) => {
+ set: vi.fn(async (key: string, value: string, _ex: string, ttl: number, ...flags: string[]) => {
if (failRedis) throw new Error('redis down')
+ if (flags.includes('NX') && redis.has(key)) return null
redis.set(key, value); ttls.set(key, ttl); return 'OK'
}),
get: vi.fn(async (key: string) => {
@@ -50,16 +51,35 @@ const fakes = vi.hoisted(() => {
rows.forEach((r) => Object.assign(r, data)); return { count: rows.length }
}),
}
+ // The account's machines, for the check that a team code never binds to a computer a normal sign-in holds.
+ const machines: Array<Record<string, unknown>> = []
+ const live = (where: Record<string, unknown>) => machines.filter((m) => !m.deletedAt &&
+ Object.entries(where).every(([k, v]) => k === 'OR' || m[k] === v))
+ const machine = {
+ findMany: vi.fn(async ({ where }: { where: Record<string, unknown> }) => live(where)),
+ findFirst: vi.fn(async ({ where }: { where: Record<string, unknown> }) => live(where)[0] ?? null),
+ updateMany: vi.fn(async ({ where, data }: { where: Record<string, unknown>; data: Record<string, unknown> }) => {
+ const rows = live(where); rows.forEach((r) => Object.assign(r, data)); return { count: rows.length }
+ }),
+ }
+ // A transaction over the same in-memory collections: what one changes, the others see.
+ const transaction = vi.fn(async (body: (tx: unknown) => Promise<unknown>) => body({ harnessSession, machine }))
+ const publishDown = vi.fn(async () => 1)
+ const activeMachineKeys = vi.fn(async (_userId: string): Promise<Array<{ pub: string; machineId: string; kind: string }>> => [])
return {
- redis, ttls, sessions, users, pub, harnessSession,
+ redis, ttls, sessions, users, machines, pub, harnessSession, machine, transaction, publishDown, activeMachineKeys,
setFailRedis: (v: boolean) => { failRedis = v },
get: vi.fn(async (id: string) => users.get(id) ?? null),
findByEmail: vi.fn(),
}
})
-vi.mock('./bus.js', () => ({ pub: fakes.pub }))
-vi.mock('./prisma.js', () => ({ prisma: { harnessSession: fakes.harnessSession } }))
+vi.mock('./bus.js', () => ({ pub: fakes.pub, publishDown: fakes.publishDown }))
+vi.mock('./deviceKeyLog.js', () => ({ activeMachineKeys: fakes.activeMachineKeys }))
+vi.mock('./prisma.js', () => ({
+ prisma: { harnessSession: fakes.harnessSession, machine: fakes.machine, $transaction: fakes.transaction },
+ machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] },
+}))
vi.mock('../services/UserService.js', () => ({
userService: { get: fakes.get, findByEmail: fakes.findByEmail },
normalizeUserEmail: (email: string) => email.trim().toLowerCase(),
@@ -68,7 +88,10 @@ vi.mock('../services/UserService.js', () => ({
vi.mock('../services/index.js', () => ({ userService: { get: fakes.get, toPublic: (u: unknown) => u } }))
import { authenticateAccessToken, SsoAuthError } from './ssoAuth.js'
-import { HANDOFF_TTL_SEC, redeemHandoff, startHandoff } from './harnessSession.js'
+import { HANDOFF_TTL_SEC, redeemHandoff, refreshHarnessSession, revokeHarnessSession, startHandoff } from './harnessSession.js'
+import { HARNESS_ACCESS_PREFIX, harnessTokenHash, newHarnessToken } from './harnessTokenFormat.js'
+import { teamConversionMessage } from './teamSession.js'
+import { ed25519 } from '@noble/curves/ed25519.js'
import { authRoutes } from '../routes/auth.js'
import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'
import { errorHandler } from '../middlewares/errorHandler.js'
@@ -76,7 +99,7 @@ import { errorHandler } from '../middlewares/errorHandler.js'
const USER = { id: 'u1', email: '[email protected]', role: 'user', autonomousEnv: 'prod' }
beforeEach(() => {
- fakes.redis.clear(); fakes.ttls.clear(); fakes.sessions.length = 0; fakes.users.clear()
+ fakes.redis.clear(); fakes.ttls.clear(); fakes.sessions.length = 0; fakes.users.clear(); fakes.machines.length = 0
fakes.users.set(USER.id, USER)
fakes.setFailRedis(false)
vi.clearAllMocks()
@@ -215,3 +238,356 @@ describe('scan to sign in — the routes', () => {
}
})
})
+
+// A teammate's agents run on the owner's Mac inside a second macOS user, whose own daemon is signed in to the owner's
+// account with a TEAM session (docs/plans/2026-10-24-swarm-team-account.md, Task 1). It must be able to do strictly
+// less than a computer: it is minted only by a computer, bound to the computer that redeemed it, and refused by every
+// connection that has not said it confines a team session to that computer's own machine.
+describe('team sessions — minting and redeeming', () => {
+ const COMPUTER = 'ab12cd34ef56ab12cd34ef56ab12cd34'
+ const OTHER_COMPUTER = 'ffff0000ffff0000ffff0000ffff0000'
+
+ it('a team code redeems to a team session bound to the computer that redeemed it', async () => {
+ const { code, expiresIn } = await startHandoff(USER.id, 'team')
+ expect(code).toMatch(/^hnh_[A-Za-z0-9_-]{43}$/)
+ expect(expiresIn).toBe(HANDOFF_TTL_SEC)
+ expect([...fakes.ttls.values()]).toEqual([HANDOFF_TTL_SEC])
+ const tokens = await redeemHandoff(code, 'MacBook Pro · Team', COMPUTER)
+ expect(tokens).toMatchObject({ expiresIn: 3600, autonomousEnv: 'prod' })
+ expect(fakes.sessions[0]).toMatchObject({ userId: USER.id, label: 'MacBook Pro · Team', kind: 'team', computerId: COMPUTER })
+ await expect(authenticateAccessToken(tokens!.token, 'prod', { allowTeamSession: true })).resolves.toEqual({
+ sub: USER.id, email: USER.email, role: 'user', autonomousEnv: 'prod',
+ harnessSessionId: 's1', harnessSessionKind: 'team', harnessComputerId: COMPUTER,
+ })
+ })
+
+ it('a viewer code minted without a kind still redeems to a viewer, a computer id or not', async () => {
+ const plain = await startHandoff(USER.id)
+ expect((await redeemHandoff(plain.code, 'phone', COMPUTER))).not.toBeNull()
+ expect(fakes.sessions[0]).toMatchObject({ kind: 'viewer' })
+ expect(fakes.sessions[0].computerId).toBeUndefined()
+ // A code minted before team sessions existed holds the bare user id: it is a viewer's.
+ const viewer = await startHandoff(USER.id, 'viewer')
+ expect([...fakes.redis.values()]).toContain(USER.id)
+ expect(await redeemHandoff(viewer.code, 'phone')).not.toBeNull()
+ expect(fakes.sessions[1]).toMatchObject({ kind: 'viewer' })
+ })
+
+ it('a team code holds no bare user id, so a server that predates team sessions can never redeem it as a viewer', async () => {
+ await startHandoff(USER.id, 'team')
+ const held = [...fakes.redis.values()][0]!
+ expect(held).not.toBe(USER.id)
+ expect(JSON.parse(held)).toEqual({ userId: USER.id, kind: 'team' })
+ })
+
+ it('a team code without a computer id, or with a malformed one, is spent and answers nothing', async () => {
+ for (const computerId of [undefined, '', 'not-a-computer']) {
+ const { code } = await startHandoff(USER.id, 'team')
+ expect(await redeemHandoff(code, 'x', computerId)).toBeNull()
+ expect(await redeemHandoff(code, 'x', COMPUTER)).toBeNull() // spent: a second try with a good id gets nothing either
+ }
+ expect(fakes.sessions).toHaveLength(0)
+ })
+
+ it('a team code never binds to a computer the account already runs with a normal sign-in', async () => {
+ fakes.machines.push({ userId: USER.id, computerId: COMPUTER, machineId: 'owner-mac', sessionKind: 'computer' })
+ fakes.machines.push({ userId: USER.id, computerId: OTHER_COMPUTER, machineId: 'legacy', sessionKind: null })
+ for (const computerId of [COMPUTER, OTHER_COMPUTER]) {
+ const { code } = await startHandoff(USER.id, 'team')
+ expect(await redeemHandoff(code, 'x', computerId)).toBeNull()
+ }
+ expect(fakes.sessions).toHaveLength(0)
+ // The team machine itself, signed in again (a re-setup), is fine.
+ fakes.machines.push({ userId: USER.id, computerId: 'abababababababababababababababab', machineId: 'team-mac', sessionKind: 'team' })
+ const { code } = await startHandoff(USER.id, 'team')
+ expect(await redeemHandoff(code, 'x', 'ABABABAB-ABAB-ABAB-ABAB-ABABABABABAB')).not.toBeNull()
+ expect(fakes.sessions[0]).toMatchObject({ kind: 'team', computerId: 'abababababababababababababababab' })
+ })
+
+ it('a team session\'s tokens have their own prefixes, which a server from before team sessions does not take as Harness ones', async () => {
+ const { code } = await startHandoff(USER.id, 'team')
+ const tokens = (await redeemHandoff(code, 'x', COMPUTER))!
+ expect(tokens.token).toMatch(/^hta_[A-Za-z0-9_-]{43}$/)
+ expect(tokens.refreshToken).toMatch(/^htr_[A-Za-z0-9_-]{43}$/)
+ expect((await refreshHarnessSession(tokens.refreshToken!))!.token).toMatch(/^hta_/)
+ // The prefix and the session's kind must agree: one dressed as the other is no token at all.
+ const viewer = (await redeemHandoff((await startHandoff(USER.id)).code, 'phone'))!
+ const teamDressedAsViewer = `hna_${tokens.token.slice(4)}`
+ fakes.redis.set(`hnauth:access:${harnessTokenHash(teamDressedAsViewer)}`, fakes.redis.get(`hnauth:access:${harnessTokenHash(tokens.token)}`)!)
+ await expect(authenticateAccessToken(teamDressedAsViewer, 'prod', { allowTeamSession: true })).rejects.toMatchObject({ code: 'INVALID_TOKEN' })
+ const viewerDressedAsTeam = `hta_${viewer.token.slice(4)}`
+ fakes.redis.set(`hnauth:access:${harnessTokenHash(viewerDressedAsTeam)}`, fakes.redis.get(`hnauth:access:${harnessTokenHash(viewer.token)}`)!)
+ await expect(authenticateAccessToken(viewerDressedAsTeam, 'prod', { allowTeamSession: true })).rejects.toMatchObject({ code: 'INVALID_TOKEN' })
+ // The refresh tokens' hashes differ with their prefixes, so a renamed one finds no session.
+ expect(await refreshHarnessSession(`hnr_${tokens.refreshToken!.slice(4)}`)).toBeNull()
+ })
+
+ it('a team session row without its computer is not a session at all', async () => {
+ const { code } = await startHandoff(USER.id, 'team')
+ const { token } = (await redeemHandoff(code, 'x', COMPUTER))!
+ delete fakes.sessions[0].computerId
+ await expect(authenticateAccessToken(token, 'prod', { allowTeamSession: true })).rejects.toMatchObject({ code: 'INVALID_TOKEN' })
+ })
+})
+
+describe('team sessions — refused by every connection that does not confine them', () => {
+ const COMPUTER = 'ab12cd34ef56ab12cd34ef56ab12cd34'
+ async function teamToken(): Promise<string> {
+ const { code } = await startHandoff(USER.id, 'team')
+ return (await redeemHandoff(code, 'team', COMPUTER))!.token
+ }
+
+ it('by default, as a machine, and where only an Autonomous sign-in will do', async () => {
+ const token = await teamToken()
+ for (const opts of [undefined, {}, { allowHarnessSession: true }, { allowHarnessSession: 'computer' as const }, { enforceEnv: false }]) {
+ const err = await authenticateAccessToken(token, 'prod', opts).catch((e: unknown) => e)
+ expect(err).toBeInstanceOf(SsoAuthError)
+ expect(err).toMatchObject({ code: 'TEAM_SESSION_LIMITED' })
+ }
+ await expect(authenticateAccessToken(token, 'prod', { allowHarnessSession: false })).rejects.toMatchObject({ code: 'INVALID_TOKEN' })
+ })
+
+ it('accepted only where the caller opts in, as a machine too', async () => {
+ const token = await teamToken()
+ await expect(authenticateAccessToken(token, 'prod', { allowHarnessSession: 'computer', allowTeamSession: true }))
+ .resolves.toMatchObject({ harnessSessionKind: 'team', harnessComputerId: COMPUTER })
+ })
+
+ it('a computer session is unchanged by the option', async () => {
+ const { code } = await startHandoff(USER.id)
+ const { token } = (await redeemHandoff(code, 'phone'))!
+ await expect(authenticateAccessToken(token, 'prod', { allowTeamSession: true })).resolves.toMatchObject({ harnessSessionKind: 'viewer' })
+ await expect(authenticateAccessToken(token, 'prod', { allowHarnessSession: 'computer', allowTeamSession: true }))
+ .rejects.toMatchObject({ code: 'INVALID_TOKEN' })
+ })
+
+ it('refreshes and signs out like any Harness session', async () => {
+ const { code } = await startHandoff(USER.id, 'team')
+ const { refreshToken } = (await redeemHandoff(code, 'team', COMPUTER))!
+ const renewed = await refreshHarnessSession(refreshToken!)
+ await expect(authenticateAccessToken(renewed!.token, 'prod', { allowTeamSession: true })).resolves.toMatchObject({ harnessSessionKind: 'team' })
+ await revokeHarnessSession(refreshToken!)
+ expect(await refreshHarnessSession(refreshToken!)).toBeNull()
+ })
+})
+
+describe('team sessions — the routes', () => {
+ const COMPUTER = 'ab12cd34ef56ab12cd34ef56ab12cd34'
+ const handoffCodes = () => [...fakes.redis.keys()].filter((key) => key.startsWith('hnauth:handoff:'))
+ let app: FastifyInstance
+ const signedIn = { sub: USER.id, email: USER.email, role: 'user', autonomousEnv: 'prod' as const }
+
+ beforeEach(async () => {
+ app = Fastify()
+ app.setErrorHandler(errorHandler)
+ registerAuthMiddleware(app, async (token, env, opts) => token === 'sso-token' ? signedIn : authenticateAccessToken(token, env, opts))
+ await app.register(authRoutes)
+ await app.ready()
+ })
+
+ const mint = (authorization: string, payload?: unknown) => app.inject({ method: 'POST', url: '/api/auth/handoff',
+ headers: { authorization }, ...(payload === undefined ? {} : { payload: payload as Record<string, unknown> }) })
+ const redeem = (payload: Record<string, unknown>) => app.inject({ method: 'POST', url: '/api/auth/handoff/redeem', payload })
+
+ it('an Autonomous sign-in mints a team code; the redeeming computer gets a team session bound to it', async () => {
+ const minted = await mint('Bearer sso-token', { kind: 'team' })
+ expect(minted.statusCode).toBe(200)
+ // The answer names what it minted, and the code is a plain token (what the team daemon's file carries).
+ expect(minted.json().data).toEqual({ code: expect.stringMatching(/^[A-Za-z0-9_-]{16,256}$/), expiresIn: HANDOFF_TTL_SEC, kind: 'team' })
+ const redeemed = await redeem({ code: minted.json().data.code, label: 'MacBook Pro · Team', computerId: COMPUTER })
+ expect(redeemed.statusCode).toBe(200)
+ expect(Object.keys(redeemed.json().data).sort()).toEqual(['autonomousEnv', 'expiresIn', 'kind', 'refreshToken', 'token'])
+ expect(redeemed.json().data.kind).toBe('team')
+ expect(fakes.sessions[0]).toMatchObject({ kind: 'team', computerId: COMPUTER, label: 'MacBook Pro · Team' })
+ })
+
+ it('a computer signed in by QR mints a team code too', async () => {
+ // A computer session as a QR claim leaves it: its row, and its access token in the store.
+ const computer = newHarnessToken(HARNESS_ACCESS_PREFIX)
+ fakes.sessions.push({ id: 'computer-1', userId: USER.id, label: 'MacBook Pro', kind: 'computer', refreshHash: 'unused' })
+ fakes.redis.set(`hnauth:access:${harnessTokenHash(computer)}`, JSON.stringify({ sessionId: 'computer-1', userId: USER.id }))
+ const minted = await mint(`Bearer ${computer}`, { kind: 'team' })
+ expect(minted.statusCode).toBe(200)
+ expect((await redeem({ code: minted.json().data.code, label: 'Team', computerId: COMPUTER })).statusCode).toBe(200)
+ expect(fakes.sessions.at(-1)).toMatchObject({ kind: 'team' })
+ })
+
+ it('without a body, or asking for a viewer, the code is a viewer\'s exactly as before', async () => {
+ for (const payload of [undefined, {}, { kind: 'viewer' }]) {
+ const minted = await mint('Bearer sso-token', payload)
+ expect(minted.statusCode).toBe(200)
+ expect(minted.json().data.kind).toBe('viewer')
+ const redeemed = await redeem({ code: minted.json().data.code, label: 'phone' })
+ expect(redeemed.statusCode).toBe(200)
+ expect(redeemed.json().data.kind).toBe('viewer')
+ expect(fakes.sessions.at(-1)).toMatchObject({ kind: 'viewer' })
+ }
+ })
+
+ it('refuses a kind it does not know, without minting', async () => {
+ for (const kind of ['computer', 'admin', 1, null]) {
+ const res = await mint('Bearer sso-token', { kind })
+ expect(res.statusCode).toBe(400)
+ expect(res.json().error.code).toBe('INVALID_HANDOFF_KIND')
+ }
+ expect(handoffCodes()).toEqual([])
+ })
+
+ it('a team session can never mint a code of any kind', async () => {
+ const { code } = await startHandoff(USER.id, 'team')
+ const { token } = (await redeemHandoff(code, 'team', COMPUTER))!
+ for (const payload of [undefined, { kind: 'team' }, { kind: 'viewer' }]) {
+ const res = await mint(`Bearer ${token}`, payload)
+ expect(res.statusCode).toBe(403)
+ }
+ expect(handoffCodes()).toEqual([])
+ })
+
+ it('a phone signed in by a scan cannot mint a team code either', async () => {
+ const { code } = await startHandoff(USER.id)
+ const { token } = (await redeemHandoff(code, 'phone'))!
+ const res = await mint(`Bearer ${token}`, { kind: 'team' })
+ expect(res.statusCode).toBe(403)
+ expect(res.json().error.code).toBe('HANDOFF_NOT_ALLOWED')
+ })
+
+ it('a team code redeemed without its computer is the same one answer as a spent code', async () => {
+ const minted = await mint('Bearer sso-token', { kind: 'team' })
+ const res = await redeem({ code: minted.json().data.code, label: 'Team' })
+ expect(res.statusCode).toBe(401)
+ expect(res.json().error.code).toBe('HANDOFF_INVALID')
+ expect(fakes.sessions).toHaveLength(0)
+ })
+})
+
+// `harness team on`: a machine used only for agents becomes a team machine in place, keeping its computer id so its
+// Swarm contributions and history survive. Only the computer itself may ask: its own Harness computer session, or a
+// signature by its key on the account's device key log. Anyone else asking for a computer in ordinary use is refused.
+describe('team sessions — a computer turning itself into a team machine', () => {
+ const BOX = 'cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd'
+ const LAPTOP = 'efefefefefefefefefefefefefefefef'
+ let app: FastifyInstance
+ const signedIn = { sub: USER.id, email: USER.email, role: 'user', autonomousEnv: 'prod' as const }
+ beforeEach(async () => {
+ app = Fastify()
+ app.setErrorHandler(errorHandler)
+ registerAuthMiddleware(app, async (token, env, opts) => token === 'sso-token' ? signedIn : authenticateAccessToken(token, env, opts))
+ await app.register(authRoutes)
+ await app.ready()
+ fakes.machines.push({ userId: USER.id, computerId: BOX, machineId: 'box-machine', autonomousEnv: 'prod', sessionKind: 'computer' })
+ })
+ const mint = (authorization: string, payload: Record<string, unknown>) => app.inject({ method: 'POST', url: '/api/auth/handoff', headers: { authorization }, payload })
+ const redeem = (payload: Record<string, unknown>) => app.inject({ method: 'POST', url: '/api/auth/handoff/redeem', payload })
+ /** A Harness computer session, as a QR sign-in leaves it, signed in as [computerId] (or as no computer it recorded). */
+ function computerSession(id: string, computerId?: string): string {
+ const token = newHarnessToken(HARNESS_ACCESS_PREFIX)
+ fakes.sessions.push({ id, userId: USER.id, label: 'Mac mini', kind: 'computer', refreshHash: `unused-${id}`, ...(computerId ? { computerId } : {}) })
+ fakes.redis.set(`hnauth:access:${harnessTokenHash(token)}`, JSON.stringify({ sessionId: id, userId: USER.id }))
+ return token
+ }
+ const machineKey = ed25519.getPublicKey(new Uint8Array(32).fill(9))
+ const proof = (overrides: { machineId?: string; at?: number; computerId?: string; priv?: Uint8Array } = {}) => {
+ const machineId = overrides.machineId ?? 'box-machine', at = overrides.at ?? Date.now()
+ const message = teamConversionMessage(USER.id, overrides.computerId ?? BOX, machineId, at)
+ const sig = ed25519.sign(new TextEncoder().encode(message), overrides.priv ?? new Uint8Array(32).fill(9))
+ return { machineId, at, sig: Buffer.from(sig).toString('base64') }
+ }
+
+ it('its own computer session converts it: redeeming ends its ordinary sign-ins and makes it a team machine, in one transaction', async () => {
+ const own = computerSession('box-session', BOX)
+ computerSession('box-older-session', BOX)
+ computerSession('laptop-session', LAPTOP)
+ const minted = await mint(`Bearer ${own}`, { kind: 'team', computerId: BOX.toUpperCase() })
+ expect(minted.statusCode, minted.body).toBe(200)
+ expect(minted.json().data).toMatchObject({ kind: 'team' })
+ const redeemed = await redeem({ code: minted.json().data.code, label: 'Mac mini · Team', computerId: BOX })
+ expect(redeemed.statusCode, redeemed.body).toBe(200)
+ expect(redeemed.json().data.kind).toBe('team')
+ expect(fakes.transaction).toHaveBeenCalledTimes(1)
+ const byId = (id: string) => fakes.sessions.find((s) => s.id === id)!
+ expect(byId('box-session').revokedAt).toBeInstanceOf(Date)
+ expect(byId('box-older-session').revokedAt).toBeInstanceOf(Date)
+ expect(byId('laptop-session').revokedAt).toBeUndefined()
+ expect(fakes.sessions.at(-1)).toMatchObject({ kind: 'team', computerId: BOX, label: 'Mac mini · Team' })
+ expect(fakes.machines[0]).toMatchObject({ machineId: 'box-machine', sessionKind: 'team' })
+ // A socket still connected under the old sign-in is told to close (lib/adapterWs.ts).
+ expect(fakes.publishDown).toHaveBeenCalledWith('box-machine', { connId: '', frame: { type: '__team_converted' } })
+ // The old sign-in is over at once.
+ const res = await app.inject({ method: 'GET', url: '/api/auth/me', headers: { authorization: `Bearer ${own}` } })
+ expect(res.statusCode).toBe(401)
+ await expect(authenticateAccessToken(redeemed.json().data.token, 'prod', { allowTeamSession: true }))
+ .resolves.toMatchObject({ harnessSessionKind: 'team', harnessComputerId: BOX })
+ })
+
+ it('a conversion code redeems only for the computer that asked', async () => {
+ const own = computerSession('box-session', BOX)
+ const minted = await mint(`Bearer ${own}`, { kind: 'team', computerId: BOX })
+ for (const computerId of [LAPTOP, undefined]) {
+ const res = await redeem({ code: minted.json().data.code, label: 'x', ...(computerId ? { computerId } : {}) })
+ expect(res.statusCode).toBe(401)
+ expect(res.json().error.code).toBe('HANDOFF_INVALID')
+ }
+ expect(fakes.sessions.find((s) => s.id === 'box-session')!.revokedAt).toBeUndefined()
+ expect(fakes.machines[0].sessionKind).toBe('computer')
+ })
+
+ it('a computer signed in with Autonomous converts itself with its machine key\'s signature', async () => {
+ fakes.activeMachineKeys.mockResolvedValue([{ pub: Buffer.from(machineKey).toString('base64'), machineId: 'box-machine', kind: 'machine' }])
+ const minted = await mint('Bearer sso-token', { kind: 'team', computerId: BOX, proof: proof() })
+ expect(minted.statusCode, minted.body).toBe(200)
+ expect((await redeem({ code: minted.json().data.code, label: 'Mac mini', computerId: BOX })).statusCode).toBe(200)
+ expect(fakes.machines[0].sessionKind).toBe('team')
+ })
+
+ it('no other session may convert a computer: not another computer, not an Autonomous sign-in without the machine\'s key, not a phone', async () => {
+ fakes.activeMachineKeys.mockResolvedValue([{ pub: Buffer.from(machineKey).toString('base64'), machineId: 'box-machine', kind: 'machine' },
+ { pub: Buffer.from(ed25519.getPublicKey(new Uint8Array(32).fill(5))).toString('base64'), machineId: 'laptop-machine', kind: 'machine' }])
+ fakes.machines.push({ userId: USER.id, computerId: LAPTOP, machineId: 'laptop-machine', autonomousEnv: 'prod', sessionKind: 'computer' })
+ const refused = async (authorization: string, payload: Record<string, unknown>) => {
+ const res = await mint(authorization, { kind: 'team', computerId: BOX, ...payload })
+ expect(res.statusCode, JSON.stringify(payload)).toBe(403)
+ expect(res.json().error.code).toBe('HANDOFF_NOT_ALLOWED')
+ }
+ await refused(`Bearer ${computerSession('laptop-session', LAPTOP)}`, {})
+ await refused(`Bearer ${computerSession('unrecorded-session')}`, {})
+ await refused('Bearer sso-token', {})
+ await refused('Bearer sso-token', { proof: { ...proof(), sig: proof({ priv: new Uint8Array(32).fill(5) }).sig } })
+ await refused('Bearer sso-token', { proof: proof({ machineId: 'laptop-machine', priv: new Uint8Array(32).fill(5) }) })
+ await refused('Bearer sso-token', { proof: proof({ at: Date.now() - 10 * 60_000 }) })
+ await refused('Bearer sso-token', { proof: proof({ computerId: LAPTOP }) })
+ await refused('Bearer sso-token', { proof: 'not a proof' })
+ // A proof is good once.
+ const once = proof()
+ expect((await mint('Bearer sso-token', { kind: 'team', computerId: BOX, proof: once })).statusCode).toBe(200)
+ await refused('Bearer sso-token', { proof: once })
+ // A phone asks for nothing, of any kind.
+ const { code } = await startHandoff(USER.id)
+ const { token: phone } = (await redeemHandoff(code, 'phone'))!
+ expect((await mint(`Bearer ${phone}`, { kind: 'team', computerId: BOX })).statusCode).toBe(403)
+ expect(fakes.sessions.filter((s) => s.revokedAt)).toEqual([])
+ expect(fakes.machines.every((m) => m.sessionKind === 'computer')).toBe(true)
+ })
+
+ it('a team session never mints, even a conversion of its own computer', async () => {
+ fakes.machines[0].sessionKind = 'team'
+ const { code } = await startHandoff(USER.id, 'team')
+ const { token } = (await redeemHandoff(code, 'team', BOX))!
+ const res = await mint(`Bearer ${token}`, { kind: 'team', computerId: BOX })
+ expect(res.statusCode).toBe(403)
+ expect(res.json().error.code).toBe('TEAM_SESSION_LIMITED')
+ })
+
+ it('a computer id in the mint is only for a team code, and only a well-formed one', async () => {
+ const own = computerSession('box-session', BOX)
+ for (const payload of [{ kind: 'viewer', computerId: BOX }, { computerId: BOX }]) {
+ const res = await mint(`Bearer ${own}`, payload)
+ expect(res.statusCode).toBe(400)
+ expect(res.json().error.code).toBe('INVALID_HANDOFF_KIND')
+ }
+ for (const computerId of ['not-a-computer', 7]) {
+ const res = await mint(`Bearer ${own}`, { kind: 'team', computerId })
+ expect(res.statusCode).toBe(400)
+ expect(res.json().error.code).toBe('INVALID_COMPUTER_ID')
+ }
+ })
+})
diff --git a/backend/src/lib/harnessSession.ts b/backend/src/lib/harnessSession.ts
index 36f87440a..ad520e36c 100644
--- a/backend/src/lib/harnessSession.ts
+++ b/backend/src/lib/harnessSession.ts
@@ -1,7 +1,9 @@
import { randomInt } from 'node:crypto'
-import { pub } from './bus.js'
+import { pub, publishDown } from './bus.js'
import type { Prisma } from '@prisma/client'
-import { prisma } from './prisma.js'
+import { machineAlive, prisma } from './prisma.js'
+import { normalizeComputerId } from './deviceAuth.js'
+import { TEAM_CONVERTED_FRAME } from './teamSession.js'
import { userService } from '../services/UserService.js'
import { storedAutonomousEnvironment, type AutonomousEnvironment } from './autonomousEnvironment.js'
import { SsoAuthError, type AuthUser } from './ssoAuth.js'
@@ -11,11 +13,15 @@ import {
HARNESS_QR_POLL_PREFIX,
HARNESS_QR_PREFIX,
HARNESS_REFRESH_PREFIX,
+ HARNESS_TEAM_ACCESS_PREFIX,
+ HARNESS_TEAM_REFRESH_PREFIX,
harnessTokenHash,
isHarnessHandoffCode,
isHarnessQrCode,
isHarnessQrPollToken,
isHarnessRefreshToken,
+ isTeamAccessToken,
+ isTeamRefreshToken,
newHarnessToken,
} from './harnessTokenFormat.js'
@@ -41,6 +47,17 @@ import {
* Nothing here is the person's Autonomous credential, and nothing here reaches the account service:
* a route that forwards the caller's token there (billing, via lib/autonomousBff.ts) cannot be used
* from a Harness session. The phone uses none of them.
+ *
+ * The same code, asked for with `{ kind: 'team' }`, signs in a Mac's team account instead: the second
+ * macOS user that runs teammates' Swarm agents (lib/teamSession.ts). Only a computer can ask for one, and
+ * the daemon that redeems it names its computer, which the session is bound to for good.
+ *
+ * computer → POST /api/auth/handoff { kind: 'team' } → { code, expiresIn, kind }
+ * team → POST /api/auth/handoff/redeem { code, label, computerId } → { token, refreshToken, expiresIn, kind }
+ *
+ * A computer may also turn ITSELF into a team machine, keeping its computer id (`harness team on`): its code
+ * names that computer, the redeem must name it too, and redeeming ends the computer's ordinary sign-ins in
+ * the same transaction. Who may ask for that is routes/auth.ts's to decide.
*/
/** How long a code in a QR stays good. The Add Phone dialog asks for a new one every minute. */
@@ -56,55 +73,140 @@ const sessionExpiry = (): Date => new Date(Date.now() + SESSION_IDLE_DAYS * 24 *
export interface HarnessTokens {
token: string
+ /** On a new session: the kind it is, so a caller stores what it was given and not what it asked for. */
+ kind?: HarnessSessionKind
/** Only on redeem: a refresh keeps the refresh token it was given. */
refreshToken?: string
expiresIn: number
autonomousEnv: AutonomousEnvironment
}
-/** A one-time code a signed-in computer puts in its Add Phone QR. */
-export async function startHandoff(userId: string): Promise<{ code: string; expiresIn: number }> {
+export type HarnessSessionKind = 'viewer' | 'computer' | 'team'
+/** What a handoff code signs in: a phone (the Add Phone QR), or a Mac's team account. */
+export type HandoffKind = 'viewer' | 'team'
+/** What a QR sign-in can ask to become. Never a team session: that one is only ever a computer's handoff. */
+export type QrSignInKind = 'viewer' | 'computer'
+
+/**
+ * A one-time code a signed-in computer puts in its Add Phone QR, or hands its team account.
+ *
+ * A viewer's code holds the bare user id, as every code did before team sessions. A team code holds JSON,
+ * so a server that predates team sessions finds no account under it and refuses it: it can never become
+ * a viewer's session, which reaches far more than a team session may.
+ */
+export async function startHandoff(
+ userId: string,
+ kind: HandoffKind = 'viewer',
+ /** A team code for this computer turning itself into a team machine, already proven to be that computer. */
+ { convert }: { convert?: string } = {},
+): Promise<{ code: string; expiresIn: number; kind: HandoffKind }> {
const code = newHarnessToken(HARNESS_HANDOFF_PREFIX)
- await pub.set(handoffKey(harnessTokenHash(code)), userId, 'EX', HANDOFF_TTL_SEC)
- return { code, expiresIn: HANDOFF_TTL_SEC }
+ const held = kind === 'team' ? JSON.stringify({ userId, kind, ...(convert ? { convert } : {}) }) : userId
+ await pub.set(handoffKey(harnessTokenHash(code)), held, 'EX', HANDOFF_TTL_SEC)
+ return { code, expiresIn: HANDOFF_TTL_SEC, kind }
+}
+
+/** Who a spent code was minted for, and as what; null for anything else. */
+function handoffOf(held: unknown): { userId: string; kind: HandoffKind; convert?: string } | null {
+ if (typeof held !== 'string' || !held) return null
+ if (!held.startsWith('{')) return { userId: held, kind: 'viewer' }
+ try {
+ const parsed = JSON.parse(held) as { userId?: unknown; kind?: unknown; convert?: unknown }
+ if (typeof parsed.userId !== 'string' || !parsed.userId || parsed.kind !== 'team') return null
+ return { userId: parsed.userId, kind: 'team', ...(typeof parsed.convert === 'string' && parsed.convert ? { convert: parsed.convert } : {}) }
+ } catch { return null }
}
/**
- * Spend [code] and sign [label]'s device in as the account that minted it. Null for a code that is
- * malformed, expired or already spent — one answer for all three, so a caller learns nothing.
+ * Spend [code] and sign [label]'s device in as the account that minted it, as the kind it was minted
+ * for. A team code also needs the redeeming daemon's [computerId], which its session is bound to. Null
+ * for a code that is malformed, expired or already spent, and for a team code without a usable computer
+ * — one answer for all of them, so a caller learns nothing.
*/
-export async function redeemHandoff(code: string, label: string): Promise<HarnessTokens | null> {
+export async function redeemHandoff(code: string, label: string, computerId?: string): Promise<HarnessTokens | null> {
if (!isHarnessHandoffCode(code)) return null
// Read and spend in ONE step: two phones racing the same QR must not both get in. MULTI rather
// than GETDEL, which a Redis older than 6.2 does not have.
const key = handoffKey(harnessTokenHash(code))
const [read] = (await pub.multi().get(key).del(key).exec()) ?? []
if (!read || read[0]) throw read?.[0] ?? new Error('handoff redeem: no reply from Redis')
- const userId = read[1]
- if (typeof userId !== 'string' || !userId) return null
- return createSession(userId, label, 'viewer')
+ const handoff = handoffOf(read[1])
+ if (!handoff) return null
+ if (handoff.kind === 'viewer') return createSession(handoff.userId, label || 'phone', 'viewer')
+ const computer = computerId ? normalizeComputerId(computerId) : null
+ if (!computer) return null
+ // The computer that asked to become a team machine, and no other.
+ if (handoff.convert) return handoff.convert === computer ? convertComputer(handoff.userId, label || 'Team', computer) : null
+ if (await computerHeldByAnotherSignIn(handoff.userId, computer)) return null
+ return createSession(handoff.userId, label || 'Team', 'team', computer)
+}
+
+// Not yet revoked. A session is created without `revokedAt`, and on MongoDB `revokedAt: null` alone
+// does not match a field that is absent — so a revoke filtered on it alone never revoked anything.
+const notRevoked: Prisma.HarnessSessionWhereInput = { OR: [{ revokedAt: null }, { revokedAt: { isSet: false } }] }
+
+/**
+ * [computerId] becomes a team machine in place: in one transaction its Harness computer sessions end, its machine
+ * rows are marked `team`, and its team session is created. A socket still connected for it under the old sign-in is
+ * then told to close (lib/adapterWs.ts). An Autonomous sign-in on that computer is not this backend's to end; if it
+ * connects again, the machine is an ordinary one again (adapterWs.ts) and the team session acts for nothing.
+ */
+async function convertComputer(userId: string, label: string, computerId: string): Promise<HarnessTokens | null> {
+ const user = await userService.get(userId)
+ if (!user) return null
+ const refreshToken = newHarnessToken(HARNESS_TEAM_REFRESH_PREFIX)
+ const { session, machineIds } = await prisma.$transaction(async (tx) => {
+ await tx.harnessSession.updateMany({ where: { userId, kind: 'computer', computerId, ...notRevoked }, data: { revokedAt: new Date() } })
+ const machines = await tx.machine.findMany({ where: { userId, computerId, ...machineAlive }, select: { machineId: true } })
+ await tx.machine.updateMany({ where: { userId, computerId, ...machineAlive }, data: { sessionKind: 'team' } })
+ const created = await tx.harnessSession.create({ data: {
+ userId, refreshHash: harnessTokenHash(refreshToken), label, kind: 'team', computerId, expiresAt: sessionExpiry(),
+ } })
+ return { session: created, machineIds: machines.map((m) => m.machineId) }
+ })
+ for (const machineId of machineIds) {
+ await publishDown(machineId, { connId: '', frame: { type: TEAM_CONVERTED_FRAME } }).catch(() => { /* best effort: the next connect decides */ })
+ }
+ return {
+ token: await issueAccess(session.id, userId, 'team'),
+ refreshToken,
+ expiresIn: HARNESS_ACCESS_TTL_SEC,
+ kind: 'team',
+ autonomousEnv: storedAutonomousEnvironment(user.autonomousEnv),
+ }
}
-export type HarnessSessionKind = 'viewer' | 'computer'
+/**
+ * Whether the account already runs [computerId] as a machine under a sign-in that is not a team one. A
+ * team session bound to that computer could connect as that machine; so it is never minted for one.
+ * Rows from before `sessionKind` count as such a sign-in: they were all made by one.
+ */
+async function computerHeldByAnotherSignIn(userId: string, computerId: string): Promise<boolean> {
+ const rows = await prisma.machine.findMany({ where: { userId, computerId, ...machineAlive }, select: { sessionKind: true } })
+ return rows.some((row) => row.sessionKind !== 'team')
+}
/** A new session for [userId]: a refresh token (stored hashed) and its first access token. */
-async function createSession(userId: string, label: string, kind: HarnessSessionKind): Promise<HarnessTokens | null> {
+async function createSession(userId: string, label: string, kind: HarnessSessionKind, computerId?: string): Promise<HarnessTokens | null> {
const user = await userService.get(userId)
if (!user) return null
- const refreshToken = newHarnessToken(HARNESS_REFRESH_PREFIX)
+ const refreshToken = newHarnessToken(kind === 'team' ? HARNESS_TEAM_REFRESH_PREFIX : HARNESS_REFRESH_PREFIX)
const session = await prisma.harnessSession.create({
data: {
userId,
refreshHash: harnessTokenHash(refreshToken),
label,
kind,
+ // A team session's bound computer; a computer's own, as its QR sign-in declared it (what lets it convert itself).
+ ...(kind !== 'viewer' && computerId ? { computerId } : {}),
expiresAt: sessionExpiry(),
},
})
return {
- token: await issueAccess(session.id, userId),
+ token: await issueAccess(session.id, userId, kind),
refreshToken,
expiresIn: HARNESS_ACCESS_TTL_SEC,
+ kind,
autonomousEnv: storedAutonomousEnvironment(user.autonomousEnv),
}
}
@@ -123,6 +225,8 @@ export async function refreshHarnessSession(refreshToken: string): Promise<Harne
where: { refreshHash: harnessTokenHash(refreshToken) },
})
if (!session || session.revokedAt || session.expiresAt <= new Date()) return null
+ // A team session's tokens carry its own prefixes, and only its (harnessTokenFormat.ts).
+ if ((session.kind === 'team') !== isTeamRefreshToken(refreshToken)) return null
const user = await userService.get(session.userId)
if (!user) return null
await prisma.harnessSession.update({
@@ -130,16 +234,12 @@ export async function refreshHarnessSession(refreshToken: string): Promise<Harne
data: { lastUsedAt: new Date(), expiresAt: sessionExpiry() },
})
return {
- token: await issueAccess(session.id, session.userId),
+ token: await issueAccess(session.id, session.userId, session.kind === 'team' ? 'team' : 'viewer'),
expiresIn: HARNESS_ACCESS_TTL_SEC,
autonomousEnv: storedAutonomousEnvironment(user.autonomousEnv),
}
}
-// Not yet revoked. A session is created without `revokedAt`, and on MongoDB `revokedAt: null` alone
-// does not match a field that is absent — so a revoke filtered on it alone never revoked anything.
-const notRevoked: Prisma.HarnessSessionWhereInput = { OR: [{ revokedAt: null }, { revokedAt: { isSet: false } }] }
-
/** Sign out: the session's refresh token stops working, and so, at once, does its access token. */
export async function revokeHarnessSession(refreshToken: string): Promise<void> {
if (!isHarnessRefreshToken(refreshToken)) return
@@ -149,8 +249,8 @@ export async function revokeHarnessSession(refreshToken: string): Promise<void>
})
}
-async function issueAccess(sessionId: string, userId: string): Promise<string> {
- const token = newHarnessToken(HARNESS_ACCESS_PREFIX)
+async function issueAccess(sessionId: string, userId: string, kind: HarnessSessionKind): Promise<string> {
+ const token = newHarnessToken(kind === 'team' ? HARNESS_TEAM_ACCESS_PREFIX : HARNESS_ACCESS_PREFIX)
await pub.set(
accessKey(harnessTokenHash(token)),
JSON.stringify({ sessionId, userId }),
@@ -173,6 +273,7 @@ export async function authenticateHarnessAccessToken(token: string): Promise<Aut
let user: Awaited<ReturnType<typeof userService.get>>
let sessionId: string
let kind: string | null | undefined
+ let computerId: string | null | undefined
try {
const raw = await pub.get(accessKey(harnessTokenHash(token)))
if (!raw) throw invalid()
@@ -182,20 +283,29 @@ export async function authenticateHarnessAccessToken(token: string): Promise<Aut
const session = await prisma.harnessSession.findUnique({ where: { id: sessionId } })
if (!session || session.revokedAt || session.userId !== held.userId) throw invalid()
kind = session.kind
+ computerId = session.computerId
user = await userService.get(held.userId)
} catch (err) {
if (err instanceof SsoAuthError) throw err
throw new SsoAuthError('Authentication service unavailable', 'AUTH_SERVICE_UNAVAILABLE')
}
if (!user) throw invalid()
- return {
+ const identity = {
sub: user.id,
email: user.email,
role: user.role,
autonomousEnv: storedAutonomousEnvironment(user.autonomousEnv),
harnessSessionId: sessionId,
- harnessSessionKind: kind === 'computer' ? 'computer' : 'viewer',
}
+ // A team session's token is never a computer's or a phone's, and the other way round (harnessTokenFormat.ts).
+ if ((kind === 'team') !== isTeamAccessToken(token)) throw invalid()
+ // A team session is nothing without the computer it is bound to: a row that lost it is no session.
+ if (kind === 'team') {
+ if (typeof computerId !== 'string' || !computerId) throw invalid()
+ return { ...identity, harnessSessionKind: 'team', harnessComputerId: computerId }
+ }
+ if (kind === 'computer') return { ...identity, harnessSessionKind: 'computer', ...(computerId ? { harnessComputerId: computerId } : {}) }
+ return { ...identity, harnessSessionKind: 'viewer' }
}
/** Revoke the session with this id (a device removed from the account's device key log). */
@@ -229,7 +339,7 @@ export interface QrSignInOrigin { ip?: string; country?: string }
interface QrRecord {
pollHash: string
label: string
- kind: HarnessSessionKind
+ kind: QrSignInKind
computerId?: string
ip?: string
country?: string
@@ -324,7 +434,7 @@ function ipHint(ip: string | undefined): string | undefined {
}
export async function startQrSignIn(
- req: { label: string; kind: HarnessSessionKind; computerId?: string; spokenCode?: boolean },
+ req: { label: string; kind: QrSignInKind; computerId?: string; spokenCode?: boolean },
origin: QrSignInOrigin,
): Promise<{ code: string; pollToken: string; expiresIn: number; spokenCode?: string }> {
const code = newHarnessToken(HARNESS_QR_PREFIX)
@@ -391,7 +501,7 @@ export async function issueBoxTicket(userId: string, email: string): Promise<{ t
export interface QrSignInLookup {
label: string
- kind: HarnessSessionKind
+ kind: QrSignInKind
country?: string
ipHint?: string
sameNetwork: boolean
@@ -494,7 +604,7 @@ export async function extendQrSignIn(pollToken: string): Promise<number | null>
* session. Created only now, of the kind the QR asked for, and handed over once: the record is read
* and removed in one step.
*/
-export async function claimQrSignIn(pollToken: string): Promise<(HarnessTokens & { email: string; kind: HarnessSessionKind }) | null> {
+export async function claimQrSignIn(pollToken: string): Promise<(HarnessTokens & { email: string; kind: QrSignInKind }) | null> {
const codeHash = await codeHashForPoll(pollToken)
if (!codeHash) return null
const [read] = (await pub.multi().get(qrKey(codeHash)).del(qrKey(codeHash)).exec()) ?? []
@@ -505,6 +615,7 @@ export async function claimQrSignIn(pollToken: string): Promise<(HarnessTokens &
await pub.del(qrPollKey(r.pollHash))
if (r.spokenCode) await pub.del(qrSpokenKey(r.spokenCode))
if (r.pollHash !== harnessTokenHash(pollToken) || r.status !== 'approved' || !r.userId || !r.email) return null
- const tokens = await createSession(r.userId, r.label, r.kind)
+ const computer = r.kind === 'computer' && r.computerId ? normalizeComputerId(r.computerId) : null
+ const tokens = await createSession(r.userId, r.label, r.kind, computer ?? undefined)
return tokens ? { ...tokens, email: r.email, kind: r.kind } : null
}
diff --git a/backend/src/lib/harnessTokenFormat.ts b/backend/src/lib/harnessTokenFormat.ts
index fefe892e9..892a06d76 100644
--- a/backend/src/lib/harnessTokenFormat.ts
+++ b/backend/src/lib/harnessTokenFormat.ts
@@ -10,6 +10,13 @@ import { createHash, randomBytes } from 'node:crypto'
*/
export const HARNESS_ACCESS_PREFIX = 'hna_'
export const HARNESS_REFRESH_PREFIX = 'hnr_'
+/**
+ * A team session's own (lib/teamSession.ts), deliberately not `hna_`/`hnr_`: a server from before team sessions took
+ * every Harness session it did not know as a phone's, which may reach every machine and route of the account. Under
+ * these prefixes such a server never reads a team token as a Harness one at all, and refuses it.
+ */
+export const HARNESS_TEAM_ACCESS_PREFIX = 'hta_'
+export const HARNESS_TEAM_REFRESH_PREFIX = 'htr_'
export const HARNESS_HANDOFF_PREFIX = 'hnh_'
/** In a computer's sign-in QR: what the phone that scans it approves. */
export const HARNESS_QR_PREFIX = 'hnq_'
@@ -21,8 +28,11 @@ const BODY = /^[A-Za-z0-9_-]{43}$/
const shaped = (token: unknown, prefix: string): token is string =>
typeof token === 'string' && token.startsWith(prefix) && BODY.test(token.slice(prefix.length))
-export const isHarnessAccessToken = (token: unknown): token is string => shaped(token, HARNESS_ACCESS_PREFIX)
-export const isHarnessRefreshToken = (token: unknown): token is string => shaped(token, HARNESS_REFRESH_PREFIX)
+export const isTeamAccessToken = (token: unknown): token is string => shaped(token, HARNESS_TEAM_ACCESS_PREFIX)
+export const isTeamRefreshToken = (token: unknown): token is string => shaped(token, HARNESS_TEAM_REFRESH_PREFIX)
+/** Any access token Harness issued itself, a team session's included. */
+export const isHarnessAccessToken = (token: unknown): token is string => shaped(token, HARNESS_ACCESS_PREFIX) || isTeamAccessToken(token)
+export const isHarnessRefreshToken = (token: unknown): token is string => shaped(token, HARNESS_REFRESH_PREFIX) || isTeamRefreshToken(token)
export const isHarnessHandoffCode = (token: unknown): token is string => shaped(token, HARNESS_HANDOFF_PREFIX)
export const isHarnessQrCode = (token: unknown): token is string => shaped(token, HARNESS_QR_PREFIX)
export const isHarnessQrPollToken = (token: unknown): token is string => shaped(token, HARNESS_QR_POLL_PREFIX)
diff --git a/backend/src/lib/observerWs.test.ts b/backend/src/lib/observerWs.test.ts
index 1cef485f5..6fad522a0 100644
--- a/backend/src/lib/observerWs.test.ts
+++ b/backend/src/lib/observerWs.test.ts
@@ -56,6 +56,16 @@ describe('isolated observer WebSocket boundary', () => {
handleObserverUpgrade({ url: '/api/observer-ws?link', headers: {} } as never, socket as never, Buffer.alloc(0)); await flush()
expect(socket.destroy).toHaveBeenCalled()
})
+ it('refuses a team sign-in (lib/teamSession.ts) before reading any grant, by link or by invitation', async () => {
+ m.auth.mockRejectedValue(Object.assign(new Error('This connection is not available to a team sign-in'), { code: 'TEAM_SESSION_LIMITED' }))
+ for (const mode of ['link', 'share']) {
+ const socket = { destroyed: false, destroy: vi.fn() }
+ handleObserverUpgrade({ url: `/api/observer-ws?${mode}=${share.id}`, headers: { 'sec-websocket-protocol': 'team-token' } } as never, socket as never, Buffer.alloc(0))
+ await flush()
+ expect(socket.destroy).toHaveBeenCalled()
+ }
+ expect(m.link).not.toHaveBeenCalled(); expect(m.grant).not.toHaveBeenCalled(); expect(m.upgrade).not.toHaveBeenCalled()
+ })
it('does not admit a connection that closed while resolving the commenter name', async () => {
let release!: (profile: unknown) => void
m.profile.mockImplementationOnce(() => new Promise(resolve => { release = resolve }))
diff --git a/backend/src/lib/ssoAuth.ts b/backend/src/lib/ssoAuth.ts
index eac21d15a..9832e21b7 100644
--- a/backend/src/lib/ssoAuth.ts
+++ b/backend/src/lib/ssoAuth.ts
@@ -22,8 +22,12 @@ export interface AuthUser {
autonomousEnv: AutonomousEnvironment
/** Set when the token is one Harness issued itself (lib/harnessSession.ts), not an Autonomous one. */
harnessSessionId?: string
- /** With [harnessSessionId]: a computer signed in by QR may connect as a machine; a viewer may not. */
- harnessSessionKind?: 'viewer' | 'computer'
+ /** With [harnessSessionId]: a computer signed in by QR may connect as a machine; a viewer may not. A team
+ * session (lib/teamSession.ts) may connect only as its own computer's machine, and do strictly less. */
+ harnessSessionKind?: 'viewer' | 'computer' | 'team'
+ /** With a team session: the computer it is bound to (normalized). With a computer session signed in by QR: the
+ * computer it signed in as, which lets it turn itself into a team machine (routes/auth.ts). */
+ harnessComputerId?: string
}
export interface SsoProfile {
@@ -34,7 +38,8 @@ export interface SsoProfile {
export class SsoAuthError extends Error {
constructor(
message: string,
- readonly code: 'INVALID_TOKEN' | 'AUTH_SERVICE_UNAVAILABLE' | 'AUTONOMOUS_ENV_MISMATCH' | 'AUTONOMOUS_ENV_NOT_ALLOWED',
+ readonly code: 'INVALID_TOKEN' | 'AUTH_SERVICE_UNAVAILABLE' | 'AUTONOMOUS_ENV_MISMATCH' | 'AUTONOMOUS_ENV_NOT_ALLOWED'
+ | 'TEAM_SESSION_LIMITED',
readonly requiredEnv?: AutonomousEnvironment,
) {
super(message)
@@ -175,6 +180,11 @@ function accessTokenMetadata(token: string): { name?: string; roles?: string[] }
* the caller connects AS a machine: only a session a phone approved for a computer (its QR sign-in)
* may — a phone's own session is a viewer's, never a daemon's. FALSE refuses every Harness session.
*
+ * @param allowTeamSession Accept a team session (lib/teamSession.ts) too. Deny by default: only a caller
+ * that confines one to its own machine passes TRUE — the REST gate (middlewares/authMiddleware.ts, with
+ * its allowlist) and the machine socket (lib/adapterWs.ts, its bound computer). Everywhere else a team
+ * session is refused with `TEAM_SESSION_LIMITED`, whatever `allowHarnessSession` says.
+ *
* @param enforceEnv Gate the caller on the account plane their user row is stamped with. TRUE for the
* web, which can be pointed at either plane and must not let the two identities cross.
*
@@ -193,11 +203,13 @@ export async function authenticateAccessToken(
{
enforceEnv = true,
allowHarnessSession = true,
+ allowTeamSession = false,
signUpAttribution,
learnGoogleSubject = true,
}: {
enforceEnv?: boolean
allowHarnessSession?: boolean | 'computer'
+ allowTeamSession?: boolean
/** The sign-in's tags (lib/signInAttribution.ts), kept on the account only if this creates it. */
signUpAttribution?: SignInAttribution
/** FALSE where the caller reads the profile live itself (`GET /api/grid/profile`), so one request
@@ -212,6 +224,10 @@ export async function authenticateAccessToken(
if (!allowHarnessSession) throw new SsoAuthError('This connection needs an Autonomous sign-in', 'INVALID_TOKEN')
const { authenticateHarnessAccessToken } = await import('./harnessSession.js')
const user = await authenticateHarnessAccessToken(token)
+ if (user.harnessSessionKind === 'team') {
+ if (!allowTeamSession) throw new SsoAuthError('This connection is not available to a team sign-in', 'TEAM_SESSION_LIMITED')
+ return user
+ }
if (allowHarnessSession === 'computer' && user.harnessSessionKind !== 'computer') {
throw new SsoAuthError('This connection needs a computer sign-in', 'INVALID_TOKEN')
}
diff --git a/backend/src/lib/ssoEntryPoint.test.ts b/backend/src/lib/ssoEntryPoint.test.ts
index 319ca98b2..12015e8ca 100644
--- a/backend/src/lib/ssoEntryPoint.test.ts
+++ b/backend/src/lib/ssoEntryPoint.test.ts
@@ -1,4 +1,7 @@
-import { describe, expect, it } from 'vitest'
+import { describe, expect, it, vi } from 'vitest'
+// Only pure functions of sso.ts are tested here. Its Redis client, opened on import, would log a refused connection
+// after this short file has already finished, which the test runner reports as an error in whichever file is then running.
+vi.mock('./bus.js', () => ({ pub: {} }))
import { normalizeEntryPoint } from './sso.js'
/**
diff --git a/backend/src/lib/ssoProvider.test.ts b/backend/src/lib/ssoProvider.test.ts
index c05ddf906..f67f07007 100644
--- a/backend/src/lib/ssoProvider.test.ts
+++ b/backend/src/lib/ssoProvider.test.ts
@@ -1,4 +1,7 @@
-import { describe, expect, it } from 'vitest'
+import { describe, expect, it, vi } from 'vitest'
+// Only pure functions of sso.ts are tested here. Its Redis client, opened on import, would log a refused connection
+// after this short file has already finished, which the test runner reports as an error in whichever file is then running.
+vi.mock('./bus.js', () => ({ pub: {} }))
import { authorizeUrl, normalizeSignInProvider, normalizeSsoClientId } from './sso.js'
/**
diff --git a/backend/src/lib/teamSession.test.ts b/backend/src/lib/teamSession.test.ts
new file mode 100644
index 000000000..00b006cd0
--- /dev/null
+++ b/backend/src/lib/teamSession.test.ts
@@ -0,0 +1,354 @@
+import { readdirSync, readFileSync, statSync } from 'node:fs'
+import { join, relative } from 'node:path'
+import { randomUUID } from 'node:crypto'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import Fastify, { type FastifyInstance } from 'fastify'
+
+// The REST gate for a team session (docs/plans/2026-10-24-swarm-team-account.md, Task 1): the real middleware and the
+// real route modules a team daemon calls, with the stores faked. The Super Tab store itself is a recorder here; what it
+// checks for a team session is covered against a real database in integration/superTabTeam.test.ts.
+const m = vi.hoisted(() => {
+ const machines: Array<Record<string, unknown>> = []
+ const matches = (row: Record<string, unknown>, where: Record<string, unknown>) => !row.deletedAt &&
+ Object.entries(where).every(([k, v]) => k === 'OR' || (typeof v === 'object' && v !== null) || row[k] === v)
+ return {
+ machines,
+ prisma: {
+ machine: {
+ findMany: vi.fn(async ({ where }: { where: Record<string, unknown> }) => machines.filter(row => matches(row, where))),
+ findFirst: vi.fn(async ({ where }: { where: Record<string, unknown> }) => machines.find(row => matches(row, where)) ?? null),
+ },
+ harnessShare: { findUnique: vi.fn(), findMany: vi.fn(), upsert: vi.fn(), updateMany: vi.fn() },
+ user: { findMany: vi.fn(), findUnique: vi.fn() },
+ },
+ deviceKeys: { read: vi.fn(), seen: vi.fn(), append: vi.fn(), acks: vi.fn(), ack: vi.fn(), touch: vi.fn() },
+ machineService: { resolveOrCreateForComputer: vi.fn(), resolveForTeamComputer: vi.fn(), listForUser: vi.fn(), get: vi.fn(), destroy: vi.fn(), rename: vi.fn() },
+ bus: { changed: vi.fn(), listChanged: vi.fn(), presence: vi.fn() },
+ }
+})
+vi.mock('./prisma.js', () => ({ prisma: m.prisma, machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] } }))
+vi.mock('./bus.js', () => ({ publishShareChanged: m.bus.changed, publishDeviceMachineListChanged: m.bus.listChanged, getAgentPresenceMany: m.bus.presence }))
+vi.mock('./deviceKeyLog.js', () => ({ readDeviceKeyLog: m.deviceKeys.read, deviceKeysSeen: m.deviceKeys.seen, appendDeviceKey: m.deviceKeys.append,
+ readDeviceAcks: m.deviceKeys.acks, appendDeviceAck: m.deviceKeys.ack, touchDeviceKey: m.deviceKeys.touch }))
+vi.mock('./machineAccess.js', () => ({ machinesSharedWith: vi.fn(async () => []) }))
+vi.mock('../superTabs/store.js', () => ({ SuperTabStore: class { mayObserve = vi.fn(async () => true) } }))
+// The real hub starts its heartbeat timers on import; these tests never attach a hub client, so it is a stub with none.
+vi.mock('./hub.js', () => ({
+ CLIENTS_FRAME: '__clients', CLIENTS_DIRTY: '__clients_dirty', LIVENESS_TICK_MS: 5_000, CLIENT_IDLE_DEADLINE_MS: 75_000,
+ DEVICE_IDLE_DEADLINE_MS: 35_000, CLIENT_HEARTBEAT_MS: 25_000, deliverTerminalUpLocal: vi.fn(), deliverUpLocal: vi.fn(),
+ pushDeviceRevoked: vi.fn(), sendClientsControl: vi.fn(), recomputeAndSendClients: vi.fn(), attachHubClient: vi.fn(),
+ trackSocketLiveness: () => () => {},
+}))
+vi.mock('../services/index.js', () => ({ machineService: m.machineService, machineBillingService: {}, userService: { get: vi.fn() } }))
+
+import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'
+import { errorHandler } from '../middlewares/errorHandler.js'
+import { superTabRoutes } from '../routes/superTabs.js'
+import { harnessShareRoutes } from '../routes/harnessShares.js'
+import { deviceKeyRoutes } from '../routes/deviceKeys.js'
+import { machineRoutes } from '../routes/machines.js'
+import { SsoAuthError, type AuthUser } from './ssoAuth.js'
+import type { SuperTabStore } from '../superTabs/store.js'
+import { TEAM_ROUTES } from './teamSession.js'
+
+const OWNER_COMPUTER = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
+const TEAM_COMPUTER = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
+const owner: AuthUser = { sub: 'owner', email: '[email protected]', role: 'user', autonomousEnv: 'prod' }
+const team: AuthUser = { ...owner, harnessSessionId: 'team-session', harnessSessionKind: 'team', harnessComputerId: TEAM_COMPUTER }
+const ownerMac = { machineId: 'owner-mac', userId: 'owner', computerId: OWNER_COMPUTER, authMode: 'remote', autonomousEnv: 'prod',
+ billingStatus: 'not_required', sessionKind: 'computer', createdAt: new Date(0) }
+const teamMac = { machineId: 'team-mac', userId: 'owner', computerId: TEAM_COMPUTER, authMode: 'remote', autonomousEnv: 'prod',
+ billingStatus: 'not_required', sessionKind: 'team', createdAt: new Date(1) }
+
+/** Like the real check (lib/ssoAuth.ts): a team session only where the caller opts in. */
+const authenticate = vi.fn(async (token: string, _env?: unknown, opts?: { allowTeamSession?: boolean }) => {
+ if (token === 'owner-token') return owner
+ if (token === 'team-token') {
+ if (!opts?.allowTeamSession) throw new SsoAuthError('This connection is not available to a team sign-in', 'TEAM_SESSION_LIMITED')
+ return team
+ }
+ throw new SsoAuthError('Invalid', 'INVALID_TOKEN')
+})
+
+/** A Super Tab store that records what reached it, for every method the routes call. */
+function recorder() {
+ const calls: Array<{ method: string; args: unknown[] }> = []
+ const methods = (prefix = ''): Record<string, unknown> => new Proxy({}, { get: (_t, name: string) => name === 'then' ? undefined
+ : name === 'native' && !prefix ? methods('native.')
+ : async (...args: unknown[]) => {
+ calls.push({ method: `${prefix}${name}`, args })
+ // What the GitHub token route goes on to use from a grant (routes/superTabs.ts `github-token`).
+ return name === 'githubAssignment'
+ ? { tabId: 'tab-1', agentId: 'agent-1', assignmentId: 'assignment-1', repositoryUrl: 'https://github.com/example/project',
+ requester: { name: 'Owner', email: '[email protected]' }, agentName: 'Builder', machineName: 'MacBook Pro · Team' }
+ : { ok: true }
+ } })
+ return { store: methods() as unknown as SuperTabStore, calls }
+}
+
+let app: FastifyInstance
+let store: ReturnType<typeof recorder>
+beforeEach(async () => {
+ vi.clearAllMocks()
+ m.machines.length = 0
+ m.machines.push({ ...ownerMac }, { ...teamMac })
+ m.deviceKeys.read.mockResolvedValue({ acct: 'owner', head: { seq: 0, hash: 'h' }, entries: [] })
+ m.prisma.harnessShare.updateMany.mockResolvedValue({ count: 1 })
+ m.prisma.harnessShare.findUnique.mockResolvedValue(null)
+ m.prisma.user.findUnique.mockResolvedValue(null)
+ m.machineService.resolveForTeamComputer.mockResolvedValue({ machine: teamMac, created: false })
+ m.machineService.resolveOrCreateForComputer.mockResolvedValue({ machine: ownerMac, created: false })
+ store = recorder()
+ app = Fastify()
+ app.setErrorHandler(errorHandler)
+ registerAuthMiddleware(app, authenticate as never)
+ // A GitHub App that hands out a fixed token: the route's own checks are the store's (githubAssignment).
+ const github = { issue: vi.fn(async () => ({ token: 'fixture-token', expiresAt: new Date(0).toISOString() })), release: vi.fn(async () => {}) }
+ await app.register(superTabRoutes, { store: store.store, github: github as never })
+ await app.register(harnessShareRoutes)
+ await app.register(deviceKeyRoutes)
+ await app.register(machineRoutes)
+ await app.ready()
+})
+afterEach(async () => { await app.close() })
+
+const call = (method: string, url: string, payload?: unknown, token = 'team-token') =>
+ app.inject({ method: method as never, url, headers: { authorization: `Bearer ${token}` }, ...(payload === undefined ? {} : { payload: payload as never }) })
+const limited = (res: { statusCode: number; json: () => { error?: { code?: string } } }) => {
+ expect(res.statusCode).toBe(403)
+ expect(res.json().error?.code).toBe('TEAM_SESSION_LIMITED')
+}
+
+const command = { operationId: 'op-1', command: { type: 'message.send', conversationId: 'lead', text: 'Done.', replyTo: null, recipientIds: [] } }
+const observation = { generation: 'g1', resources: { cpuPercent: null, memoryTotalBytes: null, memoryUsedBytes: null, diskFreeBytes: null,
+ diskTotalBytes: null, projectDiskFreeBytes: null, deviceType: null, chip: null, os: null, gpuPercent: null },
+ tools: {}, quotas: [], runningHarnessIds: [], stoppedHarnessIds: [] }
+const startOp = { operationId: 'op-2', command: { type: 'agent.startSettled', startId: 'start-1', warning: null } }
+const share = () => ({ superTabId: 'a'.repeat(24), machineId: 'team-mac', agentId: 'harness-1', name: 'Builder', engine: 'codex',
+ recipientEmail: '[email protected]', ownerPublicKey: Buffer.alloc(32, 1).toString('base64'),
+ expiresAt: new Date(Date.now() + 86_400_000).toISOString() })
+
+describe('a team session on its own machine', () => {
+ // Every route the allowlist names, as a team daemon calls it, and the store method each one reaches.
+ const own: Array<[string, string, unknown, string]> = [
+ ['GET', '/api/super-tabs/hosts/team-mac', undefined, 'hostTabs'],
+ ['GET', '/api/super-tabs/hosts/team-mac/pools', undefined, 'hostPools'],
+ ['GET', '/api/super-tabs/hosts/team-mac/assignments', undefined, 'hostAssignments'],
+ ['POST', '/api/super-tabs/hosts/team-mac/terminal', undefined, 'hostTerminal'],
+ ['GET', '/api/super-tabs/hosts/team-mac/starts/tab-1/start-1', undefined, 'start'],
+ ['POST', '/api/super-tabs/hosts/team-mac/starts/tab-1/start-1', startOp, 'execute'],
+ ['POST', '/api/super-tabs/tab-1/machines/team-mac', observation, 'observeMachine'],
+ ['GET', '/api/super-tabs/tab-1?asAgentId=agent-1', undefined, 'read'],
+ ['GET', '/api/super-tabs/tab-1/starts/start-1?asAgentId=agent-1', undefined, 'start'],
+ ['GET', '/api/super-tabs/tab-1/routing-policy?asAgentId=agent-1', undefined, 'tabPolicy'],
+ ['GET', '/api/super-tabs/tab-1/route-decisions?asAgentId=agent-1', undefined, 'routeDecisions'],
+ ['GET', '/api/super-tabs/tab-1/route-decisions/decision-1?asAgentId=agent-1', undefined, 'routeDecision'],
+ ['GET', '/api/super-tabs/tab-1/conversations/lead/messages?asAgentId=agent-1', undefined, 'messages'],
+ ['GET', '/api/super-tabs/tab-1/conversations/lead/attempts?asAgentId=agent-1', undefined, 'attempts'],
+ ['GET', '/api/super-tabs/tab-1/terminal/request-1?asAgentId=agent-1', undefined, 'terminalResult'],
+ ['POST', '/api/super-tabs/tab-1/commands', { ...command, asAgentId: 'agent-1' }, 'execute'],
+ ['GET', '/api/super-tabs/tab-1/agents/agent-1/deliveries', undefined, 'deliveries'],
+ ['GET', '/api/super-tabs/tab-1/agents/agent-1/deliveries/delivery-1', undefined, 'deliveryReceipt'],
+ ['POST', '/api/super-tabs/tab-1/agents/agent-1/deliveries/delivery-1', { type: 'claim', claimId: 'claim-1' }, 'delivery'],
+ ['POST', '/api/super-tabs/tab-1/stopped', { assignmentId: 'assignment-1', receipt: 'stopped' }, 'stopped'],
+ ['GET', '/api/super-tabs/tab-1/native/context-1', undefined, 'native.read'],
+ ['POST', '/api/super-tabs/tab-1/native/context-1', { turnId: 't1', kind: 'prompt', previousEventId: null, text: 'hi', truncated: false, interrupted: false }, 'native.append'],
+ ['GET', '/api/super-tabs/tab-1/projects/project-1/roles/dev', undefined, 'roleText'],
+ ]
+ for (const [method, url, payload, reached] of own) {
+ it(`${method} ${url.split('?')[0]} reaches the store as the team session`, async () => {
+ const res = await call(method, url, payload)
+ expect(res.statusCode, res.body).toBe(200)
+ expect(store.calls.map(c => c.method)).toEqual([reached])
+ expect(store.calls[0]!.args[0]).toMatchObject({ harnessSessionKind: 'team', harnessComputerId: TEAM_COMPUTER })
+ })
+ }
+
+ it('asks for its own agent\'s GitHub token, naming its own machine', async () => {
+ const res = await call('POST', '/api/super-tabs/tab-1/github-token?asAgentId=agent-1', { machineId: 'team-mac' })
+ expect(res.statusCode, res.body).toBe(200)
+ expect(store.calls).toEqual([{ method: 'githubAssignment', args: [expect.objectContaining({ harnessSessionKind: 'team' }), 'tab-1', 'agent-1', 'team-mac'] }])
+ })
+
+ it('registers its own computer, as a team machine', async () => {
+ const res = await call('POST', '/api/machines/resolve-computer', { computerId: TEAM_COMPUTER.toUpperCase(), label: 'MacBook Pro · Team' })
+ expect(res.statusCode, res.body).toBe(200)
+ expect(res.json().data).toEqual({ machine: { machineId: 'team-mac', computerId: TEAM_COMPUTER }, created: false })
+ expect(m.machineService.resolveForTeamComputer).toHaveBeenCalledWith(expect.objectContaining({ harnessSessionKind: 'team' }),
+ TEAM_COMPUTER, 'MacBook Pro · Team', undefined)
+ expect(m.machineService.resolveOrCreateForComputer).not.toHaveBeenCalled()
+ })
+
+ it('shares one of its harnesses with a Swarm member for a read-only view, and takes it back', async () => {
+ const id = randomUUID()
+ expect((await call('PUT', `/api/harness-shares/${id}`, share())).statusCode).toBe(200)
+ expect(m.prisma.harnessShare.upsert).toHaveBeenCalledWith(expect.objectContaining({
+ create: expect.objectContaining({ machineId: 'team-mac', superTabId: 'a'.repeat(24), ownerId: 'owner' }) }))
+ expect((await call('DELETE', `/api/harness-shares/${id}`)).statusCode).toBe(200)
+ expect(m.prisma.harnessShare.updateMany).toHaveBeenCalledWith(expect.objectContaining({
+ where: expect.objectContaining({ id, ownerId: 'owner', machineId: 'team-mac' }) }))
+ })
+
+ it('reads the account\'s device keys, to know whom to let in', async () => {
+ const res = await call('GET', '/api/device-keys?since=0')
+ expect(res.statusCode).toBe(200)
+ expect(m.deviceKeys.read).toHaveBeenCalledWith('owner', 0)
+ })
+})
+
+describe('a team session reaching past its own machine', () => {
+ it('cannot use the host routes of another machine of the account', async () => {
+ for (const [method, url, payload] of [
+ ['GET', '/api/super-tabs/hosts/owner-mac', undefined],
+ ['GET', '/api/super-tabs/hosts/owner-mac/pools', undefined],
+ ['GET', '/api/super-tabs/hosts/owner-mac/assignments', undefined],
+ ['POST', '/api/super-tabs/hosts/owner-mac/terminal', undefined],
+ ['GET', '/api/super-tabs/hosts/owner-mac/starts/tab-1/start-1', undefined],
+ ['POST', '/api/super-tabs/hosts/owner-mac/starts/tab-1/start-1', startOp],
+ ['POST', '/api/super-tabs/tab-1/machines/owner-mac', observation],
+ ] as const) limited(await call(method, url, payload))
+ expect(store.calls).toEqual([])
+ })
+
+ it('cannot read or speak as the person: every agent route needs one of its agents', async () => {
+ for (const url of ['/api/super-tabs/tab-1', '/api/super-tabs/tab-1/starts/start-1', '/api/super-tabs/tab-1/routing-policy',
+ '/api/super-tabs/tab-1/route-decisions', '/api/super-tabs/tab-1/route-decisions/decision-1',
+ '/api/super-tabs/tab-1/conversations/lead/messages', '/api/super-tabs/tab-1/conversations/lead/attempts',
+ '/api/super-tabs/tab-1/terminal/request-1', '/api/super-tabs/tab-1?asAgentId=']) limited(await call('GET', url))
+ limited(await call('POST', '/api/super-tabs/tab-1/attachments'))
+ expect(store.calls).toEqual([])
+ })
+
+ it('never gets a GitHub token naming another machine, or as no agent at all', async () => {
+ for (const machineId of ['owner-mac', undefined, 7]) {
+ limited(await call('POST', '/api/super-tabs/tab-1/github-token?asAgentId=agent-1', machineId === undefined ? {} : { machineId }))
+ }
+ limited(await call('POST', '/api/super-tabs/tab-1/github-token', { machineId: 'team-mac' }))
+ expect(store.calls).toEqual([])
+ // As an agent on another machine: the store resolves `asAgentId` through `actor()`, which refuses a team session
+ // speaking for an agent anywhere but its own machine (integration/superTabTeam.test.ts).
+ })
+
+ it('cannot register, list, rename or delete other machines, or share one', async () => {
+ const res = await call('POST', '/api/machines/resolve-computer', { computerId: OWNER_COMPUTER, label: 'MacBook Pro' })
+ limited(res)
+ expect(m.machineService.resolveForTeamComputer).not.toHaveBeenCalled()
+ expect(m.machineService.resolveOrCreateForComputer).not.toHaveBeenCalled()
+ for (const [method, url] of [['GET', '/api/machines'], ['GET', '/api/machines/team-mac'], ['GET', '/api/machines/owner-mac'],
+ ['PATCH', '/api/machines/team-mac'], ['DELETE', '/api/machines/owner-mac'], ['POST', '/api/machines/owner-mac/start'],
+ ['POST', '/api/machines'], ['GET', '/api/machines/resolve?deviceId=1']] as const) limited(await call(method, url, method === 'PATCH' ? { name: 'x' } : undefined))
+ expect(m.machineService.listForUser).not.toHaveBeenCalled()
+ })
+
+ it('cannot share another machine\'s harness, a harness outside a Swarm, or take back another machine\'s share', async () => {
+ limited(await call('PUT', `/api/harness-shares/${randomUUID()}`, { ...share(), machineId: 'owner-mac' }))
+ limited(await call('PUT', `/api/harness-shares/${randomUUID()}`, { ...share(), superTabId: null }))
+ const { superTabId: _dropped, ...noSwarm } = share()
+ limited(await call('PUT', `/api/harness-shares/${randomUUID()}`, noSwarm))
+ expect(m.prisma.harnessShare.upsert).not.toHaveBeenCalled()
+ // A share of the owner's own Mac is not this machine's to revoke: the update matches nothing.
+ m.prisma.harnessShare.updateMany.mockResolvedValueOnce({ count: 0 })
+ expect((await call('DELETE', `/api/harness-shares/${randomUUID()}`)).statusCode).toBe(404)
+ // And never lists harnesses shared with the person.
+ limited(await call('GET', '/api/harness-shares'))
+ })
+
+ it('cannot add a key to the account, vouch for one, or read when keys were used', async () => {
+ limited(await call('POST', '/api/device-keys', { entry: {} }))
+ limited(await call('POST', '/api/device-keys/acks', { ack: {} }))
+ limited(await call('GET', '/api/device-keys/acks?since=0'))
+ limited(await call('GET', '/api/device-keys/seen'))
+ expect(m.deviceKeys.append).not.toHaveBeenCalled()
+ expect(m.deviceKeys.ack).not.toHaveBeenCalled()
+ })
+
+ it('cannot use the person\'s Swarm routes: list, create, invite, join, sharing, rules, terminals or machine removal', async () => {
+ for (const [method, url, payload] of [
+ ['GET', '/api/super-tabs', undefined],
+ ['POST', '/api/super-tabs', { operationId: 'op', name: 'Mine' }],
+ ['GET', '/api/super-tabs/invitations', undefined],
+ ['GET', '/api/super-tabs/tab-1/sharing', undefined],
+ ['POST', '/api/super-tabs/tab-1/sharing', { operationId: 'op', revision: 0, access: null }],
+ ['POST', '/api/super-tabs/tab-1/join/preview', { token: 'x' }],
+ ['POST', '/api/super-tabs/tab-1/join', { operationId: 'op' }],
+ ['GET', '/api/super-tabs/routing-policy', undefined],
+ ['POST', '/api/super-tabs/routing-policy', { revision: 0, policy: {} }],
+ ['POST', '/api/super-tabs/tab-1/native', { operationId: 'op', conversationId: 'lead', agentId: 'agent-1' }],
+ ['GET', '/api/super-tabs/tab-1/machines/team-mac/removal', undefined],
+ ['GET', '/api/super-tabs/tab-1/machines/owner-mac/removal', undefined],
+ ] as const) limited(await call(method, url, payload))
+ expect(store.calls).toEqual([])
+ })
+
+ it('cannot reach a route that does not exist either: a refusal, not a not-found', async () => {
+ limited(await call('GET', '/api/nothing-here'))
+ })
+
+ it('without its machine registered yet, it can reach no host or agent route', async () => {
+ m.machines.splice(m.machines.findIndex(row => row.machineId === 'team-mac'), 1)
+ limited(await call('GET', '/api/super-tabs/hosts/team-mac'))
+ limited(await call('GET', '/api/super-tabs/tab-1?asAgentId=agent-1'))
+ limited(await call('POST', '/api/super-tabs/tab-1/commands', { ...command, asAgentId: 'agent-1' }))
+ expect(store.calls).toEqual([])
+ })
+
+ it('a row for its computer that a normal sign-in holds is not its machine', async () => {
+ m.machines.find(row => row.machineId === 'team-mac')!.sessionKind = 'computer'
+ limited(await call('GET', '/api/super-tabs/hosts/team-mac'))
+ m.machines.find(row => row.machineId === 'team-mac')!.sessionKind = undefined
+ limited(await call('GET', '/api/super-tabs/hosts/team-mac'))
+ expect(store.calls).toEqual([])
+ })
+})
+
+describe('behind the gate, each surface refuses on its own too', () => {
+ it('Grid never takes a team session as the person', async () => {
+ const { answerGridProfile } = await import('./gridProfile.js')
+ expect(await answerGridProfile(team, 'unused')).toEqual({ status: 403, code: 'TEAM_SESSION_LIMITED', message: expect.any(String) })
+ })
+})
+
+describe('the owner, unchanged', () => {
+ it('reaches the same routes, as the person', async () => {
+ expect((await call('GET', '/api/super-tabs/tab-1', undefined, 'owner-token')).statusCode).toBe(200)
+ expect((await call('GET', '/api/super-tabs/hosts/owner-mac', undefined, 'owner-token')).statusCode).toBe(200)
+ expect((await call('GET', '/api/super-tabs/hosts/team-mac', undefined, 'owner-token')).statusCode).toBe(200)
+ // A computer's GitHub token request is the store's to judge, whatever machine its body names.
+ expect((await call('POST', '/api/super-tabs/tab-1/github-token?asAgentId=agent-1', { machineId: 'owner-mac' }, 'owner-token')).statusCode).toBe(200)
+ expect(store.calls.map(c => c.args[0])).toEqual([owner, owner, owner, owner])
+ })
+})
+
+describe('the allowlist', () => {
+ it('names only routes that exist, each once', async () => {
+ const seen = new Set<string>()
+ const probe = Fastify()
+ probe.addHook('onRoute', route => {
+ for (const method of [route.method].flat()) seen.add(`${method} ${route.url}`)
+ })
+ const { registerControlRoutes } = await import('../routes/control.js')
+ await registerControlRoutes(probe, { daemons: { on: true, users: null } as never, count: async () => 0 })
+ await probe.ready()
+ const named = TEAM_ROUTES.map(r => `${r.method} ${r.url}`)
+ expect(new Set(named).size).toBe(named.length)
+ for (const route of named) expect(seen, route).toContain(route)
+ await probe.close()
+ })
+
+ it('only the REST gate and the machine socket opt in to team sessions', () => {
+ // Deny by default lives in lib/ssoAuth.ts: a team session is refused unless the caller passes `allowTeamSession`.
+ // Any new caller that does must confine the session to its machine as these two do, and be listed here.
+ const root = join(__dirname, '..')
+ const files: string[] = []
+ const walk = (dir: string) => {
+ for (const name of readdirSync(dir)) {
+ const path = join(dir, name)
+ if (statSync(path).isDirectory()) walk(path)
+ else if (name.endsWith('.ts') && !name.endsWith('.test.ts')) files.push(path)
+ }
+ }
+ walk(root)
+ const optIn = files.filter(f => /allowTeamSession\s*:\s*true/.test(readFileSync(f, 'utf8'))).map(f => relative(root, f)).sort()
+ expect(optIn).toEqual(['lib/adapterWs.ts', 'middlewares/authMiddleware.ts'])
+ })
+})
diff --git a/backend/src/lib/teamSession.ts b/backend/src/lib/teamSession.ts
new file mode 100644
index 000000000..bd8503325
--- /dev/null
+++ b/backend/src/lib/teamSession.ts
@@ -0,0 +1,171 @@
+import type { FastifyRequest } from 'fastify'
+import type { Machine, Prisma } from '@prisma/client'
+import { machineAlive, prisma } from './prisma.js'
+import { machineBillingAllowsDataPlane } from './billingState.js'
+import { AppError } from '../errors/index.js'
+import type { AuthUser } from './ssoAuth.js'
+
+/**
+ * Team sessions (docs/plans/2026-10-24-swarm-team-account.md, Task 1).
+ *
+ * Teammates' Swarm agents run on a person's Mac inside a separate standard macOS user, whose own Harness daemon signs
+ * in to the person's account. With a computer's sign-in that daemon could reach the person's other machines through
+ * the relay (`harness ps --machine …`, `harness show`, `harness new` there), read the account over REST and act in a
+ * Swarm as the person. So it signs in with a TEAM session instead (lib/harnessSession.ts): minted only by one of the
+ * account's computers, bound to the computer that redeemed it, and able to do strictly less than a computer.
+ *
+ * Every limit is the server's; none relies on the CLI behaving:
+ * - Authentication (lib/ssoAuth.ts) refuses a team session unless the caller passes `allowTeamSession`, and only two
+ * callers do: the REST gate below and the machine socket. So the web relay (`machine_select` and attach,
+ * lib/webWs.ts), the device lane (lib/deviceWs.ts), Agent Messages (lib/agentMessagesWs.ts), the observer socket
+ * (lib/observerWs.ts) and the phone's routes refuse it, and so will any socket added later.
+ * - REST (`teamRequestAllowed`, run by middlewares/authMiddleware.ts for every team request): deny by default.
+ * TEAM_ROUTES is the whole list; a route whose path names a machine must name this session's own.
+ * - The machine socket (lib/adapterWs.ts): only as its own computer's machine, and only while that row is marked
+ * `team` (`Machine.sessionKind`). It hears only device-key pushes, never the account's grid name, raises no pairing
+ * notice on the person's apps, and may take only its own key off the device key log (lib/deviceKeyLog.ts).
+ * - The Super Tab store (superTabs/store.ts, native.ts): never the person; as an agent only one running on its own
+ * machine; host routes only for its own machine; no machine contribution, pause or removal; and no command that
+ * starts, adds, moves or drives an agent on another machine.
+ *
+ * The other direction stays open: the person's own apps select the team machine like any of theirs, and Swarm members'
+ * read-only views of its agents reach it through the shares its daemon publishes (routes/harnessShares.ts).
+ */
+
+export const TEAM_SESSION_LIMITED = 'TEAM_SESSION_LIMITED'
+export const TEAM_SESSION_MESSAGE = 'A team sign-in can only run Swarm agents on its own machine.'
+
+/**
+ * A computer turning ITSELF into a team machine (`harness team on`, a machine used only for agents) keeps its computer
+ * id, so its Swarm contributions and history survive. Only that computer may ask (routes/auth.ts): its own Harness
+ * computer session, or any sign-in of the account carrying this message signed by the computer's machine key on the
+ * account's device key log (lib/deviceKeyLog.ts) — what an Autonomous sign-in, which names no computer, can show.
+ * The signature is ed25519 over these UTF-8 bytes, base64; `at` is milliseconds since the epoch.
+ */
+export function teamConversionMessage(userId: string, computerId: string, machineId: string, at: number): string {
+ return `harness team conversion v1\n${userId}\n${computerId}\n${machineId}\n${at}`
+}
+/** How far a conversion proof's `at` may be from the server's clock, either way. A proof is good once. */
+export const TEAM_CONVERSION_PROOF_MS = 5 * 60_000
+/** Sent down to a machine its computer just converted: a socket still connected under the old sign-in closes. */
+export const TEAM_CONVERTED_FRAME = '__team_converted'
+
+export function isTeamSession(user: Pick<AuthUser, 'harnessSessionKind'> | null | undefined): boolean {
+ return user?.harnessSessionKind === 'team'
+}
+
+type MachineReader = Pick<Prisma.TransactionClient, 'machine'>
+
+/**
+ * The machine a team session acts for: the account's live remote machine for the session's computer. Null for any
+ * other session, and while there is none to act for — not registered yet, removed from the account, unpaid, or any
+ * live row for that computer held by a normal sign-in (which would make it the person's machine, not a team one).
+ */
+export async function teamMachine(user: AuthUser, db: MachineReader = prisma): Promise<Machine | null> {
+ if (!isTeamSession(user) || !user.harnessComputerId) return null
+ const rows = await db.machine.findMany({
+ where: { userId: user.sub, computerId: user.harnessComputerId, authMode: 'remote', autonomousEnv: user.autonomousEnv, ...machineAlive },
+ orderBy: { createdAt: 'asc' },
+ })
+ if (rows.some(row => row.sessionKind !== 'team')) return null
+ return rows.find(row => machineBillingAllowsDataPlane(row)) ?? null
+}
+
+/** For a handler that serves a team session too: null for any other session, else the id of the machine it acts for.
+ * A team session with no machine to act for is refused. */
+export async function teamMachineScope(user: AuthUser, db: MachineReader = prisma): Promise<string | null> {
+ if (!isTeamSession(user)) return null
+ const machine = await teamMachine(user, db)
+ if (!machine) throw new AppError(TEAM_SESSION_MESSAGE, 403, TEAM_SESSION_LIMITED)
+ return machine.machineId
+}
+
+/**
+ * How a route on the list is held to the session's machine:
+ * - `open`: needs no machine yet (reading the device keys, registering its own computer — whose handler checks it);
+ * - `machine`: the path's `:machineId` must be its machine;
+ * - `agent`: speaks as one of its agents, so `asAgentId` is required; the store checks that agent runs on its machine;
+ * - `bound`: its machine must exist; the handler or store checks what the body or path names against it.
+ */
+export type TeamRouteScope = 'open' | 'machine' | 'agent' | 'bound'
+export interface TeamRoute {
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE'
+ url: string
+ scope: TeamRouteScope
+ /** The body names a machine (`machineId`): it must name this session's own, checked once the body is read. */
+ bodyMachine?: true
+}
+
+/** Everything a team daemon may call over REST: what it needs to run its own machine and host Swarm agents there. Sign-in
+ * renewal and sign-out (`/api/auth/refresh`, `/api/auth/revoke`) take the refresh token, not a session, and are open
+ * to every session already. Anything else answers 403 `TEAM_SESSION_LIMITED`. Pinned to the route table by a test. */
+export const TEAM_ROUTES: readonly TeamRoute[] = [
+ // Its own machine: registered before its socket dials, and the account's device keys, which say whom to let in.
+ { method: 'POST', url: '/api/machines/resolve-computer', scope: 'open' },
+ { method: 'GET', url: '/api/device-keys', scope: 'open' },
+ // The Swarm host loop for its machine.
+ { method: 'GET', url: '/api/super-tabs/hosts/:machineId', scope: 'machine' },
+ { method: 'GET', url: '/api/super-tabs/hosts/:machineId/pools', scope: 'machine' },
+ { method: 'GET', url: '/api/super-tabs/hosts/:machineId/assignments', scope: 'machine' },
+ { method: 'POST', url: '/api/super-tabs/hosts/:machineId/terminal', scope: 'machine' },
+ { method: 'GET', url: '/api/super-tabs/hosts/:machineId/starts/:tabId/:startId', scope: 'machine' },
+ { method: 'POST', url: '/api/super-tabs/hosts/:machineId/starts/:tabId/:startId', scope: 'machine' },
+ { method: 'POST', url: '/api/super-tabs/:tabId/machines/:machineId', scope: 'machine' },
+ // Reads as one of its agents.
+ { method: 'GET', url: '/api/super-tabs/:tabId', scope: 'agent' },
+ { method: 'GET', url: '/api/super-tabs/:tabId/starts/:startId', scope: 'agent' },
+ { method: 'GET', url: '/api/super-tabs/:tabId/routing-policy', scope: 'agent' },
+ { method: 'GET', url: '/api/super-tabs/:tabId/route-decisions', scope: 'agent' },
+ { method: 'GET', url: '/api/super-tabs/:tabId/route-decisions/:decisionId', scope: 'agent' },
+ { method: 'GET', url: '/api/super-tabs/:tabId/conversations/:conversationId/messages', scope: 'agent' },
+ { method: 'GET', url: '/api/super-tabs/:tabId/conversations/:conversationId/attempts', scope: 'agent' },
+ { method: 'GET', url: '/api/super-tabs/:tabId/terminal/:requestId', scope: 'agent' },
+ { method: 'POST', url: '/api/super-tabs/:tabId/attachments', scope: 'agent' },
+ // Its agent's one-hour GitHub token for the repository of its task (Task 4); the body's machine must be its own.
+ { method: 'POST', url: '/api/super-tabs/:tabId/github-token', scope: 'agent', bodyMachine: true },
+ // Commands as one of its agents, its agents' deliveries, stops and native terminals, its agents' role texts.
+ { method: 'POST', url: '/api/super-tabs/:tabId/commands', scope: 'bound' },
+ { method: 'GET', url: '/api/super-tabs/:tabId/agents/:agentId/deliveries', scope: 'bound' },
+ { method: 'GET', url: '/api/super-tabs/:tabId/agents/:agentId/deliveries/:deliveryId', scope: 'bound' },
+ { method: 'POST', url: '/api/super-tabs/:tabId/agents/:agentId/deliveries/:deliveryId', scope: 'bound' },
+ { method: 'POST', url: '/api/super-tabs/:tabId/stopped', scope: 'bound' },
+ { method: 'GET', url: '/api/super-tabs/:tabId/native/:contextId', scope: 'bound' },
+ { method: 'POST', url: '/api/super-tabs/:tabId/native/:contextId', scope: 'bound' },
+ { method: 'GET', url: '/api/super-tabs/:tabId/projects/:projectId/roles/:roleId', scope: 'bound' },
+ // Swarm members' read-only views of its agents: shares of its own harnesses, for a Swarm only.
+ { method: 'PUT', url: '/api/harness-shares/:id', scope: 'bound' },
+ { method: 'DELETE', url: '/api/harness-shares/:id', scope: 'bound' },
+]
+
+/** The matched route's entry on TEAM_ROUTES: by the route, not the raw URL, so an encoded spelling is the same route. */
+function teamRoute(request: FastifyRequest): TeamRoute | undefined {
+ const url = request.routeOptions?.url
+ return url ? TEAM_ROUTES.find(r => r.method === request.method && r.url === url) : undefined
+}
+
+/** The machine each admitted team request acts for, kept for the check that runs once its body is read. */
+const admitted = new WeakMap<FastifyRequest, string>()
+
+/** Whether a team session may make this request: its matched route is on TEAM_ROUTES and holds to its machine. */
+export async function teamRequestAllowed(request: FastifyRequest, user: AuthUser): Promise<boolean> {
+ const rule = teamRoute(request)
+ if (!rule) return false
+ if (rule.scope === 'open') return true
+ const machine = await teamMachine(user)
+ if (!machine) return false
+ admitted.set(request, machine.machineId)
+ if (rule.scope === 'machine') return (request.params as { machineId?: unknown } | undefined)?.machineId === machine.machineId
+ if (rule.scope === 'agent') {
+ const asAgentId = (request.query as { asAgentId?: unknown } | undefined)?.asAgentId
+ return typeof asAgentId === 'string' && asAgentId.length > 0
+ }
+ return true
+}
+
+/** Once the body is read (a preHandler, middlewares/authMiddleware.ts): a route whose body names a machine must name
+ * the one this team session acts for, whatever the route itself then checks. */
+export function teamBodyAllowed(request: FastifyRequest): boolean {
+ if (!teamRoute(request)?.bodyMachine) return true
+ const machineId = (request.body as { machineId?: unknown } | null | undefined)?.machineId
+ return typeof machineId === 'string' && machineId === admitted.get(request)
+}
diff --git a/backend/src/lib/teamSessionSockets.test.ts b/backend/src/lib/teamSessionSockets.test.ts
new file mode 100644
index 000000000..1c3d547be
--- /dev/null
+++ b/backend/src/lib/teamSessionSockets.test.ts
@@ -0,0 +1,214 @@
+import { EventEmitter } from 'node:events'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+// The sockets a team session meets (docs/plans/2026-10-24-swarm-team-account.md, Task 1). The machine socket takes one
+// only as the machine of the computer it is bound to; the web relay (machine_select, attach) and the device lane
+// refuse it outright. Authentication is faked here: what lib/ssoAuth.ts itself refuses is in harnessSession.test.ts.
+const m = vi.hoisted(() => ({
+ auth: vi.fn(), upgrade: vi.fn(),
+ machineService: { resolveOrCreateForComputer: vi.fn(), resolveForTeamComputer: vi.fn() },
+ machineUpdate: vi.fn(), machineFindUnique: vi.fn(), userFindUnique: vi.fn(),
+ claim: vi.fn(), release: vi.fn(), publishUp: vi.fn(), publishPair: vi.fn(), terminalDown: vi.fn(),
+ pushes: vi.fn(), appendKey: vi.fn(), nodeRole: vi.fn(),
+}))
+vi.mock('./ssoAuth.js', async original => ({ ...await original<typeof import('./ssoAuth.js')>(), authenticateAccessToken: m.auth }))
+vi.mock('./wsServer.js', async original => ({ ...await original<typeof import('./wsServer.js')>(), createWss: () => ({ handleUpgrade: m.upgrade }) }))
+vi.mock('../services/MachineService.js', () => ({ machineService: m.machineService }))
+vi.mock('./prisma.js', () => ({
+ prisma: { machine: { update: m.machineUpdate, findUnique: m.machineFindUnique }, user: { findUnique: m.userFindUnique } },
+ machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] },
+}))
+vi.mock('./bus.js', () => ({
+ publishUp: m.publishUp, claimMachineOwner: m.claim, releaseMachineOwner: m.release, publishDeviceE2eePair: m.publishPair,
+ publishTerminalUp: vi.fn(), subscribeTerminalDown: m.terminalDown, setMachineAppState: vi.fn(), clearMachineAppState: vi.fn(),
+}))
+vi.mock('./adapterAccountPushes.js', () => ({ relayAccountPushes: m.pushes }))
+vi.mock('./deviceKeyLog.js', () => ({ appendDeviceKey: m.appendKey, touchDeviceKey: vi.fn() }))
+vi.mock('./nodeRole.js', () => ({ attachNodeRole: m.nodeRole, PRESENCE_TTL_SEC: 30 }))
+// The real hub starts its heartbeat timers on import; these tests never attach a hub client, so it is a stub with none.
+vi.mock('./hub.js', () => ({
+ CLIENTS_FRAME: '__clients', CLIENTS_DIRTY: '__clients_dirty', LIVENESS_TICK_MS: 5_000, CLIENT_IDLE_DEADLINE_MS: 75_000,
+ DEVICE_IDLE_DEADLINE_MS: 35_000, CLIENT_HEARTBEAT_MS: 25_000, deliverTerminalUpLocal: vi.fn(), deliverUpLocal: vi.fn(),
+ pushDeviceRevoked: vi.fn(), sendClientsControl: vi.fn(), recomputeAndSendClients: vi.fn(), attachHubClient: vi.fn(),
+ trackSocketLiveness: () => () => {},
+}))
+vi.mock('./dailyTracking.js', async original => ({ ...await original<typeof import('./dailyTracking.js')>(),
+ touchMachineOnlineDay: vi.fn(async () => {}), touchUserOnlineDay: vi.fn(async () => {}), touchClientOnlineDay: vi.fn(async () => {}),
+ recordTurnStarted: vi.fn(async () => {}) }))
+
+import { handleAdapterUpgrade } from './adapterWs.js'
+import { handleWebUpgrade } from './webWs.js'
+import { handleDeviceUpgrade } from './deviceWs.js'
+import { SsoAuthError, type AuthUser } from './ssoAuth.js'
+import { AppError } from '../errors/index.js'
+
+const TEAM_COMPUTER = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
+const OWNER_COMPUTER = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
+const owner: AuthUser = { sub: 'owner', email: '[email protected]', role: 'user', autonomousEnv: 'prod' }
+const team: AuthUser = { ...owner, harnessSessionId: 'team-session', harnessSessionKind: 'team', harnessComputerId: TEAM_COMPUTER }
+const teamMac = { machineId: 'team-mac', userId: 'owner', name: 'MacBook Pro · Team', billingStatus: 'not_required', sessionKind: 'team' }
+const ownerMac = { machineId: 'owner-mac', userId: 'owner', name: 'MacBook Pro', billingStatus: 'not_required', sessionKind: null }
+const flush = async () => { for (let i = 0; i < 400; i++) await Promise.resolve() }
+
+class Socket extends EventEmitter {
+ readyState = 1; bufferedAmount = 0
+ send = vi.fn()
+ close = vi.fn((_code?: number, _reason?: string) => { this.readyState = 3; this.emit('close') })
+ terminate = vi.fn(() => this.close())
+ frame(body: unknown) { this.emit('message', Buffer.from(JSON.stringify(body)), false) }
+ sent() { return this.send.mock.calls.map(c => JSON.parse(c[0] as string)) }
+}
+const raw = () => ({ write: vi.fn(), destroy: vi.fn(), destroyed: false, on: vi.fn(), once: vi.fn() })
+const adapter = (computer: string) => ({ url: `/api/adapter-ws?computer=${computer}&label=Team&autonomousEnv=prod`,
+ headers: { 'sec-websocket-protocol': 'access-token' } })
+const status = (socket: ReturnType<typeof raw>) => String(socket.write.mock.calls.at(-1)?.[0] ?? '').split('\r\n')[0]
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ m.claim.mockResolvedValue(true)
+ m.machineUpdate.mockResolvedValue({})
+ m.userFindUnique.mockResolvedValue({ gridName: 'grid-of-the-account' })
+ m.pushes.mockResolvedValue(() => {})
+ m.terminalDown.mockResolvedValue(() => {})
+ m.publishUp.mockResolvedValue(undefined)
+ m.appendKey.mockResolvedValue({ ok: true, head: { seq: 1, hash: 'h' } })
+ m.nodeRole.mockResolvedValue({ touch: vi.fn(), detach: vi.fn(async () => {}) })
+ m.machineService.resolveForTeamComputer.mockResolvedValue({ machine: teamMac, created: false })
+ m.upgrade.mockReset()
+ m.machineService.resolveOrCreateForComputer.mockResolvedValue({ machine: ownerMac, created: false })
+})
+
+describe('the machine socket and a team session', () => {
+ it('asks for a team session explicitly, as a machine', async () => {
+ m.auth.mockResolvedValue(team)
+ handleAdapterUpgrade(adapter(TEAM_COMPUTER) as never, raw() as never, Buffer.alloc(0)); await flush()
+ expect(m.auth).toHaveBeenCalledWith('access-token', 'prod', { allowHarnessSession: 'computer', allowTeamSession: true })
+ })
+
+ it('refuses it as any computer but its own, before looking up a machine', async () => {
+ m.auth.mockResolvedValue(team)
+ const socket = raw()
+ handleAdapterUpgrade(adapter(OWNER_COMPUTER) as never, socket as never, Buffer.alloc(0)); await flush()
+ expect(status(socket)).toBe('HTTP/1.1 403 Forbidden')
+ expect(socket.destroy).toHaveBeenCalled()
+ expect(m.machineService.resolveForTeamComputer).not.toHaveBeenCalled()
+ expect(m.machineService.resolveOrCreateForComputer).not.toHaveBeenCalled()
+ expect(m.claim).not.toHaveBeenCalled()
+ expect(m.upgrade).not.toHaveBeenCalled()
+ })
+
+ it('connects it as its own computer\'s team machine', async () => {
+ m.auth.mockResolvedValue(team)
+ handleAdapterUpgrade(adapter(TEAM_COMPUTER.toUpperCase()) as never, raw() as never, Buffer.alloc(0)); await flush()
+ expect(m.machineService.resolveForTeamComputer).toHaveBeenCalledWith(team, TEAM_COMPUTER, 'Team', undefined)
+ expect(m.machineService.resolveOrCreateForComputer).not.toHaveBeenCalled()
+ expect(m.claim).toHaveBeenCalledWith('team-mac', TEAM_COMPUTER, 30)
+ expect(m.upgrade).toHaveBeenCalledTimes(1)
+ })
+
+ it('refuses it when its computer\'s machine is one a normal sign-in holds', async () => {
+ m.auth.mockResolvedValue(team)
+ m.machineService.resolveForTeamComputer.mockRejectedValue(new AppError('held', 403, 'TEAM_SESSION_LIMITED'))
+ const socket = raw()
+ handleAdapterUpgrade(adapter(TEAM_COMPUTER) as never, socket as never, Buffer.alloc(0)); await flush()
+ expect(status(socket)).toBe('HTTP/1.1 403 Forbidden')
+ expect(m.upgrade).not.toHaveBeenCalled()
+ })
+
+ it('records a computer session on the machine row before it attaches, so a former team machine is not one any more', async () => {
+ m.auth.mockResolvedValue(owner)
+ m.machineService.resolveOrCreateForComputer.mockResolvedValue({ machine: { ...ownerMac, sessionKind: 'team' }, created: false })
+ handleAdapterUpgrade(adapter(OWNER_COMPUTER) as never, raw() as never, Buffer.alloc(0)); await flush()
+ expect(m.machineService.resolveOrCreateForComputer).toHaveBeenCalledWith('owner', 'prod', OWNER_COMPUTER, 'Team', undefined, 'computer')
+ expect(m.machineUpdate).toHaveBeenCalledWith({ where: { machineId: 'owner-mac' }, data: { sessionKind: 'computer' } })
+ expect(m.machineUpdate.mock.invocationCallOrder[0]).toBeLessThan(m.upgrade.mock.invocationCallOrder[0]!)
+ // Already marked, or from before the kind was kept: no write before attaching (the connect's own update stamps it).
+ for (const sessionKind of ['computer', null]) {
+ m.machineUpdate.mockClear(); m.upgrade.mockClear()
+ m.machineService.resolveOrCreateForComputer.mockResolvedValue({ machine: { ...ownerMac, sessionKind }, created: false })
+ handleAdapterUpgrade(adapter(OWNER_COMPUTER) as never, raw() as never, Buffer.alloc(0)); await flush()
+ expect(m.machineUpdate).not.toHaveBeenCalled()
+ expect(m.upgrade).toHaveBeenCalled()
+ }
+ })
+
+ describe('once attached', () => {
+ let ws: Socket
+ afterEach(() => ws?.close())
+ const attach = async (user: AuthUser, computer: string) => {
+ ws = new Socket()
+ m.auth.mockResolvedValue(user)
+ m.upgrade.mockImplementation((_r, _s, _h, done) => done(ws))
+ handleAdapterUpgrade(adapter(computer) as never, raw() as never, Buffer.alloc(0)); await flush()
+ }
+
+ it('a team machine hears only its device-key pushes, never the account\'s grid name', async () => {
+ await attach(team, TEAM_COMPUTER)
+ expect(m.pushes).toHaveBeenCalledWith('owner', expect.any(Function), expect.objectContaining({ team: true }))
+ expect(m.machineUpdate).toHaveBeenCalledWith({ where: { machineId: 'team-mac' }, data: expect.objectContaining({ sessionKind: 'team' }) })
+ const meta = ws.sent().find(f => f.frame?.type === 'machine_meta')
+ expect(meta.frame.payload).toEqual({ name: 'MacBook Pro · Team', gridName: null })
+ })
+
+ it('a team machine appends to the key log as a team machine, and raises no pairing notice on the person\'s apps', async () => {
+ await attach(team, TEAM_COMPUTER)
+ ws.frame({ t: 'up', frame: { type: 'devlog_append', payload: { requestId: 'r1', entry: { op: 'add' } } } })
+ await flush()
+ expect(m.appendKey).toHaveBeenCalledWith('owner', { op: 'add' }, { kind: 'machine', machineId: 'team-mac', harnessSessionId: 'team-session', team: true })
+ ws.frame({ t: 'up', userEligible: true, webEligible: false, frame: { type: 'device_e2ee_pair_pending', payload: { pairId: 'p1', label: 'Dial' } } })
+ await flush()
+ expect(m.publishPair).not.toHaveBeenCalled()
+ })
+
+ it('a socket under the old sign-in closes when its computer becomes a team machine; a team socket stays', async () => {
+ m.machineService.resolveOrCreateForComputer.mockResolvedValue({ machine: { ...ownerMac, sessionKind: 'computer' }, created: false })
+ await attach(owner, OWNER_COMPUTER)
+ const deliver = m.nodeRole.mock.calls.at(-1)![0].deliver as (msg: unknown) => void
+ deliver({ connId: '', frame: { type: '__team_converted' } })
+ expect(ws.close).toHaveBeenCalledWith(4009, 'now a team machine')
+ expect(ws.sent().some(f => f.frame?.type === '__team_converted')).toBe(false)
+ await attach(team, TEAM_COMPUTER)
+ const teamDeliver = m.nodeRole.mock.calls.at(-1)![0].deliver as (msg: unknown) => void
+ teamDeliver({ connId: '', frame: { type: '__team_converted' } })
+ expect(ws.close).not.toHaveBeenCalled()
+ expect(ws.sent().some(f => f.frame?.type === '__team_converted')).toBe(false)
+ })
+
+ it('a computer keeps every account push, its grid name and its pairing notices', async () => {
+ m.machineService.resolveOrCreateForComputer.mockResolvedValue({ machine: { ...ownerMac, sessionKind: 'computer' }, created: false })
+ m.machineFindUnique.mockResolvedValue({ name: 'MacBook Pro' })
+ await attach(owner, OWNER_COMPUTER)
+ expect(m.pushes).toHaveBeenCalledWith('owner', expect.any(Function), expect.objectContaining({ team: false }))
+ expect(m.machineUpdate).toHaveBeenCalledWith({ where: { machineId: 'owner-mac' }, data: expect.objectContaining({ sessionKind: 'computer' }) })
+ expect(ws.sent().find(f => f.frame?.type === 'machine_meta').frame.payload.gridName).toBe('grid-of-the-account')
+ ws.frame({ t: 'up', frame: { type: 'devlog_append', payload: { requestId: 'r1', entry: { op: 'add' } } } })
+ ws.frame({ t: 'up', userEligible: true, webEligible: false, frame: { type: 'device_e2ee_pair_pending', payload: { pairId: 'p1', label: 'Dial' } } })
+ await flush()
+ expect(m.appendKey).toHaveBeenCalledWith('owner', { op: 'add' }, { kind: 'machine', machineId: 'owner-mac' })
+ expect(m.publishPair).toHaveBeenCalledTimes(1)
+ })
+ })
+})
+
+describe('the sockets that never take a team session', () => {
+ const teamRefusal = new SsoAuthError('This connection is not available to a team sign-in', 'TEAM_SESSION_LIMITED')
+
+ it('the web relay (machine_select, attach) closes it as refused, not as an expired sign-in to retry', async () => {
+ m.auth.mockRejectedValue(teamRefusal)
+ const ws = new Socket()
+ m.upgrade.mockImplementation((_r, _s, _h, done) => done(ws))
+ handleWebUpgrade({ url: '/api/web-ws?autonomousEnv=prod', headers: { 'sec-websocket-protocol': 'hna_team' } } as never, raw() as never, Buffer.alloc(0))
+ await flush()
+ expect(m.auth).toHaveBeenCalledWith('hna_team', 'prod')
+ expect(ws.close).toHaveBeenCalledWith(4403, 'team sign-in')
+ })
+
+ it('the device lane answers it 403', async () => {
+ m.auth.mockRejectedValue(teamRefusal)
+ const socket = raw()
+ handleDeviceUpgrade({ url: `/api/device-ws?computer=${TEAM_COMPUTER}`, headers: { 'sec-websocket-protocol': 'hna_team' } } as never, socket as never, Buffer.alloc(0))
+ await flush()
+ expect(m.auth).toHaveBeenCalledWith('hna_team', 'prod', { allowHarnessSession: 'computer' })
+ expect(status(socket)).toBe('HTTP/1.1 403 Forbidden')
+ })
+})
diff --git a/backend/src/lib/webWs.ts b/backend/src/lib/webWs.ts
index 03cd9d03a..c9ab991d9 100644
--- a/backend/src/lib/webWs.ts
+++ b/backend/src/lib/webWs.ts
@@ -115,12 +115,15 @@ export function handleWebUpgrade(req: IncomingMessage, socket: Duplex, head: Buf
const invalid = err instanceof SsoAuthError && err.code === 'INVALID_TOKEN'
const mismatch = err instanceof SsoAuthError &&
(err.code === 'AUTONOMOUS_ENV_MISMATCH' || err.code === 'AUTONOMOUS_ENV_NOT_ALLOWED')
- const code = invalid ? 4401 : mismatch ? 4403 : 1013
+ // A Mac's team account (lib/teamSession.ts) never selects or attaches to a machine here: refused for good,
+ // not an expired sign-in to refresh and retry.
+ const team = err instanceof SsoAuthError && err.code === 'TEAM_SESSION_LIMITED'
+ const code = invalid ? 4401 : mismatch || team ? 4403 : 1013
const reason = invalid
? 'auth expired'
: mismatch
? `env:${err.requiredEnv ?? 'prod'}`
- : 'auth service unavailable'
+ : team ? 'team sign-in' : 'auth service unavailable'
wss.handleUpgrade(req, socket, head, (ws) => { try { ws.close(code, reason) } catch { /* ignore */ } })
}
})().catch((err) => { logger.warn('web-ws upgrade failed', { error: String(err) }); socket.destroy() })
diff --git a/backend/src/middlewares/authMiddleware.test.ts b/backend/src/middlewares/authMiddleware.test.ts
index 05bb52331..4b5192755 100644
--- a/backend/src/middlewares/authMiddleware.test.ts
+++ b/backend/src/middlewares/authMiddleware.test.ts
@@ -57,7 +57,7 @@ describe('control-plane SSO auth middleware', () => {
const res = await request()
expect(res.statusCode).toBe(200)
expect(res.json().user.sub).toBe('internal-1')
- expect(authenticate).toHaveBeenCalledWith('sso-token', 'prod')
+ expect(authenticate).toHaveBeenCalledWith('sso-token', 'prod', { allowTeamSession: true })
})
it('keeps only the native SSO flow public and rejects legacy machine-key routes', () => {
diff --git a/backend/src/middlewares/authMiddleware.ts b/backend/src/middlewares/authMiddleware.ts
index f81eec0da..b60fbe6a6 100644
--- a/backend/src/middlewares/authMiddleware.ts
+++ b/backend/src/middlewares/authMiddleware.ts
@@ -6,6 +6,7 @@ import { parseAutonomousEnvironment, type AutonomousEnvironment } from '../lib/a
import { countryCodeFromHeaders, stampUserCountry } from '../lib/clientGeo.js'
import { isPublicCommunityRead } from '../lib/communityAccess.js'
import { GRID_PROFILE_PATH } from '../lib/gridProfile.js'
+import { isTeamSession, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, teamBodyAllowed, teamRequestAllowed } from '../lib/teamSession.js'
/** By the matched route, not the raw URL, so an encoded spelling of the path is the same route. */
const isGridProfileRequest = (request: FastifyRequest): boolean =>
@@ -100,8 +101,13 @@ export function registerAuthMiddleware(
}
// The Grid profile route reads the profile live and records it itself; a fill on top of that would
// be a second storefront read and a second stored-versus-live line for one request.
- const auth = await resolveSsoAuth(token, authenticate, autonomousEnv, isGridProfileRequest(request))
+ // A team session is accepted here only because the gate below holds it to its own machine.
+ const auth = await resolveSsoAuth(token, authenticate, autonomousEnv, isGridProfileRequest(request), { allowTeamSession: true })
if ('user' in auth) {
+ // A Mac's team account (lib/teamSession.ts) reaches only what its own machine needs: deny by default.
+ if (auth.user.harnessSessionKind === 'team' && !(await teamRequestAllowed(request, auth.user))) {
+ return reply.code(403).send({ success: false, error: { code: TEAM_SESSION_LIMITED, message: TEAM_SESSION_MESSAGE } })
+ }
request.user = auth.user
// Where the person is, per Cloudflare (`CF-IPCountry`, absent off-Cloudflare). Every control-plane
// call comes from their own computer, which is what makes this — and not the daemon's socket —
@@ -123,6 +129,13 @@ export function registerAuthMiddleware(
},
})
})
+ // The rest of the team gate, once the body is read: a machine the body names must be the team session's own.
+ // Runs before every route's own preHandlers (its validation), as an instance hook does.
+ app.addHook('preHandler', async (request: FastifyRequest, reply: FastifyReply) => {
+ if (isTeamSession(request.user) && !teamBodyAllowed(request)) {
+ return reply.code(403).send({ success: false, error: { code: TEAM_SESSION_LIMITED, message: TEAM_SESSION_MESSAGE } })
+ }
+ })
}
export async function resolveSsoAuth(
@@ -130,25 +143,30 @@ export async function resolveSsoAuth(
authenticate: typeof authenticateAccessToken = authenticateAccessToken,
autonomousEnv: AutonomousEnvironment = 'prod',
readsProfileItself = false,
+ /** Accept a team session (lib/teamSession.ts): only for a caller that then holds it to its own machine. */
+ { allowTeamSession = false }: { allowTeamSession?: boolean } = {},
): Promise<
| { user: AuthUser }
| {
status: 401 | 403 | 503
- code: 'UNAUTHORIZED' | 'AUTH_SERVICE_UNAVAILABLE' | 'AUTONOMOUS_ENV_MISMATCH' | 'AUTONOMOUS_ENV_NOT_ALLOWED'
+ code: 'UNAUTHORIZED' | 'AUTH_SERVICE_UNAVAILABLE' | 'AUTONOMOUS_ENV_MISMATCH' | 'AUTONOMOUS_ENV_NOT_ALLOWED' | 'TEAM_SESSION_LIMITED'
message: string
requiredEnv?: AutonomousEnvironment
}
> {
+ const options = { ...(readsProfileItself ? { learnGoogleSubject: false } : {}), ...(allowTeamSession ? { allowTeamSession } : {}) }
try {
return {
- user: await (readsProfileItself
- ? authenticate(token, autonomousEnv, { learnGoogleSubject: false })
- : authenticate(token, autonomousEnv)),
+ user: await (Object.keys(options).length ? authenticate(token, autonomousEnv, options) : authenticate(token, autonomousEnv)),
}
} catch (err) {
if (err instanceof SsoAuthError && err.code === 'AUTH_SERVICE_UNAVAILABLE') {
return { status: 503, code: 'AUTH_SERVICE_UNAVAILABLE', message: 'Authentication service unavailable' }
}
+ // Refused for good, not an expired sign-in: a 401 would send the caller to refresh and try again.
+ if (err instanceof SsoAuthError && err.code === 'TEAM_SESSION_LIMITED') {
+ return { status: 403, code: 'TEAM_SESSION_LIMITED', message: err.message }
+ }
if (err instanceof SsoAuthError &&
(err.code === 'AUTONOMOUS_ENV_MISMATCH' || err.code === 'AUTONOMOUS_ENV_NOT_ALLOWED')) {
return {
diff --git a/backend/src/routes/auth.ts b/backend/src/routes/auth.ts
index 33d2003a2..8ce9d3762 100644
--- a/backend/src/routes/auth.ts
+++ b/backend/src/routes/auth.ts
@@ -26,6 +26,40 @@ import { parseAutonomousEnvironment, type AutonomousEnvironment } from '../lib/a
import { isHarnessRefreshToken } from '../lib/harnessTokenFormat.js'
import { redeemHandoff, refreshHarnessSession, revokeHarnessSession, startHandoff } from '../lib/harnessSession.js'
import { normalizeSignInAttribution, type SignInAttribution } from '../lib/signInAttribution.js'
+import { createHash } from 'node:crypto'
+import { ed25519 } from '@noble/curves/ed25519.js'
+import { normalizeComputerId } from '../lib/deviceAuth.js'
+import { activeMachineKeys } from '../lib/deviceKeyLog.js'
+import { machineAlive, prisma } from '../lib/prisma.js'
+import { pub } from '../lib/bus.js'
+import { TEAM_CONVERSION_PROOF_MS, teamConversionMessage } from '../lib/teamSession.js'
+import type { AuthUser } from '../lib/ssoAuth.js'
+
+/**
+ * Whether [user] is the computer [computerId] itself, which alone may turn itself into a team machine
+ * (lib/teamSession.ts). Its own Harness computer session says so; any other sign-in of the account must carry
+ * that computer's machine key's signature over `teamConversionMessage`, fresh, and used once.
+ */
+async function isThisComputer(user: AuthUser, computerId: string, proof: unknown): Promise<boolean> {
+ if (user.harnessSessionKind === 'computer' && user.harnessComputerId === computerId) return true
+ if (!proof || typeof proof !== 'object') return false
+ const { machineId, at, sig } = proof as { machineId?: unknown; at?: unknown; sig?: unknown }
+ if (typeof machineId !== 'string' || !machineId || machineId.length > 128 || typeof sig !== 'string' || sig.length > 128
+ || typeof at !== 'number' || !Number.isSafeInteger(at) || Math.abs(Date.now() - at) > TEAM_CONVERSION_PROOF_MS) return false
+ const machine = await prisma.machine.findFirst({ where: { machineId, userId: user.sub, computerId, autonomousEnv: user.autonomousEnv, ...machineAlive } })
+ if (!machine) return false
+ const key = (await activeMachineKeys(user.sub)).find((k) => k.kind === 'machine' && k.machineId === machineId)
+ if (!key) return false
+ let signed = false
+ try {
+ signed = ed25519.verify(Buffer.from(sig, 'base64'), new TextEncoder().encode(teamConversionMessage(user.sub, computerId, machineId, at)),
+ Buffer.from(key.pub, 'base64'))
+ } catch { signed = false }
+ if (!signed) return false
+ // Once: a proof seen on the way cannot be shown again.
+ const once = await pub.set(`hnauth:teamproof:${createHash('sha256').update(sig).digest('hex')}`, '1', 'EX', Math.ceil(2 * TEAM_CONVERSION_PROOF_MS / 1000), 'NX')
+ return once === 'OK'
+}
/** Reporting only: a sign-in whose attribution cannot be stored still signs in. */
async function recordAttribution(userId: string, attribution: SignInAttribution): Promise<void> {
@@ -247,12 +281,26 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
// its Add Phone QR; the phone that scans it redeems the code for a session of its own. An
// Autonomous sign-in can hand one off, and so can a computer a phone signed in by QR
// (routes/qrSignIn.ts) — a phone's own session cannot mint more of itself.
- app.post('/api/auth/handoff', async (req, reply) => {
+ // `{ kind: 'team' }` asks for a code for this Mac's team account instead (lib/teamSession.ts): same
+ // lifetime, same answer, which names the kind minted. A team session can never mint one of either kind.
+ // `{ kind: 'team', computerId }` is a computer turning ITSELF into a team machine (`harness team on`): only
+ // that computer may ask (isThisComputer), and the code redeems for that computer alone.
+ app.post<{ Body: { kind?: unknown; computerId?: unknown; proof?: unknown } | undefined }>('/api/auth/handoff', async (req, reply) => {
if (req.user!.harnessSessionId && req.user!.harnessSessionKind !== 'computer') {
return sendError(reply, 'Add a phone from a computer signed in to Harness', 'HANDOFF_NOT_ALLOWED', 403)
}
+ const body = req.body && typeof req.body === 'object' ? req.body as { kind?: unknown; computerId?: unknown; proof?: unknown } : {}
+ const asked = body.kind
+ if ((asked !== undefined && asked !== 'viewer' && asked !== 'team') || (body.computerId !== undefined && asked !== 'team')) {
+ return sendError(reply, 'Ask for a phone or a team sign-in code', 'INVALID_HANDOFF_KIND', 400)
+ }
+ const convert = body.computerId === undefined ? undefined : typeof body.computerId === 'string' ? normalizeComputerId(body.computerId) : null
+ if (convert === null) return sendError(reply, 'Name this computer by its id', 'INVALID_COMPUTER_ID', 400)
try {
- return sendSuccess(reply, await startHandoff(req.user!.sub))
+ if (convert && !(await isThisComputer(req.user!, convert, body.proof))) {
+ return sendError(reply, 'Only this computer can make itself a team machine', 'HANDOFF_NOT_ALLOWED', 403)
+ }
+ return sendSuccess(reply, await startHandoff(req.user!.sub, asked === 'team' ? 'team' : 'viewer', convert ? { convert } : {}))
} catch (e) {
logger.error('handoff start failed', e)
return sendError(reply, 'Authentication service unavailable', 'AUTH_SERVICE_UNAVAILABLE', 503)
@@ -261,12 +309,14 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
// Unauthenticated BY DESIGN, like /refresh: the code is the credential. It is 32 random bytes,
// good for one redeem within 90 seconds, so there is nothing to guess and nothing to replay.
- app.post<{ Body: { code?: string; label?: string } }>('/api/auth/handoff/redeem', async (req, reply) => {
+ // A team code also needs the redeeming daemon's `computerId`: its session is bound to that computer.
+ app.post<{ Body: { code?: string; label?: string; computerId?: string } }>('/api/auth/handoff/redeem', async (req, reply) => {
const code = typeof req.body?.code === 'string' ? req.body.code.trim() : ''
- const label = (typeof req.body?.label === 'string' ? req.body.label.trim() : '').slice(0, 80) || 'phone'
+ const label = (typeof req.body?.label === 'string' ? req.body.label.trim() : '').slice(0, 80)
+ const computerId = typeof req.body?.computerId === 'string' ? req.body.computerId : undefined
try {
- const tokens = await redeemHandoff(code, label)
- // Expired, spent, or never ours — one answer, so a caller learns nothing from which.
+ const tokens = await redeemHandoff(code, label, computerId)
+ // Expired, spent, never ours, or a team code without its computer — one answer, so a caller learns nothing from which.
if (!tokens) return sendError(reply, 'That code has expired. Scan the new one.', 'HANDOFF_INVALID', 401)
logger.info('handoff redeemed', { label })
return sendSuccess(reply, tokens)
diff --git a/backend/src/routes/control.test.ts b/backend/src/routes/control.test.ts
new file mode 100644
index 000000000..647e018ca
--- /dev/null
+++ b/backend/src/routes/control.test.ts
@@ -0,0 +1,100 @@
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+import Fastify, { type FastifyInstance } from 'fastify'
+
+// Deny by default, against the route table production serves: every control-API route a team session is not
+// explicitly allowed (lib/teamSession.ts TEAM_ROUTES) answers it 403, whatever the route. The session is a real one,
+// minted and redeemed through lib/harnessSession.ts against in-memory stores, so the real authentication runs.
+const fakes = vi.hoisted(() => {
+ const redis = new Map<string, string>()
+ const sessions: Array<Record<string, unknown> & { id: string }> = []
+ const pick = (where: Record<string, unknown>) => sessions.find(s => Object.entries(where).every(([k, v]) => s[k] === v)) ?? null
+ return {
+ redis, sessions,
+ pub: {
+ set: vi.fn(async (key: string, value: string) => { redis.set(key, value); return 'OK' }),
+ get: vi.fn(async (key: string) => redis.get(key) ?? null),
+ multi: vi.fn(() => {
+ const ops: Array<() => unknown> = []
+ const chain = {
+ get: (key: string) => { ops.push(() => redis.get(key) ?? null); return chain },
+ del: (key: string) => { ops.push(() => (redis.delete(key) ? 1 : 0)); return chain },
+ exec: async () => ops.map(op => [null, op()]),
+ }
+ return chain
+ }),
+ },
+ prisma: {
+ harnessSession: {
+ create: vi.fn(async ({ data }: { data: Record<string, unknown> }) => {
+ const row = { id: `s${sessions.length + 1}`, ...data }; sessions.push(row); return row
+ }),
+ findUnique: vi.fn(async ({ where }: { where: Record<string, unknown> }) => pick(where)),
+ },
+ machine: {
+ findMany: vi.fn(async ({ where }: { where: Record<string, unknown> }) => where.computerId === 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
+ ? [{ machineId: 'team-mac', userId: 'owner', computerId: where.computerId, billingStatus: 'not_required', sessionKind: 'team' }] : []),
+ },
+ },
+ user: { id: 'owner', email: '[email protected]', role: 'user', autonomousEnv: 'prod' },
+ }
+})
+vi.mock('../lib/bus.js', () => ({ pub: fakes.pub }))
+vi.mock('../lib/prisma.js', () => ({ prisma: fakes.prisma, machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] } }))
+// The real hub starts its heartbeat timers on import; these tests never attach a hub client, so it is a stub with none.
+vi.mock('../lib/hub.js', () => ({
+ CLIENTS_FRAME: '__clients', CLIENTS_DIRTY: '__clients_dirty', LIVENESS_TICK_MS: 5_000, CLIENT_IDLE_DEADLINE_MS: 75_000,
+ DEVICE_IDLE_DEADLINE_MS: 35_000, CLIENT_HEARTBEAT_MS: 25_000, deliverTerminalUpLocal: vi.fn(), deliverUpLocal: vi.fn(),
+ pushDeviceRevoked: vi.fn(), sendClientsControl: vi.fn(), recomputeAndSendClients: vi.fn(), attachHubClient: vi.fn(),
+ trackSocketLiveness: () => () => {},
+}))
+vi.mock('../services/UserService.js', () => ({
+ userService: { get: vi.fn(async (id: string) => id === fakes.user.id ? fakes.user : null) },
+ normalizeUserEmail: (email: string) => email.trim().toLowerCase(),
+ isProvisionalUserEmail: () => false,
+}))
+
+import { registerAuthMiddleware, shouldSkipAuth } from '../middlewares/authMiddleware.js'
+import { errorHandler } from '../middlewares/errorHandler.js'
+import { redeemHandoff, startHandoff } from '../lib/harnessSession.js'
+import { TEAM_ROUTES } from '../lib/teamSession.js'
+import { registerControlRoutes } from './control.js'
+
+let app: FastifyInstance
+let token: string
+const routes: Array<{ method: string; url: string }> = []
+
+beforeAll(async () => {
+ const { code } = await startHandoff(fakes.user.id, 'team')
+ token = (await redeemHandoff(code, 'MacBook Pro · Team', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'))!.token
+ app = Fastify()
+ app.setErrorHandler(errorHandler)
+ app.addHook('onRoute', route => {
+ for (const method of [route.method].flat()) if (method !== 'HEAD' && method !== 'OPTIONS') routes.push({ method, url: route.url })
+ })
+ registerAuthMiddleware(app)
+ await registerControlRoutes(app, { daemons: { on: true, users: null }, count: async () => 0 })
+ await app.ready()
+})
+afterAll(async () => { await app?.close() })
+
+describe('a team session against every control route', () => {
+ it('is refused everywhere the allowlist does not name, the phone\'s own routes included', async () => {
+ const allowed = new Set(TEAM_ROUTES.map(r => `${r.method} ${r.url}`))
+ const swept: string[] = []
+ for (const { method, url } of routes) {
+ if (allowed.has(`${method} ${url}`)) continue
+ const path = url.replace(/:[A-Za-z]+/g, 'x0').replace(/\*/g, 'x0')
+ // A public route takes no sign-in at all (health, sign-in itself, shared-secret callers): nothing to refuse.
+ if (shouldSkipAuth(path) && !path.startsWith('/api/mobile/')) continue
+ const res = await app.inject({ method: method as never, url: path, headers: { authorization: `Bearer ${token}` } })
+ expect(res.statusCode, `${method} ${url}: ${res.body}`).toBe(403)
+ expect(res.json().error?.code, `${method} ${url}`).toBe('TEAM_SESSION_LIMITED')
+ swept.push(`${method} ${url}`)
+ }
+ // The table is the real one: the sweep covered the account's sensitive routes, not an empty list.
+ for (const route of ['GET /api/machines', 'POST /api/auth/handoff', 'GET /api/auth/me', 'GET /api/connector-vault', 'GET /api/desk',
+ 'POST /api/auth/qr/approve', 'POST /api/device-auth/approve', 'GET /api/grid/profile', 'PUT /api/machines/:machineId/share',
+ 'GET /api/agent-messages', 'GET /api/harness-shares', 'GET /api/super-tabs', 'POST /api/super-tabs/:tabId/join',
+ 'GET /api/mobile/v1/overview', 'POST /api/device-keys']) expect(swept).toContain(route)
+ })
+})
diff --git a/backend/src/routes/control.ts b/backend/src/routes/control.ts
new file mode 100644
index 000000000..8c00d070a
--- /dev/null
+++ b/backend/src/routes/control.ts
@@ -0,0 +1,73 @@
+import type { FastifyInstance } from 'fastify'
+import type { DaemonsSwitch } from '../lib/daemonsSwitch.js'
+import type { JevRouteOptions } from './jevRoute.js'
+import { cursorRoutes } from './cursor.js'
+import { voiceRoutes } from './voice.js'
+import { harnessShareRoutes } from './harnessShares.js'
+import { machineShareRoutes } from './machineShares.js'
+import { harnessLinkRoutes } from './harnessLinks.js'
+import { communityRoutes } from './community.js'
+import { communityTranslateRoutes } from './communityTranslate.js'
+import { communityCommentRoutes } from './communityComments.js'
+import { communityCreatorRoutes } from './communityCreators.js'
+import { communityNotificationRoutes } from './communityNotifications.js'
+import { communityReportRoutes } from './communityReports.js'
+import { communityEditRoutes } from './communityEdit.js'
+import { deviceKeyRoutes } from './deviceKeys.js'
+import { qrSignInRoutes } from './qrSignIn.js'
+import { deskRoutes } from './desk.js'
+import { connectorRoutes } from './connectors.js'
+import { connectorVaultRoutes } from './connectorVault.js'
+import { agentMessagesRoutes } from './agentMessages.js'
+import { superTabRoutes } from './superTabs.js'
+import { zooRoutes } from './zoo.js'
+import { experimentalSettingsRoutes } from './experimentalSettings.js'
+import { deviceAuthRoutes } from './deviceAuth.js'
+import { healthRoutes, authRoutes, userRoutes, machineRoutes, planRoutes, gridRoutes, deviceRoutes, mobileRoutes, appRoutes, analyticsRoutes, productUsageRoutes, agentRouteRoutes, jevRouteRoutes, storeRoutes } from './index.js'
+
+/**
+ * Every control-API route, in the order the server registers them (server.ts, after the authentication hook). One
+ * list, so what is checked against the route table — a team session's deny-by-default sweep (routes/control.test.ts)
+ * — is the table production serves.
+ */
+export async function registerControlRoutes(app: FastifyInstance, opts: { daemons: DaemonsSwitch; count: JevRouteOptions['count'] }): Promise<void> {
+ await app.register(healthRoutes)
+ await app.register(authRoutes)
+ await app.register(userRoutes)
+ await app.register(machineRoutes)
+ await app.register(planRoutes)
+ await app.register(gridRoutes) // the account's private harness grid name
+ await app.register(deviceRoutes)
+ await app.register(mobileRoutes)
+ await app.register(appRoutes)
+ await app.register(analyticsRoutes)
+ await app.register(productUsageRoutes)
+ await app.register(agentRouteRoutes) // which agent a task belongs to — the prompt lives here, not in the CLI
+ await app.register(jevRouteRoutes, { count: opts.count }) // ⌘B's Jev decisions on Harness's key, for people with none of their own
+ await app.register(cursorRoutes) // standalone STT + LLM for the Cursor desktop app (self-contained)
+ // The cabled dial's transcription, authenticated by the caller's SSO token rather than a shared secret.
+ // Absent from the auth middleware's skip-list on purpose: that absence IS the gate.
+ await app.register(voiceRoutes)
+ await app.register(deviceAuthRoutes) // device-authorization grant: how the desktop app gets a machine key
+ await app.register(storeRoutes) // the Harness Store's ratings and reviews; the catalogue is the CLI's registry
+ await app.register(harnessShareRoutes)
+ await app.register(machineShareRoutes)
+ await app.register(harnessLinkRoutes)
+ await app.register(communityRoutes)
+ await app.register(communityEditRoutes) // an author edits their publication in place
+ await app.register(communityCommentRoutes) // a harness page reads its earlier comments
+ await app.register(communityCreatorRoutes) // a creator's page: their name, followers and the reader's follow
+ await app.register(communityReportRoutes) // readers report a publication or comment; reviewers restore or remove it
+ await app.register(communityNotificationRoutes) // a creator's bell: comments, replies and forks of their work
+ await app.register(communityTranslateRoutes) // a Hub draft's words in English, for its author to review
+ await app.register(qrSignInRoutes) // sign a computer in by scanning its QR with a signed-in phone
+ await app.register(deviceKeyRoutes) // the account's device key log: signing in is what trusts a device
+ await app.register(deskRoutes) // the account's tabs, the same on every computer (lib/desk.ts)
+ await app.register(connectorRoutes) // sign-in to GitHub, Slack, Google… for local agents (lib/connectorGateway.ts)
+ await app.register(connectorVaultRoutes) // those connections sealed for the account's computers, which keep them in step
+ await app.register(agentMessagesRoutes) // which tabs' harnesses may message each other (lib/agentMessages.ts)
+ await app.register(superTabRoutes)
+ await app.register(experimentalSettingsRoutes, { daemons: opts.daemons })
+ // Availability is separate from opt-in: every account starts off, and its collection is retained.
+ await app.register(zooRoutes, { daemons: opts.daemons, requireAccountOptIn: true })
+}
diff --git a/backend/src/routes/deviceKeys.test.ts b/backend/src/routes/deviceKeys.test.ts
index c912af206..88f1a080a 100644
--- a/backend/src/routes/deviceKeys.test.ts
+++ b/backend/src/routes/deviceKeys.test.ts
@@ -159,3 +159,34 @@ describe('device key routes', () => {
})
})
})
+
+// Behind the REST gate (lib/teamSession.ts) these are refused already; the handlers refuse a team session themselves too,
+// so a gate that ever let one through still could not add an app key or vouch for one.
+describe('device key routes and a team session', () => {
+ let app: FastifyInstance
+ const team = { ...user, harnessSessionId: 'team-session', harnessSessionKind: 'team' as const, harnessComputerId: 'b'.repeat(32) }
+ beforeEach(async () => {
+ vi.resetAllMocks()
+ app = Fastify(); app.setErrorHandler(errorHandler)
+ app.addHook('onRequest', async request => { request.user = team })
+ await app.register(deviceKeyRoutes); await app.ready()
+ })
+ afterEach(async () => { await app.close() })
+
+ it('reads the log, but marks no key as seen', async () => {
+ m.read.mockResolvedValue({ acct: 'user-1', head, entries: [] })
+ const r = await app.inject({ method: 'GET', url: `/api/device-keys?since=0&self=${encodeURIComponent(Buffer.alloc(32, 1).toString('base64'))}` })
+ expect(r.statusCode).toBe(200)
+ expect(m.touch).not.toHaveBeenCalled()
+ })
+
+ it('never appends a key or an acknowledgement for it', async () => {
+ for (const [url, payload] of [['/api/device-keys', { entry: { op: 'add' } }], ['/api/device-keys/acks', { ack: { pub: 'x' } }]] as const) {
+ const r = await app.inject({ method: 'POST', url, payload })
+ expect(r.statusCode).toBe(403)
+ expect(r.json().error.code).toBe('TEAM_SESSION_LIMITED')
+ }
+ expect(m.append).not.toHaveBeenCalled()
+ expect(m.appendAck).not.toHaveBeenCalled()
+ })
+})
diff --git a/backend/src/routes/deviceKeys.ts b/backend/src/routes/deviceKeys.ts
index ed5e4a837..35da5efa1 100644
--- a/backend/src/routes/deviceKeys.ts
+++ b/backend/src/routes/deviceKeys.ts
@@ -3,6 +3,7 @@ import { z } from 'zod'
import { appendDeviceAck, appendDeviceKey, deviceKeysSeen, readDeviceAcks, readDeviceKeyLog, touchDeviceKey } from '../lib/deviceKeyLog.js'
import { validateBody, validateQuery } from '../middlewares/validation.js'
import { sendError, sendSuccess } from '../utils/response.js'
+import { isTeamSession, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../lib/teamSession.js'
const query = z.object({
since: z.coerce.number().int().min(0).default(0),
@@ -47,7 +48,8 @@ const ackBody = z.object({ ack: z.record(z.string(), z.unknown()) }).strict()
export async function deviceKeyRoutes(app: FastifyInstance): Promise<void> {
app.get<{ Querystring: z.infer<typeof query> }>('/api/device-keys', { preHandler: validateQuery(query) }, async (req, reply) => {
reply.header('Cache-Control', 'no-store')
- if (req.query.self !== undefined) touchDeviceKey(req.user!.sub, req.query.self)
+ // Not for a team account (lib/teamSession.ts): it would keep any key of the person's looking in use, out of the sweeps.
+ if (req.query.self !== undefined && !isTeamSession(req.user)) touchDeviceKey(req.user!.sub, req.query.self)
sendSuccess(reply, await readDeviceKeyLog(req.user!.sub, req.query.since))
})
@@ -66,6 +68,9 @@ export async function deviceKeyRoutes(app: FastifyInstance): Promise<void> {
app.post<{ Body: z.infer<typeof body> }>('/api/device-keys', { preHandler: validateBody(body) }, async (req, reply) => {
const user = req.user!
+ // A key added here is one the account's machines let in as an app: never a team account's (lib/teamSession.ts),
+ // whichever gate it came through. Its machine key goes over its own socket, which keeps it to that machine.
+ if (isTeamSession(user)) return sendError(reply, TEAM_SESSION_MESSAGE, TEAM_SESSION_LIMITED, 403)
if (!allowAppend(user.sub)) return sendError(reply, 'Too many changes to your devices. Try again in a minute.', 'RATE_LIMITED', 429)
const result = await appendDeviceKey(user.sub, req.body.entry, { kind: 'viewer', harnessSessionId: user.harnessSessionId })
if (result.ok) return sendSuccess(reply, { head: result.head })
@@ -88,6 +93,8 @@ export async function deviceKeyRoutes(app: FastifyInstance): Promise<void> {
// which every device checks itself, so the channel it came over adds nothing.
app.post<{ Body: z.infer<typeof ackBody> }>('/api/device-keys/acks', { preHandler: validateBody(ackBody) }, async (req, reply) => {
const user = req.user!
+ // "It's mine" is the person's word: a team account never vouches for a key on the person's devices.
+ if (isTeamSession(user)) return sendError(reply, TEAM_SESSION_MESSAGE, TEAM_SESSION_LIMITED, 403)
if (!allowAck(user.sub)) return sendError(reply, 'Too many changes to your devices. Try again in a minute.', 'RATE_LIMITED', 429)
const result = await appendDeviceAck(user.sub, req.body.ack)
if (result.ok) return sendSuccess(reply, { created: result.created })
diff --git a/backend/src/routes/harnessShares.test.ts b/backend/src/routes/harnessShares.test.ts
index bdf0b6bba..d526b8aa9 100644
--- a/backend/src/routes/harnessShares.test.ts
+++ b/backend/src/routes/harnessShares.test.ts
@@ -160,6 +160,27 @@ describe('account-bound harness invitations', () => {
mocks.prisma.machine.findFirst.mockResolvedValueOnce({ ...machine, billingStatus: 'pending' })
expect(await recipientShare('share', ken)).toBeNull()
})
+ // A team machine (lib/teamSession.ts) hosts Swarm agents for teammates. Its daemon shares an agent's terminal with the
+ // Swarm members who may watch it, and nothing else: only its own machine's harnesses, only for a Swarm.
+ it('lets a team session share only its own machine\'s harnesses, for a Swarm, and take back only those', async () => {
+ const TEAM_COMPUTER = 'b'.repeat(32)
+ const teamMachine = { ...machine, machineId: 'team-mac', computerId: TEAM_COMPUTER, sessionKind: 'team' }
+ mocks.auth.mockResolvedValue({ ...owner, harnessSessionId: 'team-session', harnessSessionKind: 'team', harnessComputerId: TEAM_COMPUTER })
+ mocks.prisma.machine.findMany.mockResolvedValue([teamMachine])
+ mocks.prisma.machine.findFirst.mockResolvedValue(teamMachine)
+ const swarm = { ...input(), machineId: 'team-mac', superTabId: 'a'.repeat(24) }
+ expect((await put(swarm)).statusCode).toBe(200)
+ for (const payload of [{ ...swarm, machineId: 'm1' }, { ...swarm, superTabId: null }, { ...input(), machineId: 'team-mac' }]) {
+ const res = await put(payload)
+ expect(res.statusCode).toBe(403)
+ expect(res.json().error.code).toBe('TEAM_SESSION_LIMITED')
+ }
+ expect(mocks.prisma.harnessShare.upsert).toHaveBeenCalledTimes(1)
+ const id = randomUUID()
+ expect((await app.inject({ method: 'DELETE', url: `/api/harness-shares/${id}`, headers: auth })).statusCode).toBe(200)
+ expect(mocks.prisma.harnessShare.updateMany).toHaveBeenLastCalledWith({ where: { id, ownerId: 'owner', autonomousEnv: 'prod', machineId: 'team-mac' },
+ data: { revokedAt: expect.any(Date) } })
+ })
it('rechecks Super Tab membership for session admission and excludes revoked views from inventory', async () => {
mocks.auth.mockResolvedValue(ken)
const share = { id: 'share', ...input(), superTabId: 'a'.repeat(24), ownerId: owner.sub, expiresAt: new Date(input().expiresAt) }
diff --git a/backend/src/routes/harnessShares.ts b/backend/src/routes/harnessShares.ts
index 031f5c50c..7bc1884f1 100644
--- a/backend/src/routes/harnessShares.ts
+++ b/backend/src/routes/harnessShares.ts
@@ -7,6 +7,7 @@ import { machineBillingAllowsDataPlane } from '../lib/billingState.js'
import { validateBody, validateParams } from '../middlewares/validation.js'
import { sendError, sendSuccess } from '../utils/response.js'
import type { AuthUser } from '../lib/ssoAuth.js'
+import { TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, teamMachineScope } from '../lib/teamSession.js'
const params = z.object({ id: z.string().uuid() })
const body = z.object({
@@ -87,6 +88,12 @@ export async function harnessShareRoutes(app: FastifyInstance): Promise<void> {
'/api/harness-shares/:id', { preHandler: [validateParams(params), validateBody(body)] },
async (req, reply) => {
const input = req.body
+ // A Mac's team account (lib/teamSession.ts) shares only its own machine's harnesses, and only with a Swarm's
+ // members, whom the observer socket checks again on every connection.
+ const team = await teamMachineScope(req.user!)
+ if (team !== null && (input.machineId !== team || !input.superTabId)) {
+ return sendError(reply, TEAM_SESSION_MESSAGE, TEAM_SESSION_LIMITED, 403)
+ }
const machine = await prisma.machine.findFirst({ where: {
machineId: input.machineId, userId: req.user!.sub, autonomousEnv: req.user!.autonomousEnv, ...machineAlive,
} })
@@ -113,8 +120,10 @@ export async function harnessShareRoutes(app: FastifyInstance): Promise<void> {
app.delete<{ Params: z.infer<typeof params> }>('/api/harness-shares/:id',
{ preHandler: [validateParams(params)] }, async (req, reply) => {
+ // A team session takes back only its own machine's shares.
+ const team = await teamMachineScope(req.user!)
const changed = await prisma.harnessShare.updateMany({ where: {
- id: req.params.id, ownerId: req.user!.sub, autonomousEnv: req.user!.autonomousEnv,
+ id: req.params.id, ownerId: req.user!.sub, autonomousEnv: req.user!.autonomousEnv, ...(team === null ? {} : { machineId: team }),
}, data: { revokedAt: new Date() } })
if (!changed.count) return sendError(reply, 'Invitation not found.', 'NOT_FOUND', 404)
await publishShareChanged(req.params.id)
diff --git a/backend/src/routes/machines.ts b/backend/src/routes/machines.ts
index 532281fa8..cc3e58c16 100644
--- a/backend/src/routes/machines.ts
+++ b/backend/src/routes/machines.ts
@@ -16,6 +16,7 @@ import { env } from '../config/env.js'
import { probeProvider, ProviderProbeError } from '../lib/providerProbe.js'
import { normalizeComputerId } from '../lib/deviceAuth.js'
import { machinesSharedWith } from '../lib/machineAccess.js'
+import { isTeamSession, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../lib/teamSession.js'
const createBody = z.object({
// Defaults to the caller; admins may provision for another user.
@@ -319,13 +320,19 @@ export async function machineRoutes(app: FastifyInstance): Promise<void> {
async (req, reply) => {
const computerId = normalizeComputerId(req.body.computerId)
if (!computerId) return sendError(reply, 'Invalid computer id', 'BAD_REQUEST', 400)
- const result = await machineService.resolveOrCreateForComputer(
- req.user!.sub,
- req.user!.autonomousEnv,
- computerId,
- req.body.label ?? 'computer',
- req.body.machineId,
- )
+ // A Mac's team account registers its own computer, as a team machine, and nothing else (lib/teamSession.ts).
+ const team = isTeamSession(req.user)
+ if (team && computerId !== req.user!.harnessComputerId) return sendError(reply, TEAM_SESSION_MESSAGE, TEAM_SESSION_LIMITED, 403)
+ const result = team
+ ? await machineService.resolveForTeamComputer(req.user!, computerId, req.body.label ?? 'computer', req.body.machineId)
+ : await machineService.resolveOrCreateForComputer(
+ req.user!.sub,
+ req.user!.autonomousEnv,
+ computerId,
+ req.body.label ?? 'computer',
+ req.body.machineId,
+ 'computer',
+ )
// The server-internal machine API key must never leave this SSO endpoint.
return sendSuccess(reply, {
machine: { machineId: result.machine.machineId, computerId: result.machine.computerId },
diff --git a/backend/src/server.ts b/backend/src/server.ts
index c584a1d57..4301dec4b 100644
--- a/backend/src/server.ts
+++ b/backend/src/server.ts
@@ -7,32 +7,10 @@ import { DAEMONS, env } from './config/env.js'
import { registerJsonBodyParser } from './lib/jsonBodyParser.js'
import { errorHandler } from './middlewares/errorHandler.js'
import { registerAuthMiddleware } from './middlewares/authMiddleware.js'
-import { cursorRoutes } from './routes/cursor.js'
-import { voiceRoutes } from './routes/voice.js'
-import { harnessShareRoutes } from './routes/harnessShares.js'
-import { machineShareRoutes } from './routes/machineShares.js'
-import { harnessLinkRoutes } from './routes/harnessLinks.js'
-import { communityRoutes } from './routes/community.js'
-import { communityTranslateRoutes } from './routes/communityTranslate.js'
-import { communityCommentRoutes } from './routes/communityComments.js'
-import { communityCreatorRoutes } from './routes/communityCreators.js'
-import { communityNotificationRoutes } from './routes/communityNotifications.js'
-import { communityReportRoutes } from './routes/communityReports.js'
-import { communityEditRoutes } from './routes/communityEdit.js'
-import { deviceKeyRoutes } from './routes/deviceKeys.js'
-import { qrSignInRoutes } from './routes/qrSignIn.js'
-import { deskRoutes } from './routes/desk.js'
-import { connectorRoutes } from './routes/connectors.js'
-import { connectorVaultRoutes } from './routes/connectorVault.js'
-import { agentMessagesRoutes } from './routes/agentMessages.js'
-import { superTabRoutes } from './routes/superTabs.js'
-import { zooRoutes } from './routes/zoo.js'
-import { experimentalSettingsRoutes } from './routes/experimentalSettings.js'
+import { registerControlRoutes } from './routes/control.js'
import { describeDaemonsSwitch } from './lib/daemonsSwitch.js'
import { handleObserverUpgrade } from './lib/observerWs.js'
import { handleAgentMessagesUpgrade } from './lib/agentMessagesWs.js'
-import { deviceAuthRoutes } from './routes/deviceAuth.js'
-import { healthRoutes, authRoutes, userRoutes, machineRoutes, planRoutes, gridRoutes, deviceRoutes, mobileRoutes, appRoutes, analyticsRoutes, productUsageRoutes, agentRouteRoutes, jevRouteRoutes, storeRoutes } from './routes/index.js'
import { startSubdomainProxy, startMeshProxy } from './lib/subdomainProxy.js'
import { handleDeviceUpgrade } from './lib/deviceWs.js'
import { handleWebUpgrade } from './lib/webWs.js'
@@ -169,45 +147,7 @@ async function start(): Promise<void> {
// SSO access-token gate for the control API (data-plane auth happens before Fastify).
registerAuthMiddleware(app)
- await app.register(healthRoutes)
- await app.register(authRoutes)
- await app.register(userRoutes)
- await app.register(machineRoutes)
- await app.register(planRoutes)
- await app.register(gridRoutes) // the account's private harness grid name
- await app.register(deviceRoutes)
- await app.register(mobileRoutes)
- await app.register(appRoutes)
- await app.register(analyticsRoutes)
- await app.register(productUsageRoutes)
- await app.register(agentRouteRoutes) // which agent a task belongs to — the prompt lives here, not in the CLI
- await app.register(jevRouteRoutes, { count: redisCount }) // ⌘B's Jev decisions on Harness's key, for people with none of their own
- await app.register(cursorRoutes) // standalone STT + LLM for the Cursor desktop app (self-contained)
- // The cabled dial's transcription, authenticated by the caller's SSO token rather than a shared secret.
- // Absent from the auth middleware's skip-list on purpose: that absence IS the gate.
- await app.register(voiceRoutes)
- await app.register(deviceAuthRoutes) // device-authorization grant: how the desktop app gets a machine key
- await app.register(storeRoutes) // the Harness Store's ratings and reviews; the catalogue is the CLI's registry
- await app.register(harnessShareRoutes)
- await app.register(machineShareRoutes)
- await app.register(harnessLinkRoutes)
- await app.register(communityRoutes)
- await app.register(communityEditRoutes) // an author edits their publication in place
- await app.register(communityCommentRoutes) // a harness page reads its earlier comments
- await app.register(communityCreatorRoutes) // a creator's page: their name, followers and the reader's follow
- await app.register(communityReportRoutes) // readers report a publication or comment; reviewers restore or remove it
- await app.register(communityNotificationRoutes) // a creator's bell: comments, replies and forks of their work
- await app.register(communityTranslateRoutes) // a Hub draft's words in English, for its author to review
- await app.register(qrSignInRoutes) // sign a computer in by scanning its QR with a signed-in phone
- await app.register(deviceKeyRoutes) // the account's device key log: signing in is what trusts a device
- await app.register(deskRoutes) // the account's tabs, the same on every computer (lib/desk.ts)
- await app.register(connectorRoutes) // sign-in to GitHub, Slack, Google… for local agents (lib/connectorGateway.ts)
- await app.register(connectorVaultRoutes) // those connections sealed for the account's computers, which keep them in step
- await app.register(agentMessagesRoutes) // which tabs' harnesses may message each other (lib/agentMessages.ts)
- await app.register(superTabRoutes)
- await app.register(experimentalSettingsRoutes, { daemons: DAEMONS })
- // Availability is separate from opt-in: every account starts off, and its collection is retained.
- await app.register(zooRoutes, { daemons: DAEMONS, requireAccountOptIn: true })
+ await registerControlRoutes(app, { daemons: DAEMONS, count: redisCount })
logger.info(describeDaemonsSwitch(DAEMONS))
// Dedicated public subdomain app-proxy on its own port (Host-header routed → tunnelled to the node app).
diff --git a/backend/src/services/MachineService.computer.test.ts b/backend/src/services/MachineService.computer.test.ts
index a849d3970..0dbc52629 100644
--- a/backend/src/services/MachineService.computer.test.ts
+++ b/backend/src/services/MachineService.computer.test.ts
@@ -12,12 +12,16 @@ const create = vi.hoisted(() => vi.fn())
const planFindFirst = vi.hoisted(() => vi.fn())
const redisSet = vi.hoisted(() => vi.fn())
const consumeNewIdQuota = vi.hoisted(() => vi.fn())
+const findUnique = vi.hoisted(() => vi.fn())
+const update = vi.hoisted(() => vi.fn())
+const sessionUpdateMany = vi.hoisted(() => vi.fn())
vi.mock('../lib/prisma.js', () => ({
machineAlive: {},
prisma: {
- machine: { findMany, count, create, findUnique: vi.fn() },
+ machine: { findMany, count, create, findUnique, update },
subscriptionPlan: { findFirst: planFindFirst },
+ harnessSession: { updateMany: sessionUpdateMany },
},
}))
vi.mock('../lib/bus.js', () => ({
@@ -78,3 +82,77 @@ describe('resolveOrCreateForComputer', () => {
expect(consumeNewIdQuota).not.toHaveBeenCalled()
})
})
+
+// A Mac's team account (lib/teamSession.ts): its daemon becomes its own computer's machine, marked `team`, and never
+// one of the person's machines.
+describe('resolveForTeamComputer', () => {
+ const TEAM = 'b'.repeat(32)
+ const team = { sub: 'u1', email: '[email protected]', role: 'user', autonomousEnv: 'prod' as const,
+ harnessSessionId: 'team-session', harnessSessionKind: 'team' as const, harnessComputerId: TEAM }
+
+ it('creates its computer\'s machine as a team machine', async () => {
+ const out = await machineService.resolveForTeamComputer(team, TEAM, 'MacBook Pro · Team')
+ expect(out.created).toBe(true)
+ expect(create).toHaveBeenCalledWith({ data: expect.objectContaining({ userId: 'u1', computerId: TEAM, sessionKind: 'team' }) })
+ })
+
+ it('reuses its team machine', async () => {
+ findMany.mockResolvedValue([{ machineId: 'm1', billingStatus: 'not_required', sessionKind: 'team' }])
+ expect(await machineService.resolveForTeamComputer(team, TEAM, 'x')).toMatchObject({ created: false, machine: { machineId: 'm1' } })
+ })
+
+ it('refuses any other computer, and any session that is not a team one, before looking anything up', async () => {
+ await expect(machineService.resolveForTeamComputer(team, COMPUTER, 'x')).rejects.toMatchObject({ statusCode: 403, code: 'TEAM_SESSION_LIMITED' })
+ const { harnessSessionKind: _kind, ...computer } = team
+ await expect(machineService.resolveForTeamComputer(computer, TEAM, 'x')).rejects.toMatchObject({ statusCode: 403 })
+ expect(findMany).not.toHaveBeenCalled()
+ })
+
+ it('refuses a computer the account runs under a normal sign-in, rows from before the kind was kept included', async () => {
+ for (const sessionKind of ['computer', null, undefined]) {
+ findMany.mockResolvedValue([{ machineId: 'm1', billingStatus: 'not_required', sessionKind }])
+ await expect(machineService.resolveForTeamComputer(team, TEAM, 'x')).rejects.toMatchObject({ statusCode: 403, code: 'TEAM_SESSION_LIMITED' })
+ }
+ expect(create).not.toHaveBeenCalled()
+ })
+})
+
+describe('destroying a team machine', () => {
+ beforeEach(async () => {
+ const bus = await import('../lib/bus.js')
+ vi.mocked(bus.publishDown).mockResolvedValue(1 as never)
+ vi.mocked(bus.clearAgentPresence).mockResolvedValue(undefined as never)
+ })
+
+ it('signs its team account out with it, so it cannot come back as a new machine', async () => {
+ findUnique.mockResolvedValue({ machineId: 'm1', userId: 'u1', managerId: '', authMode: 'remote', billingStatus: 'not_required',
+ autonomousEnv: 'prod', computerId: 'b'.repeat(32), sessionKind: 'team' })
+ update.mockResolvedValue({})
+ sessionUpdateMany.mockResolvedValue({ count: 1 })
+ await machineService.destroy('a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4', { sub: 'u1', role: 'user', autonomousEnv: 'prod' })
+ expect(sessionUpdateMany).toHaveBeenCalledWith({
+ where: { userId: 'u1', kind: 'team', computerId: 'b'.repeat(32), OR: [{ revokedAt: null }, { revokedAt: { isSet: false } }] },
+ data: { revokedAt: expect.any(Date) },
+ })
+ })
+
+ it('signs its computer\'s team account out even when a normal sign-in served the row last', async () => {
+ findUnique.mockResolvedValue({ machineId: 'm1', userId: 'u1', managerId: '', authMode: 'remote', billingStatus: 'not_required',
+ autonomousEnv: 'prod', computerId: 'a'.repeat(32), sessionKind: 'computer' })
+ update.mockResolvedValue({})
+ sessionUpdateMany.mockResolvedValue({ count: 0 })
+ await machineService.destroy('a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4', { sub: 'u1', role: 'user', autonomousEnv: 'prod' })
+ // Only team sessions bound to that computer: a computer's or a phone's own sign-in is not touched.
+ expect(sessionUpdateMany).toHaveBeenCalledWith({
+ where: { userId: 'u1', kind: 'team', computerId: 'a'.repeat(32), OR: [{ revokedAt: null }, { revokedAt: { isSet: false } }] },
+ data: { revokedAt: expect.any(Date) },
+ })
+ })
+
+ it('touches no session for a machine with no computer', async () => {
+ findUnique.mockResolvedValue({ machineId: 'm1', userId: 'u1', managerId: '', authMode: 'remote', billingStatus: 'not_required', autonomousEnv: 'prod' })
+ update.mockResolvedValue({})
+ await machineService.destroy('a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4', { sub: 'u1', role: 'user', autonomousEnv: 'prod' })
+ expect(sessionUpdateMany).not.toHaveBeenCalled()
+ })
+})
diff --git a/backend/src/services/MachineService.ts b/backend/src/services/MachineService.ts
index db53f02f7..f56a99039 100644
--- a/backend/src/services/MachineService.ts
+++ b/backend/src/services/MachineService.ts
@@ -14,6 +14,8 @@ import { env } from '../config/env.js'
import { encryptMachineCredential } from '../lib/machineCredential.js'
import { machineBillingService } from './MachineBillingService.js'
import { storedAutonomousEnvironment, type AutonomousEnvironment } from '../lib/autonomousEnvironment.js'
+import { TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../lib/teamSession.js'
+import type { AuthUser } from '../lib/ssoAuth.js'
/** The agent's tier / how it runs Claude, resolved through its plan.
* 'self' | 'managed' = a docker agent-node on a manager host; 'remote' = the user's own computer
@@ -55,6 +57,9 @@ export interface OwnerMachine {
// Hostname of the COMPUTER on its last connect (remote machines) — secondary detail on the card,
// never the name. Null if no computer has ever connected.
hostname: string | null
+ // How that computer signed in on its last connect: `team` for a Mac's team account (lib/teamSession.ts),
+ // `computer` for any other sign-in, null before it was recorded.
+ sessionKind: 'team' | 'computer' | null
}
interface PlanInfo {
@@ -90,6 +95,7 @@ function toOwner(b: Machine, status = 'unknown', agentCount = 0, plan?: PlanInfo
engine: normalizeEngine(engine),
name: b.name ?? null,
hostname: b.hostname ?? null,
+ sessionKind: b.sessionKind === 'team' || b.sessionKind === 'computer' ? b.sessionKind : null,
}
}
@@ -419,6 +425,8 @@ export const machineService = {
computerId: string,
label: string,
claimedMachineId?: string,
+ /** How the computer is signing in, recorded on a machine created now (`Machine.sessionKind`). */
+ sessionKind?: 'team' | 'computer',
): Promise<{ machine: Machine; created: boolean }> {
// A caller that still holds a machine id we have DELETED must be told so, never quietly given a
// new machine. Deletion is soft, so `machineAlive` below simply does not find the old row — and
@@ -491,6 +499,7 @@ export const machineService = {
// Seeded from the computer's hostname so the card is never a bare id. The owner can rename it;
// a later connect only ever refreshes `hostname`, never this.
name: label.trim().slice(0, 120) || null,
+ ...(sessionKind ? { sessionKind } : {}),
},
})
await publishDeviceMachineListChanged(userId, { reason: 'created' }).catch(() => { /* best effort */ })
@@ -499,6 +508,27 @@ export const machineService = {
})
},
+ /**
+ * The machine a team session (lib/teamSession.ts) is: its own computer's, created on first sight as a team machine.
+ * Refused (403, which the CLI takes as signed out) for any other computer, and for a computer the account runs under
+ * a normal sign-in — a team session must never become one of the person's machines.
+ */
+ async resolveForTeamComputer(
+ user: AuthUser,
+ computerId: string,
+ label: string,
+ claimedMachineId?: string,
+ ): Promise<{ machine: Machine; created: boolean }> {
+ const refuse = (): AppError => new AppError(TEAM_SESSION_MESSAGE, 403, TEAM_SESSION_LIMITED)
+ if (user.harnessSessionKind !== 'team' || !user.harnessComputerId || computerId !== user.harnessComputerId) throw refuse()
+ const held = await prisma.machine.findMany({ where: { userId: user.sub, computerId, ...machineAlive }, select: { sessionKind: true } })
+ if (held.some((row) => row.sessionKind !== 'team')) throw refuse()
+ const resolved = await machineService.resolveOrCreateForComputer(user.sub, user.autonomousEnv, computerId, label, claimedMachineId, 'team')
+ // Another sign-in took the row between the check and here: still not this session's machine.
+ if (resolved.machine.sessionKind !== 'team') throw refuse()
+ return resolved
+ },
+
/** List a user's agents (with best-effort live status). Includes the api key (owner only). */
async listForUser(userId: string, autonomousEnv?: AutonomousEnvironment): Promise<OwnerMachine[]> {
const rows = await prisma.machine.findMany({
@@ -632,6 +662,14 @@ export const machineService = {
// down-frames to the adapter socket; connId '' = not client-scoped.
await publishDown(machineId, { connId: '', frame: { type: 'machine_revoked' } }).catch(() => { /* best effort */ })
await clearAgentPresence(machineId).catch(() => { /* best effort */ })
+ // A team sign-in bound to this computer ends with it (lib/teamSession.ts), whatever kind of sign-in served the row
+ // last: a team daemon must not come back as a new machine for the same computer.
+ if (binding.computerId) {
+ await prisma.harnessSession.updateMany({
+ where: { userId: binding.userId, kind: 'team', computerId: binding.computerId, OR: [{ revokedAt: null }, { revokedAt: { isSet: false } }] },
+ data: { revokedAt: new Date() },
+ }).catch((err: unknown) => logger.warn('team session revoke failed', { machineId, error: String(err) }))
+ }
} else {
// Managed: reap the container + node row in the background (idempotent on the manager → retryable).
void destroyNodeWithRetry(machineId, binding.managerId)
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 1a6f840a2..6872e32bd 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -1161,7 +1161,11 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (state.conversations.some(c => activeWork(c) && c.assignment?.agentId === target.id)) fail('WORK_ACTIVE', 'Finish active work before stopping this worker.')
// Administrative withdrawal never attests physical stopping or releases native capacity.
if (hostStop) releaseHarness(state, target.machineId, target.harnessId)
- if (actor.kind === 'agent') result.releasedBy = actor.machineOwnerId
+ if (actor.kind === 'agent') {
+ result.releasedBy = actor.machineOwnerId
+ // Which machine confirmed it: a team session's retry is answered only for its own (store.ts).
+ result.releasedMachineId = target.machineId
+ }
if (forceStop) result.forceReleased = target.id
} else if (target.workDecision === 'stop') {
fail('FORBIDDEN', 'Only its contributor or tab owner can force-withdraw a stopping worker.', 403)
diff --git a/backend/src/superTabs/credentials.test.ts b/backend/src/superTabs/credentials.test.ts
index e9d3b9eea..f0f561ab1 100644
--- a/backend/src/superTabs/credentials.test.ts
+++ b/backend/src/superTabs/credentials.test.ts
@@ -39,6 +39,8 @@ describe('findCredentials: every kind it removes', () => {
['jwt', 'an encrypted JWT (five segments)', fake.jwe()],
['harness', 'a Harness access token', fake.harness('hna')],
['harness', 'a Harness refresh token', fake.harness('hnr')],
+ ['harness', 'a Harness team access token', fake.harness('hta')],
+ ['harness', 'a Harness team refresh token', fake.harness('htr')],
['harness', 'a Harness handoff code', fake.harness('hnh')],
['harness', 'a Harness sign-in QR code', fake.harness('hnq')],
['harness', 'a Harness QR poll token', fake.harness('hnp')],
diff --git a/backend/src/superTabs/credentials.ts b/backend/src/superTabs/credentials.ts
index 096c43116..077df0282 100644
--- a/backend/src/superTabs/credentials.ts
+++ b/backend/src/superTabs/credentials.ts
@@ -1,5 +1,6 @@
import {
HARNESS_ACCESS_PREFIX, HARNESS_HANDOFF_PREFIX, HARNESS_QR_POLL_PREFIX, HARNESS_QR_PREFIX, HARNESS_REFRESH_PREFIX,
+ HARNESS_TEAM_ACCESS_PREFIX, HARNESS_TEAM_REFRESH_PREFIX,
} from '../lib/harnessTokenFormat.js'
/**
@@ -78,7 +79,9 @@ interface Rule {
accept: (secret: string) => boolean | number
}
-const HARNESS_PREFIXES = [HARNESS_ACCESS_PREFIX, HARNESS_REFRESH_PREFIX, HARNESS_HANDOFF_PREFIX, HARNESS_QR_PREFIX, HARNESS_QR_POLL_PREFIX]
+// A team session's tokens (lib/teamSession.ts) have their own prefixes; pasted, they are as live as any other sign-in.
+const HARNESS_PREFIXES = [HARNESS_ACCESS_PREFIX, HARNESS_REFRESH_PREFIX, HARNESS_TEAM_ACCESS_PREFIX, HARNESS_TEAM_REFRESH_PREFIX,
+ HARNESS_HANDOFF_PREFIX, HARNESS_QR_PREFIX, HARNESS_QR_POLL_PREFIX]
// Keys whose value is the secret: DB_PASSWORD, x-api-key, client_secret, access_token, "token": … Not `pwd` (a folder), and
// nothing public (.NET's publicKeyToken).
const KEY = String.raw`(?![\w.-]*public)[A-Za-z0-9_.-]*?(?:password|passwd|passphrase|secret|token|api[_-]?key|apikey|access[_-]?key|private[_-]?key|credentials?)`
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.ts
index 79a7e72f2..8844076e6 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -15,7 +15,9 @@ export interface ContributedMachine {
engines: string[]
maxAgents: number
paused: boolean
- observation?: MachineObservation & { receivedAt: number }
+ /** `sessionKind` is how the reporting machine is signed in, stamped from its session by the store, never taken from
+ * the report: `team` for a Mac's team account (lib/teamSession.ts), `computer` for any other. Absent on older readings. */
+ observation?: MachineObservation & { receivedAt: number; sessionKind?: 'team' | 'computer' }
/** Set by machine.remove: an online machine stays listed, paused, while its host deletes the Swarm's folders there, until
* the host says it cleaned up (machine.cleaned) or REMOVAL_FALLBACK_MS passes. An offline one leaves the list at once and
* its cleanup waits for its host (expireRemovals). */
diff --git a/backend/src/superTabs/native.ts b/backend/src/superTabs/native.ts
index 53e3bf2ab..9488419b0 100644
--- a/backend/src/superTabs/native.ts
+++ b/backend/src/superTabs/native.ts
@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto'
import type { Prisma, SuperTab, SuperTabNativeContext } from '@prisma/client'
import { z } from 'zod'
import type { AuthUser } from '../lib/ssoAuth.js'
+import { isTeamSession, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../lib/teamSession.js'
import { activeWork, agent, appendPullRequestUrls, author, conversation, fail, isLeads, stableId, SuperTabError,
type Actor, type Agent, type Author, type Conversation, type SuperTabState } from './model.js'
import { canReadProject, groupProject, readConversation } from './projects.js'
@@ -28,6 +29,8 @@ interface Deps {
row(tx: Transaction, user: AuthUser, tabId: string): Promise<{ row: SuperTab; state: SuperTabState }>
agentGrant(tx: Transaction, state: SuperTabState, target: Agent): Promise<void>
contribution(tx: Transaction, state: SuperTabState, actor: Actor, command: { machineId: string }): Promise<Grant>
+ /** The one machine a team session (lib/teamSession.ts) hosts for; null for any other sign-in. */
+ teamHost(tx: Transaction, user: AuthUser): Promise<string | null>
}
const json = (value: unknown): Prisma.InputJsonValue => JSON.parse(JSON.stringify(value)) as Prisma.InputJsonValue
const digest = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex')
@@ -75,6 +78,8 @@ export class SuperTabNativeStore {
}
async open(user: AuthUser, tabId: string, input: z.infer<typeof openNativeSchema>) {
+ // A person opens a terminal; a team session has no person to open one as.
+ if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)
const request = openNativeSchema.parse(input)
return this.deps.transaction(async tx => {
const { state } = await this.deps.row(tx, user, tabId)
@@ -108,8 +113,11 @@ export class SuperTabNativeStore {
?? fail('NOT_FOUND', 'This terminal context is unavailable.', 404)
const binding = record.binding as unknown as Binding
if (binding.machineOwnerId !== user.sub) fail('FORBIDDEN', 'Only the execution host can record this terminal.', 403)
+ // A team session records only the terminals of its own machine's agents.
+ const team = await this.deps.teamHost(tx, user)
+ if (team !== null && binding.machineId !== team) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)
const verified = await this.validate(tx, state, record)
- return { ...verified, row, state, record }
+ return { ...verified, row, state, record, team: team !== null }
}
async read(user: AuthUser, tabId: string, contextId: string) {
@@ -171,7 +179,7 @@ export class SuperTabNativeStore {
async append(user: AuthUser, tabId: string, contextId: string, input: NativeEvent) {
const event = nativeEventSchema.parse(input)
return this.deps.transaction(async tx => {
- const { row, state, record, binding, target, group } = await this.hosted(tx, user, tabId, contextId)
+ const { row, state, record, binding, target, group, team } = await this.hosted(tx, user, tabId, contextId)
const eventId = stableId('native-event', contextId, event.turnId, event.kind), requestHash = digest(event)
const prior = await tx.superTabOperation.findUnique({ where: { id: eventId } })
if (prior) {
@@ -204,8 +212,12 @@ export class SuperTabNativeStore {
await tx.superTabDelivery.create({ data: { id: stableId(eventId, recipient), tabId, conversationId: group.id,
messageId: eventId, nativeContextId: contextId, agentId: recipient, machineId: lead.machineId, machineOwnerId: lead.machineOwnerId,
assignmentId: activeWork(group) && group.assignment?.agentId === recipient ? group.assignment.id : null,
- membershipGeneration: lead.membershipGeneration, authorKind: 'person', authorId: binding.operator.id,
- authorGeneration: binding.operator.membershipGeneration } })
+ membershipGeneration: lead.membershipGeneration,
+ // What a team host (lib/teamSession.ts) reports is the agent's word, never the person's: it reaches the Lead as
+ // from the agent, so a team account cannot put words in the mouth of the person who opened the terminal.
+ ...(team
+ ? { authorKind: 'agent', authorId: target.id, authorGeneration: target.membershipGeneration }
+ : { authorKind: 'person', authorId: binding.operator.id, authorGeneration: binding.operator.membershipGeneration }) } })
}
noteProjectReports(state, [{ id: eventId, conversationId: group.id, author: observedBy, text,
replyTo: null, recipients }], revision, Date.now())
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index d66ae0270..a08efd735 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -3,6 +3,7 @@ import { createHash } from 'node:crypto'
import type { Prisma, PrismaClient, SuperTab, SuperTabDelivery, SuperTabMessage } from '@prisma/client'
import type { AuthUser } from '../lib/ssoAuth.js'
import { machineAlive } from '../lib/prisma.js'
+import { isTeamSession, teamMachine, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../lib/teamSession.js'
import { machineShareGrant, sharedVia } from '../lib/machineSharePolicy.js'
import { machineBillingAllowsDataPlane } from '../lib/billingState.js'
import { applyCommand, authorizeCommandAccess, operationSchema, PAIR_CHAIN_LIMIT, postable, type Command, type CommandContext } from './commands.js'
@@ -127,12 +128,68 @@ export class SuperTabStore {
row: async (tx, user, tabId) => { const row = await this.row(tx, user, tabId); return { row, state: stateOf(row) } },
agentGrant: (tx, state, target) => this.agentGrant(tx, state, target),
contribution: (tx, state, actor, command) => this.contribution(tx, state, actor, command),
+ teamHost: (tx, user) => this.teamHost(tx, user),
})
}
+ // ── A Mac's team account (lib/teamSession.ts) ────────────────────────────────────────────────────
+ // Its daemon is signed in as the person, so `user.sub` alone would let it speak for the person and for every machine
+ // of theirs. It may host only its own machine and speak only as the agents running there.
+
+ /** The one machine a team session hosts for; null for any other sign-in. One with no machine to act for does nothing. */
+ private async teamHost(tx: Transaction, user: AuthUser): Promise<string | null> {
+ if (!isTeamSession(user)) return null
+ return (await teamMachine(user, tx))?.machineId ?? fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)
+ }
+
+ /** A host route of a team session must name its own machine. */
+ private async hostFor(tx: Transaction, user: AuthUser, machineId: string): Promise<void> {
+ const team = await this.teamHost(tx, user)
+ if (team !== null && team !== machineId) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)
+ }
+
+ /** What only the person does: a team session has no person to be. */
+ private personOnly(user: AuthUser): void {
+ if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)
+ }
+
+ /**
+ * What a team session's agent may command beyond the Swarm's own rules for that agent: a machine is the person's to
+ * contribute, pause or remove, and nothing may start, add, move or drive an agent on another machine. Messages and
+ * work reports go to the Swarm as from any agent. An agent that is gone is left to the command's own answer.
+ */
+ private teamCommand(state: SuperTabState, team: string, user: AuthUser, command: Command): void {
+ const refuse = () => fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)
+ const onTeam = (agentId: string) => {
+ const target = state.agents.find(a => a.id === agentId)
+ if (target && target.machineId !== team) refuse()
+ }
+ switch (command.type) {
+ case 'machine.contribute': case 'machine.pause': case 'machine.remove': return refuse()
+ case 'machine.cleaned': case 'tab.project': case 'agent.add':
+ if (command.machineId !== team) refuse()
+ return
+ case 'agent.rebind':
+ if (command.machineId !== team) refuse()
+ return onTeam(command.agentId)
+ case 'agent.start':
+ if (command.request.machineId !== team) refuse()
+ return
+ case 'agent.screen': case 'agent.input': case 'work.assign': case 'conversation.agent':
+ case 'agent.release': case 'agent.stopLease': case 'agent.remove':
+ return onTeam(command.agentId)
+ case 'agent.sessionClosed': {
+ const closing = state.closingSessions?.find(c => c.agentId === command.agentId && c.harnessId === command.harnessId && c.machineOwnerId === user.sub)
+ if (closing && closing.machineId !== team) refuse()
+ return
+ }
+ }
+ }
+
private policyId(user: AuthUser) { return stableId('routing-policy', user.sub, user.autonomousEnv) }
async accountPolicy(user: AuthUser) {
+ this.personOnly(user)
const row = await this.db.routingPolicy.findUnique({ where: { id: this.policyId(user) } })
if (!row) return { policy: DEFAULT_ROUTING_POLICY, revision: 0, isDefault: true }
const { policy } = effectivePolicy(row.policy, null)
@@ -140,6 +197,7 @@ export class SuperTabStore {
}
async saveAccountPolicy(user: AuthUser, revision: number, input: RoutingPolicy) {
+ this.personOnly(user)
const policy = routingPolicySchema.parse(input)
return transaction(this.db, async tx => {
const id = this.policyId(user)
@@ -171,9 +229,16 @@ export class SuperTabStore {
}
private async actor(tx: Transaction, user: AuthUser, state: SuperTabState, agentId?: string): Promise<Actor> {
- if (!agentId) return { kind: 'person', userId: user.sub, email: user.email }
+ const team = await this.teamHost(tx, user)
+ if (!agentId) {
+ // A team session never speaks or reads as the person.
+ if (team !== null) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)
+ return { kind: 'person', userId: user.sub, email: user.email }
+ }
const target = agent(state, agentId)
if (target.machineOwnerId !== user.sub) fail('FORBIDDEN', 'Only the execution host can speak as this agent.', 403)
+ // ...and as an agent only one running on its own machine, never the person's agents elsewhere.
+ if (team !== null && target.machineId !== team) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)
await this.agentGrant(tx, state, target)
return { kind: 'agent', agentId, machineOwnerId: user.sub }
}
@@ -221,6 +286,7 @@ export class SuperTabStore {
}
async create(user: AuthUser, operationId: string, name: string, projectVisibility?: ProjectVisibility) {
+ this.personOnly(user)
const id = stableId('super-tab', user.autonomousEnv, user.sub, operationId)
const requestHash = hash({ name, ...(projectVisibility ? { projectVisibility } : {}) })
return transaction(this.db, async tx => {
@@ -237,6 +303,7 @@ export class SuperTabStore {
}
async list(user: AuthUser, after?: string) {
+ this.personOnly(user)
const rows = await this.db.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, memberIds: { has: user.sub },
...(after ? { id: { gt: after } } : {}) }, orderBy: { id: 'asc' }, take: 101 })
return { tabs: rows.slice(0, 100).map(row => {
@@ -246,6 +313,7 @@ export class SuperTabStore {
}
async invitations(user: AuthUser) {
+ this.personOnly(user)
const email = user.email.trim().toLowerCase()
const rows = await this.db.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, invitedEmails: { has: email } }, take: 100 })
return rows.flatMap(row => {
@@ -256,6 +324,7 @@ export class SuperTabStore {
}
async sharing(user: AuthUser, tabId: string) {
+ this.personOnly(user)
return transaction(this.db, async tx => {
const state = stateOf(await this.row(tx, user, tabId))
requireSharingOwner(state, user.sub)
@@ -264,6 +333,7 @@ export class SuperTabStore {
}
async saveSharing(user: AuthUser, tabId: string, input: SaveSharing) {
+ this.personOnly(user)
const request = saveSharingSchema.parse(input)
return transaction(this.db, async tx => {
const row = await this.row(tx, user, tabId), state = stateOf(row)
@@ -288,6 +358,7 @@ export class SuperTabStore {
/** A signed-in preview contains no projects, people, machines, or conversation data. It never joins. */
async previewJoin(user: AuthUser, tabId: string, token?: string) {
+ this.personOnly(user)
return transaction(this.db, async tx => {
const state = stateOf(await this.row(tx, user, tabId))
const sharing = authorizeSwarmJoin(state, user.email, token)
@@ -297,6 +368,7 @@ export class SuperTabStore {
}
async join(user: AuthUser, tabId: string, input: JoinSwarm) {
+ this.personOnly(user)
const request = joinSwarmSchema.parse(input)
return transaction(this.db, async tx => {
const row = await this.row(tx, user, tabId), state = stateOf(row)
@@ -377,15 +449,19 @@ export class SuperTabStore {
ended = []
const row = await this.row(tx, user, tabId)
const original = stateOf(row)
+ const team = await this.teamHost(tx, user)
// Removal retries can arrive after the actor itself left. Return only this host's exact prior receipt.
if (command.type === 'agent.remove' && asAgentId === command.agentId && !original.agents.some(a => a.id === asAgentId)) {
const prior = await tx.superTabOperation.findUnique({ where: { id: stableId(tabId, `agent:${asAgentId}`, operationId) } })
- if (prior && prior.requestHash === hash(command) && (prior.result as Record<string, unknown>).releasedBy === user.sub) {
+ const result = prior?.result as Record<string, unknown> | undefined
+ // A team session's only if the removed agent ran on its machine; a receipt from before that was recorded is not.
+ if (prior && prior.requestHash === hash(command) && result?.releasedBy === user.sub && (team === null || result.releasedMachineId === team)) {
return { revision: prior.revision, result: prior.result }
}
fail('FORBIDDEN', 'Only the execution host can confirm this removal.', 403)
}
if (hostMachineId && !['agent.startDispatch', 'agent.started', 'agent.startFailed', 'agent.startSettled', 'route.modelResult'].includes(command.type)) fail('FORBIDDEN', 'A host can only settle its queued starts.', 403)
+ if (team !== null && !hostMachineId) this.teamCommand(original, team, user, command)
// A removed agent's or machine's host confirms its close or cleanup as the machine owner, who may have left the Swarm with it.
const actor: Actor = command.type === 'agent.sessionClosed' || command.type === 'machine.cleaned' ? { kind: 'person', userId: user.sub, email: user.email }
: hostMachineId && 'startId' in command
@@ -807,9 +883,13 @@ export class SuperTabStore {
const unavailable = () => fail('NOT_FOUND', 'This role is unavailable.', 404)
const project = projectsOf(state).find(p => p.id === projectId) ?? unavailable()
const role = project.roles?.find(r => r.id === roleId) ?? unavailable()
+ const team = await this.teamHost(tx, user)
if (asAgentId) {
await this.actor(tx, user, state, asAgentId)
if (ledProject(state, asAgentId)?.id !== project.id) unavailable()
+ } else if (team !== null) {
+ // A team session is never the project's owner: it reads a text only for an agent its own machine hosts.
+ if (!await this.hostsProject(tx, state, user, project.id, team)) unavailable()
} else if (!(user.sub === project.ownerId && state.people.some(p => p.id === user.sub)) && !await this.hostsProject(tx, state, user, project.id)) {
unavailable()
}
@@ -819,9 +899,11 @@ export class SuperTabStore {
})
}
- /** Whether this account could host one of the project's agents now, by the same live grant as its host reads. */
- private async hostsProject(tx: Transaction, state: SuperTabState, user: AuthUser, projectId: string): Promise<boolean> {
- for (const target of state.agents.filter(a => a.machineOwnerId === user.sub && agentProjectId(state, a) === projectId)) {
+ /** Whether this account could host one of the project's agents now, by the same live grant as its host reads; on
+ * [machineId] alone when given. */
+ private async hostsProject(tx: Transaction, state: SuperTabState, user: AuthUser, projectId: string, machineId?: string): Promise<boolean> {
+ for (const target of state.agents.filter(a => a.machineOwnerId === user.sub && (!machineId || a.machineId === machineId)
+ && agentProjectId(state, a) === projectId)) {
try { agent(state, target.id); await this.agentGrant(tx, state, target); return true }
catch (error) { if (!(error instanceof SuperTabError)) throw error }
}
@@ -872,6 +954,7 @@ export class SuperTabStore {
* requester changed, is answered with the reason instead, so input is never typed late or into another pane. */
async hostTerminal(user: AuthUser, machineId: string) {
return transaction(this.db, async tx => {
+ await this.hostFor(tx, user, machineId)
const owned = await tx.machine.findFirst({ where: { machineId, userId: user.sub, autonomousEnv: user.autonomousEnv, ...machineAlive } })
if (!owned || !machineBillingAllowsDataPlane(owned)) fail('HOST_UNAVAILABLE', 'This execution host is unavailable.', 403)
const now = this.now()
@@ -970,6 +1053,7 @@ export class SuperTabStore {
/** The caller's own tags in this Swarm, newest first: still waiting, or answered and marked done. */
async mentions(user: AuthUser, tabId: string, state: 'waiting' | 'earlier') {
+ this.personOnly(user)
return transaction(this.db, async tx => {
const row = await this.row(tx, user, tabId)
return { mentions: await listMentions(tx, tabId, stateOf(row), { kind: 'person', userId: user.sub, email: user.email }, this.now(), state === 'waiting') }
@@ -1018,6 +1102,7 @@ export class SuperTabStore {
/** Narrow authority: the machine owner can finish a specific queued start,
* never submit arbitrary commands as its initiating person or lead. */
private async poolHostActor(tx: Transaction, user: AuthUser, state: SuperTabState, machineId: string, startId: string): Promise<Actor> {
+ await this.hostFor(tx, user, machineId)
const start = state.starts?.find(s => s.id === startId) ?? fail('NOT_FOUND', 'This start is unavailable.', 404)
const pool = machineContribution(state, machineId)
if (!pool || pool.contributorId !== user.sub || pool.generation !== start.poolGeneration || start.request.machineId !== machineId || start.machineOwnerId !== user.sub) {
@@ -1040,6 +1125,7 @@ export class SuperTabStore {
async hostPools(user: AuthUser, machineId: string) {
return transaction(this.db, async tx => {
+ await this.hostFor(tx, user, machineId)
const owned = await tx.machine.findFirst({ where: { machineId, userId: user.sub, autonomousEnv: user.autonomousEnv, ...machineAlive } })
if (!owned || !machineBillingAllowsDataPlane(owned)) fail('HOST_UNAVAILABLE', 'This execution host is unavailable.', 403)
const rows = await tx.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, machineIds: { has: machineId } }, ...HOST_TABS })
@@ -1075,6 +1161,7 @@ export class SuperTabStore {
/** The owner's Swarms with the Local models add-on: what the owner's computer creates on grid and keeps in step. */
async hostGrids(user: AuthUser) {
+ this.personOnly(user)
const rows = await this.db.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, ownerId: user.sub }, take: 100 })
return rows.flatMap(row => swarmGridRow(row.id, stateOf(row)) ?? [])
}
@@ -1082,6 +1169,7 @@ export class SuperTabStore {
async observeMachine(user: AuthUser, tabId: string, machineId: string, input: MachineObservation) {
const observation = machineObservationSchema.parse(input)
return transaction(this.db, async tx => {
+ await this.hostFor(tx, user, machineId)
const row = await this.row(tx, user, tabId), state = structuredClone(stateOf(row))
const pool = machineContribution(state, machineId)
if (!pool || pool.contributorId !== user.sub || pool.generation !== observation.generation) fail('CONTRIBUTION_REVOKED', 'Read the current machine contribution.', 403)
@@ -1098,7 +1186,9 @@ export class SuperTabStore {
return { revision: row.revision + 1 }
}
recordAgentPresence(state, machineId, observation.runningHarnessIds, now)
- pool.observation = { ...observation, quotas: observation.quotas.filter(q => contributedEngines(pool, observation).includes(q.engine)), receivedAt: now }
+ pool.observation = { ...observation, quotas: observation.quotas.filter(q => contributedEngines(pool, observation).includes(q.engine)), receivedAt: now,
+ // How the machine is signed in, from the session that reported and never from the report (lib/teamSession.ts).
+ sessionKind: isTeamSession(user) ? 'team' : 'computer' }
// Current-generation physical stop proof also finishes a close whose membership was already withdrawn.
for (const proof of observation.stoppedReservations ?? []) {
if (!observation.stoppedHarnessIds.includes(proof.harnessId)) continue
@@ -1118,6 +1208,7 @@ export class SuperTabStore {
async hostTabs(user: AuthUser, machineId: string) {
return transaction(this.db, async tx => {
+ await this.hostFor(tx, user, machineId)
const owned = await tx.machine.findFirst({ where: { machineId, userId: user.sub, autonomousEnv: user.autonomousEnv, ...machineAlive } })
if (!owned || !machineBillingAllowsDataPlane(owned)) fail('HOST_UNAVAILABLE', 'This execution host is unavailable.', 403)
const rows = await tx.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, machineIds: { has: machineId } }, ...HOST_TABS })
@@ -1170,6 +1261,8 @@ export class SuperTabStore {
}
async mayObserve(user: AuthUser, tabId: string, machineId: string, harnessId: string, machineOwnerId: string): Promise<boolean> {
+ // Watching is a person's: a team session has no person to watch as.
+ if (isTeamSession(user)) return false
try {
return await transaction(this.db, async tx => {
const state = stateOf(await this.row(tx, user, tabId))
@@ -1188,6 +1281,7 @@ export class SuperTabStore {
* its outstanding native sessions, without regaining conversation access. */
async hostAssignments(user: AuthUser, machineId: string) {
return transaction(this.db, async tx => {
+ await this.hostFor(tx, user, machineId)
const owned = await tx.machine.findFirst({ where: { machineId, userId: user.sub, autonomousEnv: user.autonomousEnv, ...machineAlive } })
if (!owned || !machineBillingAllowsDataPlane(owned)) fail('HOST_UNAVAILABLE', 'This execution host is unavailable.', 403)
const rows = await tx.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, machineIds: { has: machineId } }, ...HOST_TABS })
@@ -1272,6 +1366,7 @@ export class SuperTabStore {
const previous = state.agents.find(a => a.id === agentId && a.membershipGeneration === row.membershipGeneration)
const owner = row.machineOwnerId ?? previous?.machineOwnerId
if (owner !== user.sub) fail('FORBIDDEN', 'Only the recorded execution host can read this receipt.', 403)
+ await this.hostFor(tx, user, row.machineId)
const machine = await tx.machine.findFirst({ where: { machineId: row.machineId, userId: owner,
autonomousEnv: user.autonomousEnv, ...machineAlive } })
if (!machine || !machineBillingAllowsDataPlane(machine)) fail('HOST_UNAVAILABLE', 'This execution host is unavailable.', 403)
@@ -1358,6 +1453,7 @@ export class SuperTabStore {
const assignment = group?.assignment
if (!assignment || assignment.execution.machineOwnerId !== user.sub) fail('FORBIDDEN', 'Only the execution host can confirm this stop.', 403)
const execution = assignment.execution
+ await this.hostFor(tx, user, execution.machineId)
const machine = await tx.machine.findFirst({ where: { machineId: execution.machineId, userId: user.sub, autonomousEnv: user.autonomousEnv, ...machineAlive } })
if (!machine) fail('HOST_UNAVAILABLE', 'This execution host is unavailable.', 403)
const id = stableId('stop', tabId, assignmentId)
diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.ts
index 78701c606..bf4df8341 100644
--- a/backend/vitest.super-tabs.config.ts
+++ b/backend/vitest.super-tabs.config.ts
@@ -1,4 +1,4 @@
import { defineConfig } from 'vitest/config'
-export default defineConfig({ test: { include: ['integration/superTabs.test.ts', 'integration/superTabSharing.test.ts', 'integration/superTabGithub.test.ts'], hookTimeout: 120000, testTimeout: 30000,
+export default defineConfig({ test: { include: ['integration/superTabs.test.ts', 'integration/superTabSharing.test.ts', 'integration/superTabGithub.test.ts', 'integration/superTabTeam.test.ts'], hookTimeout: 120000, testTimeout: 30000,
fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })
diff --git a/docs/plans/2026-10-24-swarm-team-account.md b/docs/plans/2026-10-24-swarm-team-account.md
new file mode 100644
index 000000000..390181667
--- /dev/null
+++ b/docs/plans/2026-10-24-swarm-team-account.md
@@ -0,0 +1,98 @@
+# Swarm team account implementation plan
+
+> **For agentic workers:** run each behaviour test red, implement, then verify green. Branch from current `main`; one PR per task.
+
+**Goal:** A teammate's agents can work on my Mac without reading my personal data, and their commits never use my GitHub login. With both in place, a Swarm can pool every company machine's spare capacity safely.
+
+**Why:** Company machines also hold personal mail, photos, browser sessions and personal accounts. In one live Swarm (6 people, 26 agents, 21–23 Oct 2026), 18 of 113 agent starts were one person's Lead starting an agent on another person's machine. Each ran as that machine's owner with full permissions: the owner's files, GitHub login and subscription. People asked which machine their work went to, asked for work on their own machine, and removed a machine from the Swarm.
+
+**Decision:** a separate standard macOS user for team work, not a VM. It keeps native toolchains (Xcode, Flutter desktop), costs one admin password, and separates company work from personal data. A VM stays for a future public Swarm or jobs that need administrator rights.
+
+## The experience
+
+1. A person's Mac joins a Swarm. macOS asks once for an administrator password. There is no Harness setup screen.
+2. Harness creates a hidden standard user, makes the owner's home folder private, and runs a second Harness daemon as that user. It appears as its own machine, e.g. "MacBook Pro · Team", marked **Private ✓** once the privacy check passes.
+3. Teammates' work only runs on Team machines. The owner's own agents keep running as the owner, as today.
+4. The owner approves Claude Code and Codex for team work once, in the browser. That is an explicit choice to share that subscription.
+5. Agents push and open PRs with a Harness GitHub App token for that one repository. The machine owner's GitHub login is never used.
+
+A machine used only for agents (a Mac mini, a Linux or Windows box) opts in as a whole with `harness team on`; it needs no second user.
+
+## Findings that shape the design
+
+- **Sign-in exists.** A signed-in computer can mint a one-time handoff code (`POST /api/auth/handoff`, 90 s, single use) that a new client redeems for its own session (`backend/src/lib/harnessSession.ts`).
+- **Identity is per user.** The computer id lives in the daemon's data folder (`cli/src/config/env.ts`), so a daemon running as another user gets its own machine id.
+- **A normal computer session is too strong.** The agent client reaches the account's other machines through the relay (`cli/src/agentClient/daemon.ts`, `machine_select`). A team daemon signed in as an ordinary computer would let a team agent run `harness ps --machine <owner's Mac>` or read the owner's personal harnesses. The team daemon needs its own session kind.
+- **A second account alone is not private.** On macOS the home folder defaults to `drwxr-x---` with group `staff`, and every local account is in `staff`. Folders like `~/code` (755) and files like `~/.gitconfig` (644) are readable by any other local account. Setup must make the home folder `700` and prove it.
+- **GitHub user tokens cannot be narrowed to one repository.** Installation tokens can (repository and permission scoped, one hour). Version one uses installation tokens and attributes the requester as GitHub's Copilot coding agent does: the PR is opened by the Harness app, assigned to the person who delegated, with that person as commit co-author. A "John via Harness" user-token mode can follow if wanted; it trades the one-repository limit for the attribution line.
+
+## Constraints
+
+- Never weaken an existing permission: a team session can do strictly less than a computer session.
+- Never fall back to running a teammate's work as the machine owner when the team account is missing, failing its privacy check, or offline. Report it on the machine instead.
+- Credentials stay out of chat and out of the team account where possible: no copying the owner's GitHub, Claude or Codex login into it.
+- Tests use disposable data folders, disposable MongoDB and the fresh-Mac VM rig. Never create a user, change permissions or install a launchd job on a developer's own Mac in tests.
+- Existing contributed machines keep their running agents. New cross-person starts follow the new rule; the release notes say so.
+
+## Task 1: Team session kind (backend)
+
+Files: `backend/src/lib/harnessSession.ts`, `backend/src/routes/auth.ts`, the relay's machine selection in `backend/src/lib/deviceWs.ts`/`bus.ts`, Super Tab host routes.
+
+- [x] Tests: a team session cannot select another machine, list or attach the account's harnesses, mint a handoff, change account settings or sign phones in; it can run its own daemon, receive Swarm starts for its own machine and post as its Swarm agents.
+- [x] Add `team` to `HarnessSessionKind`. A computer session mints a team handoff code; redeeming it creates a team session bound to the redeeming computer id.
+- [x] Enforce the limits server-side in the relay and routes, not in the CLI.
+
+How it works (`backend/src/lib/teamSession.ts` has the full list):
+
+- **Minting.** `POST /api/auth/handoff` with `{ "kind": "team" }` from a computer session or an Autonomous sign-in returns `{ code, expiresIn, kind: "team" }` (90 s, single use; the code is `hnh_` plus 43 URL-safe characters). Without a body, or with `{ "kind": "viewer" }`, it mints a viewer code exactly as before, and the answer now also says `kind: "viewer"`. A team or phone session can never mint. `POST /api/auth/handoff/redeem` takes `{ code, label, computerId }` and returns `{ token, refreshToken, expiresIn, autonomousEnv, kind }`, where `kind` is `team` or `viewer`. A client should store a team sign-in only when the answer says `kind: "team"`. Any failure gets the same 401 `HANDOFF_INVALID`: a spent or expired code, a team code without a valid `computerId`, or a team code for a computer the account already runs under a normal sign-in. A team session may use `/api/auth/refresh` and `/api/auth/revoke` like any session.
+- **A computer converting itself (`harness team on`).** `{ "kind": "team", "computerId": "<this computer>" }` asks for a code that turns that computer into a team machine and keeps its computer id, so its Swarm contributions and history survive. Only the computer itself may ask:
+ - its own Harness computer session, whose recorded computer id matches (QR sign-ins record it from now on); or
+ - any sign-in of the account, with `"proof": { "machineId", "at", "sig" }`. `sig` is base64 ed25519 over `teamConversionMessage(userId, computerId, machineId, at)` (`lib/teamSession.ts`), signed by that machine's key on the account's device key log. It must be within 5 minutes of the server's clock and is accepted once. This is the route for a computer signed in with Autonomous, whose sign-in names no computer.
+
+ Every other caller gets 403 `HANDOFF_NOT_ALLOWED`, so a computer id already in ordinary use stays refused to everyone else. The code redeems only with that same `computerId`. Redeeming ends the computer's Harness computer sessions, marks its machine rows `team` and creates the team session, all in one transaction. A socket still connected under the old sign-in is then closed (4009). The backend cannot end an Autonomous sign-in. The CLI must discard it, because if it connects again the machine becomes an ordinary machine again and the team session can act for nothing.
+- **Team tokens.** A team session's access and refresh tokens are `hta_…` and `htr_…`, not the `hna_`/`hnr_` of other Harness sessions. A server running code from before team sessions read any Harness session it did not recognise as a phone's, which reaches every machine and route. Under the new prefixes such a server, during a rolling deploy or after a rollback, refuses a team token instead.
+- **Deny by default.** Authentication refuses a team session unless the caller opts in. Only two callers opt in: the REST gate and the machine socket. The web relay (`machine_select`, attach), the device socket, Agent Messages, the observer socket and the phone's routes all refuse it. Over REST, a team session may call only the routes in `TEAM_ROUTES`. Every other route answers 403 `TEAM_SESSION_LIMITED`.
+- **Its own machine only.** The machine socket accepts a team session only as its bound computer's machine. A team session may use Super Tab host routes only for that machine, and may speak only as agents running there, never as the person. It cannot contribute, pause or remove a machine, or start, add or drive an agent on another machine. It may share only its own harnesses, and only for a Swarm (the read-only views of Swarm members). It may remove only its own key from the device key log, and it reads the log without marking any key as in use. What it records from a native terminal reaches the Lead as from the agent, never as from the person who opened the terminal. Deleting a machine signs out any team session bound to that machine's computer, whichever sign-in served the machine last.
+- **GitHub token (Task 4).** `POST /api/super-tabs/:tabId/github-token?asAgentId=…` with `{ machineId }` is on the list. A team session must name one of its agents and its own machine. A body naming any other machine, or none, is refused before the route runs. The store's `githubAssignment` resolves the agent through `actor()`, which refuses a team session speaking for an agent on another machine. Computer sessions are unchanged. Team tokens (`hta_`, `htr_`) are among the Harness tokens Swarm chat removes when pasted (Task 5).
+- **Visible for Task 3.** `Machine.sessionKind` is `team` or `computer`: how the computer signed in on its last connection. When a normal sign-in takes over a team machine, the field changes to `computer` before that socket attaches, so the machine stops being a team machine at once. Null on older rows, which are never team machines. A team session acts only for a row marked `team`. The owner's machine list (`GET /api/machines`) also returns it as `sessionKind`. A Super Tab machine observation gets `observation.sessionKind` from the session that reported it, never from the report.
+
+## Task 2: Team account setup and privacy check (CLI)
+
+Files: new `cli/src/team/` (setup script, launchd job, privacy check), `cli/src/superTabs/host.ts` (observation), CLI help.
+
+- [ ] `harness team setup` builds one privileged script and runs it behind the macOS administrator prompt: a hidden standard user with a random password, its home folder, the owner's home set to `700`, the Harness runtime copied into the team home, and a `/Library/LaunchDaemons` job running the team daemon as that user.
+- [ ] The owner's daemon mints a team handoff code and passes it to the team daemon over a file only the team user can read; the code is single use and expires in 90 seconds.
+- [ ] Privacy check, run as the team user: reading a sentinel file in the owner's home, listing it, reading `~/.gitconfig`, the login Keychain folder and a browser profile path must all fail. The result is published as the machine's observation and shown as **Private ✓** or the failing item.
+- [ ] `harness team on|off` marks a whole dedicated machine as a team machine.
+- [ ] `harness team remove` undoes setup: stops the job, deletes the user and its home, leaves the owner's folder permissions as set.
+- [ ] Engine sign-in in the team account: Harness starts Claude Code's long-lived token setup and Codex device sign-in there and surfaces the approval link to the owner.
+- [ ] End to end in the VM rig: setup from a signed-in owner, the check passes, a Swarm start lands in the team account, removal leaves nothing behind.
+
+## Task 3: Routing rule and automatic setup (backend, CLI)
+
+Files: `backend/src/superTabs/machines.ts`, `store.ts`, `routeDecisions.ts`; `cli/src/superTabs/host.ts`.
+
+- [ ] Tests: a start for a project owned by someone other than the machine's contributor is refused on a personal machine and admitted on a Team machine whose privacy check passed; routing proposes only eligible machines and says why the others were skipped.
+- [ ] Joining a Swarm, or contributing a Mac, asks the CLI to run `harness team setup` once. A declined or failed prompt leaves the Mac serving only its owner's projects, with one line on the machine saying why.
+- [ ] Migration: existing contributions keep running agents; new cross-person starts follow the rule.
+
+## Task 4: Harness GitHub App (backend, CLI)
+
+Files: new `backend/src/github/` (app auth, token endpoint), `cli/src/superTabs/start.ts` (environment), a `harness git-credential` helper.
+
+- [ ] Register the app (contents and pull requests write, checks and actions read). The owner installs it on the organization.
+- [ ] Endpoint: a Swarm agent's daemon asks for a token for its current assignment; the backend checks the assignment and the project's repository and mints an installation token for that one repository, one hour.
+- [ ] Team account sessions get `credential.helper = !harness git-credential` and `GH_TOKEN` from the same source, refreshed before expiry. The owner's `gh` and git credentials are never read.
+- [ ] Commits carry `Co-authored-by:` the requesting person and trailers naming the agent and machine; the PR is assigned to the requester.
+- [ ] Tests with a fake GitHub: wrong assignment, other repository and expired token are refused.
+
+## Task 5: Secrets in Swarm chat (backend)
+
+Files: `backend/src/superTabs/commands.ts` (`message.send`), a small detector module.
+
+- [ ] Tests for JWTs, GitHub tokens, OpenAI and Anthropic keys, AWS keys, Slack tokens and private key blocks; ordinary hashes and commit ids pass.
+- [ ] Redact before storing, keep the rest of the message, and tell the sender what was removed and that the credential should be revoked.
+
+## Out of scope
+
+VMs; team accounts on Windows and Linux (dedicated machines use `harness team on`); blocking the team user from the owner's local network services with per-user firewall rules (next); pooling or reselling subscriptions.