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(backend): sign a computer in by scanning its QR with a signed-in phone
0xken15d14ebab0987c
diff --git a/SECURITY.md b/SECURITY.mdindex fe882df81..4d4cbd984 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -26,6 +26,14 @@ This is deliberate, and it is not prevented, only made visible: each device annonot trusted before ("New device: X"), the device list shows every one with a Remove, and devicescompare the log among themselves so a backend cannot show one device a key the others do not see.+**A phone can sign a computer in by scanning its QR.** Approving one hands that computer the account's+terminals, so two mistakes matter: approving a stranger's computer (a QR you were shown), and a+stranger approving yours with their phone (a QR they photographed). The phone shows what is asking,+where from, and whether it is on the phone's network — another network takes a two-second hold, not a+tap — and the computer asks its own person whose account approved it before any session exists.+A computer signed in this way can add a phone of its own; that chain is intended. Its session is+Harness's own, so billing and grid still need an SSO sign-in.+## For implementersTwo obligations in the protocol are security-relevant, and both are easy to get subtly wrong:diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex bec1ff445..a1c22298f 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -710,6 +710,9 @@ model HarnessSession {refreshHash String @unique/// What the device calls itself ("Dee's iPhone"), for a list of signed-in devices.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.+ kind 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/adapterWs.ts b/backend/src/lib/adapterWs.tsindex 20481f6dc..83767e789 100644--- a/backend/src/lib/adapterWs.ts+++ b/backend/src/lib/adapterWs.ts@@ -171,7 +171,7 @@ export function handleAdapterUpgrade(req: IncomingMessage, socket: Duplex, head:const countryCode = countryCodeFromHeaders(req.headers)void (async () => {let user- try { user = await authenticateAccessToken(accessToken, autonomousEnv, { allowHarnessSession: false }) } catch (err) {+ 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')) {try { socket.write('HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n') } catch { /* ignore */ }socket.destroy()@@ -186,7 +186,7 @@ export function handleAdapterUpgrade(req: IncomingMessage, socket: Duplex, head: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))+ wss.handleUpgrade(req, socket, head, (ws) => void attachAdapter(ws, machineId, machine.userId, machine.name, label, computerId, clientVersion, countryCode, user.harnessSessionId))})().catch((err) => {if (err instanceof AppError) {// 403 is the revoked-machine answer from `resolveOrCreateForComputer`, 429 its new-id rate limit@@ -201,7 +201,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): Promise<void> {+async function attachAdapter(ws: WebSocket, machineId: string, userId: string, currentName: string | null, label?: string, computerId?: string, clientVersion?: string, countryCode?: string, harnessSessionId?: string): 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')@@ -452,7 +452,7 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, csend({ t: 'down', connId: '', frame: { type: 'devlog_append_result', payload: { requestId, error: 'RATE_LIMITED' } } })return}- void appendDeviceKey(userId, p.entry, { kind: 'machine', machineId })+ void appendDeviceKey(userId, p.entry, { kind: 'machine', machineId, ...(harnessSessionId ? { harnessSessionId } : {}) }).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 } : {}) } } }))diff --git a/backend/src/lib/clientGeo.ts b/backend/src/lib/clientGeo.tsindex 89aaab196..a08a2c008 100644--- a/backend/src/lib/clientGeo.ts+++ b/backend/src/lib/clientGeo.ts@@ -28,6 +28,18 @@ export function countryCodeFromHeaders(headers: IncomingHttpHeaders): string | ureturn v}+/**+ * The caller's address as Cloudflare saw it (`cf-connecting-ip`), else the socket's. Only a hint —+ * shown to a person approving a sign-in, compared to tell "same network" — never an identity.+ */+export function clientIpFromHeaders(headers: IncomingHttpHeaders, socketAddress?: string): string | undefined {+ const raw = headers['cf-connecting-ip']+ const v = (Array.isArray(raw) ? raw[0] : raw)?.trim()+ const ip = v || socketAddress+ if (!ip || ip.length > 64 || !/^[0-9a-fA-F:.]+$/.test(ip)) return undefined+ return ip.startsWith('::ffff:') ? ip.slice(7) : ip+}+/** Minimum age of the last stamp before the same country is written again for one user. */export const USER_COUNTRY_WRITE_MS = 60 * 60 * 1000/** Cache entries older than this are evicted on the next sweep; sweeps run only past `USER_COUNTRY_CACHE_MAX`. */diff --git a/backend/src/lib/deviceKeyLog.test.ts b/backend/src/lib/deviceKeyLog.test.tsindex d37b1fc28..336572331 100644--- a/backend/src/lib/deviceKeyLog.test.ts+++ b/backend/src/lib/deviceKeyLog.test.ts@@ -127,6 +127,14 @@ describe('appendDeviceKey', () => {expect(m.publishDown).toHaveBeenCalledWith(MID2, { connId: '', frame: { type: 'machine_revoked', payload: { reason: 'device_removed', pub: box2.pub } } })})+ it('ends the Harness session of a removed computer that a phone signed in by QR', async () => {+ await appendDeviceKey(USER, await addEntry(box1, 'machine', MID1, 'box1'), { kind: 'machine', machineId: MID1 })+ await appendDeviceKey(USER, await addEntry(box2, 'machine', MID2, 'box2'), { kind: 'machine', machineId: MID2, harnessSessionId: 'sess-qr' })+ await appendDeviceKey(USER, await removeEntry(box2.pub, box1), { kind: 'machine', machineId: MID1 })+ expect(m.publishDown).toHaveBeenCalledWith(MID2, expect.objectContaining({ frame: expect.objectContaining({ type: 'machine_revoked' }) }))+ expect(m.revoke).toHaveBeenCalledWith({ where: { id: 'sess-qr', userId: USER, OR: [{ revokedAt: null }, { revokedAt: { isSet: false } }] }, data: { revokedAt: expect.any(Date) } })+ })+it('refuses a machine signing a removal with another machine key', async () => {await appendDeviceKey(USER, await addEntry(box1, 'machine', MID1, 'box1'), { kind: 'machine', machineId: MID1 })await appendDeviceKey(USER, await addEntry(box2, 'machine', MID2, 'box2'), { kind: 'machine', machineId: MID2 })diff --git a/backend/src/lib/deviceKeyLog.ts b/backend/src/lib/deviceKeyLog.tsindex 99ca5c7a3..94c2a8918 100644--- a/backend/src/lib/deviceKeyLog.ts+++ b/backend/src/lib/deviceKeyLog.ts@@ -1,6 +1,7 @@import { prisma } from './prisma.js'import { pub, publishDeviceKeysChanged, publishDown } from './bus.js'import { logger } from '../utils/logger.js'+import { revokeHarnessSessionById } from './harnessSession.js'import {applyDevLogEntries, DevLogError, emptyDevLogState, parseDevLogEntry,type DevLogEntry, type DevLogHead, type DevLogState,@@ -30,7 +31,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 }+ | { kind: 'machine'; machineId: string; harnessSessionId?: string }| { kind: 'viewer'; harnessSessionId?: string }export async function readDeviceKeyLog(userId: string, since: number): Promise<{ acct: string; head: DevLogHead; entries: unknown[] }> {@@ -90,7 +91,9 @@ export async function appendDeviceKey(userId: string, raw: unknown, channel: Devawait prisma.deviceKeyLogEntry.create({data: {userId, seq: entry.seq, hash: head.hash, entry: JSON.stringify(entry),- sessionId: entry.op === 'add' && channel.kind === 'viewer' ? channel.harnessSessionId ?? null : null,+ // The Harness session that added this key (a phone signed in by QR, or a computer a phone+ // signed in), so removing the key signs that session out too.+ sessionId: entry.op === 'add' ? channel.harnessSessionId ?? null : null,},})} catch (err) {@@ -119,8 +122,11 @@ async function signOut(userId: string, kind: string, machineId: string, pubKey:// Named, so the machine knows its KEY is gone (not just its sign-in) and signs in again with a new// one; a daemon that predates the log reads only the type, as for a deleted machine.await publishDown(machineId, { connId: '', frame: { type: 'machine_revoked', payload: { reason: 'device_removed', pub: pubKey } } })- } else if (sessionId) {- await prisma.harnessSession.updateMany({ where: { id: sessionId, userId, OR: [{ revokedAt: null }, { revokedAt: { isSet: false } }] }, data: { revokedAt: new Date() } })+ }+ // A Harness session (a phone, or a computer a phone signed in by QR) ends here too — a machine+ // that ignores `machine_revoked` must not keep a session it could sign a new key in with.+ if (sessionId) {+ await revokeHarnessSessionById(sessionId, userId)}} catch (err) {logger.warn('device key removal sign-out failed', { userId, kind, error: String(err) })diff --git a/backend/src/lib/deviceWs.ts b/backend/src/lib/deviceWs.tsindex 1594fb851..d9342a279 100644--- a/backend/src/lib/deviceWs.ts+++ b/backend/src/lib/deviceWs.ts@@ -339,7 +339,7 @@ export function handleDeviceUpgrade(req: IncomingMessage, socket: Duplex, head:void (async () => {let usertry {- user = await authenticateAccessToken(accessToken, autonomousEnv, { allowHarnessSession: false })+ user = await authenticateAccessToken(accessToken, autonomousEnv, { allowHarnessSession: 'computer' })} catch (err) {if (err instanceof SsoAuthError && (err.code === 'AUTONOMOUS_ENV_MISMATCH' || err.code === 'AUTONOMOUS_ENV_NOT_ALLOWED')) {denyWith(403, 'Forbidden')diff --git a/backend/src/lib/harnessSession.test.ts b/backend/src/lib/harnessSession.test.tsindex 33ccc755d..52bf59b64 100644--- a/backend/src/lib/harnessSession.test.ts+++ b/backend/src/lib/harnessSession.test.ts@@ -100,7 +100,7 @@ describe('scan to sign in — the handoff', () => {expect(fakes.sessions[0].refreshHash).not.toBe(tokens!.refreshToken)await expect(authenticateAccessToken(tokens!.token)).resolves.toEqual({- sub: USER.id, email: USER.email, role: 'user', autonomousEnv: 'prod', harnessSessionId: 's1',+ sub: USER.id, email: USER.email, role: 'user', autonomousEnv: 'prod', harnessSessionId: 's1', harnessSessionKind: 'viewer',})expect(fetchSpy).not.toHaveBeenCalled()expect(fakes.findByEmail).not.toHaveBeenCalled()diff --git a/backend/src/lib/harnessSession.ts b/backend/src/lib/harnessSession.tsindex 2222af456..f2ba7618f 100644--- a/backend/src/lib/harnessSession.ts+++ b/backend/src/lib/harnessSession.ts@@ -7,9 +7,13 @@ import { SsoAuthError, type AuthUser } from './ssoAuth.js'import {HARNESS_ACCESS_PREFIX,HARNESS_HANDOFF_PREFIX,+ HARNESS_QR_POLL_PREFIX,+ HARNESS_QR_PREFIX,HARNESS_REFRESH_PREFIX,harnessTokenHash,isHarnessHandoffCode,+ isHarnessQrCode,+ isHarnessQrPollToken,isHarnessRefreshToken,newHarnessToken,} from './harnessTokenFormat.js'@@ -77,6 +81,13 @@ export async function redeemHandoff(code: string, label: string): Promise<Harnesif (!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')+}++export type HarnessSessionKind = 'viewer' | 'computer'++/** 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> {const user = await userService.get(userId)if (!user) return nullconst refreshToken = newHarnessToken(HARNESS_REFRESH_PREFIX)@@ -85,6 +96,7 @@ export async function redeemHandoff(code: string, label: string): Promise<HarnesuserId,refreshHash: harnessTokenHash(refreshToken),label,+ kind,expiresAt: sessionExpiry(),},})@@ -159,6 +171,7 @@ export async function authenticateHarnessAccessToken(token: string): Promise<Autconst invalid = (): SsoAuthError => new SsoAuthError('Invalid or expired access token', 'INVALID_TOKEN')let user: Awaited<ReturnType<typeof userService.get>>let sessionId: string+ let kind: string | null | undefinedtry {const raw = await pub.get(accessKey(harnessTokenHash(token)))if (!raw) throw invalid()@@ -167,6 +180,7 @@ export async function authenticateHarnessAccessToken(token: string): Promise<AutsessionId = held.sessionIdconst session = await prisma.harnessSession.findUnique({ where: { id: sessionId } })if (!session || session.revokedAt || session.userId !== held.userId) throw invalid()+ kind = session.kinduser = await userService.get(held.userId)} catch (err) {if (err instanceof SsoAuthError) throw err@@ -179,5 +193,218 @@ export async function authenticateHarnessAccessToken(token: string): Promise<Autrole: user.role,autonomousEnv: storedAutonomousEnvironment(user.autonomousEnv),harnessSessionId: sessionId,+ harnessSessionKind: kind === 'computer' ? 'computer' : 'viewer',}}++/** Revoke the session with this id (a device removed from the account's device key log). */+export async function revokeHarnessSessionById(sessionId: string, userId: string): Promise<void> {+ await prisma.harnessSession.updateMany({ where: { id: sessionId, userId, ...notRevoked }, data: { revokedAt: new Date() } })+}++// ── Sign in a computer by scanning its QR with a signed-in phone ──────────────────────────────────+//+// computer → POST /api/auth/qr/start (no auth) → { code, pollToken } code → the QR, pollToken kept+// phone → POST /api/auth/qr/lookup (signed in) → what is asking: its name, kind, where it is+// phone → POST /api/auth/qr/approve (signed in) → approved for the phone's account+// computer → POST /api/auth/qr/poll (no auth) → pending | denied | expired | approved {email}+// computer asks the person "Sign in as <email>?" — someone else's phone may have approved it+// computer → POST /api/auth/qr/claim (no auth) → the session, created now, handed over once+//+// Signing in is what makes the account's devices trust a computer (the device key log), so approving+// is handing over the account's terminals, and both ends get a say: the phone sees what is asking and+// from where, and the computer sees whose account it would join before any session exists.++export const QR_SIGN_IN_TTL_SEC = 120+/** How long one code may be kept alive by extending it, all told. */+export const QR_SIGN_IN_MAX_LIFE_SEC = 600++export interface QrSignInOrigin { ip?: string; country?: string }++interface QrRecord {+ pollHash: string+ label: string+ kind: HarnessSessionKind+ computerId?: string+ ip?: string+ country?: string+ createdAt: number+ status: 'pending' | 'approved' | 'denied'+ userId?: string+ email?: string+}++const qrKey = (hash: string): string => `hnauth:qr:${hash}`+const qrPollKey = (hash: string): string => `hnauth:qrpoll:${hash}`+const qrLockKey = (hash: string): string => `hnauth:qrlock:${hash}`++async function readQr(codeHash: string): Promise<QrRecord | null> {+ const raw = await pub.get(qrKey(codeHash))+ if (!raw) return null+ try { return JSON.parse(raw) as QrRecord } catch { return null }+}++/** Seconds left of a code's whole life ([QR_SIGN_IN_MAX_LIFE_SEC] from its start). */+function qrLifeLeft(r: QrRecord): number {+ return QR_SIGN_IN_MAX_LIFE_SEC - Math.floor((Date.now() - r.createdAt) / 1000)+}++async function codeHashForPoll(pollToken: string): Promise<string | null> {+ if (!isHarnessQrPollToken(pollToken)) return null+ return pub.get(qrPollKey(harnessTokenHash(pollToken)))+}++/** Two addresses on one network: the same IPv4 address, or the same IPv6 /64. */+export function sameNetwork(a: string | undefined, b: string | undefined): boolean {+ if (!a || !b) return false+ if (a.includes(':') && b.includes(':')) {+ const prefix = (ip: string): string => ip.toLowerCase().split(':').slice(0, 4).join(':')+ return prefix(a) === prefix(b)+ }+ return a === b+}++/** An address shown to the person, with its last part hidden: `1.2.3.x`, `2001:db8:1:2::x`. */+function ipHint(ip: string | undefined): string | undefined {+ if (!ip) return undefined+ if (ip.includes(':')) return `${ip.toLowerCase().split(':').slice(0, 4).join(':')}::x`+ const parts = ip.split('.')+ return parts.length === 4 ? `${parts.slice(0, 3).join('.')}.x` : undefined+}++export async function startQrSignIn(+ req: { label: string; kind: HarnessSessionKind; computerId?: string },+ origin: QrSignInOrigin,+): Promise<{ code: string; pollToken: string; expiresIn: number }> {+ const code = newHarnessToken(HARNESS_QR_PREFIX)+ const pollToken = newHarnessToken(HARNESS_QR_POLL_PREFIX)+ const codeHash = harnessTokenHash(code)+ const record: QrRecord = {+ pollHash: harnessTokenHash(pollToken),+ label: req.label,+ kind: req.kind,+ ...(req.computerId ? { computerId: req.computerId } : {}),+ ...(origin.ip ? { ip: origin.ip } : {}),+ ...(origin.country ? { country: origin.country } : {}),+ createdAt: Date.now(),+ status: 'pending',+ }+ await pub.multi()+ .set(qrKey(codeHash), JSON.stringify(record), 'EX', QR_SIGN_IN_TTL_SEC)+ .set(qrPollKey(record.pollHash), codeHash, 'EX', QR_SIGN_IN_TTL_SEC)+ .exec()+ return { code, pollToken, expiresIn: QR_SIGN_IN_TTL_SEC }+}++export interface QrSignInLookup {+ label: string+ kind: HarnessSessionKind+ country?: string+ ipHint?: string+ sameNetwork: boolean+ status: QrRecord['status']+}++/** What is asking to sign in, for the phone about to approve it. Null for a code that is gone. */+export async function lookupQrSignIn(code: string, phone: QrSignInOrigin): Promise<QrSignInLookup | null> {+ if (!isHarnessQrCode(code)) return null+ const r = await readQr(harnessTokenHash(code))+ if (!r) return null+ return {+ label: r.label,+ kind: r.kind,+ ...(r.country ? { country: r.country } : {}),+ ...(ipHint(r.ip) ? { ipHint: ipHint(r.ip) } : {}),+ sameNetwork: sameNetwork(r.ip, phone.ip),+ status: r.status,+ }+}++/** Approve (for the phone's account) or deny. One answer per code: the first one given stands. */+export async function answerQrSignIn(+ code: string,+ answer: { approve: true; userId: string; email: string } | { approve: false },+): Promise<'ok' | 'gone' | 'answered'> {+ if (!isHarnessQrCode(code)) return 'gone'+ const codeHash = harnessTokenHash(code)+ const r = await readQr(codeHash)+ if (!r) return 'gone'+ const locked = await pub.set(qrLockKey(codeHash), '1', 'EX', QR_SIGN_IN_MAX_LIFE_SEC, 'NX')+ if (locked !== 'OK' || r.status !== 'pending') return 'answered'+ // XX throughout: a code that ran out between the read and here stays gone, never comes back+ // without an expiry.+ if (!answer.approve) {+ await pub.set(qrKey(codeHash), JSON.stringify({ ...r, status: 'denied' }), 'KEEPTTL', 'XX')+ return 'ok'+ }+ // Approved, the code waits on the person at the computer, who still has to say yes and may be+ // slower than the code's two minutes: it lives out its whole life instead, with nothing to extend.+ const next: QrRecord = { ...r, status: 'approved', userId: answer.userId, email: answer.email }+ const left = Math.max(1, qrLifeLeft(r))+ await pub.multi()+ .set(qrKey(codeHash), JSON.stringify(next), 'EX', left, 'XX')+ .expire(qrPollKey(r.pollHash), left)+ .exec()+ return 'ok'+}++/** The computer cancelling its own QR (it closed, or the person said "not my account"). */+export async function cancelQrSignIn(pollToken: string): Promise<void> {+ const codeHash = await codeHashForPoll(pollToken)+ if (!codeHash) return+ const r = await readQr(codeHash)+ if (!r || r.pollHash !== harnessTokenHash(pollToken)) return+ await pub.multi().del(qrKey(codeHash)).del(qrPollKey(r.pollHash)).set(qrLockKey(codeHash), '1', 'EX', QR_SIGN_IN_MAX_LIFE_SEC).exec()+}++export type QrSignInPoll =+ | { status: 'pending' }+ | { status: 'denied' }+ | { status: 'expired' }+ | { status: 'approved'; email: string }++/** Where the computer's QR stands. `approved` names the account — no session exists yet. */+export async function pollQrSignIn(pollToken: string): Promise<QrSignInPoll> {+ const codeHash = await codeHashForPoll(pollToken)+ if (!codeHash) return { status: 'expired' }+ const r = await readQr(codeHash)+ if (!r || r.pollHash !== harnessTokenHash(pollToken)) return { status: 'expired' }+ if (r.status === 'approved' && r.email) return { status: 'approved', email: r.email }+ if (r.status === 'denied') return { status: 'denied' }+ return { status: 'pending' }+}++/** Keep the same code alive a while longer (so an approval given at the last second still counts),+ * up to [QR_SIGN_IN_MAX_LIFE_SEC] in all. Null when it is gone or too old. */+export async function extendQrSignIn(pollToken: string): Promise<number | null> {+ const codeHash = await codeHashForPoll(pollToken)+ if (!codeHash) return null+ const r = await readQr(codeHash)+ if (!r || r.pollHash !== harnessTokenHash(pollToken)) return null+ const left = qrLifeLeft(r)+ if (left <= 0) return null+ // An approved code already lives out its whole life (answerQrSignIn); extending would shorten it.+ if (r.status === 'approved') return left+ const ttl = Math.min(QR_SIGN_IN_TTL_SEC, left)+ await pub.multi().expire(qrKey(codeHash), ttl).expire(qrPollKey(r.pollHash), ttl).exec()+ return ttl+}++/**+ * The computer, having shown the person whose account approved it and been told to go on, takes its+ * 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> {+ const codeHash = await codeHashForPoll(pollToken)+ if (!codeHash) return null+ const [read] = (await pub.multi().get(qrKey(codeHash)).del(qrKey(codeHash)).exec()) ?? []+ if (!read || read[0]) throw read?.[0] ?? new Error('qr claim: no reply from Redis')+ if (typeof read[1] !== 'string') return null+ let r: QrRecord+ try { r = JSON.parse(read[1]) as QrRecord } catch { return null }+ await pub.del(qrPollKey(r.pollHash))+ if (r.pollHash !== harnessTokenHash(pollToken) || r.status !== 'approved' || !r.userId || !r.email) return null+ const tokens = await createSession(r.userId, r.label, r.kind)+ return tokens ? { ...tokens, email: r.email, kind: r.kind } : null+}diff --git a/backend/src/lib/harnessTokenFormat.ts b/backend/src/lib/harnessTokenFormat.tsindex 059eb16b1..fefe892e9 100644--- a/backend/src/lib/harnessTokenFormat.ts+++ b/backend/src/lib/harnessTokenFormat.ts@@ -11,6 +11,10 @@ import { createHash, randomBytes } from 'node:crypto'export const HARNESS_ACCESS_PREFIX = 'hna_'export const HARNESS_REFRESH_PREFIX = 'hnr_'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_'+/** Held by the computer showing that QR, to learn the answer and claim the session. Never shown. */+export const HARNESS_QR_POLL_PREFIX = 'hnp_'const BODY = /^[A-Za-z0-9_-]{43}$/@@ -20,6 +24,8 @@ const shaped = (token: unknown, prefix: string): token is string =>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 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)export function newHarnessToken(prefix: string): string {return prefix + randomBytes(32).toString('base64url')diff --git a/backend/src/lib/ssoAuth.ts b/backend/src/lib/ssoAuth.tsindex 9566ff32c..4d7df8607 100644--- a/backend/src/lib/ssoAuth.ts+++ b/backend/src/lib/ssoAuth.ts@@ -20,6 +20,8 @@ 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'}export interface SsoProfile {@@ -167,8 +169,9 @@ function accessTokenMetadata(token: string): { name?: string; roles?: string[] }/** Validate the token, mirror the external identity, then return the app's internal user identity. *//**- * @param allowHarnessSession Accept a Harness-issued token (lib/harnessSession.ts). FALSE where the- * caller connects AS a machine — a phone's session is a viewer's, never a daemon's.+ * @param allowHarnessSession Accept a Harness-issued token (lib/harnessSession.ts). `'computer'` where+ * 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 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.@@ -185,7 +188,7 @@ function accessTokenMetadata(token: string): { name?: string; roles?: string[] }export async function authenticateAccessToken(token: string,autonomousEnv: AutonomousEnvironment = 'prod',- { enforceEnv = true, allowHarnessSession = true }: { enforceEnv?: boolean; allowHarnessSession?: boolean } = {},+ { enforceEnv = true, allowHarnessSession = true }: { enforceEnv?: boolean; allowHarnessSession?: boolean | 'computer' } = {},): Promise<AuthUser> {// A sign-in Harness issued itself — a phone signed in by scanning a computer's QR. It names its// user outright, so there is no account plane to choose and nothing to ask the account service.@@ -193,7 +196,11 @@ export async function authenticateAccessToken(if (isHarnessAccessToken(token)) {if (!allowHarnessSession) throw new SsoAuthError('This connection needs an Autonomous sign-in', 'INVALID_TOKEN')const { authenticateHarnessAccessToken } = await import('./harnessSession.js')- return authenticateHarnessAccessToken(token)+ const user = await authenticateHarnessAccessToken(token)+ if (allowHarnessSession === 'computer' && user.harnessSessionKind !== 'computer') {+ throw new SsoAuthError('This connection needs a computer sign-in', 'INVALID_TOKEN')+ }+ return user}const profile = await profileCache.resolve(token, autonomousEnv, () => fetchSsoProfile(token, autonomousEnv))const metadata = accessTokenMetadata(token)diff --git a/backend/src/middlewares/authMiddleware.ts b/backend/src/middlewares/authMiddleware.tsindex 3b4bcf679..b50495051 100644--- a/backend/src/middlewares/authMiddleware.ts+++ b/backend/src/middlewares/authMiddleware.ts@@ -24,6 +24,13 @@ export function shouldSkipAuth(url: string): boolean {// (lib/harnessSession.ts). Revoke takes the refresh token, the same authority /refresh does.// `/api/auth/handoff` itself is NOT listed: minting a code needs the computer's sign-in.path === '/api/auth/handoff/redeem' ||+ // A computer signing in by QR (routes/qrSignIn.ts) has no token yet: its poll token is the+ // credential for what it may learn and claim. The phone's half (lookup/approve/deny) is NOT here.+ path === '/api/auth/qr/start' ||+ path === '/api/auth/qr/poll' ||+ path === '/api/auth/qr/extend' ||+ path === '/api/auth/qr/claim' ||+ path === '/api/auth/qr/cancel' ||path === '/api/auth/revoke' ||path === '/api/auth/logout-url' ||// Public app-deploy registration — agent-key gated (x-api-key), self-validated in itsdiff --git a/backend/src/routes/auth.ts b/backend/src/routes/auth.tsindex d5afbb2c7..369f15934 100644--- a/backend/src/routes/auth.ts+++ b/backend/src/routes/auth.ts@@ -212,10 +212,11 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {})// 4) Scan to sign in (lib/harnessSession.ts). A signed-in computer asks for a one-time code for- // its Add Phone QR; the phone that scans it redeems the code for a session of its own. Only an- // Autonomous sign-in can hand one off — a phone's session cannot mint more of itself.+ // 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) => {- if (req.user!.harnessSessionId) {+ 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)}try {diff --git a/backend/src/routes/machines.ts b/backend/src/routes/machines.tsindex 1de95d026..fc0cf762e 100644--- a/backend/src/routes/machines.ts+++ b/backend/src/routes/machines.ts@@ -8,6 +8,8 @@ import { isMachineId } from '../utils/slug.js'import { sendSuccess, sendCreated, sendError } from '../utils/response.js'import { logger } from '../utils/logger.js'import { bearerToken } from '../lib/ssoAuth.js'+import { isHarnessAccessToken } from '../lib/harnessTokenFormat.js'+import { AppError } from '../errors/index.js'import { requestedWebOrigin, resolveWebOrigin } from '../lib/sso.js'import { storedAutonomousEnvironment } from '../lib/autonomousEnvironment.js'import { env } from '../config/env.js'@@ -60,6 +62,12 @@ const billingCompleteBody = z.object({function requestAccessToken(authorization: string | undefined): string {const token = bearerToken(authorization)if (!token) throw new Error('Authenticated request is missing its SSO access token')+ // Billing is the Autonomous account's own business, and the caller's token is forwarded there+ // (lib/autonomousBff.ts). A session Harness issued itself — a phone, or a computer signed in by+ // scanning its QR — means nothing to that service: say what to do instead of a 502 from upstream.+ if (isHarnessAccessToken(token)) {+ throw new AppError('Billing needs your Autonomous sign-in. Sign in with SSO on this device (harness login --sso).', 403, 'NEEDS_AUTONOMOUS_SIGN_IN')+ }return token}diff --git a/backend/src/routes/qrSignIn.test.ts b/backend/src/routes/qrSignIn.test.tsnew file mode 100644index 000000000..571c050e3--- /dev/null+++ b/backend/src/routes/qrSignIn.test.ts@@ -0,0 +1,180 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import Fastify, { type FastifyInstance } from 'fastify'++// In-memory Redis and sessions, so the real QR sign-in, session and authentication code runs.+const fakes = vi.hoisted(() => {+ const redis = new Map<string, string>()+ const ttls = new Map<string, number>()+ const sessions: Array<Record<string, unknown> & { id: string }> = []+ const users = new Map<string, Record<string, unknown>>()+ const pick = (where: Record<string, unknown>) =>+ sessions.find((s) => Object.entries(where).every(([k, v]) => s[k] === v)) ?? null+ const set = (key: string, value: string, ...opts: unknown[]) => {+ if (opts.includes('NX') && redis.has(key)) return null+ if (opts.includes('XX') && !redis.has(key)) return null+ redis.set(key, value)+ const ex = opts.indexOf('EX')+ if (ex >= 0) ttls.set(key, opts[ex + 1] as number)+ else if (!opts.includes('KEEPTTL')) ttls.delete(key)+ return 'OK'+ }+ const pub = {+ set: vi.fn(async (key: string, value: string, ...opts: unknown[]) => set(key, value, ...opts)),+ get: vi.fn(async (key: string) => redis.get(key) ?? null),+ del: vi.fn(async (key: string) => (redis.delete(key) ? 1 : 0)),+ 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 },+ set: (key: string, value: string, ...opts: unknown[]) => { ops.push(() => set(key, value, ...opts)); return chain },+ expire: (key: string, sec: number) => { ops.push(() => (redis.has(key) ? (ttls.set(key, sec), 1) : 0)); return chain },+ exec: async () => ops.map((op) => [null, op()]),+ }+ return chain+ }),+ }+ const harnessSession = {+ create: vi.fn(async ({ data }: { data: Record<string, unknown> }) => {+ const row = { id: `s${sessions.length + 1}`, revokedAt: null, ...data }+ sessions.push(row); return row+ }),+ findUnique: vi.fn(async ({ where }: { where: Record<string, unknown> }) => pick(where)),+ update: vi.fn(async ({ where, data }: { where: { id: string }; data: Record<string, unknown> }) => {+ const row = pick(where)!; Object.assign(row, data); return row+ }),+ updateMany: vi.fn(async () => ({ count: 0 })),+ }+ return { redis, ttls, sessions, users, pub, harnessSession, get: vi.fn(async (id: string) => users.get(id) ?? null) }+})++vi.mock('../lib/bus.js', () => ({ pub: fakes.pub }))+vi.mock('../lib/prisma.js', () => ({ prisma: { harnessSession: fakes.harnessSession } }))+vi.mock('../services/UserService.js', () => ({+ userService: { get: fakes.get, findByEmail: vi.fn() },+ normalizeUserEmail: (email: string) => email.trim().toLowerCase(),+ isProvisionalUserEmail: () => false,+}))+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 { qrSignInRoutes } from './qrSignIn.js'+import { authRoutes } from './auth.js'+import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'+import { errorHandler } from '../middlewares/errorHandler.js'++const USER = 'u1'+const COMPUTER_ID = '45fd3b2c-6ac9-4bde-be9d-ef1d31beb937'++describe('sign a computer in by scanning its QR', () => {+ let app: FastifyInstance+ let phone: string++ beforeEach(async () => {+ fakes.redis.clear()+ fakes.ttls.clear()+ fakes.sessions.length = 0+ fakes.users.set(USER, { id: USER, email: '[email protected]', role: 'user', autonomousEnv: 'prod' })+ // The phone: itself signed in by an earlier QR (a Harness viewer session).+ const { code } = await startHandoff(USER)+ phone = (await redeemHandoff(code, 'phone'))!.token+ app = Fastify()+ app.setErrorHandler(errorHandler)+ registerAuthMiddleware(app)+ await app.register(authRoutes)+ await app.register(qrSignInRoutes)+ await app.ready()+ })++ const post = (url: string, payload: unknown, headers: Record<string, string> = {}) =>+ app.inject({ method: 'POST', url, payload: payload as never, headers })+ const asPhone = (ip = '1.2.3.4') => ({ authorization: `Bearer ${phone}`, 'cf-connecting-ip': ip })+ const start = async (ip = '1.2.3.4') =>+ (await post('/api/auth/qr/start', { label: 'MacBook Pro', kind: 'computer', computerId: COMPUTER_ID }, { 'cf-connecting-ip': ip, 'cf-ipcountry': 'VN' })).json().data as { code: string; pollToken: string }++ it('signs the computer in only after the phone approves and the computer claims', async () => {+ const { code, pollToken } = await start()+ expect((await post('/api/auth/qr/poll', { pollToken })).json().data).toEqual({ status: 'pending' })+ const look = (await post('/api/auth/qr/lookup', { code }, asPhone())).json().data+ expect(look).toMatchObject({ label: 'MacBook Pro', kind: 'computer', country: 'VN', ipHint: '1.2.3.x', sameNetwork: true })+ expect((await post('/api/auth/qr/approve', { code }, asPhone())).statusCode).toBe(200)+ // Approved names the account, and nothing more: no session exists yet.+ expect((await post('/api/auth/qr/poll', { pollToken })).json().data).toEqual({ status: 'approved', email: '[email protected]' })+ expect(fakes.sessions).toHaveLength(1)+ const claimed = (await post('/api/auth/qr/claim', { pollToken })).json().data+ expect(claimed).toMatchObject({ email: '[email protected]', kind: 'computer', autonomousEnv: 'prod' })+ expect(fakes.sessions.at(-1)).toMatchObject({ kind: 'computer', label: 'MacBook Pro', userId: USER })+ // Once only.+ expect((await post('/api/auth/qr/claim', { pollToken })).statusCode).toBe(401)+ // The computer's session may connect as a machine; the phone's may not.+ await expect(authenticateAccessToken(claimed.token, 'prod', { allowHarnessSession: 'computer' })).resolves.toMatchObject({ sub: USER, harnessSessionKind: 'computer' })+ await expect(authenticateAccessToken(phone, 'prod', { allowHarnessSession: 'computer' })).rejects.toBeInstanceOf(SsoAuthError)+ })++ it('tells the phone when the computer is on another network, without its full address', async () => {+ const { code } = await start('9.8.7.6')+ const look = (await post('/api/auth/qr/lookup', { code }, asPhone('1.2.3.4'))).json().data+ expect(look).toMatchObject({ sameNetwork: false, ipHint: '9.8.7.x' })+ })++ it('a denial reaches the computer, and nothing can be claimed', async () => {+ const { code, pollToken } = await start()+ await post('/api/auth/qr/deny', { code }, asPhone())+ expect((await post('/api/auth/qr/poll', { pollToken })).json().data).toEqual({ status: 'denied' })+ expect((await post('/api/auth/qr/claim', { pollToken })).statusCode).toBe(401)+ })++ it('takes the first answer only', async () => {+ const { code } = await start()+ expect((await post('/api/auth/qr/approve', { code }, asPhone())).statusCode).toBe(200)+ expect((await post('/api/auth/qr/deny', { code }, asPhone())).statusCode).toBe(409)+ })++ it('the computer can take its QR back', async () => {+ const { code, pollToken } = await start()+ await post('/api/auth/qr/cancel', { pollToken })+ expect((await post('/api/auth/qr/poll', { pollToken })).json().data).toEqual({ status: 'expired' })+ expect((await post('/api/auth/qr/approve', { code }, asPhone())).statusCode).toBe(404)+ })++ it('a computer must say which computer it is', async () => {+ const r = await post('/api/auth/qr/start', { label: 'x', kind: 'computer' })+ expect(r.statusCode).toBe(400)+ })++ it('keeps one code alive, but not forever', async () => {+ const { pollToken } = await start()+ expect((await post('/api/auth/qr/extend', { pollToken })).json().data.expiresIn).toBeGreaterThan(0)+ const now = Date.now()+ const spy = vi.spyOn(Date, 'now').mockReturnValue(now + (QR_SIGN_IN_MAX_LIFE_SEC + 1) * 1000)+ expect((await post('/api/auth/qr/extend', { pollToken })).statusCode).toBe(410)+ spy.mockRestore()+ })++ it('once approved, waits out its whole life for the computer to say yes', async () => {+ const { code, pollToken } = await start()+ const keys = [...fakes.redis.keys()].filter((k) => k.startsWith('hnauth:qr'))+ expect(keys.map((k) => fakes.ttls.get(k))).toEqual([120, 120])+ expect((await post('/api/auth/qr/approve', { code }, asPhone())).statusCode).toBe(200)+ // The person at the computer may be slower than two minutes: it now lives to the end of its life,+ // and an extend the computer had in flight does not cut that short again.+ for (const k of keys) expect(fakes.ttls.get(k)).toBeGreaterThan(QR_SIGN_IN_MAX_LIFE_SEC - 5)+ expect((await post('/api/auth/qr/extend', { pollToken })).json().data.expiresIn).toBeGreaterThan(QR_SIGN_IN_MAX_LIFE_SEC - 5)+ for (const k of keys) expect(fakes.ttls.get(k)).toBeGreaterThan(QR_SIGN_IN_MAX_LIFE_SEC - 5)+ expect((await post('/api/auth/qr/claim', { pollToken })).statusCode).toBe(200)+ })++ it('the phone half needs a sign-in; the computer half does not', async () => {+ const { code } = await start()+ expect((await post('/api/auth/qr/lookup', { code })).statusCode).toBe(401)+ })++ it('a computer signed in by QR may add a phone; a phone signed in by QR may not', async () => {+ const { code, pollToken } = await start()+ await post('/api/auth/qr/approve', { code }, asPhone())+ const computer = (await post('/api/auth/qr/claim', { pollToken })).json().data.token+ expect((await post('/api/auth/handoff', {}, { authorization: `Bearer ${computer}` })).statusCode).toBe(200)+ expect((await post('/api/auth/handoff', {}, { authorization: `Bearer ${phone}` })).statusCode).toBe(403)+ })+})diff --git a/backend/src/routes/qrSignIn.ts b/backend/src/routes/qrSignIn.tsnew file mode 100644index 000000000..2ebf0929f--- /dev/null+++ b/backend/src/routes/qrSignIn.ts@@ -0,0 +1,113 @@+import type { FastifyInstance, FastifyReply } from 'fastify'+import { z } from 'zod'+import {+ answerQrSignIn, cancelQrSignIn, claimQrSignIn, extendQrSignIn, lookupQrSignIn, pollQrSignIn, startQrSignIn,+} from '../lib/harnessSession.js'+import { clientIpFromHeaders, countryCodeFromHeaders } from '../lib/clientGeo.js'+import { validateBody } from '../middlewares/validation.js'+import { sendError, sendSuccess } from '../utils/response.js'+import { logger } from '../utils/logger.js'++/**+ * Sign a computer in by scanning its QR with a signed-in phone (lib/harnessSession.ts has the flow).+ * The computer's half — start, poll, extend, claim, cancel — carries no sign-in, only its poll token;+ * the phone's half — lookup, approve, deny — carries the phone's, whatever kind it is.+ */++const start = z.object({+ label: z.string().trim().min(1).max(80),+ kind: z.enum(['computer', 'viewer']),+ // A computer names the computer it is, so the session it gets is one; an app does not.+ computerId: z.string().regex(/^[0-9a-fA-F-]{16,64}$/).optional(),+}).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()++/** Per-process fixed windows: generous for a person, a wall for a loop. */+function limiter(perMinute: number) {+ const windows = new Map<string, { start: number; count: number }>()+ return (key: string, now = Date.now()): boolean => {+ const w = windows.get(key)+ if (!w || now - w.start >= 60_000) {+ if (windows.size >= 20_000) windows.clear()+ windows.set(key, { start: now, count: 1 })+ return true+ }+ return ++w.count <= perMinute+ }+}+const startLimit = limiter(10)+const pollLimit = limiter(90)+const answerLimit = limiter(20)++const unavailable = (reply: FastifyReply, e: unknown, what: string) => {+ logger.error(`qr sign-in ${what} failed`, e)+ return sendError(reply, 'Authentication service unavailable', 'AUTH_SERVICE_UNAVAILABLE', 503)+}+const tooMany = (reply: FastifyReply) => sendError(reply, 'Too many tries. Wait a minute.', 'RATE_LIMITED', 429)++export async function qrSignInRoutes(app: FastifyInstance): Promise<void> {+ app.post<{ Body: z.infer<typeof start> }>('/api/auth/qr/start', { preHandler: validateBody(start) }, async (req, reply) => {+ const ip = clientIpFromHeaders(req.headers, req.socket.remoteAddress)+ if (!startLimit(ip ?? 'unknown')) return tooMany(reply)+ if (req.body.kind === 'computer' && !req.body.computerId) {+ return sendError(reply, 'A computer names itself to sign in.', 'COMPUTER_ID_REQUIRED', 400)+ }+ try {+ return sendSuccess(reply, await startQrSignIn(req.body, { ...(ip ? { ip } : {}), ...(countryCodeFromHeaders(req.headers) ? { country: countryCodeFromHeaders(req.headers) } : {}) }))+ } catch (e) { return unavailable(reply, e, 'start') }+ })++ app.post<{ Body: z.infer<typeof byPoll> }>('/api/auth/qr/poll', { preHandler: validateBody(byPoll) }, async (req, reply) => {+ if (!pollLimit(req.body.pollToken)) return tooMany(reply)+ try { return sendSuccess(reply, await pollQrSignIn(req.body.pollToken)) } catch (e) { return unavailable(reply, e, 'poll') }+ })++ app.post<{ Body: z.infer<typeof byPoll> }>('/api/auth/qr/extend', { preHandler: validateBody(byPoll) }, async (req, reply) => {+ if (!pollLimit(req.body.pollToken)) return tooMany(reply)+ try {+ const expiresIn = await extendQrSignIn(req.body.pollToken)+ if (expiresIn === null) return sendError(reply, 'This code has expired.', 'QR_EXPIRED', 410)+ return sendSuccess(reply, { expiresIn })+ } catch (e) { return unavailable(reply, e, 'extend') }+ })++ app.post<{ Body: z.infer<typeof byPoll> }>('/api/auth/qr/claim', { preHandler: validateBody(byPoll) }, async (req, reply) => {+ if (!pollLimit(req.body.pollToken)) return tooMany(reply)+ try {+ const tokens = await claimQrSignIn(req.body.pollToken)+ if (!tokens) return sendError(reply, 'Nothing to claim: scan again.', 'QR_INVALID', 401)+ logger.info('qr sign-in claimed', { kind: tokens.kind })+ return sendSuccess(reply, tokens)+ } catch (e) { return unavailable(reply, e, 'claim') }+ })++ app.post<{ Body: z.infer<typeof byPoll> }>('/api/auth/qr/cancel', { preHandler: validateBody(byPoll) }, async (req, reply) => {+ try { await cancelQrSignIn(req.body.pollToken); return sendSuccess(reply, { cancelled: true }) } catch (e) { return unavailable(reply, e, 'cancel') }+ })++ // The phone's half.+ app.post<{ Body: z.infer<typeof byCode> }>('/api/auth/qr/lookup', { preHandler: validateBody(byCode) }, async (req, reply) => {+ if (!answerLimit(req.user!.sub)) return tooMany(reply)+ try {+ const ip = clientIpFromHeaders(req.headers, req.socket.remoteAddress)+ const found = await lookupQrSignIn(req.body.code, ip ? { ip } : {})+ if (!found) return sendError(reply, 'That code has expired. Scan the new one.', 'QR_INVALID', 404)+ return sendSuccess(reply, found)+ } catch (e) { return unavailable(reply, e, 'lookup') }+ })++ const answer = (approve: boolean) => async (req: { body: z.infer<typeof byCode>; user?: { sub: string; email: string } }, reply: FastifyReply) => {+ const user = req.user!+ if (!answerLimit(user.sub)) return tooMany(reply)+ try {+ const out = await answerQrSignIn(req.body.code, approve ? { approve: true, userId: user.sub, email: user.email } : { approve: false })+ if (out === 'gone') return sendError(reply, 'That code has expired. Scan the new one.', 'QR_INVALID', 404)+ if (out === 'answered') return sendError(reply, 'This code was already answered.', 'QR_ANSWERED', 409)+ logger.info(`qr sign-in ${approve ? 'approved' : 'denied'}`, { userId: user.sub })+ return sendSuccess(reply, { ok: true })+ } catch (e) { return unavailable(reply, e, approve ? 'approve' : 'deny') }+ }+ 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))+}diff --git a/backend/src/server.ts b/backend/src/server.tsindex f739a7287..0177a01f9 100644--- a/backend/src/server.ts+++ b/backend/src/server.ts@@ -12,6 +12,7 @@ import { voiceRoutes } from './routes/voice.js'import { harnessShareRoutes } from './routes/harnessShares.js'import { harnessLinkRoutes } from './routes/harnessLinks.js'import { deviceKeyRoutes } from './routes/deviceKeys.js'+import { qrSignInRoutes } from './routes/qrSignIn.js'import { deskRoutes } from './routes/desk.js'import { tabChannelRoutes } from './routes/tabChannels.js'import { zooRoutes } from './routes/zoo.js'@@ -171,6 +172,7 @@ async function start(): Promise<void> {await app.register(storeRoutes) // the Harness Store's ratings and reviews; the catalogue is the CLI's registryawait app.register(harnessShareRoutes)await app.register(harnessLinkRoutes)+ await app.register(qrSignInRoutes) // sign a computer in by scanning its QR with a signed-in phoneawait app.register(deviceKeyRoutes) // the account's device key log: signing in is what trusts a deviceawait app.register(deskRoutes) // the account's tabs, the same on every computer (lib/desk.ts)if (env.HARNESS_CHANNELS) await app.register(tabChannelRoutes)