The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat: sign a headless box in with a ticket from the phone (#1021)
0xken1550da5db82479
diff --git a/backend/src/lib/harnessSession.ts b/backend/src/lib/harnessSession.tsindex f2ba7618f..b6665e072 100644--- a/backend/src/lib/harnessSession.ts+++ b/backend/src/lib/harnessSession.ts@@ -296,6 +296,36 @@ export async function startQrSignIn(return { code, pollToken, expiresIn: QR_SIGN_IN_TTL_SEC }}+/** How long a box ticket waits for its box: the phone hands it over on the box's own hotspot, and the+ * box only spends it once it is on the person's Wi-Fi. */+export const BOX_TICKET_TTL_SEC = 30 * 60++/**+ * A QR sign-in already approved by the signed-in phone, for a headless box that has no screen to show+ * a QR on. The phone passes the poll token (the ticket) to the box over its setup hotspot; the box+ * spends it with the ordinary `/api/auth/qr/claim`. The code itself is never handed out, and the+ * answer lock is taken now, so nobody can look the record up or answer it again.+ */+export async function issueBoxTicket(userId: string, email: string): Promise<{ ticket: string; expiresIn: number }> {+ const codeHash = harnessTokenHash(newHarnessToken(HARNESS_QR_PREFIX))+ const ticket = newHarnessToken(HARNESS_QR_POLL_PREFIX)+ const record: QrRecord = {+ pollHash: harnessTokenHash(ticket),+ label: 'Harness',+ kind: 'computer',+ createdAt: Date.now(),+ status: 'approved',+ userId,+ email,+ }+ await pub.multi()+ .set(qrKey(codeHash), JSON.stringify(record), 'EX', BOX_TICKET_TTL_SEC)+ .set(qrPollKey(record.pollHash), codeHash, 'EX', BOX_TICKET_TTL_SEC)+ .set(qrLockKey(codeHash), '1', 'EX', BOX_TICKET_TTL_SEC)+ .exec()+ return { ticket, expiresIn: BOX_TICKET_TTL_SEC }+}+export interface QrSignInLookup {label: stringkind: HarnessSessionKinddiff --git a/backend/src/routes/qrSignIn.test.ts b/backend/src/routes/qrSignIn.test.tsindex 571c050e3..a95db12da 100644--- a/backend/src/routes/qrSignIn.test.ts+++ b/backend/src/routes/qrSignIn.test.ts@@ -58,7 +58,7 @@ vi.mock('../services/UserService.js', () => ({vi.mock('../services/index.js', () => ({ userService: { get: fakes.get, toPublic: (u: unknown) => u } }))import { authenticateAccessToken, SsoAuthError } from '../lib/ssoAuth.js'-import { redeemHandoff, startHandoff, QR_SIGN_IN_MAX_LIFE_SEC } from '../lib/harnessSession.js'+import { redeemHandoff, startHandoff, BOX_TICKET_TTL_SEC, QR_SIGN_IN_MAX_LIFE_SEC } from '../lib/harnessSession.js'import { qrSignInRoutes } from './qrSignIn.js'import { authRoutes } from './auth.js'import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'@@ -177,4 +177,35 @@ describe('sign a computer in by scanning its QR', () => {expect((await post('/api/auth/handoff', {}, { authorization: `Bearer ${computer}` })).statusCode).toBe(200)expect((await post('/api/auth/handoff', {}, { authorization: `Bearer ${phone}` })).statusCode).toBe(403)})++ describe('a box ticket', () => {+ const ticket = async () => (await post('/api/auth/box/ticket', {}, asPhone())).json().data as { ticket: string; expiresIn: number }++ it('signs a headless box in as a computer, once, with nothing to scan or confirm', async () => {+ const t = await ticket()+ expect(t.expiresIn).toBe(BOX_TICKET_TTL_SEC)+ const keys = [...fakes.redis.keys()].filter((k) => k.startsWith('hnauth:qr'))+ expect(keys).toHaveLength(3) // the record, its poll key, and the answer lock+ for (const k of keys) expect(fakes.ttls.get(k)).toBe(BOX_TICKET_TTL_SEC)+ expect((await post('/api/auth/qr/poll', { pollToken: t.ticket })).json().data).toEqual({ status: 'approved', email: '[email protected]' })+ const claimed = (await post('/api/auth/qr/claim', { pollToken: t.ticket })).json().data+ expect(claimed).toMatchObject({ email: '[email protected]', kind: 'computer' })+ expect(fakes.sessions.at(-1)).toMatchObject({ kind: 'computer', label: 'Harness', userId: USER })+ await expect(authenticateAccessToken(claimed.token, 'prod', { allowHarnessSession: 'computer' })).resolves.toMatchObject({ sub: USER, harnessSessionKind: 'computer' })+ const again = await post('/api/auth/qr/claim', { pollToken: t.ticket })+ expect(again.statusCode).toBe(401)+ expect(again.json().error.code).toBe('QR_INVALID')+ })++ it('needs a sign-in and takes no body', async () => {+ expect((await post('/api/auth/box/ticket', {})).statusCode).toBe(401)+ expect((await post('/api/auth/box/ticket', { label: 'x' }, asPhone())).statusCode).toBe(400)+ })++ it('is a wall for a loop', async () => {+ const codes: number[] = []+ for (let i = 0; i < 11; i++) codes.push((await post('/api/auth/box/ticket', {}, asPhone())).statusCode)+ expect(codes.at(-1)).toBe(429)+ })+ })})diff --git a/backend/src/routes/qrSignIn.ts b/backend/src/routes/qrSignIn.tsindex 2ebf0929f..cf922b521 100644--- a/backend/src/routes/qrSignIn.ts+++ b/backend/src/routes/qrSignIn.ts@@ -1,7 +1,7 @@import type { FastifyInstance, FastifyReply } from 'fastify'import { z } from 'zod'import {- answerQrSignIn, cancelQrSignIn, claimQrSignIn, extendQrSignIn, lookupQrSignIn, pollQrSignIn, startQrSignIn,+ answerQrSignIn, cancelQrSignIn, claimQrSignIn, extendQrSignIn, issueBoxTicket, lookupQrSignIn, pollQrSignIn, startQrSignIn,} from '../lib/harnessSession.js'import { clientIpFromHeaders, countryCodeFromHeaders } from '../lib/clientGeo.js'import { validateBody } from '../middlewares/validation.js'@@ -22,6 +22,7 @@ const start = z.object({}).strict()const byCode = z.object({ code: z.string().min(1).max(128) }).strict()const byPoll = z.object({ pollToken: z.string().min(1).max(128) }).strict()+const noBody = z.object({}).strict()/** Per-process fixed windows: generous for a person, a wall for a loop. */function limiter(perMinute: number) {@@ -39,6 +40,7 @@ function limiter(perMinute: number) {const startLimit = limiter(10)const pollLimit = limiter(90)const answerLimit = limiter(20)+const ticketLimit = limiter(10)const unavailable = (reply: FastifyReply, e: unknown, what: string) => {logger.error(`qr sign-in ${what} failed`, e)@@ -110,4 +112,15 @@ export async function qrSignInRoutes(app: FastifyInstance): Promise<void> {}app.post<{ Body: z.infer<typeof byCode> }>('/api/auth/qr/approve', { preHandler: validateBody(byCode) }, answer(true))app.post<{ Body: z.infer<typeof byCode> }>('/api/auth/qr/deny', { preHandler: validateBody(byCode) }, answer(false))++ // A headless box: the phone approves before there is a code to scan, and hands the box the ticket.+ app.post('/api/auth/box/ticket', { preHandler: validateBody(noBody) }, async (req, reply) => {+ const user = req.user!+ if (!ticketLimit(user.sub)) return tooMany(reply)+ try {+ const out = await issueBoxTicket(user.sub, user.email)+ logger.info('box ticket issued', { userId: user.sub })+ return sendSuccess(reply, out)+ } catch (e) { return unavailable(reply, e, 'ticket') }+ })}diff --git a/cli/scripts/box-claim-e2e.ts b/cli/scripts/box-claim-e2e.tsnew file mode 100644index 000000000..525725d59--- /dev/null+++ b/cli/scripts/box-claim-e2e.ts@@ -0,0 +1,239 @@+/** Box ticket E2E: a headless box signed in with the ticket a phone issued (`/api/auth/box/ticket`,+ * `harness login --ticket=`). No Docker and no real account: the real backend on an in-memory Mongo+ * replica set and Redis, a fixture SSO profile standing in for the phone's sign-in, and two CLI boxes+ * each in its own HOME / auth / data folder under a temp root — never the developer's ~/.harness.+ *+ * HARNESS_BOX_E2E=1 HARNESS_E2E_SERVICES_DIR=<dir with mongodb-memory-server and redis-memory-server> \+ * npx tsx scripts/box-claim-e2e.ts+ *+ * HARNESS_E2E_MONGOD / HARNESS_E2E_REDIS_SERVER point at system binaries instead of downloaded ones.+ */+import { execFile, spawn, type ChildProcess } from 'node:child_process'+import { createServer } from 'node:http'+import { createServer as netServer } from 'node:net'+import { createWriteStream, existsSync, readFileSync } from 'node:fs'+import { mkdir, mkdtemp, rm } from 'node:fs/promises'+import { createRequire } from 'node:module'+import { tmpdir } from 'node:os'+import { dirname, join, resolve } from 'node:path'+import { fileURLToPath } from 'node:url'+import { promisify } from 'node:util'+import { randomUUID } from 'node:crypto'+import { setTimeout as delay } from 'node:timers/promises'++if (process.env.HARNESS_BOX_E2E !== '1') throw new Error('Opt in with HARNESS_BOX_E2E=1')+const servicesDir = process.env.HARNESS_E2E_SERVICES_DIR+if (!servicesDir) throw new Error('HARNESS_E2E_SERVICES_DIR must contain mongodb-memory-server and redis-memory-server')+const services = createRequire(join(resolve(servicesDir), 'package.json'))+const { MongoMemoryReplSet } = services('mongodb-memory-server')+const { RedisMemoryServer } = services('redis-memory-server')+const exec = promisify(execFile)+const repo = resolve(dirname(fileURLToPath(import.meta.url)), '../..')+const root = await mkdtemp(join(tmpdir(), 'harness-box-e2e-'))+const children: ChildProcess[] = []+const cleanups: Array<() => unknown | Promise<unknown>> = []+const boxes: Box[] = []+console.log(`Artifacts and logs: ${root}`)++const pass = (message: string) => console.log(`PASS ${message}`)+function check(ok: unknown, message: string, detail?: unknown): void {+ if (!ok) throw new Error(`${message}${detail === undefined ? '' : `: ${JSON.stringify(detail)}`}`)+}+async function until(label: string, ok: () => Promise<unknown>, ms = 30_000): Promise<void> {+ const end = Date.now() + ms+ while (Date.now() < end) {+ if (await ok().catch(() => false)) return+ await delay(250)+ }+ throw new Error(`Timed out: ${label}; logs: ${root}`)+}+async function freePort(): Promise<number> {+ const server = netServer()+ await new Promise<void>((done) => server.listen(0, '127.0.0.1', done))+ const port = (server.address() as { port: number }).port+ await new Promise<void>((done) => server.close(() => done()))+ return port+}++interface Box { name: string; home: string; port: number; computerId: string; env: NodeJS.ProcessEnv }+let cli = ''++/** A computer of its own: HOME, auth, data, tmux and port all under the temp root. */+async function newBox(name: string, backendPort: number): Promise<Box> {+ const home = join(root, name)+ await mkdir(join(home, 'tmux'), { recursive: true })+ const port = await freePort()+ const computerId = randomUUID()+ const env: NodeJS.ProcessEnv = {+ ...process.env,+ TMUX: '', TMUX_PANE: '', TMUX_TMPDIR: join(home, 'tmux'), HOME: home, PORT: String(port),+ HARNESS_AUTH_DIR: join(home, 'auth'), ADAPTER_DATA_DIR: join(home, 'data'),+ ADAPTER_RUNTIME_DIR: join(home, 'runtime'), ADAPTER_CLI_DIR: join(home, 'cli'),+ ADAPTER_COMPUTER_ID: computerId, ADAPTER_COMPUTER_ID_FILE: join(home, 'computer-id'),+ BACKEND_WS_URL: `ws://127.0.0.1:${backendPort}`, WEB_URL: `http://127.0.0.1:${backendPort}`,+ ADAPTER_UPDATE_DISABLE: 'true', DISABLE_HOOK_INSTALL: 'true', ANALYTICS_ENABLED: 'false',+ CABLE_DISABLE: 'true', CABLE_FW_DISABLE: 'true',+ HARNESS_GRID_BIN: join(home, 'grid-unavailable'), DISABLE_GRID_INSTALL: 'true',+ }+ const box = { name, home, port, computerId, env }+ boxes.push(box)+ return box+}++async function harness(box: Box, args: string[]): Promise<{ code: number; stdout: string; stderr: string }> {+ try {+ const { stdout, stderr } = await exec(process.execPath, [cli, ...args], { env: box.env, timeout: 90_000 })+ return { code: 0, stdout, stderr }+ } catch (err) {+ const e = err as { code?: number; stdout?: string; stderr?: string }+ return { code: typeof e.code === 'number' ? e.code : 1, stdout: e.stdout ?? '', stderr: e.stderr ?? '' }+ }+}+/** The result line of a `--json` login. A sign-in that swaps the daemon's identity prints the daemon's+ * status block after it, so it is not simply the last line. */+function result(stdout: string): Record<string, unknown> {+ for (const line of stdout.split('\n')) {+ try {+ const parsed = JSON.parse(line) as Record<string, unknown>+ if (parsed?.type === 'result') return parsed+ } catch { /* the status block */ }+ }+ return {}+}+const daemonStatus = async (box: Box) =>+ (await (await fetch(`http://127.0.0.1:${box.port}/api/status`)).json()) as { machineId?: string; connected?: boolean; signedIn?: boolean }+const session = (box: Box) => JSON.parse(readFileSync(join(box.home, 'auth', 'session.json'), 'utf8')) as Record<string, unknown>++let failed = true+try {+ // ── Services, the phone's account, the backend ──────────────────────────────────────────────────+ const mongo = await MongoMemoryReplSet.create({+ binary: { ...(process.env.HARNESS_E2E_MONGOD ? { systemBinary: process.env.HARNESS_E2E_MONGOD } : {}) },+ replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' },+ })+ cleanups.push(() => mongo.stop())+ const redis = new RedisMemoryServer({ binary: {+ ...(process.env.HARNESS_E2E_REDIS_SERVER ? { systemBinary: process.env.HARNESS_E2E_REDIS_SERVER } : {}),+ } })+ cleanups.push(() => redis.stop())+ const redisPort = await redis.getPort()++ const phoneToken = `phone-fixture-${randomUUID()}`+ const userId = randomUUID().replaceAll('-', '')+ const email = `${userId}@local.invalid`+ const sso = createServer((req, res) => {+ res.setHeader('content-type', 'application/json')+ if (req.headers.authorization !== `Bearer ${phoneToken}`) { res.writeHead(401).end('{}'); return }+ res.end(JSON.stringify({ status: 1, data: { id: userId, email } }))+ })+ await new Promise<void>((done) => sso.listen(0, '127.0.0.1', done))+ cleanups.push(() => new Promise((done) => sso.close(done)))++ const [backendPort, proxyPort] = await Promise.all([freePort(), freePort()])+ const mongoUri = new URL(mongo.getUri('harness'))+ mongoUri.searchParams.set('directConnection', 'true')+ const backendEnv = {+ ...process.env, NODE_ENV: 'test', PORT: String(backendPort), PORT_APP_PROXY: String(proxyPort),+ DATABASE_URL: mongoUri.toString(), REDIS_URL: `redis://127.0.0.1:${redisPort}`,+ HARNESS_BILLING_ENABLED: 'false', MESH_ENABLED: 'false', TERMINAL_P2P_ROLLOUT_PERCENT: '0',+ SSO_PROFILE_URL: `http://127.0.0.1:${(sso.address() as { port: number }).port}/profile`, SSO_IDENTITY_URL: '',+ HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=',+ }+ await exec(join(repo, 'backend/node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'],+ { cwd: join(repo, 'backend'), env: backendEnv, timeout: 120_000 })+ const backend = spawn(process.execPath, ['--import', 'tsx', 'src/server.ts'],+ { cwd: join(repo, 'backend'), env: backendEnv, detached: true, stdio: ['ignore', 'pipe', 'pipe'] })+ const backendLog = createWriteStream(join(root, 'backend.log'))+ backend.stdout!.pipe(backendLog)+ backend.stderr!.pipe(backendLog)+ children.push(backend)+ const api = `http://127.0.0.1:${backendPort}`+ await until('backend health', async () => (await fetch(`${api}/api/health`)).ok, 90_000)+ pass('backend up on in-memory Mongo + Redis')++ /** The phone: a signed-in account calling the backend. */+ const phone = async (method: 'GET' | 'POST', path: string, body?: unknown) => {+ const res = await fetch(`${api}${path}`, {+ method,+ headers: { authorization: `Bearer ${phoneToken}`, 'x-autonomous-env': 'prod', ...(body === undefined ? {} : { 'content-type': 'application/json' }) },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),+ })+ const json = await res.json() as { data?: any; error?: unknown }+ if (!res.ok) throw new Error(`${method} ${path} → ${res.status} ${JSON.stringify(json.error)}`)+ return json.data+ }+ const newTicket = async (): Promise<string> => {+ const out = await phone('POST', '/api/auth/box/ticket', {}) as { ticket?: string; expiresIn?: number }+ check(out.ticket?.startsWith('hnp_') && out.expiresIn === 1800, 'ticket issued', out)+ return out.ticket!+ }++ // ── The box CLI, built from this working tree ───────────────────────────────────────────────────+ const bundleDir = join(root, 'bundle')+ await exec(process.execPath, ['build-bundle.mjs'], {+ cwd: join(repo, 'cli'), timeout: 300_000,+ env: { ...process.env, BUNDLE_OUT_DIR: bundleDir, ADAPTER_VERSION: '0.0.0-dev.box-e2e' },+ })+ cli = join(bundleDir, 'cli.js')+ check(existsSync(cli), 'CLI bundle built', cli)+ const box1 = await newBox('box1', backendPort)+ const box2 = await newBox('box2', backendPort)++ // ── A blank box: its daemon runs, serving only itself ───────────────────────────────────────────+ const started = await harness(box1, ['start'])+ check(started.code === 0, 'box1 starts signed out', started)+ await until('box1 daemon answers', async () => (await daemonStatus(box1)).signedIn === false)+ pass('blank box: daemon up, this computer only (not signed in)')++ // ── The phone issues a ticket; the box spends it ────────────────────────────────────────────────+ const ticket = await newTicket()+ pass('phone issued a box ticket')+ const login = await harness(box1, ['login', `--ticket=${ticket}`, '--json'])+ check(login.code === 0, 'box1 login --ticket', login)+ check(result(login.stdout).status === 'success' && result(login.stdout).email === email, 'box1 signed in as the phone\'s account', result(login.stdout))+ const signed = session(box1)+ check(signed.method === 'qr' && typeof signed.machineId === 'string', 'box1 session on disk', signed)+ pass(`box signed in as ${email}, machine ${signed.machineId}`)++ await until('box1 daemon on the new identity, connected', async () => {+ const s = await daemonStatus(box1)+ return s.machineId === signed.machineId && s.connected === true+ }, 60_000)+ pass('daemon restarted onto the machine id and connected to the backend')++ const compact = (id: unknown) => String(id).replaceAll('-', '').toLowerCase()+ await until('phone sees the box running', async () => {+ const { machines } = await phone('GET', '/api/machines') as { machines: Array<{ machineId: string; computerId?: string; status?: string }> }+ return machines.some((m) => m.machineId === signed.machineId && compact(m.computerId) === compact(box1.computerId) && m.status === 'running')+ }, 60_000)+ pass('phone lists the box in Machines, running')++ // ── A ticket is spent once ──────────────────────────────────────────────────────────────────────+ const reused = await harness(box2, ['login', `--ticket=${ticket}`, '--json'])+ check(reused.code !== 0 && result(reused.stdout).code === 'TICKET_INVALID', 'a spent ticket is refused', reused)+ check(!existsSync(join(box2.home, 'auth', 'session.json')), 'no session for box2 from a spent ticket')+ pass('a spent ticket is TICKET_INVALID')++ // ── A claimed box takes no second ticket, and does not spend it ─────────────────────────────────+ const second = await newTicket()+ const again = await harness(box1, ['login', '--force', `--ticket=${second}`, '--json'])+ check(again.code !== 0 && result(again.stdout).code === 'ALREADY_SIGNED_IN', 'a signed-in box refuses a ticket', again)+ check(session(box1).machineId === signed.machineId, 'box1 kept its identity')+ const box2Login = await harness(box2, ['login', `--ticket=${second}`, '--json'])+ check(box2Login.code === 0 && result(box2Login.stdout).status === 'success', 'the refused ticket still works for its box', box2Login)+ pass('a signed-in box refuses a ticket and leaves it unspent')++ failed = false+ console.log('\nALL PASS')+} catch (err) {+ console.error(`\nFAIL ${(err as Error).message}`)+} finally {+ for (const box of boxes) await harness(box, ['stop']).catch(() => {})+ for (const child of children.reverse()) {+ if (child.pid && child.exitCode == null) { try { process.kill(-child.pid, 'SIGTERM') } catch { /* gone */ } }+ }+ for (const c of cleanups.reverse()) await Promise.resolve(c()).catch(() => {})+ if (!failed && process.env.HARNESS_BOX_E2E_KEEP !== '1') await rm(root, { recursive: true, force: true })+ else console.error(`Logs retained at ${root}`)+ process.exit(failed ? 1 : 0)+}diff --git a/cli/src/authCommand.spec.ts b/cli/src/authCommand.spec.tsindex 458e62b38..27f9c8e1d 100644--- a/cli/src/authCommand.spec.ts+++ b/cli/src/authCommand.spec.ts@@ -98,6 +98,9 @@ function runAsync(root: string, args: string[], backendUrl?: string): Promise<{* `auth status` make — real network shape, canned answers, so the CLI's own code runs unmodified.* `routes` stubs any other path (the QR sign-in's `/api/auth/qr/*`). A handler may answer with a* promise, so a test can hold a step open. `calls` records every request in arrival order. */+/** A route's refusal, answered as the backend's own error envelope with [status]. */+class Refusal { constructor(readonly status: number, readonly code: string, readonly message: string) {} }+function fakeBackend(handlers: {authorizeNative?: (body: any) => anyexchange?: (body: any) => any@@ -113,6 +116,11 @@ function fakeBackend(handlers: {const body = raw ? JSON.parse(raw) : {}calls.push({ url: req.url ?? '', body })const send = (data: unknown): void => {+ if (data instanceof Refusal) {+ res.writeHead(data.status, { 'content-type': 'application/json' })+ res.end(JSON.stringify({ success: false, error: { code: data.code, message: data.message } }))+ return+ }res.writeHead(200, { 'content-type': 'application/json' })res.end(JSON.stringify({ success: true, data }))}@@ -660,3 +668,54 @@ describe('harness login (human)', () => {expect(result.stdout).toContain(` ✓ Already signed in — this machine is "${hostname().slice(0, 60)}" · ${fp}\n Run \`harness start\` to connect this computer.`)})})++describe('harness login --ticket', () => {+ const claimed = () => ({ token: 'tok_box', refreshToken: 'r', expiresIn: 3600, email: '[email protected]' })++ it('spends the ticket and signs the box in, with nothing to scan or confirm', async () => {+ const root = tempRoot()+ const { base, calls } = await fakeBackend({+ routes: { '/api/auth/qr/claim': claimed, '/api/auth/me': () => ({ user: { id: 'acct_box' } }) },+ resolveComputer: () => ({ machine: { machineId: 'm_box' } }),+ })+ const result = await runAsync(root, ['login', '--ticket=hnp_ticket', '--json'], base)+ expect(result.status).toBe(0)+ expect(JSON.parse(result.stdout.trim())).toEqual({ type: 'result', status: 'success', email: '[email protected]', fingerprint: expect.stringMatching(FP) })+ expect(calls).toContainEqual({ url: '/api/auth/qr/claim', body: { pollToken: 'hnp_ticket' } })+ expect(calls.map((c) => c.url)).not.toContain('/api/auth/qr/start')+ expect(JSON.parse(readFileSync(join(root, 'auth', 'session.json'), 'utf8'))).toMatchObject({ accessToken: 'tok_box', method: 'qr', machineId: 'm_box', signInAcct: 'acct_box' })+ }, 30_000)++ it('refuses on a computer that is already signed in, even with --force, and leaves the ticket unspent', async () => {+ const root = tempRoot()+ seedSession(root)+ const { base, calls } = await fakeBackend({ routes: { '/api/auth/qr/claim': claimed } })+ const result = await runAsync(root, ['login', '--force', '--ticket=hnp_ticket', '--json'], base)+ expect(result.status).toBe(1)+ expect(JSON.parse(result.stdout.trim())).toMatchObject({ type: 'result', status: 'error', code: 'ALREADY_SIGNED_IN' })+ expect(calls).toEqual([])+ }, 30_000)++ it('a spent ticket stays a sign-in when the machine lookup fails, so the daemon still moves onto the account', async () => {+ const root = tempRoot()+ const { base } = await fakeBackend({+ routes: { '/api/auth/qr/claim': claimed },+ resolveComputer: () => new Refusal(503, 'UNAVAILABLE', 'try later'),+ })+ const result = await runAsync(root, ['login', '--ticket=hnp_ticket', '--json'], base)+ expect(result.status).toBe(0)+ expect(JSON.parse(result.stdout.trim())).toMatchObject({ type: 'result', status: 'success', email: '[email protected]' })+ const saved = JSON.parse(readFileSync(join(root, 'auth', 'session.json'), 'utf8')) as Record<string, unknown>+ expect(saved).toMatchObject({ accessToken: 'tok_box', method: 'qr' })+ expect(saved).not.toHaveProperty('machineId')+ }, 30_000)++ it('says TICKET_INVALID for a ticket the backend refuses, and writes no session', async () => {+ const root = tempRoot()+ const { base } = await fakeBackend({ routes: { '/api/auth/qr/claim': () => new Refusal(401, 'QR_INVALID', 'Nothing to claim: scan again.') } })+ const result = await runAsync(root, ['login', '--ticket=hnp_spent', '--json'], base)+ expect(result.status).toBe(1)+ expect(JSON.parse(result.stdout.trim())).toMatchObject({ type: 'result', status: 'error', code: 'TICKET_INVALID' })+ expect(existsSync(join(root, 'auth', 'session.json'))).toBe(false)+ }, 30_000)+})diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex ee48db047..52a6f7697 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -45,7 +45,7 @@ import { flashCommand } from './lib/flash.js'import { awaitLoginCallback, extractCallbackParams, LOGIN_TIMEOUT_MESSAGE, type LoginCallbackParams } from './lib/loginCallback.js'import { AUTH_DIR, AuthSessionError, AuthSessionManager, clearAuthSession, knownSsoClientId, newSignInEpoch, readAuthSession, ssoClientIdFor, writeAuthSession, type AuthSession } from './lib/authSession.js'import { handOffToGrid } from './lib/gridHandoff.js'-import { qrSignIn } from './lib/qrSignIn.js'+import { claimTicket, qrSignIn, type QrSignInTokens } from './lib/qrSignIn.js'import { pickSignInMethod, signInMethodFlag, signInProviderName, withSignInProvider, type SignInMethod, type SignInProvider } from './lib/signInMethodPicker.js'import { watchJsonDriver, type JsonDriver } from './lib/jsonDriver.js'import { terminalQr } from './lib/terminalQr.js'@@ -397,7 +397,7 @@ async function loginCommand(foreground: boolean,force: boolean,json: boolean,- opts: { chained?: boolean; entryPoint?: string; method?: SignInMethod | 'ask' } = {},+ opts: { chained?: boolean; entryPoint?: string; method?: SignInMethod | 'ask'; ticket?: string } = {},): Promise<SignInOutcome> {if (foreground) throw new Error('`harness login` does not run the adapter. Use `harness start -f`.')// Which surface asked to sign in. A person in a terminal is `cli`; the desktop app runs this same@@ -472,6 +472,9 @@ async function loginCommand(setWaiting(false)}}+ // A box ticket before anything else: unlike every other sign-in it must never land on a computer+ // that is already signed in, even with --force — the ticket stays unspent for the box it was for.+ if (opts.ticket) return await ticketSignIn(json, emit, opts.ticket, (email) => succeed(false, email))if (readAuthSession() && !force) {// Guarded exactly like the identical call after the exchange below. Unguarded, a hiccup on// `/api/machines/resolve-computer` reached `onError`, which is JSON-unaware — so the ONE mode a@@ -581,12 +584,7 @@ async function qrSignInCommand(succeed: (email: string) => Promise<SignInOutcome>,hooks: SignInHooks = {},): Promise<SignInOutcome> {- const fail = (code: string, message: string): SignInOutcome => {- if (json) emit({ type: 'result', status: 'error', code, message })- else console.error(`\n ✗ ${message}\n`)- process.exitCode = 1- return { signedIn: false }- }+ const fail = signInFailure(json, emit)let shown = falseconst result = await qrSignIn({post: (path, body) => postJson(path, body),@@ -615,7 +613,51 @@ async function qrSignInCommand(},})if (!result.ok) return fail(result.code, result.message)- const { tokens } = result+ return await saveSignIn(result.tokens, (message) => fail('BACKEND_ERROR', message), succeed)+}++/** A refused sign-in: its coded result line under --json, a line on stderr otherwise; exit code 1. */+function signInFailure(json: boolean, emit: (line: Record<string, unknown>) => void): (code: string, message: string) => SignInOutcome {+ return (code, message) => {+ if (json) emit({ type: 'result', status: 'error', code, message })+ else console.error(`\n ✗ ${message}\n`)+ process.exitCode = 1+ return { signedIn: false }+ }+}++/**+ * `harness login --ticket=<t>`: a headless box (no screen for a QR, no one to confirm) signed in with+ * the ticket the phone handed it during setup. Refused on a computer that is already signed in, before+ * the ticket is spent: whoever set this box up first keeps it.+ */+async function ticketSignIn(+ json: boolean,+ emit: (line: Record<string, unknown>) => void,+ ticket: string,+ succeed: (email: string) => Promise<SignInOutcome>,+): Promise<SignInOutcome> {+ const fail = signInFailure(json, emit)+ if (readAuthSession()) return fail('ALREADY_SIGNED_IN', 'This computer is already signed in. The ticket was not used.')+ const result = await claimTicket((path, body) => postJson(path, body), ticket)+ if (!result.ok) return fail(result.code, result.message)+ // The ticket is spent and the session written: a failure here would leave the box signed in yet+ // reporting failure, its retry refused as ALREADY_SIGNED_IN and its daemon never moved onto the+ // account. The machine id is not needed for that — the daemon starts on the computer id and+ // resolves it itself (`resolveMachineIfUnknown`) — so the sign-in stands.+ return await saveSignIn(result.tokens, (message) => {+ console.error(` (machine id not resolved yet — ${message}; the daemon resolves it as it starts)`)+ return succeed(result.tokens.email)+ }, succeed)+}++/** A QR or ticket sign-in's session on disk, its account recorded and its machine resolved.+ * `unresolved` answers a machine lookup that failed after the session was already written. */+async function saveSignIn(+ tokens: QrSignInTokens,+ unresolved: (message: string) => SignInOutcome | Promise<SignInOutcome>,+ succeed: (email: string) => Promise<SignInOutcome>,+): Promise<SignInOutcome> {const signInEpoch = newSignInEpoch()const autonomousEnv = tokens.autonomousEnv ?? env.AUTONOMOUS_ENVwriteAuthSession({@@ -633,7 +675,7 @@ async function qrSignInCommand(try {await resolveComputerMachine()} catch (err) {- return fail('BACKEND_ERROR', (err as Error).message)+ return await unresolved((err as Error).message)}return await succeed(tokens.email)}@@ -2441,6 +2483,7 @@ switch (cmd) {// account: the desktop app reads that line and does not wait for a restart it observes anyway.loginCommand(foreground, flags.includes('--force'), flags.includes('--json'), {entryPoint: entryPointFlag(),+ ticket: flags.find((f) => f.startsWith('--ticket='))?.slice('--ticket='.length) || undefined,method: signInMethodFlag(flags) ?? (flags.includes('--json') || !process.stdin.isTTY ? undefined : 'ask'),}).then((outcome) => outcome.signedIn ? restartDaemonForIdentity(outcome.stoppedDaemon) : undefined)diff --git a/cli/src/lib/controlPlane.ts b/cli/src/lib/controlPlane.tsindex 2dc7a5b12..974859fce 100644--- a/cli/src/lib/controlPlane.ts+++ b/cli/src/lib/controlPlane.ts@@ -40,9 +40,11 @@ export async function requestJson<T>(...(body === undefined ? {} : { body: JSON.stringify(body) }),signal: signal ?? AbortSignal.timeout(PROXY_BACKEND_TIMEOUT_MS),})- const json = (await res.json().catch(() => ({}))) as { success?: boolean; data?: T; error?: { message?: string } }+ const json = (await res.json().catch(() => ({}))) as { success?: boolean; data?: T; error?: { message?: string; code?: string } }if (!res.ok || json.success === false) {- throw new Error(json.error?.message || `HTTP ${res.status}`)+ // `status` and the backend's `code` ride along, for a caller that answers a refusal differently+ // from a backend that is down.+ throw Object.assign(new Error(json.error?.message || `HTTP ${res.status}`), { status: res.status, code: json.error?.code })}return json.data as T}diff --git a/cli/src/lib/qrSignIn.spec.ts b/cli/src/lib/qrSignIn.spec.tsindex 59ab9d29d..77318d567 100644--- a/cli/src/lib/qrSignIn.spec.ts+++ b/cli/src/lib/qrSignIn.spec.ts@@ -1,5 +1,5 @@import { describe, expect, it, vi } from 'vitest'-import { qrSignIn, qrSignInLink, type QrSignInDeps } from './qrSignIn.js'+import { claimTicket, qrSignIn, qrSignInLink, type QrSignInDeps } from './qrSignIn.js'import { terminalQr } from './terminalQr.js'/** A backend that answers the QR sign-in routes from a script of poll answers. */@@ -107,3 +107,20 @@ describe('terminalQr', () => {expect(lines.length).toBe(Math.ceil(width / 2))})})++describe('claimTicket', () => {+ const refused = (status: number) => Object.assign(new Error('refused'), { status })++ it('claims the ticket as the poll token and hands back the session', async () => {+ const post = vi.fn(async () => ({ token: 'hna_x', email: '[email protected]' })) as unknown as QrSignInDeps['post']+ expect(await claimTicket(post, 'hnp_t')).toEqual({ ok: true, tokens: { token: 'hna_x', email: '[email protected]' } })+ expect(post).toHaveBeenCalledWith('/api/auth/qr/claim', { pollToken: 'hnp_t' })+ })++ it('a refused ticket is TICKET_INVALID; a backend in trouble is BACKEND_ERROR', async () => {+ const reject = (err: Error) => vi.fn(async () => { throw err }) as unknown as QrSignInDeps['post']+ expect(await claimTicket(reject(refused(401)), 'hnp_t')).toMatchObject({ ok: false, code: 'TICKET_INVALID' })+ expect(await claimTicket(reject(refused(503)), 'hnp_t')).toMatchObject({ ok: false, code: 'BACKEND_ERROR' })+ expect(await claimTicket(reject(new Error('fetch failed')), 'hnp_t')).toMatchObject({ ok: false, code: 'BACKEND_ERROR' })+ })+})diff --git a/cli/src/lib/qrSignIn.ts b/cli/src/lib/qrSignIn.tsindex a56f8fcbe..77cd6efec 100644--- a/cli/src/lib/qrSignIn.ts+++ b/cli/src/lib/qrSignIn.ts@@ -26,7 +26,7 @@ export interface QrSignInTokens {email: string}-export type QrSignInFailure = 'BACKEND_ERROR' | 'DENIED' | 'EXPIRED' | 'CANCELLED'+export type QrSignInFailure = 'BACKEND_ERROR' | 'DENIED' | 'EXPIRED' | 'CANCELLED' | 'TICKET_INVALID'export type QrSignInResult = { ok: true; tokens: QrSignInTokens } | { ok: false; code: QrSignInFailure; message: string }@@ -100,3 +100,20 @@ export async function qrSignIn(deps: QrSignInDeps): Promise<QrSignInResult> {}}}++/**+ * Spend a box ticket (backend `issueBoxTicket`): the poll token of a QR sign-in the phone approved+ * before handing it to this headless box, so there is nothing to show and no one here to confirm.+ * A ticket the backend refuses (spent, expired, made up) is `TICKET_INVALID` — another try with the+ * same one cannot help; anything else is `BACKEND_ERROR`, which can.+ */+export async function claimTicket(post: QrSignInDeps['post'], ticket: string): Promise<QrSignInResult> {+ try {+ const tokens = await post<QrSignInTokens>('/api/auth/qr/claim', { pollToken: ticket })+ if (!tokens?.token) throw new Error('the backend returned no session')+ return { ok: true, tokens }+ } catch (err) {+ if ((err as { status?: number }).status === 401) return { ok: false, code: 'TICKET_INVALID', message: 'This ticket was already used or has expired.' }+ return { ok: false, code: 'BACKEND_ERROR', message: (err as Error).message }+ }+}