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.

feat: sign the desktop app, web and CLI in by scanning a QR with your phone (#519)

0xken15d8c2f184f86f
diff --git a/cli/package-lock.json b/cli/package-lock.json
index e9379644d..fdb5eb7ef 100644
--- a/cli/package-lock.json
+++ b/cli/package-lock.json
@@ -16,12 +16,14 @@
"bonjour-service": "^1.4.4",
"chokidar": "^4.0.0",
"dotenv": "^17.2.3",
+ "qrcode-generator": "^2.0.4",
"werift": "0.24.4",
"ws": "^8.18.0",
"zod": "^4.0.0"
},
"bin": {
- "harness": "dist/cli.js"
+ "harness": "dist/cli.js",
+ "hn": "dist/cli.js"
},
"devDependencies": {
"@types/node": "^20.14.10",
@@ -2268,6 +2270,12 @@
"node": ">=16.0.0"
}
},
+ "node_modules/qrcode-generator": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/qrcode-generator/-/qrcode-generator-2.0.4.tgz",
+ "integrity": "sha512-mZSiP6RnbHl4xL2Ap5HfkjLnmxfKcPWpWe/c+5XxCuetEenqmNFf1FH/ftXPCtFG5/TDobjsjz6sSNL0Sr8Z9g==",
+ "license": "MIT"
+ },
"node_modules/readdirp": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz",
diff --git a/cli/package.json b/cli/package.json
index b580438f7..c5affd85f 100644
--- a/cli/package.json
+++ b/cli/package.json
@@ -33,6 +33,7 @@
"bonjour-service": "^1.4.4",
"chokidar": "^4.0.0",
"dotenv": "^17.2.3",
+ "qrcode-generator": "^2.0.4",
"werift": "0.24.4",
"ws": "^8.18.0",
"zod": "^4.0.0"
diff --git a/cli/src/authCommand.spec.ts b/cli/src/authCommand.spec.ts
index 354549a3b..4c7299daf 100644
--- a/cli/src/authCommand.spec.ts
+++ b/cli/src/authCommand.spec.ts
@@ -153,6 +153,7 @@ describe('harness auth status --json', () => {
machineId: 'm_seeded',
autonomousEnv: 'prod',
expiresAt: expect.any(Number),
+ method: 'sso',
})
})
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index dc69e803d..9587ca703 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -70,6 +70,9 @@ import { LocalPresence, PAIR_HARNESS_DSH, ZooTurnCounter, ZooTurnReporter } from
import { ZooLessonReporter } from './lib/zooLessons.js'
import { DAEMONS_OFF, DAEMONS_OFF_DETAIL, DaemonsSwitch, localKillSwitch, zooPassthrough, type ZooRead } from './lib/daemonsSwitch.js'
import { handOffToGrid } from './lib/gridHandoff.js'
+import { qrSignIn } from './lib/qrSignIn.js'
+import { pickSignInMethod } from './lib/signInMethodPicker.js'
+import { terminalQr } from './lib/terminalQr.js'
import { ensureGridInstalled } from './lib/gridInstall.js'
import { ensureHarnessGrid, type EnsureStatus } from './lib/gridEnsure.js'
import { passThroughToGridLogout } from './lib/gridLogout.js'
@@ -397,8 +400,10 @@ ${PROCESS_ENGINES.map((engine) => ` ${ENGINE_CLI_COMMANDS[engine]}`).join('\n')
A launcher that hands the pane to one of these works the same — "ori claude" is a Claude Code agent.
Machine:
- harness login sign in with SSO and save this computer's session
- harness login --force stop the daemon and sign in with a different SSO account
+ harness login sign in (asks: SSO in your browser, or scan a QR with your phone)
+ harness login --sso sign in with SSO in your browser, without asking
+ harness login --qr sign in by scanning a QR with Harness on your phone, without asking
+ harness login --force stop the daemon and sign in with a different account
harness login --json emit machine-readable NDJSON instead of opening a browser (for GUI clients)
harness login --entry-point=desktop record which surface started the sign-in (GUI clients; default cli)
harness auth status --json print {loggedIn,...} for this computer's saved session
@@ -704,9 +709,15 @@ async function authStatusCommand(json: boolean): Promise<void> {
machineId: latest?.machineId,
autonomousEnv: latest?.autonomousEnv,
expiresAt: latest?.expiresAt,
+ method: latest?.method ?? 'sso',
}
if (json) console.log(JSON.stringify(payload))
- else console.log(`\n ${payload.loggedIn ? '✓ Signed in' : '✗ Not signed in'}${payload.machineId ? ` (machine ${payload.machineId})` : ''}\n`)
+ else {
+ console.log(`\n ${payload.loggedIn ? '✓ Signed in' : '✗ Not signed in'}${payload.machineId ? ` (machine ${payload.machineId})` : ''}${payload.loggedIn && payload.method === 'qr' ? ' — by your phone' : ''}\n`)
+ // A session a phone approved is Harness's own: the Autonomous services behind billing and grid
+ // do not take it. Say so where the person looks, not only when one of them refuses.
+ if (payload.loggedIn && payload.method === 'qr') console.log(' Billing and grid need an SSO sign-in: harness login --force --sso\n')
+ }
}
/**
@@ -763,7 +774,7 @@ async function loginCommand(
foreground: boolean,
force: boolean,
json: boolean,
- opts: { chained?: boolean; entryPoint?: string } = {},
+ opts: { chained?: boolean; entryPoint?: string; method?: 'sso' | 'qr' | 'ask' } = {},
): 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
@@ -773,13 +784,19 @@ async function loginCommand(
// Harness only. Grid is an add-on: this computer is signed in to it the first time a grid feature is
// used (`ensureGrid` in the daemon, `lib/gridAttach.ts`) — with this session's token, no second
// browser — and never as a side effect of signing in to Harness.
- const succeed = async (alreadySignedIn: boolean): Promise<SignInOutcome> => {
+ const succeed = async (alreadySignedIn: boolean, email?: string): Promise<SignInOutcome> => {
if (opts.chained) return { signedIn: true, alreadySignedIn }
- if (json) emit(alreadySignedIn ? { type: 'result', status: 'success', alreadySignedIn: true } : { type: 'result', status: 'success' })
+ if (json) emit(alreadySignedIn ? { type: 'result', status: 'success', alreadySignedIn: true } : { type: 'result', status: 'success', ...(email ? { email } : {}) })
else if (alreadySignedIn) console.log('\n ✓ Already signed in. Run `harness start` to connect this computer.\n')
- else console.log('\n ✓ Signed in. Run `harness start` to connect this computer.\n')
+ else console.log(`\n ✓ Signed in${email ? ` as ${email}` : ''}. Run \`harness start\` to connect this computer.\n`)
return { signedIn: true, alreadySignedIn }
}
+ // SSO in the browser, or a QR the phone scans. Asked only of a person at a terminal with no flag; a
+ // client driving --json says `--qr` or gets the browser, as before.
+ let method: 'sso' | 'qr' = opts.method === 'qr' ? 'qr' : 'sso'
+ const signIn = (): Promise<SignInOutcome> => method === 'qr'
+ ? qrSignInCommand(json, emit, (email) => succeed(false, email))
+ : browserSignIn(json, emit, () => succeed(false), entryPoint)
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
@@ -800,7 +817,16 @@ async function loginCommand(
}
return await succeed(true)
}
- if (!force) return await browserSignIn(json, emit, () => succeed(false), entryPoint)
+ if (opts.method === 'ask') {
+ const picked = await askSignInMethod()
+ if (!picked) {
+ console.error('\n ✗ Not signed in.\n')
+ process.exitCode = 1
+ return { signedIn: false }
+ }
+ method = picked
+ }
+ if (!force) return await signIn()
// A forced login may intentionally switch SSO accounts. The old daemon must not keep streaming
// under its existing socket while this process replaces the durable session — and no NEW daemon
// may come up on the old session in the meantime. The desktop app re-runs `harness start` whenever
@@ -817,7 +843,7 @@ async function loginCommand(
// the browser. There is nothing to race either: the lock is held, and the identity swap happens
// afterwards, once there is an identity to swap to (`restartDaemonForIdentity`).
if (readAuthSession()) await stopDaemonProcess()
- return await browserSignIn(json, emit, () => succeed(false), entryPoint)
+ return await signIn()
}, {
onWaiting: (owner) => console.error(` the daemon is ${describeSpawnLockOwner(owner)} — waiting for it to finish…`),
})
@@ -840,6 +866,84 @@ async function loginCommand(
}
}
+/** `harness login` at a terminal, with no flag: which way to sign in. Enter is SSO, as it always was. */
+async function askSignInMethod(): Promise<'sso' | 'qr' | null> {
+ const method = await pickSignInMethod({ input: process.stdin, output: process.stdout })
+ if (method) console.log(` (next time: harness login --${method})`)
+ return method
+}
+
+/** One line from standard input — the person at the terminal, or the app driving `--json`. */
+function askLine(question: string): Promise<string> {
+ return new Promise((resolve) => {
+ const rl = createInterface({ input: process.stdin, ...(question ? { output: process.stdout } : {}) })
+ let done = false
+ const finish = (line: string): void => { if (done) return; done = true; rl.close(); resolve(line) }
+ rl.on('close', () => finish(''))
+ if (question) rl.question(question, finish)
+ else rl.once('line', finish)
+ })
+}
+
+/**
+ * The QR half of a sign-in (lib/qrSignIn.ts): show a QR, wait for a signed-in phone to approve it,
+ * ask the person here whether to sign in as the account that approved, then save the session.
+ * Under --json the QR is an event (`{"type":"qr"}`) and the question is one too
+ * (`{"type":"confirm","email"}`), answered with a `yes` or `no` line on standard input.
+ */
+async function qrSignInCommand(
+ json: boolean,
+ emit: (line: Record<string, unknown>) => void,
+ succeed: (email: string) => Promise<SignInOutcome>,
+): 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 }
+ }
+ let shown = false
+ const result = await qrSignIn({
+ post: (path, body) => postJson(path, body),
+ label: hostname().slice(0, 80),
+ computerId: computerId(),
+ show: (link, expiresIn) => {
+ if (json) { emit({ type: 'qr', url: link, expiresIn }); return }
+ if (shown) return
+ shown = true
+ console.log('\n On your phone, open Harness ▸ Settings ▸ Sign in a computer, and scan:\n')
+ console.log(terminalQr(link).split('\n').map((l) => ` ${l}`).join('\n'))
+ console.log('\n Waiting for your phone…')
+ },
+ confirm: async (email) => {
+ if (json) {
+ emit({ type: 'confirm', email })
+ return (await askLine('')).trim().toLowerCase() === 'yes'
+ }
+ const answer = await askLine(`\n Your phone approved this sign-in for ${email}.\n Sign in as ${email}? [Y/n] `)
+ return !/^n/i.test(answer.trim())
+ },
+ })
+ if (!result.ok) return fail(result.code, result.message)
+ const { tokens } = result
+ writeAuthSession({
+ version: 1,
+ accessToken: tokens.token,
+ ...(tokens.refreshToken ? { refreshToken: tokens.refreshToken } : {}),
+ ...(tokens.expiresIn ? { expiresAt: Date.now() + tokens.expiresIn * 1000 } : {}),
+ autonomousEnv: tokens.autonomousEnv ?? env.AUTONOMOUS_ENV,
+ computerId: computerId(),
+ method: 'qr',
+ updatedAt: Date.now(),
+ })
+ try {
+ await resolveComputerMachine()
+ } catch (err) {
+ return fail('BACKEND_ERROR', (err as Error).message)
+ }
+ return await succeed(tokens.email)
+}
+
/**
* The browser half of a sign-in: a loopback callback server, the SSO page, the code exchange, and
* the new session — machine id included — on disk. Under --json every failure is a result line and
@@ -7840,7 +7944,7 @@ async function groupCommand(sub: string | undefined, arg: string | undefined, js
console.log('\n No trust group yet. Link another machine (`harness link connect <machineId>`) or a phone to start one.\n')
process.exit(0)
}
- console.log('\n Trust group — each of these reaches every other without a password:\n')
+ console.log('\n Trust group — each of these reaches every other:\n')
members.forEach((m, i) => {
const id = m.kind === 'machine' ? m.machineId : 'viewer app'
console.log(` ${String(i + 1).padStart(2)}. ${m.label} ${id} ${m.fingerprint}`)
@@ -8248,7 +8352,10 @@ switch (cmd) {
case 'login':
// The result line goes out FIRST (loginCommand prints it), then the daemon is swapped onto the
// 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() })
+ loginCommand(foreground, flags.includes('--force'), flags.includes('--json'), {
+ entryPoint: entryPointFlag(),
+ method: flags.includes('--qr') ? 'qr' : flags.includes('--sso') || flags.includes('--json') || !process.stdin.isTTY ? 'sso' : 'ask',
+ })
.then((outcome) => outcome.signedIn ? restartDaemonForIdentity() : undefined)
.catch(onError)
break
diff --git a/cli/src/lib/authSession.ts b/cli/src/lib/authSession.ts
index 0da8a91d2..e535116d2 100644
--- a/cli/src/lib/authSession.ts
+++ b/cli/src/lib/authSession.ts
@@ -10,6 +10,9 @@ export interface AuthSession {
autonomousEnv: 'prod' | 'stag'
computerId: string
machineId?: string
+ /** How this computer signed in: `qr` — a phone scanned its QR (a Harness-issued session, which
+ * the Autonomous services behind billing and grid do not take); absent or `sso` — the browser. */
+ method?: 'sso' | 'qr'
updatedAt: number
}
@@ -41,6 +44,7 @@ function parse(raw: string): AuthSession | null {
autonomousEnv: value.autonomousEnv,
computerId: value.computerId,
...(typeof value.machineId === 'string' && value.machineId ? { machineId: value.machineId } : {}),
+ ...(value.method === 'qr' || value.method === 'sso' ? { method: value.method } : {}),
updatedAt: typeof value.updatedAt === 'number' ? value.updatedAt : 0,
}
} catch { return null }
diff --git a/cli/src/lib/gridHandoff.spec.ts b/cli/src/lib/gridHandoff.spec.ts
index 5ccd2ca53..13782a1e7 100644
--- a/cli/src/lib/gridHandoff.spec.ts
+++ b/cli/src/lib/gridHandoff.spec.ts
@@ -82,6 +82,17 @@ describe('handOffToGrid — which grid it runs', () => {
expect(updateCheckSeenBy('override')).toBe('1')
})
+ it('does not hand grid a session a phone approved: grid signs in with the Autonomous account', async () => {
+ const override = fakeGrid(join(root, 'elsewhere'), 'override')
+ process.env.HARNESS_GRID_BIN = override
+ const { handOffToGrid } = await load()
+
+ const result = await handOffToGrid('hna_' + 'x'.repeat(43), { json: true })
+
+ expect(result).toMatchObject({ code: 'GRID_NEEDS_SSO', exitCode: 1 })
+ expect(result.message).toContain('harness login --force --sso')
+ })
+
it('prefers the managed runtime over a grid on PATH', async () => {
fakeGrid(join(root, 'path-bin'), 'path')
process.env.PATH = join(root, 'path-bin')
diff --git a/cli/src/lib/gridHandoff.ts b/cli/src/lib/gridHandoff.ts
index 08e851b30..5c424cd86 100644
--- a/cli/src/lib/gridHandoff.ts
+++ b/cli/src/lib/gridHandoff.ts
@@ -29,7 +29,7 @@ export const GRID_HANDOFF_FLAG = '--harness'
*/
const ARGPARSE_USAGE_EXIT = 2
-export type GridHandoffCode = 'OK' | 'GRID_CLI_MISSING' | 'GRID_CLI_OUTDATED' | 'GRID_LOGIN_FAILED'
+export type GridHandoffCode = 'OK' | 'GRID_CLI_MISSING' | 'GRID_CLI_OUTDATED' | 'GRID_LOGIN_FAILED' | 'GRID_NEEDS_SSO'
export interface GridHandoffResult {
code: GridHandoffCode
@@ -105,6 +105,11 @@ export async function handOffToGrid(
// installing one, not a spawn error the caller has to recognise — and a present-but-unrunnable
// one (EACCES, never ENOENT) is caught too. Resolved off this process's own environment, which is
// the one place the override and the runtime dir are read from.
+ // A computer a phone signed in by QR holds a session Harness issued itself; grid signs in with the
+ // Autonomous account, which does not know it. Say what to do rather than let `grid` refuse it.
+ if (token.startsWith('hna_')) {
+ return { code: 'GRID_NEEDS_SSO', exitCode: 1, message: 'Grid needs an SSO sign-in on this computer: harness login --force --sso', stdout: '', stderr: '' }
+ }
const binary = gridBinaryPath()
if (!binaryOnPath(binary)) {
return { code: 'GRID_CLI_MISSING', exitCode: 1, message: MISSING_MESSAGE, stdout: '', stderr: '' }
diff --git a/cli/src/lib/qrSignIn.spec.ts b/cli/src/lib/qrSignIn.spec.ts
new file mode 100644
index 000000000..fc740d7b0
--- /dev/null
+++ b/cli/src/lib/qrSignIn.spec.ts
@@ -0,0 +1,99 @@
+import { describe, expect, it, vi } from 'vitest'
+import { 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. */
+function backend(polls: Array<{ status: string; email?: string }>, opts: { extend?: 'ok' | 'fail'; claim?: 'ok' | 'fail' } = {}) {
+ const calls: Array<{ path: string; body: unknown }> = []
+ let clock = 0
+ const post = vi.fn(async (path: string, body: unknown) => {
+ calls.push({ path, body })
+ if (path === '/api/auth/qr/start') return { code: 'hnq_code', pollToken: 'hnp_poll', expiresIn: 120 }
+ if (path === '/api/auth/qr/poll') return polls.shift() ?? { status: 'pending' }
+ if (path === '/api/auth/qr/extend') {
+ if (opts.extend === 'fail') throw new Error('This code has expired.')
+ return { expiresIn: 120 }
+ }
+ if (path === '/api/auth/qr/claim') {
+ if (opts.claim === 'fail') throw new Error('Nothing to claim')
+ return { token: 'hna_x', refreshToken: 'hnr_x', expiresIn: 3600, autonomousEnv: 'prod', email: '[email protected]' }
+ }
+ if (path === '/api/auth/qr/cancel') return { cancelled: true }
+ throw new Error(`unexpected ${path}`)
+ })
+ const deps = (confirm = true): QrSignInDeps & { shown: string[] } => {
+ const shown: string[] = []
+ return {
+ post: post as QrSignInDeps['post'],
+ show: (link) => { shown.push(link) },
+ confirm: vi.fn(async () => confirm),
+ label: 'MacBook Pro',
+ computerId: 'c-1',
+ sleep: async (ms) => { clock += ms },
+ now: () => clock,
+ pollEveryMs: 2_000,
+ shown,
+ }
+ }
+ return { calls, deps, paths: () => calls.map((c) => c.path) }
+}
+
+describe('qrSignIn', () => {
+ it('shows the QR, waits, asks the person, and only then claims the session', async () => {
+ const b = backend([{ status: 'pending' }, { status: 'approved', email: '[email protected]' }])
+ const d = b.deps(true)
+ const r = await qrSignIn(d)
+ expect(r).toEqual({ ok: true, tokens: expect.objectContaining({ token: 'hna_x', email: '[email protected]' }) })
+ expect(d.shown).toEqual([qrSignInLink('hnq_code')])
+ expect(d.confirm).toHaveBeenCalledWith('[email protected]')
+ expect(b.paths()).toEqual(['/api/auth/qr/start', '/api/auth/qr/poll', '/api/auth/qr/poll', '/api/auth/qr/claim'])
+ expect(b.calls[0].body).toEqual({ label: 'MacBook Pro', kind: 'computer', computerId: 'c-1' })
+ })
+
+ it('claims nothing when the person says no to that account, and takes the QR back', async () => {
+ const b = backend([{ status: 'approved', email: '[email protected]' }])
+ const r = await qrSignIn(b.deps(false))
+ expect(r).toMatchObject({ ok: false, code: 'CANCELLED' })
+ expect(b.paths()).not.toContain('/api/auth/qr/claim')
+ expect(b.paths()).toContain('/api/auth/qr/cancel')
+ })
+
+ it('reports a denial', async () => {
+ const r = await qrSignIn(backend([{ status: 'denied' }]).deps())
+ expect(r).toMatchObject({ ok: false, code: 'DENIED' })
+ })
+
+ it('keeps the same code alive past its first two minutes', async () => {
+ const polls: Array<{ status: string; email?: string }> = Array.from({ length: 50 }, () => ({ status: 'pending' }))
+ polls.push({ status: 'approved', email: '[email protected]' })
+ const b = backend(polls)
+ const d = b.deps()
+ const r = await qrSignIn(d)
+ expect(r.ok).toBe(true)
+ expect(b.paths().filter((p) => p === '/api/auth/qr/extend').length).toBeGreaterThan(0)
+ // One code throughout: the one the phone may already be looking at.
+ expect(new Set(d.shown)).toEqual(new Set([qrSignInLink('hnq_code')]))
+ })
+
+ it('gives up when the code can live no longer', async () => {
+ const b = backend(Array.from({ length: 200 }, () => ({ status: 'pending' })), { extend: 'fail' })
+ const r = await qrSignIn(b.deps())
+ expect(r).toMatchObject({ ok: false, code: 'EXPIRED' })
+ })
+
+ it('reports a backend that cannot start one', async () => {
+ const r = await qrSignIn({ ...backend([]).deps(), post: async () => { throw new Error('HTTP 404') } })
+ expect(r).toMatchObject({ ok: false, code: 'BACKEND_ERROR', message: 'HTTP 404' })
+ })
+})
+
+describe('terminalQr', () => {
+ it('draws a square code with a quiet zone, two module rows per line', () => {
+ const lines = terminalQr(qrSignInLink('hnq_code'), { color: false }).split('\n')
+ const width = lines[0].length
+ expect(lines.every((l) => l.length === width)).toBe(true)
+ // The quiet zone is light: full blocks all round the first line.
+ expect(lines[0]).toBe('█'.repeat(width))
+ expect(lines.length).toBe(Math.ceil(width / 2))
+ })
+})
diff --git a/cli/src/lib/qrSignIn.ts b/cli/src/lib/qrSignIn.ts
new file mode 100644
index 000000000..ba87b67fd
--- /dev/null
+++ b/cli/src/lib/qrSignIn.ts
@@ -0,0 +1,99 @@
+/**
+ * Sign this computer in by showing a QR that a signed-in phone scans and approves
+ * (backend lib/harnessSession.ts, routes/qrSignIn.ts):
+ *
+ * start → show the QR → poll (keeping the same code alive) → approved {email}
+ * → ask the person "Sign in as <email>?" → claim the session → the caller writes it.
+ *
+ * The question is not a formality. Signing in is what makes the account's devices trust this
+ * computer, so a stranger who photographs the QR and approves it with THEIR phone would otherwise
+ * get this computer's terminals. Nothing is created until the person here says yes.
+ */
+
+/** Where a sign-in QR points. The phone's scanner parses exactly this; the code rides in the
+ * fragment, which a browser never sends anywhere. */
+export const QR_SIGN_IN_ORIGIN = 'https://harness.autonomous.ai'
+
+export function qrSignInLink(code: string): string {
+ return `${QR_SIGN_IN_ORIGIN}/signin#k=${encodeURIComponent(code)}`
+}
+
+export interface QrSignInTokens {
+ token: string
+ refreshToken?: string
+ expiresIn?: number
+ autonomousEnv?: 'prod' | 'stag'
+ email: string
+}
+
+export type QrSignInFailure = 'BACKEND_ERROR' | 'DENIED' | 'EXPIRED' | 'CANCELLED'
+
+export type QrSignInResult = { ok: true; tokens: QrSignInTokens } | { ok: false; code: QrSignInFailure; message: string }
+
+export interface QrSignInDeps {
+ /** POST to the backend without a sign-in; resolves the response's `data`, rejects on an error. */
+ post: <T>(path: string, body: unknown) => Promise<T>
+ /** A new (or the same, extended) code to show. */
+ show: (link: string, expiresIn: number) => void
+ /** Ask the person whether to sign in as [email]. */
+ confirm: (email: string) => Promise<boolean>
+ label: string
+ computerId: string
+ sleep?: (ms: number) => Promise<void>
+ now?: () => number
+ pollEveryMs?: number
+}
+
+/** Extend the code this long before it runs out, so an approval given at the last moment counts. */
+const EXTEND_BEFORE_MS = 30_000
+
+export async function qrSignIn(deps: QrSignInDeps): Promise<QrSignInResult> {
+ const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)))
+ const now = deps.now ?? (() => Date.now())
+ const every = deps.pollEveryMs ?? 2_000
+ let started: { code: string; pollToken: string; expiresIn: number }
+ try {
+ started = await deps.post('/api/auth/qr/start', { label: deps.label, kind: 'computer', computerId: deps.computerId })
+ } catch (err) {
+ return { ok: false, code: 'BACKEND_ERROR', message: (err as Error).message }
+ }
+ const { pollToken } = started
+ const link = qrSignInLink(started.code)
+ let expiresAt = now() + started.expiresIn * 1000
+ deps.show(link, started.expiresIn)
+ const cancel = async (): Promise<void> => { await deps.post('/api/auth/qr/cancel', { pollToken }).catch(() => {}) }
+ for (;;) {
+ await sleep(every)
+ if (expiresAt - now() < EXTEND_BEFORE_MS) {
+ try {
+ const { expiresIn } = await deps.post<{ expiresIn: number }>('/api/auth/qr/extend', { pollToken })
+ expiresAt = now() + expiresIn * 1000
+ deps.show(link, expiresIn)
+ } catch {
+ return { ok: false, code: 'EXPIRED', message: 'The code expired. Run `harness login` again.' }
+ }
+ }
+ let state: { status: string; email?: string }
+ try {
+ state = await deps.post('/api/auth/qr/poll', { pollToken })
+ } catch {
+ continue // a blip; the next poll tries again
+ }
+ if (state.status === 'pending') continue
+ if (state.status === 'denied') return { ok: false, code: 'DENIED', message: 'Sign-in was denied on the phone.' }
+ if (state.status !== 'approved' || !state.email) {
+ return { ok: false, code: 'EXPIRED', message: 'The code expired. Run `harness login` again.' }
+ }
+ if (!(await deps.confirm(state.email))) {
+ await cancel()
+ return { ok: false, code: 'CANCELLED', message: `Not signed in as ${state.email}.` }
+ }
+ try {
+ const tokens = await deps.post<QrSignInTokens>('/api/auth/qr/claim', { pollToken })
+ if (!tokens?.token) throw new Error('the backend returned no session')
+ return { ok: true, tokens: { ...tokens, email: tokens.email ?? state.email } }
+ } catch (err) {
+ return { ok: false, code: 'BACKEND_ERROR', message: (err as Error).message }
+ }
+ }
+}
diff --git a/cli/src/lib/signInMethodPicker.spec.ts b/cli/src/lib/signInMethodPicker.spec.ts
new file mode 100644
index 000000000..324d981c5
--- /dev/null
+++ b/cli/src/lib/signInMethodPicker.spec.ts
@@ -0,0 +1,60 @@
+import { PassThrough } from 'node:stream'
+import { describe, expect, it, vi } from 'vitest'
+import { pickSignInMethod } from './signInMethodPicker.js'
+
+function tty() {
+ const input = new PassThrough() as unknown as NodeJS.ReadStream & { isTTY: boolean; setRawMode: (raw: boolean) => void }
+ input.isTTY = true
+ input.setRawMode = vi.fn()
+ const chunks: string[] = []
+ const output = new PassThrough()
+ output.on('data', (chunk: Buffer) => chunks.push(chunk.toString()))
+ const codes: Record<string, string> = { up: '\x1b[A', down: '\x1b[B', enter: '\r', esc: '\x1b', 'ctrl-c': '\x03' }
+ return {
+ input, output,
+ written: () => chunks.join(''),
+ press: (...keys: string[]) => { for (const key of keys) (input as unknown as PassThrough).write(codes[key] ?? key) },
+ }
+}
+const tick = () => new Promise((resolve) => setTimeout(resolve, 5))
+
+describe('pickSignInMethod', () => {
+ it('starts on SSO, so Enter alone is the browser as it always was', async () => {
+ const io = tty()
+ const picked = pickSignInMethod(io)
+ await tick()
+ expect(io.written()).toContain('❯ SSO in your browser')
+ io.press('enter')
+ expect(await picked).toBe('sso')
+ expect(io.input.setRawMode).toHaveBeenLastCalledWith(false)
+ })
+
+ it('moves with the arrows (and j/k), wrapping, and takes Enter', async () => {
+ const io = tty()
+ const picked = pickSignInMethod(io)
+ await tick()
+ io.press('down')
+ await tick()
+ expect(io.written().split('❯ ').at(-1)).toMatch(/^Scan a QR/)
+ io.press('j', 'k', 'up', 'up', 'enter') // qr→sso→qr→sso→qr
+ expect(await picked).toBe('qr')
+ })
+
+ it('1 and 2 take their row at once', async () => {
+ const io = tty()
+ const picked = pickSignInMethod(io)
+ await tick()
+ io.press('2')
+ expect(await picked).toBe('qr')
+ })
+
+ it('Esc and Ctrl-C leave with nothing chosen', async () => {
+ for (const key of ['esc', 'ctrl-c']) {
+ const io = tty()
+ const picked = pickSignInMethod(io)
+ await tick()
+ io.press(key)
+ expect(await picked).toBeNull()
+ }
+ })
+})
diff --git a/cli/src/lib/signInMethodPicker.ts b/cli/src/lib/signInMethodPicker.ts
new file mode 100644
index 000000000..3b022b80b
--- /dev/null
+++ b/cli/src/lib/signInMethodPicker.ts
@@ -0,0 +1,55 @@
+import { emitKeypressEvents } from 'node:readline'
+
+export type SignInMethod = 'sso' | 'qr'
+
+const OPTIONS: Array<{ method: SignInMethod; label: string }> = [
+ { method: 'sso', label: 'SSO in your browser' },
+ { method: 'qr', label: 'Scan a QR with Harness on your phone' },
+]
+
+/**
+ * `harness login` at a terminal with no flag: how to sign in. ↑/↓ (or k/j) move, Enter takes,
+ * 1 or 2 take that row at once, Esc / q / Ctrl-C leave with null. Starts on SSO, as Enter always
+ * did. Drawn in place like `harness remote`'s machine picker — the rows are rewritten on every move.
+ */
+export function pickSignInMethod(io: {
+ input: NodeJS.ReadStream & { isTTY?: boolean }
+ output: NodeJS.WritableStream
+}): Promise<SignInMethod | null> {
+ const { input, output } = io
+ return new Promise((resolve) => {
+ let index = 0
+ let drawn = 0
+ const draw = (): void => {
+ if (drawn) output.write(`\x1b[${drawn}A\x1b[J`)
+ const lines = [
+ ' Sign in with: ↑/↓ choose · Enter select · Esc cancel',
+ ...OPTIONS.map((o, at) => ` ${at === index ? '❯' : ' '} ${o.label}`),
+ ]
+ output.write(lines.join('\n') + '\n')
+ drawn = lines.length
+ }
+ const finish = (method: SignInMethod | null): void => {
+ input.off('keypress', onKey)
+ if (input.isTTY) input.setRawMode(false)
+ input.pause()
+ resolve(method)
+ }
+ const onKey = (text: string | undefined, key: { name?: string; ctrl?: boolean } = {}): void => {
+ if ((key.ctrl && key.name === 'c') || key.name === 'escape' || key.name === 'q') { finish(null); return }
+ if (key.name === 'return' || key.name === 'enter') { finish(OPTIONS[index]!.method); return }
+ const n = Number(text)
+ if (Number.isInteger(n) && n >= 1 && n <= OPTIONS.length) { index = n - 1; draw(); finish(OPTIONS[index]!.method); return }
+ if (key.name === 'up' || key.name === 'k') index = (index - 1 + OPTIONS.length) % OPTIONS.length
+ else if (key.name === 'down' || key.name === 'j') index = (index + 1) % OPTIONS.length
+ else return
+ draw()
+ }
+ emitKeypressEvents(input)
+ if (input.isTTY) input.setRawMode(true)
+ input.resume()
+ input.on('keypress', onKey)
+ output.write('\n')
+ draw()
+ })
+}
diff --git a/cli/src/lib/terminalQr.ts b/cli/src/lib/terminalQr.ts
new file mode 100644
index 000000000..0eb5ea2f2
--- /dev/null
+++ b/cli/src/lib/terminalQr.ts
@@ -0,0 +1,27 @@
+import qrcode from 'qrcode-generator'
+
+/**
+ * A QR code drawn in a terminal: two module rows per text line with half blocks, dark on light, and
+ * a quiet zone phones need to find the code. Colours are forced (black on white) rather than left to
+ * the terminal's theme, because a light-on-dark code is one many scanners refuse.
+ */
+export function terminalQr(text: string, { margin = 2, color = true }: { margin?: number; color?: boolean } = {}): string {
+ const qr = qrcode(0, 'M')
+ qr.addData(text)
+ qr.make()
+ const size = qr.getModuleCount()
+ const dark = (r: number, c: number): boolean =>
+ r >= 0 && c >= 0 && r < size && c < size && qr.isDark(r, c)
+ const lines: string[] = []
+ for (let r = -margin; r < size + margin; r += 2) {
+ let line = ''
+ for (let c = -margin; c < size + margin; c++) {
+ const top = dark(r, c)
+ const bottom = dark(r + 1, c)
+ // Drawn in the LIGHT colour: a full block is two light modules, a space two dark ones.
+ line += top && bottom ? ' ' : top ? '▄' : bottom ? '▀' : '█'
+ }
+ lines.push(color ? `\x1b[97;40m${line}\x1b[0m` : line)
+ }
+ return lines.join('\n')
+}
diff --git a/desktop/lib/auth/cli_login.dart b/desktop/lib/auth/cli_login.dart
index 38ed6f12c..0c1cee56f 100644
--- a/desktop/lib/auth/cli_login.dart
+++ b/desktop/lib/auth/cli_login.dart
@@ -3,6 +3,7 @@ import 'dart:convert';
import 'dart:io';
import '../core/harness_cli_runner.dart';
+import 'phone_sign_in.dart';
import 'sign_in_client.dart';
class CliAuthStatus {
@@ -46,7 +47,7 @@ class CliNotAvailableException implements Exception {
/// signed-in session, and driving `harness login --json`'s NDJSON event stream when it does not. The
/// CLI owns the SSO session end to end (`~/.harness/auth/session.json`) — this app never sees, stores,
/// or refreshes an access token itself.
-class CliLogin implements SignInClient {
+class CliLogin implements SignInClient, PhoneSignInClient {
final HarnessCliRunner _runner;
Process? _activeProcess;
int _loginRevision = 0;
@@ -74,8 +75,22 @@ class CliLogin implements SignInClient {
/// the CLI's own loopback callback server completes the flow (or throws on failure/cancellation).
/// The process is killed if [cancel] is called while this is in flight.
@override
- Future<void> login({
- required void Function(String url) onAuthorizeUrl,
+ Future<void> login({required void Function(String url) onAuthorizeUrl}) =>
+ _login(const [], onAuthorizeUrl: onAuthorizeUrl);
+
+ /// `harness login --qr`: the QR arrives as an event, and so does the question of whose account
+ /// approved it — answered with a `yes` or `no` line on the process's standard input.
+ @override
+ Future<void> loginWithPhone({
+ required void Function(String link, int expiresIn) onQr,
+ required Future<bool> Function(String email) onConfirm,
+ }) => _login(const ['--qr'], onQr: onQr, onConfirm: onConfirm);
+
+ Future<void> _login(
+ List<String> extra, {
+ void Function(String url)? onAuthorizeUrl,
+ void Function(String link, int expiresIn)? onQr,
+ Future<bool> Function(String email)? onConfirm,
}) async {
// A cancelled spawn can finish after a replacement login has started.
// Each process owns only its attempt, including its eventual cleanup.
@@ -88,6 +103,7 @@ class CliLogin implements SignInClient {
'login',
'--force',
'--json',
+ ...extra,
'--entry-point=desktop',
]);
} catch (error) {
@@ -110,6 +126,8 @@ class CliLogin implements SignInClient {
var gotResult = false;
var success = false;
String? message;
+ String? code;
+ var tooOld = false;
await for (final raw in lines) {
if (revision != _loginRevision) continue;
final line = raw.trim();
@@ -122,26 +140,56 @@ class CliLogin implements SignInClient {
}
switch (json['type']) {
case 'authorize_url':
+ // Asked for a QR and given a browser page: a CLI from before `--qr`, which ignores the
+ // flag and starts SSO. Nothing would ever be shown — stop it and say why.
+ if (onQr != null) {
+ tooOld = true;
+ process.kill();
+ break;
+ }
final url = json['url'];
- if (url is String) onAuthorizeUrl(url);
+ if (url is String) onAuthorizeUrl?.call(url);
+ case 'qr':
+ final url = json['url'], expiresIn = json['expiresIn'];
+ if (url is String) {
+ onQr?.call(url, expiresIn is int ? expiresIn : 120);
+ }
+ case 'confirm':
+ final email = json['email'];
+ final yes =
+ email is String && onConfirm != null && await onConfirm(email);
+ if (revision != _loginRevision) break;
+ process.stdin.writeln(yes ? 'yes' : 'no');
+ await process.stdin.flush();
case 'result':
gotResult = true;
success = json['status'] == 'success';
message = json['message'] as String?;
+ code = json['code'] as String?;
}
}
final exitCode = await process.exitCode;
if (revision != _loginRevision) {
throw StateError('Sign-in was cancelled.');
}
- if (!gotResult || !success) {
- throw StateError(
- message ??
- (exitCode != 0
- ? 'Sign-in was cancelled.'
- : 'Sign-in did not complete.'),
+ if (tooOld) {
+ throw const PhoneSignInException(
+ 'CLI_TOO_OLD',
+ 'This computer\'s Harness CLI is too old to sign in with a phone. Use Sign in, or update Harness.',
);
}
+ if (!gotResult || !success) {
+ final text =
+ message ??
+ (exitCode != 0
+ ? 'Sign-in was cancelled.'
+ : 'Sign-in did not complete.');
+ // A phone sign-in says why it ended, so the screen can offer the right next step.
+ if (onQr != null && code != null) {
+ throw PhoneSignInException(code, text);
+ }
+ throw StateError(text);
+ }
} finally {
if (identical(_activeProcess, process)) _activeProcess = null;
}
diff --git a/desktop/lib/auth/phone_sign_in.dart b/desktop/lib/auth/phone_sign_in.dart
new file mode 100644
index 000000000..5b0b67dd4
--- /dev/null
+++ b/desktop/lib/auth/phone_sign_in.dart
@@ -0,0 +1,33 @@
+/// Signing in by a QR that a signed-in phone scans and approves (backend `routes/qrSignIn.ts`) —
+/// beside SSO, for the sign-in clients that can: the CLI's (`harness login --qr`) and a viewer's.
+///
+/// A client that cannot is simply not one of these, and the login screen offers SSO alone.
+abstract interface class PhoneSignInClient {
+ /// Shows [onQr] the link to encode (again, whenever its life is extended), waits for a phone to
+ /// approve it, then asks [onConfirm] whether to sign in as the account that approved — someone
+ /// else's phone may have. Resolves once signed in; throws [PhoneSignInException] otherwise.
+ Future<void> loginWithPhone({
+ required void Function(String link, int expiresIn) onQr,
+ required Future<bool> Function(String email) onConfirm,
+ });
+}
+
+/// Why a phone sign-in did not finish. [code]: `DENIED` (on the phone), `EXPIRED`, `CANCELLED`
+/// (the person here said no, or went back), `BACKEND_ERROR`, `UNAVAILABLE` (a backend without it).
+class PhoneSignInException implements Exception {
+ const PhoneSignInException(this.code, this.message);
+
+ final String code;
+ final String message;
+
+ @override
+ String toString() => message;
+}
+
+/// Where a sign-in QR points; the phone's scanner reads exactly this (mobile `SignInCode`).
+String phoneSignInLink(String code) => Uri(
+ scheme: 'https',
+ host: 'harness.autonomous.ai',
+ path: '/signin',
+ fragment: 'k=${Uri.encodeQueryComponent(code)}',
+).toString();
diff --git a/desktop/lib/core/browser_label.dart b/desktop/lib/core/browser_label.dart
new file mode 100644
index 000000000..71888cee5
--- /dev/null
+++ b/desktop/lib/core/browser_label.dart
@@ -0,0 +1,43 @@
+import 'browser_label_native.dart'
+ if (dart.library.js_interop) 'browser_label_web.dart'
+ as impl;
+
+/// What a browser calls itself on the account's devices, and to the phone approving its sign-in:
+/// "Chrome on macOS". A browser cannot read its computer's name, and "Browser" twice in the
+/// Devices list told nobody which one to remove.
+String browserLabel() => browserLabelFrom(impl.userAgent());
+
+/// "Chrome on macOS" from a user agent — pure, so it is tested without a browser.
+String browserLabelFrom(String ua) {
+ String? browser;
+ if (ua.contains('Edg/')) {
+ browser = 'Edge';
+ } else if (ua.contains('OPR/')) {
+ browser = 'Opera';
+ } else if (ua.contains('Firefox/') || ua.contains('FxiOS/')) {
+ browser = 'Firefox';
+ } else if (ua.contains('Chrome/') || ua.contains('CriOS/')) {
+ browser = 'Chrome';
+ } else if (ua.contains('Safari/')) {
+ browser = 'Safari';
+ }
+ String? os;
+ if (ua.contains('iPhone')) {
+ os = 'iPhone';
+ } else if (ua.contains('iPad')) {
+ os = 'iPad';
+ } else if (ua.contains('Android')) {
+ os = 'Android';
+ } else if (ua.contains('CrOS')) {
+ os = 'ChromeOS';
+ } else if (ua.contains('Mac OS X') || ua.contains('Macintosh')) {
+ os = 'macOS';
+ } else if (ua.contains('Windows')) {
+ os = 'Windows';
+ } else if (ua.contains('Linux')) {
+ os = 'Linux';
+ }
+ if (browser == null && os == null) return 'Web browser';
+ if (browser == null) return 'Browser on $os';
+ return os == null ? browser : '$browser on $os';
+}
diff --git a/desktop/lib/core/browser_label_native.dart b/desktop/lib/core/browser_label_native.dart
new file mode 100644
index 000000000..345602fdb
--- /dev/null
+++ b/desktop/lib/core/browser_label_native.dart
@@ -0,0 +1 @@
+String userAgent() => '';
diff --git a/desktop/lib/core/browser_label_web.dart b/desktop/lib/core/browser_label_web.dart
new file mode 100644
index 000000000..98230f8a7
--- /dev/null
+++ b/desktop/lib/core/browser_label_web.dart
@@ -0,0 +1,3 @@
+import 'package:web/web.dart' as web;
+
+String userAgent() => web.window.navigator.userAgent;
diff --git a/desktop/lib/screens/login_screen.dart b/desktop/lib/screens/login_screen.dart
index dc98317ee..e051e0023 100644
--- a/desktop/lib/screens/login_screen.dart
+++ b/desktop/lib/screens/login_screen.dart
@@ -1,8 +1,11 @@
+import 'dart:async';
+
import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/services.dart';
+import '../shared/widgets/qr_code_view.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../state/app_state.dart';
import '../widgets/login_fleet_map.dart';
@@ -385,6 +388,19 @@ class _ActionState extends State<_Action> {
),
label: Text(signingOutFailed ? 'Retry sign out' : 'Sign in'),
),
+ // The other way in: a QR a phone already signed in scans and approves. Not on a web page
+ // at phone width — that page IS the phone.
+ if (notifier.canSignInWithPhone &&
+ !signingOutFailed &&
+ !(kIsWeb && MediaQuery.sizeOf(context).width < 720)) ...[
+ const SizedBox(height: 10),
+ OutlinedButton.icon(
+ key: const Key('login-scan-with-phone'),
+ onPressed: notifier.loginWithPhone,
+ icon: const Icon(AppIcons.smartphone, size: 16),
+ label: const Text('Scan with your phone'),
+ ),
+ ],
const SizedBox(height: 12),
Semantics(
liveRegion: signingOutFailed || notifier.sessionExpired,
@@ -402,6 +418,94 @@ class _ActionState extends State<_Action> {
);
}
+ // A phone approved this sign-in: whose account is it? Someone else's phone may have scanned
+ // the code, and nothing is signed in until the person here says yes.
+ if (notifier.pendingConfirmEmail case final email?) {
+ final previous = notifier.previousAccountEmail;
+ final changed =
+ previous != null && previous.toLowerCase() != email.toLowerCase();
+ return Column(
+ children: [
+ Text(
+ 'Sign in as $email?',
+ key: const Key('login-phone-confirm'),
+ textAlign: TextAlign.center,
+ style: grid.AppType.heading(),
+ ),
+ const SizedBox(height: 8),
+ Text(
+ changed
+ ? 'This computer was signed in as $previous. Continue only if $email is yours.'
+ : 'Your phone approved this sign-in. Continue only if this is your account.',
+ textAlign: TextAlign.center,
+ style: Theme.of(context).textTheme.bodySmall
+ ?.copyWith(color: changed ? grid.AppPalette.warn : null),
+ ),
+ const SizedBox(height: 14),
+ Wrap(
+ spacing: 8,
+ alignment: WrapAlignment.center,
+ children: [
+ FilledButton(
+ key: const Key('login-phone-continue'),
+ autofocus: true,
+ onPressed: () => notifier.confirmPhoneSignIn(true),
+ child: const Text('Continue'),
+ ),
+ TextButton(
+ key: const Key('login-phone-refuse'),
+ onPressed: () => notifier.confirmPhoneSignIn(false),
+ child: const Text('Cancel'),
+ ),
+ ],
+ ),
+ ],
+ );
+ }
+
+ // Waiting for a phone to scan the QR.
+ if (notifier.pendingQrLink case final link?) {
+ return _RevealOnShow(
+ child: Column(
+ children: [
+ QrCodeView(
+ key: const Key('login-phone-qr'),
+ data: link,
+ side: 200,
+ semanticLabel: 'QR code to sign in with your phone',
+ ),
+ const SizedBox(height: 12),
+ Text(
+ 'On your phone: Harness ▸ Settings ▸ Sign in a computer',
+ textAlign: TextAlign.center,
+ style: Theme.of(context).textTheme.bodySmall,
+ ),
+ const SizedBox(height: 12),
+ Wrap(
+ spacing: 8,
+ alignment: WrapAlignment.center,
+ children: [
+ OutlinedButton(
+ onPressed: () {
+ notifier.cancelLogin();
+ unawaited(notifier.login());
+ },
+ child: const Text('Use browser instead'),
+ ),
+ TextButton(
+ onPressed: notifier.cancelLogin,
+ style: TextButton.styleFrom(
+ foregroundColor: grid.AppPalette.textSecondary,
+ ),
+ child: const Text('Cancel'),
+ ),
+ ],
+ ),
+ ],
+ ),
+ );
+ }
+
final url = notifier.pendingAuthorizeUrl;
final message =
notifier.loginBrowserError ??
@@ -732,3 +836,28 @@ class _SignInSheetState extends State<_SignInSheet> {
Navigator.of(context).pop(false);
}
}
+
+/// Scrolls its child into view when it first appears: the QR and its Cancel are taller than the
+/// button they replace, and on a short window they would otherwise land below the fold.
+class _RevealOnShow extends StatefulWidget {
+ const _RevealOnShow({required this.child});
+
+ final Widget child;
+
+ @override
+ State<_RevealOnShow> createState() => _RevealOnShowState();
+}
+
+class _RevealOnShowState extends State<_RevealOnShow> {
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted) return;
+ unawaited(Scrollable.ensureVisible(context, alignment: 1));
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) => widget.child;
+}
diff --git a/desktop/lib/settings/sections/account_devices_section.dart b/desktop/lib/settings/sections/account_devices_section.dart
index cfcc570d3..de622061f 100644
--- a/desktop/lib/settings/sections/account_devices_section.dart
+++ b/desktop/lib/settings/sections/account_devices_section.dart
@@ -172,7 +172,7 @@ class _AccountDevicesSectionState extends State<AccountDevicesSection> {
return SectionScaffold(
title: 'Your devices',
subtitle: 'Every computer and app signed in to your account. Each one reaches your machines '
- 'end to end encrypted — no password. Remove one you do not recognise.',
+ 'end to end encrypted. Remove one you do not recognise.',
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
diff --git a/desktop/lib/shared/widgets/qr_code_view.dart b/desktop/lib/shared/widgets/qr_code_view.dart
new file mode 100644
index 000000000..3a5a88598
--- /dev/null
+++ b/desktop/lib/shared/widgets/qr_code_view.dart
@@ -0,0 +1,98 @@
+import 'package:flutter/material.dart';
+import 'package:qr/qr.dart';
+
+/// [data] as a QR code: dark modules on a white square with its quiet zone.
+///
+/// ⚠️ White and black whatever the theme. A dark-mode QR — light modules on a
+/// dark field — is one many phone cameras will not read, and the four-module
+/// white margin (the "quiet zone") is part of the code, not decoration: it is
+/// how a scanner finds the edges. So the white square stays, on every palette.
+class QrCodeView extends StatelessWidget {
+ const QrCodeView({super.key, required this.data, required this.side, required this.semanticLabel});
+
+ /// What the code says — the whole link, secret included.
+ final String data;
+ final double side;
+
+ /// What a screen reader says it is — what the code is FOR.
+ final String semanticLabel;
+
+ static const _quietModules = 4;
+
+ // One entry: the dialog rebuilds on every font or palette change, and
+ // choosing the best of eight mask patterns is not free.
+ static (String, QrImage)? _cached;
+
+ static QrImage _imageOf(String data) {
+ if (_cached case (final cachedData, final image) when cachedData == data) {
+ return image;
+ }
+ final image = QrImage(
+ QrCode.fromData(data: data, errorCorrectLevel: QrErrorCorrectLevel.M),
+ );
+ _cached = (data, image);
+ return image;
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final image = _imageOf(data);
+ final module = side / (image.moduleCount + _quietModules * 2);
+ return Semantics(
+ image: true,
+ label: semanticLabel,
+ child: Container(
+ width: side,
+ height: side,
+ decoration: BoxDecoration(
+ color: Colors.white,
+ borderRadius: BorderRadius.circular(module * 2),
+ ),
+ child: CustomPaint(painter: _QrPainter(image, data)),
+ ),
+ );
+ }
+}
+
+class _QrPainter extends CustomPainter {
+ _QrPainter(this.image, this.data);
+
+ final QrImage image;
+ final String data;
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ final count = image.moduleCount;
+ final total = count + QrCodeView._quietModules * 2;
+ // Snapped to half a point — a whole device pixel on a Retina screen — so
+ // neighbouring modules meet exactly instead of leaving hairline seams.
+ final module = (size.shortestSide / total * 2).floorToDouble() / 2;
+ final origin = Offset(
+ (size.width - module * count) / 2,
+ (size.height - module * count) / 2,
+ );
+ final path = Path();
+ for (var y = 0; y < count; y++) {
+ for (var x = 0; x < count; x++) {
+ if (!image.isDark(y, x)) continue;
+ path.addRect(
+ Rect.fromLTWH(
+ origin.dx + x * module,
+ origin.dy + y * module,
+ module,
+ module,
+ ),
+ );
+ }
+ }
+ canvas.drawPath(
+ path,
+ Paint()
+ ..color = Colors.black
+ ..isAntiAlias = false,
+ );
+ }
+
+ @override
+ bool shouldRepaint(_QrPainter oldDelegate) => oldDelegate.data != data;
+}
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 8320735e3..5be07a723 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -23,6 +23,7 @@ import '../viewer/viewer_location.dart';
import '../viewer/group_sync.dart' show GroupSyncOutcome;
import '../auth/auth_session.dart';
import '../auth/peer_link_client.dart';
+import '../auth/phone_sign_in.dart';
import '../auth/sign_in_client.dart';
import '../auth/cli_link.dart';
import '../auth/cli_login.dart';
@@ -36,6 +37,7 @@ import '../core/agent_preference.dart';
import '../core/dsh_catalog.dart';
import '../core/harness_catalog.dart';
import '../core/engine_availability.dart';
+import '../core/browser_label.dart';
import '../core/local_hostname.dart';
import '../core/local_git_projects.dart';
import '../core/test_run.dart';
@@ -2083,6 +2085,21 @@ class AppNotifier extends ChangeNotifier {
// over. It identifies the current sign-in link; [signingIn] tracks the whole
// attempt, including CLI startup and workspace restoration.
String? pendingAuthorizeUrl;
+
+ /// Signing in by a phone (`auth/phone_sign_in.dart`): the QR to show while a phone approves it.
+ String? pendingQrLink;
+
+ /// The account a phone approved this sign-in for, waiting on [confirmPhoneSignIn] — someone
+ /// else's phone may have approved it, and nothing is signed in until the person here says yes.
+ String? pendingConfirmEmail;
+
+ /// Who was signed in here before, so the confirmation can say when the account changes.
+ String? previousAccountEmail;
+
+ Completer<bool>? _phoneConfirm;
+
+ /// Whether this build can sign in by a phone at all (the CLI's, and a viewer's, can).
+ bool get canSignInWithPhone => cliLogin is PhoneSignInClient;
bool openingLoginBrowser = false;
String? loginBrowserError;
int _loginBrowserRevision = 0;
@@ -4524,6 +4541,83 @@ class AppNotifier extends ChangeNotifier {
if (_authWorkCurrent(revision)) notifyListeners();
}
+ /// Sign in by a QR a signed-in phone approves, then a yes here to the account it names.
+ Future<void> loginWithPhone() async {
+ final client = cliLogin;
+ if (_disposed || signingIn || signingOut || signOutError != null || client is! PhoneSignInClient) return;
+ final wasGuest = isGuest;
+ final revision = _invalidateAuthWork();
+ previousAccountEmail = currentUser?.email;
+ _closedHistory.clear();
+ _monitorHarnesses.clear();
+ _lastError = null;
+ status = AppStatus.bootstrapping;
+ signingIn = true;
+ pendingAuthorizeUrl = null;
+ _clearPhoneSignIn();
+ notifyListeners();
+ try {
+ if (_workspaceCleanup case final cleanup?) {
+ await cleanup;
+ if (!_authWorkCurrent(revision)) return;
+ }
+ await (client as PhoneSignInClient).loginWithPhone(
+ onQr: (link, _) {
+ if (!_authWorkCurrent(revision) || pendingQrLink == link) return;
+ pendingQrLink = link;
+ notifyListeners();
+ },
+ onConfirm: (email) {
+ if (!_authWorkCurrent(revision)) return Future.value(false);
+ final answer = _phoneConfirm = Completer<bool>();
+ pendingConfirmEmail = email;
+ notifyListeners();
+ return answer.future;
+ },
+ );
+ if (!_authWorkCurrent(revision)) return;
+ _loginAuthorized = true;
+ _clearPhoneSignIn();
+ notifyListeners();
+ signedIn = true;
+ await _finishBootstrapSignedIn();
+ if (!_authWorkCurrent(revision) || status != AppStatus.authenticated) return;
+ _guestDeskRestorePending = false;
+ } catch (error) {
+ if (!_authWorkCurrent(revision)) return;
+ status = wasGuest ? AppStatus.authenticated : AppStatus.unauthenticated;
+ _lastError = error.toString();
+ _lastErrorRetryable = true;
+ if (wasGuest && _guestDeskRestorePending && !signedIn) {
+ unawaited(_becomeGuest(revision: revision));
+ }
+ } finally {
+ if (_authWorkCurrent(revision)) {
+ _loginAuthorized = false;
+ _clearPhoneSignIn();
+ signingIn = false;
+ }
+ }
+ if (_authWorkCurrent(revision)) notifyListeners();
+ }
+
+ /// The person's answer to "Sign in as [pendingConfirmEmail]?".
+ void confirmPhoneSignIn(bool yes) {
+ final answer = _phoneConfirm;
+ _phoneConfirm = null;
+ pendingConfirmEmail = null;
+ if (answer != null && !answer.isCompleted) answer.complete(yes);
+ notifyListeners();
+ }
+
+ void _clearPhoneSignIn() {
+ pendingQrLink = null;
+ pendingConfirmEmail = null;
+ final answer = _phoneConfirm;
+ _phoneConfirm = null;
+ if (answer != null && !answer.isCompleted) answer.complete(false);
+ }
+
void _resetLoginBrowser() {
++_loginBrowserRevision;
openingLoginBrowser = false;
@@ -4581,6 +4675,7 @@ class AppNotifier extends ChangeNotifier {
final revision = _invalidateAuthWork();
signingIn = false;
pendingAuthorizeUrl = null;
+ _clearPhoneSignIn();
status = isGuest ? AppStatus.authenticated : AppStatus.unauthenticated;
_lastError = null;
_lastErrorRetryable = false;
@@ -5638,9 +5733,11 @@ class AppNotifier extends ChangeNotifier {
/// How this app names itself in the account's devices.
String _deviceLabel() {
+ // A browser has no computer name to give: "Chrome on macOS". An existing "Browser" entry is
+ // renamed to this on its next sync (`viewer/device_log_sync.dart`).
+ if (kIsWeb) return browserLabel();
final host = localHostnameOrNull();
- if (host != null && host.isNotEmpty) return host;
- return kIsWeb ? 'Browser · ${defaultTargetPlatform.name}' : 'Desktop app';
+ return host != null && host.isNotEmpty ? host : 'Desktop app';
}
DateTime? _deviceLogReadAt;
@@ -5745,7 +5842,7 @@ class AppNotifier extends ChangeNotifier {
// Fire-and-forget from the connection handler: a state file that is locked for a moment must not
// surface as an unhandled error. The next session retries.
try {
- final label = localHostnameOrNull() ?? 'Desktop';
+ final label = _deviceLabel();
final GroupSyncOutcome outcome = await links.syncGroup(
machineId,
label: label,
diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dart
index cf3682b72..6e0fe19fb 100644
--- a/desktop/lib/state/swarm_search.dart
+++ b/desktop/lib/state/swarm_search.dart
@@ -961,7 +961,7 @@ class SwarmSearchController extends ChangeNotifier {
? '[ Add ]'
: 'New Harness';
String get createDescription => isMachineMode
- ? 'On the other computer:\n\n1. Install the app or CLI.\n2. Sign in to the same account.\n\nIt appears here and connects on its own — no password.'
+ ? 'On the other computer:\n\n1. Install the app or CLI.\n2. Sign in to the same account.\n\nIt appears here and connects on its own.'
: isModelMode
? 'Add an API key\n\n'
'OpenRouter or a Custom API: Use its models to run a harness.\n'
diff --git a/desktop/lib/viewer/browser_login.dart b/desktop/lib/viewer/browser_login.dart
index 2c4a921a8..7eeae5de6 100644
--- a/desktop/lib/viewer/browser_login.dart
+++ b/desktop/lib/viewer/browser_login.dart
@@ -2,8 +2,11 @@ import 'dart:async';
import 'dart:convert';
import '../auth/cli_login.dart' show CliAuthStatus;
+import '../auth/phone_sign_in.dart';
import '../auth/sign_in_client.dart';
+import '../core/browser_label.dart';
import 'direct_auth.dart';
+import 'qr_sign_in.dart';
import 'direct_auth_api.dart';
import '../sharing/shared_agent_location.dart';
import 'viewer_location.dart';
@@ -20,7 +23,7 @@ abstract interface class LoginBrowser {
/// Same-tab OAuth using the backend's existing PKCE transaction endpoints.
/// The callback must match the attempt started in this tab. Neither tokens nor
/// transaction identifiers are placed in a public workspace URL.
-class BrowserLogin implements SignInClient {
+class BrowserLogin implements SignInClient, PhoneSignInClient {
BrowserLogin({
required this.auth,
required this.browser,
@@ -104,6 +107,25 @@ class BrowserLogin implements SignInClient {
return CliAuthStatus(loggedIn: loggedIn);
}
+ @override
+ Future<void> loginWithPhone({
+ required void Function(String link, int expiresIn) onQr,
+ required Future<bool> Function(String email) onConfirm,
+ }) async {
+ cancel();
+ final revision = _revision;
+ final tokens = await viewerQrSignIn(
+ api: auth.api,
+ label: browserLabel(),
+ onQr: onQr,
+ onConfirm: onConfirm,
+ stillCurrent: () => revision == _revision,
+ );
+ _requireCurrent(revision);
+ await auth.signIn(tokens, stillCurrent: () => revision == _revision);
+ _requireCurrent(revision);
+ }
+
@override
Future<void> login({
required void Function(String url) onAuthorizeUrl,
diff --git a/desktop/lib/viewer/direct_auth_api.dart b/desktop/lib/viewer/direct_auth_api.dart
index e969f4fba..79decfbe4 100644
--- a/desktop/lib/viewer/direct_auth_api.dart
+++ b/desktop/lib/viewer/direct_auth_api.dart
@@ -132,6 +132,50 @@ class DirectAuthApi {
(throw const DirectAuthException('Sign-in returned no access token.'));
}
+ // -- signing in by a QR a signed-in phone approves (backend routes/qrSignIn.ts) --
+
+ Future<({String code, String pollToken, int expiresIn})> qrStart({required String label}) async {
+ final data = unwrapApiResponse(
+ await _dio.post('/api/auth/qr/start', data: {'label': label, 'kind': 'viewer'}),
+ );
+ final code = data is Map ? data['code'] : null, poll = data is Map ? data['pollToken'] : null;
+ final expiresIn = data is Map ? data['expiresIn'] : null;
+ if (code is! String || poll is! String || expiresIn is! int) {
+ throw const DirectAuthException('Sign-in by phone is not available here.');
+ }
+ return (code: code, pollToken: poll, expiresIn: expiresIn);
+ }
+
+ /// `pending`, `denied`, `expired`, or `approved` with the account's email.
+ Future<({String status, String? email})> qrPoll(String pollToken) async {
+ final data = unwrapApiResponse(await _dio.post('/api/auth/qr/poll', data: {'pollToken': pollToken}));
+ final status = data is Map ? data['status'] : null, email = data is Map ? data['email'] : null;
+ return (status: status is String ? status : 'expired', email: email is String ? email : null);
+ }
+
+ /// The same code, alive a while longer; null when it can live no longer.
+ Future<int?> qrExtend(String pollToken) async {
+ try {
+ final data = unwrapApiResponse(await _dio.post('/api/auth/qr/extend', data: {'pollToken': pollToken}));
+ final expiresIn = data is Map ? data['expiresIn'] : null;
+ return expiresIn is int ? expiresIn : null;
+ } catch (_) {
+ return null;
+ }
+ }
+
+ Future<IssuedTokens> qrClaim(String pollToken) async {
+ final data = unwrapApiResponse(await _dio.post('/api/auth/qr/claim', data: {'pollToken': pollToken}));
+ return IssuedTokens.fromData(data) ??
+ (throw const DirectAuthException('Sign-in returned no access token.'));
+ }
+
+ Future<void> qrCancel(String pollToken) async {
+ try {
+ await _dio.post('/api/auth/qr/cancel', data: {'pollToken': pollToken});
+ } catch (_) {}
+ }
+
/// authSession.ts `refreshRequest`, down to its one subtle rule: only a 401 or
/// `REFRESH_TOKEN_INVALID` means the session is dead. An unusable refresh token and a real outage
/// both come back as the same 503, and reading that as dead would delete a refresh token nothing
diff --git a/desktop/lib/viewer/direct_login_native.dart b/desktop/lib/viewer/direct_login_native.dart
index 3ccb8d207..e9d02c67b 100644
--- a/desktop/lib/viewer/direct_login_native.dart
+++ b/desktop/lib/viewer/direct_login_native.dart
@@ -2,16 +2,19 @@ import 'dart:async';
import 'dart:io';
import '../auth/cli_login.dart';
+import '../auth/phone_sign_in.dart';
import '../auth/sign_in_client.dart';
+import '../core/local_hostname.dart';
import 'direct_auth.dart';
import 'direct_auth_api.dart';
+import 'qr_sign_in.dart';
/// Signing in with no harness CLI — cli.ts `loginCommand`, run by the app: a loopback listener for
/// the SSO redirect, `authorize-native` for the page to show, `exchange` for the tokens.
///
/// It deliberately skips the CLI's closing `resolve-computer`, which registers the computer as a
/// Harness machine. A viewer is not one.
-class DirectLogin implements SignInClient {
+class DirectLogin implements SignInClient, PhoneSignInClient {
DirectLogin({required this.auth});
final DirectAuth auth;
@@ -61,6 +64,25 @@ class DirectLogin implements SignInClient {
}
}
+ @override
+ Future<void> loginWithPhone({
+ required void Function(String link, int expiresIn) onQr,
+ required Future<bool> Function(String email) onConfirm,
+ }) async {
+ cancel();
+ final revision = _loginRevision;
+ final tokens = await viewerQrSignIn(
+ api: auth.api,
+ label: localHostnameOrNull() ?? 'Desktop app',
+ onQr: onQr,
+ onConfirm: onConfirm,
+ stillCurrent: () => revision == _loginRevision,
+ );
+ _requireCurrent(revision);
+ await auth.signIn(tokens, stillCurrent: () => revision == _loginRevision);
+ _requireCurrent(revision);
+ }
+
@override
void cancel() {
++_loginRevision;
diff --git a/desktop/lib/viewer/qr_sign_in.dart b/desktop/lib/viewer/qr_sign_in.dart
new file mode 100644
index 000000000..f0fb0102e
--- /dev/null
+++ b/desktop/lib/viewer/qr_sign_in.dart
@@ -0,0 +1,74 @@
+import 'dart:async';
+
+import '../auth/phone_sign_in.dart';
+import 'direct_auth_api.dart';
+
+/// A viewer build signing itself in by a QR a signed-in phone approves — cli `lib/qrSignIn.ts`,
+/// for an app with no CLI: start, show, poll (keeping the same code alive), ask the person whose
+/// account approved, and only then claim the session. An app asks as `viewer`: it may reach the
+/// account's machines, never connect as one.
+Future<IssuedTokens> viewerQrSignIn({
+ required DirectAuthApi api,
+ required String label,
+ required void Function(String link, int expiresIn) onQr,
+ required Future<bool> Function(String email) onConfirm,
+ required bool Function() stillCurrent,
+ Future<void> Function(Duration)? sleep,
+ DateTime Function()? now,
+ Duration pollEvery = const Duration(seconds: 2),
+}) async {
+ final wait = sleep ?? Future<void>.delayed;
+ final clock = now ?? DateTime.now;
+ final ({String code, String pollToken, int expiresIn}) started;
+ try {
+ started = await api.qrStart(label: label);
+ } catch (error) {
+ throw PhoneSignInException('UNAVAILABLE', '$error');
+ }
+ final link = phoneSignInLink(started.code);
+ var expiresAt = clock().add(Duration(seconds: started.expiresIn));
+ onQr(link, started.expiresIn);
+ Never gone(String code, String message) => throw PhoneSignInException(code, message);
+ for (;;) {
+ await wait(pollEvery);
+ if (!stillCurrent()) {
+ unawaited(api.qrCancel(started.pollToken));
+ gone('CANCELLED', 'Sign-in was cancelled.');
+ }
+ if (expiresAt.difference(clock()) < const Duration(seconds: 30)) {
+ int? more;
+ try {
+ more = await api.qrExtend(started.pollToken);
+ } catch (_) {
+ // As the CLI does: a code that cannot be kept alive is an expired one, said as such.
+ }
+ if (more == null) gone('EXPIRED', 'The code expired. Try again.');
+ expiresAt = clock().add(Duration(seconds: more));
+ onQr(link, more);
+ }
+ final ({String status, String? email}) state;
+ try {
+ state = await api.qrPoll(started.pollToken);
+ } catch (_) {
+ continue;
+ }
+ switch (state.status) {
+ case 'pending':
+ continue;
+ case 'denied':
+ gone('DENIED', 'Sign-in was denied on the phone.');
+ case 'approved' when state.email != null:
+ if (!await onConfirm(state.email!) || !stillCurrent()) {
+ unawaited(api.qrCancel(started.pollToken));
+ gone('CANCELLED', 'Not signed in as ${state.email}.');
+ }
+ try {
+ return await api.qrClaim(started.pollToken);
+ } catch (error) {
+ gone('BACKEND_ERROR', '$error');
+ }
+ default:
+ gone('EXPIRED', 'The code expired. Try again.');
+ }
+ }
+}
diff --git a/desktop/lib/widgets/add_phone_dialog.dart b/desktop/lib/widgets/add_phone_dialog.dart
index c33e1487e..a4151aecc 100644
--- a/desktop/lib/widgets/add_phone_dialog.dart
+++ b/desktop/lib/widgets/add_phone_dialog.dart
@@ -5,8 +5,8 @@ import 'dart:math' as math;
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
-import 'package:qr/qr.dart';
+import '../shared/widgets/qr_code_view.dart';
import '../api/api_client.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shortcuts/app_keymap.dart';
@@ -758,12 +758,7 @@ String _pairedAgo(DateTime at) {
String _thisComputer() =>
defaultTargetPlatform == TargetPlatform.macOS ? 'Mac' : 'computer';
-/// [data] as a QR code: dark modules on a white square with its quiet zone.
-///
-/// ⚠️ White and black whatever the theme. A dark-mode QR — light modules on a
-/// dark field — is one many phone cameras will not read, and the four-module
-/// white margin (the "quiet zone") is part of the code, not decoration: it is
-/// how a scanner finds the edges. So the white square stays, on every palette.
+/// The Add Phone QR — [QrCodeView], named for the one thing it is here.
class PhonePairQr extends StatelessWidget {
const PhonePairQr({super.key, required this.data, required this.side});
@@ -771,82 +766,7 @@ class PhonePairQr extends StatelessWidget {
final String data;
final double side;
- static const _quietModules = 4;
-
- // One entry: the dialog rebuilds on every font or palette change, and
- // choosing the best of eight mask patterns is not free.
- static (String, QrImage)? _cached;
-
- static QrImage _imageOf(String data) {
- if (_cached case (final cachedData, final image) when cachedData == data) {
- return image;
- }
- final image = QrImage(
- QrCode.fromData(data: data, errorCorrectLevel: QrErrorCorrectLevel.M),
- );
- _cached = (data, image);
- return image;
- }
-
- @override
- Widget build(BuildContext context) {
- final image = _imageOf(data);
- final module = side / (image.moduleCount + _quietModules * 2);
- return Semantics(
- image: true,
- label: 'QR code to add your phone',
- child: Container(
- width: side,
- height: side,
- decoration: BoxDecoration(
- color: Colors.white,
- borderRadius: BorderRadius.circular(module * 2),
- ),
- child: CustomPaint(painter: _QrPainter(image, data)),
- ),
- );
- }
-}
-
-class _QrPainter extends CustomPainter {
- _QrPainter(this.image, this.data);
-
- final QrImage image;
- final String data;
-
- @override
- void paint(Canvas canvas, Size size) {
- final count = image.moduleCount;
- final total = count + PhonePairQr._quietModules * 2;
- // Snapped to half a point — a whole device pixel on a Retina screen — so
- // neighbouring modules meet exactly instead of leaving hairline seams.
- final module = (size.shortestSide / total * 2).floorToDouble() / 2;
- final origin = Offset(
- (size.width - module * count) / 2,
- (size.height - module * count) / 2,
- );
- final path = Path();
- for (var y = 0; y < count; y++) {
- for (var x = 0; x < count; x++) {
- if (!image.isDark(y, x)) continue;
- path.addRect(
- Rect.fromLTWH(
- origin.dx + x * module,
- origin.dy + y * module,
- module,
- module,
- ),
- );
- }
- }
- canvas.drawPath(
- path,
- Paint()
- ..color = Colors.black
- ..isAntiAlias = false,
- );
- }
-
@override
- bool shouldRepaint(_QrPainter oldDelegate) => oldDelegate.data != data;
+ Widget build(BuildContext context) =>
+ QrCodeView(data: data, side: side, semanticLabel: 'QR code to add your phone');
}
diff --git a/desktop/test/browser_label_test.dart b/desktop/test/browser_label_test.dart
new file mode 100644
index 000000000..18fe5b47a
--- /dev/null
+++ b/desktop/test/browser_label_test.dart
@@ -0,0 +1,44 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/browser_label.dart';
+
+void main() {
+ test('names the browser and its OS', () {
+ expect(
+ browserLabelFrom(
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/130.0 Safari/537.36',
+ ),
+ 'Chrome on macOS',
+ );
+ expect(
+ browserLabelFrom(
+ 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 Chrome/130.0 Safari/537.36 Edg/130.0',
+ ),
+ 'Edge on Windows',
+ );
+ expect(
+ browserLabelFrom(
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 Version/18.0 Safari/605.1.15',
+ ),
+ 'Safari on macOS',
+ );
+ expect(
+ browserLabelFrom(
+ 'Mozilla/5.0 (X11; Linux x86_64; rv:131.0) Gecko/20100101 Firefox/131.0',
+ ),
+ 'Firefox on Linux',
+ );
+ expect(
+ browserLabelFrom(
+ 'Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 Chrome/130.0 Mobile Safari/537.36',
+ ),
+ 'Chrome on Android',
+ );
+ expect(
+ browserLabelFrom(
+ 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 CriOS/130.0 Mobile/15E148 Safari/604.1',
+ ),
+ 'Chrome on iPhone',
+ );
+ expect(browserLabelFrom(''), 'Web browser');
+ });
+}
diff --git a/desktop/test/login_screen_phone_test.dart b/desktop/test/login_screen_phone_test.dart
new file mode 100644
index 000000000..f8075f7e0
--- /dev/null
+++ b/desktop/test/login_screen_phone_test.dart
@@ -0,0 +1,89 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/auth/cli_login.dart';
+import 'package:harness/auth/sign_in_client.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/screens/login_screen.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+
+/// The login screen's second way in: a QR a signed-in phone approves, then a yes here to the
+/// account that approved it.
+
+/// Shows a QR, then asks the account question, and records the answer — no process started.
+class _PhoneLogin extends CliLogin {
+ final answers = <bool>[];
+ final Completer<void> finished = Completer<void>();
+
+ @override
+ Future<void> loginWithPhone({
+ required void Function(String link, int expiresIn) onQr,
+ required Future<bool> Function(String email) onConfirm,
+ }) async {
+ onQr('https://harness.autonomous.ai/signin#k=hnq_${'a' * 43}', 120);
+ await Future<void>.delayed(const Duration(milliseconds: 10));
+ answers.add(await onConfirm('[email protected]'));
+ await finished.future;
+ if (!answers.last) throw StateError('Not signed in as [email protected].');
+ }
+}
+
+Widget _host(AppNotifier app) => MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.light),
+ home: MediaQuery(
+ data: const MediaQueryData(size: Size(880, 700)),
+ child: grid.BrightnessScope(
+ child: ListenableBuilder(listenable: app, builder: (_, _) => LoginScreen(notifier: app)),
+ ),
+ ),
+);
+
+void main() {
+ testWidgets('offers "Scan with your phone", shows the QR, then asks whose account', (tester) async {
+ grid.AppTheme.brightness.value = Brightness.light;
+ final login = _PhoneLogin();
+ final app = AppNotifier(config: AppConfig.dev, authSession: AuthSession(), configStore: null, cliLogin: login)
+ ..status = AppStatus.unauthenticated;
+ addTearDown(app.dispose);
+ await tester.pumpWidget(_host(app));
+ expect(find.byKey(const Key('login-scan-with-phone')), findsOneWidget);
+
+ await tester.tap(find.byKey(const Key('login-scan-with-phone')));
+ await tester.pump();
+ expect(find.byKey(const Key('login-phone-qr')), findsOneWidget);
+ expect(find.textContaining('Sign in a computer'), findsOneWidget);
+
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(find.text('Sign in as [email protected]?'), findsOneWidget);
+ await tester.tap(find.byKey(const Key('login-phone-refuse')));
+ await tester.pump();
+ expect(login.answers, [false]);
+ login.finished.complete();
+ await tester.pump();
+ expect(app.signingIn, isFalse);
+ expect(find.byKey(const Key('login-scan-with-phone')), findsOneWidget);
+ });
+
+ testWidgets('a build that cannot sign in by phone does not offer it', (tester) async {
+ grid.AppTheme.brightness.value = Brightness.light;
+ final app = AppNotifier(config: AppConfig.dev, authSession: AuthSession(), configStore: null, cliLogin: _SsoOnly())
+ ..status = AppStatus.unauthenticated;
+ addTearDown(app.dispose);
+ await tester.pumpWidget(_host(app));
+ expect(find.byKey(const Key('login-scan-with-phone')), findsNothing);
+ });
+}
+
+class _SsoOnly implements SignInClient {
+ @override
+ Future<CliAuthStatus> checkStatus() async => const CliAuthStatus(loggedIn: false);
+ @override
+ Future<void> login({required void Function(String url) onAuthorizeUrl}) async {}
+ @override
+ void cancel() {}
+ @override
+ Future<void> logout() async {}
+}
diff --git a/desktop/test/phone_sign_in_test.dart b/desktop/test/phone_sign_in_test.dart
new file mode 100644
index 000000000..f57d196dc
--- /dev/null
+++ b/desktop/test/phone_sign_in_test.dart
@@ -0,0 +1,273 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/cli_login.dart';
+import 'package:harness/auth/phone_sign_in.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/harness_cli_runner.dart';
+import 'package:harness/viewer/direct_auth_api.dart';
+import 'package:harness/viewer/qr_sign_in.dart';
+
+/// Signing in by a QR a signed-in phone approves: the CLI's (`harness login --qr`, driven over NDJSON
+/// with the account question answered on stdin) and a viewer's own (`viewer/qr_sign_in.dart`).
+
+class _Runner extends HarnessCliRunner {
+ _Runner(this.process);
+ final _Process process;
+ List<String>? arguments;
+ @override
+ Future<Process> start(List<String> arguments) async {
+ this.arguments = arguments;
+ return process;
+ }
+}
+
+class _Process implements Process {
+ final output = StreamController<List<int>>();
+ final errors = StreamController<List<int>>();
+ final input = StreamController<List<int>>();
+ late final IOSink _stdin = IOSink(input.sink);
+ final ended = Completer<int>();
+ final written = <String>[];
+
+ _Process() {
+ input.stream.transform(utf8.decoder).listen(written.add);
+ }
+
+ void emit(Map<String, dynamic> event) =>
+ output.add(utf8.encode('${jsonEncode(event)}\n'));
+ void finish([int exitCode = 0]) {
+ unawaited(output.close());
+ unawaited(errors.close());
+ if (!ended.isCompleted) ended.complete(exitCode);
+ }
+
+ @override
+ Stream<List<int>> get stdout => output.stream;
+ @override
+ Stream<List<int>> get stderr => errors.stream;
+ @override
+ IOSink get stdin => _stdin;
+ @override
+ Future<int> get exitCode => ended.future;
+ bool killed = false;
+ @override
+ bool kill([ProcessSignal signal = ProcessSignal.sigterm]) {
+ killed = true;
+ return true;
+ }
+
+ @override
+ int get pid => 1;
+}
+
+class _Api extends DirectAuthApi {
+ _Api(this.polls) : super(config: AppConfig.dev);
+ final List<String> polls;
+ final calls = <String>[];
+ @override
+ Future<({String code, String pollToken, int expiresIn})> qrStart({
+ required String label,
+ }) async {
+ calls.add('start:$label');
+ return (code: 'hnq_code', pollToken: 'hnp_poll', expiresIn: 120);
+ }
+
+ @override
+ Future<({String status, String? email})> qrPoll(String pollToken) async {
+ calls.add('poll');
+ final next = polls.isEmpty ? 'pending' : polls.removeAt(0);
+ return (status: next, email: next == 'approved' ? '[email protected]' : null);
+ }
+
+ @override
+ Future<int?> qrExtend(String pollToken) async {
+ calls.add('extend');
+ return 120;
+ }
+
+ @override
+ Future<IssuedTokens> qrClaim(String pollToken) async {
+ calls.add('claim');
+ return const IssuedTokens(
+ token: 'hna_x',
+ refreshToken: 'hnr_x',
+ expiresIn: 3600,
+ );
+ }
+
+ @override
+ Future<void> qrCancel(String pollToken) async => calls.add('cancel');
+}
+
+void main() {
+ group('CliLogin.loginWithPhone', () {
+ test('shows the QR, answers the account question on stdin, and finishes on success', () async {
+ final process = _Process();
+ final runner = _Runner(process);
+ final links = <String>[];
+ final asked = <String>[];
+ final done = CliLogin(runner: runner).loginWithPhone(
+ onQr: (link, _) => links.add(link),
+ onConfirm: (email) async {
+ asked.add(email);
+ return true;
+ },
+ );
+ await Future<void>.delayed(Duration.zero);
+ expect(runner.arguments, [
+ 'login',
+ '--force',
+ '--json',
+ '--qr',
+ '--entry-point=desktop',
+ ]);
+ process.emit({
+ 'type': 'qr',
+ 'url': 'https://harness.autonomous.ai/signin#k=hnq_x',
+ 'expiresIn': 120,
+ });
+ process.emit({'type': 'confirm', 'email': '[email protected]'});
+ await Future<void>.delayed(const Duration(milliseconds: 20));
+ expect(process.written.join(), 'yes\n');
+ process.emit({
+ 'type': 'result',
+ 'status': 'success',
+ 'email': '[email protected]',
+ });
+ process.finish();
+ await done;
+ expect(links, ['https://harness.autonomous.ai/signin#k=hnq_x']);
+ expect(asked, ['[email protected]']);
+ });
+
+ test('says no on stdin when the person refuses the account, and reports why it ended', () async {
+ final process = _Process();
+ final done = CliLogin(runner: _Runner(process))
+ .loginWithPhone(onQr: (_, _) {}, onConfirm: (_) async => false);
+ await Future<void>.delayed(Duration.zero);
+ process.emit({'type': 'confirm', 'email': '[email protected]'});
+ await Future<void>.delayed(const Duration(milliseconds: 20));
+ expect(process.written.join(), 'no\n');
+ process.emit({
+ 'type': 'result',
+ 'status': 'error',
+ 'code': 'CANCELLED',
+ 'message': 'Not signed in as [email protected].',
+ });
+ process.finish(1);
+ await expectLater(
+ done,
+ throwsA(
+ isA<PhoneSignInException>().having(
+ (e) => e.code,
+ 'code',
+ 'CANCELLED',
+ ),
+ ),
+ );
+ });
+
+ test('a CLI from before --qr starts SSO instead: stops it and says the CLI is too old', () async {
+ final process = _Process();
+ final done = CliLogin(runner: _Runner(process)).loginWithPhone(
+ onQr: (_, _) => fail('no QR from an old CLI'),
+ onConfirm: (_) async => fail('nothing to confirm'),
+ );
+ await Future<void>.delayed(Duration.zero);
+ process.emit({
+ 'type': 'authorize_url',
+ 'url': 'https://sso.example/authorize',
+ });
+ await Future<void>.delayed(const Duration(milliseconds: 20));
+ expect(process.killed, isTrue);
+ process.finish(143);
+ await expectLater(
+ done,
+ throwsA(
+ isA<PhoneSignInException>().having(
+ (e) => e.code,
+ 'code',
+ 'CLI_TOO_OLD',
+ ),
+ ),
+ );
+ });
+ });
+
+ group('viewerQrSignIn', () {
+ test('claims only after the person confirms the account', () async {
+ final api = _Api(['pending', 'approved']);
+ final links = <String>[];
+ final tokens = await viewerQrSignIn(
+ api: api,
+ label: 'Browser',
+ onQr: (link, _) => links.add(link),
+ onConfirm: (email) async => email == '[email protected]',
+ stillCurrent: () => true,
+ sleep: (_) async {},
+ );
+ expect(tokens.token, 'hna_x');
+ expect(links, [phoneSignInLink('hnq_code')]);
+ expect(api.calls, ['start:Browser', 'poll', 'poll', 'claim']);
+ });
+
+ test('a refusal claims nothing and takes the QR back', () async {
+ final api = _Api(['approved']);
+ await expectLater(
+ viewerQrSignIn(
+ api: api,
+ label: 'b',
+ onQr: (_, _) {},
+ onConfirm: (_) async => false,
+ stillCurrent: () => true,
+ sleep: (_) async {},
+ ),
+ throwsA(
+ isA<PhoneSignInException>().having(
+ (e) => e.code,
+ 'code',
+ 'CANCELLED',
+ ),
+ ),
+ );
+ expect(api.calls, isNot(contains('claim')));
+ expect(api.calls, contains('cancel'));
+ });
+
+ test('a denial on the phone ends it', () async {
+ await expectLater(
+ viewerQrSignIn(
+ api: _Api(['denied']),
+ label: 'b',
+ onQr: (_, _) {},
+ onConfirm: (_) async => true,
+ stillCurrent: () => true,
+ sleep: (_) async {},
+ ),
+ throwsA(
+ isA<PhoneSignInException>().having((e) => e.code, 'code', 'DENIED'),
+ ),
+ );
+ });
+
+ test('keeps the same code alive while it waits', () async {
+ var clock = DateTime(2026);
+ final api = _Api([...List.filled(60, 'pending'), 'approved']);
+ final links = <String>[];
+ await viewerQrSignIn(
+ api: api,
+ label: 'b',
+ onQr: (link, _) => links.add(link),
+ onConfirm: (_) async => true,
+ stillCurrent: () => true,
+ sleep: (d) async => clock = clock.add(d),
+ now: () => clock,
+ );
+ expect(api.calls, contains('extend'));
+ expect(links.toSet(), {phoneSignInLink('hnq_code')});
+ });
+ });
+}
diff --git a/mobile/lib/api/api_client.dart b/mobile/lib/api/api_client.dart
index 6a8794e63..ed0c7b669 100644
--- a/mobile/lib/api/api_client.dart
+++ b/mobile/lib/api/api_client.dart
@@ -145,6 +145,22 @@ class ApiClient {
}
}
+ // -- signing a computer in by its QR (backend routes/qrSignIn.ts) --
+
+ /// What is asking to sign in: `{label, kind, country?, ipHint?, sameNetwork, status}`.
+ Future<Map<String, dynamic>> signInLookup(String code) async {
+ final res = await _dio.post('/api/auth/qr/lookup', data: {'code': code});
+ return Map<String, dynamic>.from(unwrapApiResponse(res) as Map);
+ }
+
+ Future<void> approveSignIn(String code) async {
+ unwrapApiResponse(await _dio.post('/api/auth/qr/approve', data: {'code': code}));
+ }
+
+ Future<void> denySignIn(String code) async {
+ unwrapApiResponse(await _dio.post('/api/auth/qr/deny', data: {'code': code}));
+ }
+
// -- the desk: the account's tabs, the same on every computer --
/// `{revision, tabs}` as the backend holds it (its `routes/desk.ts`); null on
diff --git a/mobile/lib/phone/approve_sign_in.dart b/mobile/lib/phone/approve_sign_in.dart
new file mode 100644
index 000000000..2d0908f66
--- /dev/null
+++ b/mobile/lib/phone/approve_sign_in.dart
@@ -0,0 +1,260 @@
+import 'dart:async';
+
+import 'package:flutter/gestures.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/widgets/app_dialog.dart'
+ show appDialogButtonStyle, kDialogControlRadius, showAppDialog;
+import 'package:harness_mobile/state/app_state.dart';
+
+import 'tty.dart';
+import 'welcome/connect_code.dart';
+import 'welcome/scan_to_connect.dart';
+
+/// Settings ▸ Sign in a computer: scan the QR a computer shows (`harness login`, or the desktop
+/// app's "Scan with your phone") and approve its sign-in with this phone's account.
+///
+/// Approving hands that computer the account's terminals — signing in is what makes the account's
+/// devices trust it — so the prompt says what is asking and from where, and makes a computer on
+/// another network take a deliberate hold rather than a tap. The computer then asks its own person
+/// whose account it is joining; nothing is created until it says yes.
+Future<void> signInAComputer(BuildContext context, AppNotifier notifier, {Widget? camera}) async {
+ final code = await scanForSignIn(context, camera: camera);
+ if (code == null || !context.mounted) return;
+ await approveComputerSignIn(context, notifier, code);
+}
+
+/// The prompt and the answer for one scanned [code].
+Future<void> approveComputerSignIn(BuildContext context, AppNotifier notifier, SignInCode code) async {
+ final Map<String, dynamic> asking;
+ try {
+ asking = await notifier.api.signInLookup(code.code);
+ } catch (error) {
+ if (context.mounted) await _tell(context, "Couldn't read that code", '$error');
+ return;
+ }
+ if (!context.mounted) return;
+ if (asking['status'] != 'pending') {
+ await _tell(context, 'Already answered', 'That code was already answered. Scan the new one.');
+ return;
+ }
+ final answer = await showAppDialog<_Answer>(
+ context: context,
+ builder: (_) => _ApproveDialog(
+ label: (asking['label'] as String?)?.trim().isNotEmpty == true ? asking['label'] as String : 'A computer',
+ computer: asking['kind'] == 'computer',
+ sameNetwork: asking['sameNetwork'] == true,
+ where: [
+ if (asking['country'] is String) asking['country'] as String,
+ if (asking['ipHint'] is String) asking['ipHint'] as String,
+ ].join(' · '),
+ ),
+ );
+ if (answer == null || !context.mounted) return;
+ try {
+ if (answer == _Answer.approve) {
+ await notifier.api.approveSignIn(code.code);
+ HapticFeedback.mediumImpact();
+ if (context.mounted) {
+ await _tell(context, 'Approved', 'Confirm the account on the computer to finish signing it in.');
+ }
+ } else {
+ await notifier.api.denySignIn(code.code);
+ }
+ } catch (error) {
+ if (context.mounted) await _tell(context, "Couldn't answer", '$error');
+ }
+}
+
+/// One line of news where the person is: the answer went through, or why it did not.
+Future<void> _tell(BuildContext context, String title, String message) async {
+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(
+ SnackBar(
+ key: const Key('approve-sign-in-news'),
+ content: Text('$title. $message'),
+ behavior: SnackBarBehavior.floating,
+ ),
+ );
+}
+
+enum _Answer { approve, deny }
+
+class _ApproveDialog extends StatelessWidget {
+ const _ApproveDialog({
+ required this.label,
+ required this.computer,
+ required this.sameNetwork,
+ required this.where,
+ });
+
+ final String label;
+ final bool computer;
+ final bool sameNetwork;
+ final String where;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final warn = Theme.of(context).colorScheme.error;
+ final accent = AppPalette.accentOnSurface;
+ final text = TextStyle(color: AppPalette.textSecondary, fontSize: 15, height: 1.45);
+ return Dialog(
+ insetPadding: const EdgeInsets.symmetric(horizontal: Tty.origin, vertical: 24),
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 360),
+ child: Padding(
+ padding: const EdgeInsets.all(20),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
+ children: [
+ Container(
+ width: 40,
+ height: 40,
+ decoration: BoxDecoration(
+ color: (sameNetwork ? accent : warn).withValues(alpha: 0.14),
+ borderRadius: BorderRadius.circular(kDialogControlRadius),
+ ),
+ child: Icon(
+ computer ? LucideIcons.laptop300 : LucideIcons.appWindow300,
+ size: 20,
+ color: sameNetwork ? accent : warn,
+ ),
+ ),
+ const SizedBox(width: 14),
+ Expanded(
+ child: Text(
+ 'Sign in $label?',
+ key: const Key('approve-sign-in-title'),
+ style: TextStyle(
+ color: AppPalette.textPrimary,
+ fontSize: 17,
+ fontWeight: AppFont.semibold,
+ height: 1.3,
+ ),
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 14),
+ Text(
+ computer
+ ? 'A computer, to your account — it will run your agents and reach your machines.'
+ : 'An app, to your account — it will reach your machines.',
+ style: text,
+ ),
+ const SizedBox(height: 10),
+ Text(
+ sameNetwork
+ ? '✓ On the same network as this phone.'
+ : '⚠ On another network${where.isEmpty ? '' : ' ($where)'}. Only approve a computer you can see.',
+ key: const Key('approve-sign-in-network'),
+ style: text.copyWith(color: sameNetwork ? AppPalette.textSecondary : warn),
+ ),
+ const SizedBox(height: 22),
+ Row(
+ children: [
+ Expanded(
+ child: FilledButton(
+ key: const Key('approve-sign-in-deny'),
+ style: appDialogButtonStyle(background: AppSurface.recess, foreground: AppPalette.textPrimary),
+ onPressed: () => Navigator.of(context).pop(_Answer.deny),
+ child: Text(sameNetwork ? 'Deny' : 'Not me'),
+ ),
+ ),
+ const SizedBox(width: 10),
+ Expanded(
+ child: sameNetwork
+ ? FilledButton(
+ key: const Key('approve-sign-in-approve'),
+ style: appDialogButtonStyle(background: accent, foreground: Colors.white),
+ onPressed: () => Navigator.of(context).pop(_Answer.approve),
+ child: const Text('Approve'),
+ )
+ : _HoldToApprove(onApproved: () => Navigator.of(context).pop(_Answer.approve)),
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// Approve for a computer on another network: a two-second hold, so a prompt tapped through by
+/// habit does not hand a stranger the account's terminals.
+class _HoldToApprove extends StatefulWidget {
+ const _HoldToApprove({required this.onApproved});
+
+ final VoidCallback onApproved;
+
+ static const hold = Duration(seconds: 2);
+
+ @override
+ State<_HoldToApprove> createState() => _HoldToApproveState();
+}
+
+class _HoldToApproveState extends State<_HoldToApprove> with SingleTickerProviderStateMixin {
+ late final AnimationController _progress = AnimationController(vsync: this, duration: _HoldToApprove.hold);
+
+ @override
+ void dispose() {
+ _progress.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final warn = Theme.of(context).colorScheme.error;
+ return RawGestureDetector(
+ key: const Key('approve-sign-in-hold'),
+ gestures: {
+ LongPressGestureRecognizer: GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>(
+ () => LongPressGestureRecognizer(duration: _HoldToApprove.hold),
+ (r) {
+ r.onLongPressDown = (_) {
+ unawaited(_progress.forward(from: 0));
+ };
+ r.onLongPressCancel = () {
+ _progress.reset();
+ };
+ r.onLongPress = () {
+ HapticFeedback.heavyImpact();
+ widget.onApproved();
+ };
+ },
+ ),
+ },
+ child: AnimatedBuilder(
+ animation: _progress,
+ builder: (context, _) => ClipRRect(
+ borderRadius: BorderRadius.circular(kDialogControlRadius),
+ child: Stack(
+ alignment: Alignment.center,
+ children: [
+ Container(height: 44, color: AppSurface.recess),
+ Positioned.fill(
+ child: FractionallySizedBox(
+ alignment: Alignment.centerLeft,
+ widthFactor: _progress.value,
+ child: Container(color: warn.withValues(alpha: 0.7)),
+ ),
+ ),
+ Text(
+ 'Hold to approve',
+ style: TextStyle(color: AppPalette.textPrimary, fontWeight: AppFont.semibold),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/devices_page.dart b/mobile/lib/phone/devices_page.dart
index 640f0fb37..a3f19c0a2 100644
--- a/mobile/lib/phone/devices_page.dart
+++ b/mobile/lib/phone/devices_page.dart
@@ -191,7 +191,7 @@ class _DevicesPageState extends State<DevicesPage> {
const SizedBox(height: 8),
TtyText(
'Every computer and app signed in to your account. Each reaches your machines '
- 'end to end encrypted, with no password. Remove one you do not recognise.',
+ 'end to end encrypted. Remove one you do not recognise.',
color: tty.dim,
),
if (frozen) ...[
diff --git a/mobile/lib/phone/settings_page.dart b/mobile/lib/phone/settings_page.dart
index 95d7ba271..8740e30b0 100644
--- a/mobile/lib/phone/settings_page.dart
+++ b/mobile/lib/phone/settings_page.dart
@@ -16,6 +16,7 @@ import 'package:harness_mobile/state/app_state.dart';
import 'package:harness_mobile/terminal/terminal_font_store.dart';
import 'package:harness_mobile/terminal/terminal_theme_store.dart';
+import 'approve_sign_in.dart';
import 'devices_page.dart';
import 'machines_tab.dart';
import 'phone_navigation.dart' show phoneRoute;
@@ -171,6 +172,13 @@ class _Body extends StatelessWidget {
),
// Every device signed in to the account — each trusted by the others because of that, so
// this is where one that is not yours is seen and taken out.
+ // A computer showing its sign-in QR (`harness login`, or the desktop app's "Scan with your
+ // phone"): this phone approves it with its own account.
+ SettingsRow(
+ key: const Key('settings-sign-in-computer'),
+ title: 'Sign in a computer',
+ onTap: () => unawaited(signInAComputer(context, notifier)),
+ ),
SettingsRow(
title: 'Your devices',
value: notifier.newDevices.isEmpty ? null : '${notifier.newDevices.length} new',
diff --git a/mobile/lib/phone/welcome/connect_code.dart b/mobile/lib/phone/welcome/connect_code.dart
index dd0b5379b..88dc244df 100644
--- a/mobile/lib/phone/welcome/connect_code.dart
+++ b/mobile/lib/phone/welcome/connect_code.dart
@@ -76,3 +76,41 @@ class ConnectCode {
].join('&'),
).toString();
}
+
+/// What a computer signing in by QR shows — the desktop app's "Scan with your phone", or
+/// `harness login` choosing it (backend `routes/qrSignIn.ts`):
+///
+/// ```
+/// https://harness.autonomous.ai/signin#k=<code>
+/// ```
+///
+/// The code is in the fragment, like [ConnectCode]'s, so a Camera app that opens the link sends it
+/// nowhere. It is only an address: approving it takes this phone's own sign-in, and the computer
+/// still asks its person whose account it is joining before anything is created.
+class SignInCode {
+ const SignInCode(this.code);
+
+ final String code;
+
+ static const path = '/signin';
+ static final _shape = RegExp(r'^hnq_[A-Za-z0-9_-]{43}$');
+
+ static SignInCode? parse(String raw) {
+ final uri = Uri.tryParse(raw.trim());
+ if (uri == null ||
+ uri.scheme != 'https' ||
+ uri.host != ConnectCode.host ||
+ uri.path != path) {
+ return null;
+ }
+ final code = Uri.splitQueryString(uri.fragment)['k']?.trim() ?? '';
+ return _shape.hasMatch(code) ? SignInCode(code) : null;
+ }
+
+ static String link(String code) => Uri(
+ scheme: 'https',
+ host: ConnectCode.host,
+ path: path,
+ fragment: 'k=${Uri.encodeQueryComponent(code)}',
+ ).toString();
+}
diff --git a/mobile/lib/phone/welcome/connect_computer.dart b/mobile/lib/phone/welcome/connect_computer.dart
index 04e8a3fa9..fed35f2dc 100644
--- a/mobile/lib/phone/welcome/connect_computer.dart
+++ b/mobile/lib/phone/welcome/connect_computer.dart
@@ -1,3 +1,4 @@
+import '../approve_sign_in.dart';
import 'dart:async';
import 'package:flutter/material.dart';
@@ -99,6 +100,9 @@ class _ConnectComputerPageState extends State<ConnectComputerPage> {
context,
fallbackLabel: 'Not now',
camera: widget.scanCamera,
+ // The computer may be showing its sign-in QR instead: approving that signs it in, which is
+ // what setting it up needs anyway.
+ onSignInCode: (code) => unawaited(approveComputerSignIn(context, widget.notifier, code)),
);
if (!mounted || code == null) return;
final machineId = code.machineId, pairCode = code.pairCode;
diff --git a/mobile/lib/phone/welcome/scan_to_connect.dart b/mobile/lib/phone/welcome/scan_to_connect.dart
index 11cf9e785..6682eeb87 100644
--- a/mobile/lib/phone/welcome/scan_to_connect.dart
+++ b/mobile/lib/phone/welcome/scan_to_connect.dart
@@ -36,9 +36,22 @@ class ScanToConnectPage extends StatefulWidget {
this.signingIn = false,
this.fallbackLabel = 'Use email instead',
this.camera,
+ this.onSignInCode,
+ this.acceptConnectCodes = true,
+ this.title = 'Scan the code on your computer',
+ this.hint = 'On your Mac: Harness ▸ Add Phone…',
});
final ValueChanged<ConnectCode> onCode;
+
+ /// A computer's sign-in QR ([SignInCode]) was read — offered only where the page takes one.
+ final ValueChanged<SignInCode>? onSignInCode;
+
+ /// Whether an Add Phone QR ([ConnectCode]) is one this page takes.
+ final bool acceptConnectCodes;
+
+ final String title;
+ final String hint;
final VoidCallback onUseEmail;
final VoidCallback onBack;
@@ -63,7 +76,15 @@ class _ScanToConnectPageState extends State<ScanToConnectPage> {
void _onDetect(BarcodeCapture capture) {
if (_done) return;
for (final barcode in capture.barcodes) {
- final code = ConnectCode.parse(barcode.rawValue ?? '');
+ final raw = barcode.rawValue ?? '';
+ final signIn = widget.onSignInCode == null ? null : SignInCode.parse(raw);
+ if (signIn != null) {
+ _done = true;
+ HapticFeedback.mediumImpact();
+ widget.onSignInCode!(signIn);
+ return;
+ }
+ final code = widget.acceptConnectCodes ? ConnectCode.parse(raw) : null;
if (code == null) continue;
_done = true;
HapticFeedback.mediumImpact();
@@ -120,7 +141,7 @@ class _ScanToConnectPageState extends State<ScanToConnectPage> {
Padding(
padding: const EdgeInsets.symmetric(horizontal: Tty.origin),
child: TtyText(
- widget.signingIn ? 'Signing in…' : 'Scan the code on your computer',
+ widget.signingIn ? 'Signing in…' : widget.title,
size: TtySize.title,
weight: FontWeight.w600,
),
@@ -129,7 +150,7 @@ class _ScanToConnectPageState extends State<ScanToConnectPage> {
Padding(
padding: const EdgeInsets.symmetric(horizontal: Tty.origin),
child: TtyText(
- 'On your Mac: Harness ▸ Add Phone…',
+ widget.hint,
color: tty.faint,
size: TtySize.meta,
),
@@ -170,12 +191,17 @@ class _ScanToConnectPageState extends State<ScanToConnectPage> {
/// The camera over the current page, and the code it read — null when the person went back or
/// took the other way ([fallbackLabel]). For a phone that is already signed in and wants a
/// computer: unlocking one, or pairing with one just set up.
+///
+/// [onSignInCode]: a computer's sign-in QR read here instead is handed on (after the camera closes)
+/// rather than ignored — the person pointed the phone at a computer, whichever code it showed.
Future<ConnectCode?> scanForCode(
BuildContext context, {
required String fallbackLabel,
Widget? camera,
+ ValueChanged<SignInCode>? onSignInCode,
}) async {
ConnectCode? scanned;
+ SignInCode? signIn;
await Navigator.of(context).push(
phoneRoute(
(page) => Scaffold(
@@ -188,6 +214,43 @@ Future<ConnectCode?> scanForCode(
scanned = code;
Navigator.of(page).pop();
},
+ onSignInCode: onSignInCode == null
+ ? null
+ : (code) {
+ signIn = code;
+ Navigator.of(page).pop();
+ },
+ onUseEmail: () => Navigator.of(page).pop(),
+ onBack: () => Navigator.of(page).pop(),
+ ),
+ ),
+ ),
+ ),
+ );
+ if (signIn case final code?) onSignInCode?.call(code);
+ return scanned;
+}
+
+/// The camera over the current page, for a computer's sign-in QR only — Settings ▸ Sign in a
+/// computer. Null when the person went back.
+Future<SignInCode?> scanForSignIn(BuildContext context, {Widget? camera}) async {
+ SignInCode? scanned;
+ await Navigator.of(context).push(
+ phoneRoute(
+ (page) => Scaffold(
+ backgroundColor: Tty.of(page).ground,
+ body: SafeArea(
+ child: ScanToConnectPage(
+ camera: camera,
+ title: 'Scan the code on the computer',
+ hint: 'On the computer: Sign in ▸ Scan with your phone',
+ fallbackLabel: 'Not now',
+ acceptConnectCodes: false,
+ onCode: (_) {},
+ onSignInCode: (code) {
+ scanned = code;
+ Navigator.of(page).pop();
+ },
onUseEmail: () => Navigator.of(page).pop(),
onBack: () => Navigator.of(page).pop(),
),
diff --git a/mobile/test/approve_sign_in_test.dart b/mobile/test/approve_sign_in_test.dart
new file mode 100644
index 000000000..f825e9960
--- /dev/null
+++ b/mobile/test/approve_sign_in_test.dart
@@ -0,0 +1,95 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/api/api_client.dart';
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/phone/approve_sign_in.dart';
+import 'package:harness_mobile/phone/welcome/connect_code.dart';
+import 'package:harness_mobile/state/app_state.dart';
+
+/// Answers the QR sign-in routes from a script, and records what the phone said.
+class _Api extends ApiClient {
+ _Api(this.asking) : super(config: AppConfig.dev, session: AuthSession());
+
+ final Map<String, dynamic> asking;
+ final answers = <String>[];
+
+ @override
+ Future<Map<String, dynamic>> signInLookup(String code) async => asking;
+ @override
+ Future<void> approveSignIn(String code) async => answers.add('approve:$code');
+ @override
+ Future<void> denySignIn(String code) async => answers.add('deny:$code');
+}
+
+final _code = 'hnq_${'a' * 43}';
+
+void main() {
+ group('SignInCode', () {
+ test('reads the link a computer shows, and nothing else', () {
+ expect(SignInCode.parse(SignInCode.link(_code))?.code, _code);
+ expect(SignInCode.parse('https://harness.autonomous.ai/signin#k=nope'), isNull);
+ expect(SignInCode.parse('https://evil.example/signin#k=$_code'), isNull);
+ expect(SignInCode.parse(ConnectCode.link('[email protected]')), isNull);
+ });
+ });
+
+ Future<_Api> pump(WidgetTester tester, Map<String, dynamic> asking) async {
+ final app = AppNotifier(config: AppConfig.dev, authSession: AuthSession(), configStore: null);
+ addTearDown(app.dispose);
+ final api = _Api(asking);
+ app.api = api;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ onPressed: () => approveComputerSignIn(context, app, SignInCode(_code)),
+ child: const Text('go'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('go'));
+ await tester.pumpAndSettle();
+ return api;
+ }
+
+ testWidgets('a computer on this network is approved with a tap', (tester) async {
+ final api = await pump(tester, {'label': 'MacBook Pro', 'kind': 'computer', 'sameNetwork': true, 'status': 'pending'});
+ expect(find.text('Sign in MacBook Pro?'), findsOneWidget);
+ expect(find.textContaining('same network'), findsOneWidget);
+ await tester.tap(find.byKey(const Key('approve-sign-in-approve')));
+ await tester.pumpAndSettle();
+ expect(api.answers, ['approve:$_code']);
+ });
+
+ testWidgets('a computer on another network says where, and a tap does not approve it', (tester) async {
+ final api = await pump(tester, {'label': 'MacBook Pro', 'kind': 'computer', 'sameNetwork': false, 'country': 'VN', 'ipHint': '1.2.3.x', 'status': 'pending'});
+ expect(find.textContaining('another network (VN · 1.2.3.x)'), findsOneWidget);
+ expect(find.byKey(const Key('approve-sign-in-approve')), findsNothing);
+ await tester.tap(find.byKey(const Key('approve-sign-in-hold')));
+ await tester.pumpAndSettle();
+ expect(api.answers, isEmpty);
+ // Held for the whole two seconds: approved.
+ final gesture = await tester.startGesture(tester.getCenter(find.byKey(const Key('approve-sign-in-hold'))));
+ await tester.pump(const Duration(milliseconds: 2100));
+ await gesture.up();
+ await tester.pumpAndSettle();
+ expect(api.answers, ['approve:$_code']);
+ });
+
+ testWidgets('"Not me" denies it', (tester) async {
+ final api = await pump(tester, {'label': 'MacBook Pro', 'kind': 'computer', 'sameNetwork': false, 'status': 'pending'});
+ await tester.tap(find.byKey(const Key('approve-sign-in-deny')));
+ await tester.pumpAndSettle();
+ expect(api.answers, ['deny:$_code']);
+ });
+
+ testWidgets('a code already answered asks nothing', (tester) async {
+ final api = await pump(tester, {'label': 'x', 'kind': 'computer', 'sameNetwork': true, 'status': 'approved'});
+ expect(find.byKey(const Key('approve-sign-in-title')), findsNothing);
+ expect(api.answers, isEmpty);
+ });
+}