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-in): a spoken code for devices with no screen (#1410) (#1427)

0xken152cf857fe3468
diff --git a/backend/src/lib/harnessSession.ts b/backend/src/lib/harnessSession.ts
index b6665e072..36f87440a 100644
--- a/backend/src/lib/harnessSession.ts
+++ b/backend/src/lib/harnessSession.ts
@@ -1,3 +1,4 @@
+import { randomInt } from 'node:crypto'
import { pub } from './bus.js'
import type { Prisma } from '@prisma/client'
import { prisma } from './prisma.js'
@@ -211,6 +212,10 @@ export async function revokeHarnessSessionById(sessionId: string, userId: string
// computer asks the person "Sign in as <email>?" — someone else's phone may have approved it
// computer → POST /api/auth/qr/claim (no auth) → the session, created now, handed over once
//
+// A device with no screen (a lamp, #1410) asks for a spoken code at start: eight digits it says aloud
+// and the person types on the phone, which stand in for the QR's code at lookup and answer. The device
+// still asks "Sign in as <email>?" (aloud), so a stranger who heard the digits gains nothing by them.
+//
// Signing in is what makes the account's devices trust a computer (the device key log), so approving
// is handing over the account's terminals, and both ends get a say: the phone sees what is asking and
// from where, and the computer sees whose account it would join before any session exists.
@@ -232,11 +237,57 @@ interface QrRecord {
status: 'pending' | 'approved' | 'denied'
userId?: string
email?: string
+ /** Its spoken code, when the device asked for one; it lives and dies with the record. */
+ spokenCode?: string
}
const qrKey = (hash: string): string => `hnauth:qr:${hash}`
const qrPollKey = (hash: string): string => `hnauth:qrpoll:${hash}`
const qrLockKey = (hash: string): string => `hnauth:qrlock:${hash}`
+const qrSpokenKey = (digits: string): string => `hnauth:qrspoken:${digits}`
+
+/** A spoken code: eight digits, easy to say and to type on a phone's number pad. */
+const SPOKEN_CODE = /^\d{8}$/
+
+/** Whether [code] is a spoken code (eight digits, typed with any spacing) rather than a QR's. */
+export function isSpokenCode(code: string): boolean {
+ return SPOKEN_CODE.test(code.replace(/[\s-]/g, ''))
+}
+
+// Eight digits are a small space, so the wrong ones an account types are counted, per hour and per
+// day, in Redis so every replica shares them (the per-process 20/min alone let one account try
+// ~28,800 a day per replica, review of #1427). Misses only: a person who mistypes once is unaffected.
+export const SPOKEN_CODE_MISSES_PER_HOUR = 10
+export const SPOKEN_CODE_MISSES_PER_DAY = 30
+const SPOKEN_MISS_WINDOWS = [
+ { suffix: 'h', ms: 60 * 60_000, max: SPOKEN_CODE_MISSES_PER_HOUR },
+ { suffix: 'd', ms: 24 * 60 * 60_000, max: SPOKEN_CODE_MISSES_PER_DAY },
+] as const
+const spokenMissKey = (userId: string, suffix: string): string => `hnauth:spokenmiss:${userId}:${suffix}`
+// INCR every window, arming its expiry on first use, in one atomic round trip (as bus.ts's new-id quota).
+const SPOKEN_MISS_SCRIPT = `
+for i, key in ipairs(KEYS) do
+ if redis.call('incr', key) == 1 then redis.call('pexpire', key, ARGV[i]) end
+end
+return 1`
+
+/** False once [userId] has missed too many spoken codes: even the right one then waits for the window. */
+export async function spokenCodeGuessesLeft(userId: string): Promise<boolean> {
+ const counts = await Promise.all(SPOKEN_MISS_WINDOWS.map((w) => pub.get(spokenMissKey(userId, w.suffix))))
+ return counts.every((count, i) => Number(count ?? 0) < SPOKEN_MISS_WINDOWS[i]!.max)
+}
+
+export async function recordSpokenCodeMiss(userId: string): Promise<void> {
+ const keys = SPOKEN_MISS_WINDOWS.map((w) => spokenMissKey(userId, w.suffix))
+ await pub.eval(SPOKEN_MISS_SCRIPT, keys.length, ...keys, ...SPOKEN_MISS_WINDOWS.map((w) => w.ms))
+}
+
+/** The record a phone's code names: the QR's own code, or a spoken one typed with any spacing. */
+async function codeHashFor(code: string): Promise<string | null> {
+ const digits = code.replace(/[\s-]/g, '')
+ if (SPOKEN_CODE.test(digits)) return pub.get(qrSpokenKey(digits))
+ return isHarnessQrCode(code) ? harnessTokenHash(code) : null
+}
async function readQr(codeHash: string): Promise<QrRecord | null> {
const raw = await pub.get(qrKey(codeHash))
@@ -273,12 +324,14 @@ function ipHint(ip: string | undefined): string | undefined {
}
export async function startQrSignIn(
- req: { label: string; kind: HarnessSessionKind; computerId?: string },
+ req: { label: string; kind: HarnessSessionKind; computerId?: string; spokenCode?: boolean },
origin: QrSignInOrigin,
-): Promise<{ code: string; pollToken: string; expiresIn: number }> {
+): Promise<{ code: string; pollToken: string; expiresIn: number; spokenCode?: string }> {
const code = newHarnessToken(HARNESS_QR_PREFIX)
const pollToken = newHarnessToken(HARNESS_QR_POLL_PREFIX)
const codeHash = harnessTokenHash(code)
+ // Only on request: a spoken code is a far smaller space than the QR's, so a QR sign-in never has one.
+ const spokenCode = req.spokenCode ? await claimSpokenCode(codeHash) : undefined
const record: QrRecord = {
pollHash: harnessTokenHash(pollToken),
label: req.label,
@@ -288,12 +341,22 @@ export async function startQrSignIn(
...(origin.country ? { country: origin.country } : {}),
createdAt: Date.now(),
status: 'pending',
+ ...(spokenCode ? { spokenCode } : {}),
}
await pub.multi()
.set(qrKey(codeHash), JSON.stringify(record), 'EX', QR_SIGN_IN_TTL_SEC)
.set(qrPollKey(record.pollHash), codeHash, 'EX', QR_SIGN_IN_TTL_SEC)
.exec()
- return { code, pollToken, expiresIn: QR_SIGN_IN_TTL_SEC }
+ return { code, pollToken, expiresIn: QR_SIGN_IN_TTL_SEC, ...(spokenCode ? { spokenCode } : {}) }
+}
+
+/** Eight digits no live sign-in holds, taken for [codeHash]. Live codes are few, so a clash is rare. */
+async function claimSpokenCode(codeHash: string): Promise<string> {
+ for (let attempt = 0; attempt < 10; attempt++) {
+ const digits = String(randomInt(0, 100_000_000)).padStart(8, '0')
+ if (await pub.set(qrSpokenKey(digits), codeHash, 'EX', QR_SIGN_IN_TTL_SEC, 'NX') === 'OK') return digits
+ }
+ throw new Error('qr start: no free spoken code')
}
/** How long a box ticket waits for its box: the phone hands it over on the box's own hotspot, and the
@@ -337,8 +400,9 @@ export interface QrSignInLookup {
/** What is asking to sign in, for the phone about to approve it. Null for a code that is gone. */
export async function lookupQrSignIn(code: string, phone: QrSignInOrigin): Promise<QrSignInLookup | null> {
- if (!isHarnessQrCode(code)) return null
- const r = await readQr(harnessTokenHash(code))
+ const codeHash = await codeHashFor(code)
+ if (!codeHash) return null
+ const r = await readQr(codeHash)
if (!r) return null
return {
label: r.label,
@@ -355,8 +419,8 @@ export async function answerQrSignIn(
code: string,
answer: { approve: true; userId: string; email: string } | { approve: false },
): Promise<'ok' | 'gone' | 'answered'> {
- if (!isHarnessQrCode(code)) return 'gone'
- const codeHash = harnessTokenHash(code)
+ const codeHash = await codeHashFor(code)
+ if (!codeHash) return 'gone'
const r = await readQr(codeHash)
if (!r) return 'gone'
const locked = await pub.set(qrLockKey(codeHash), '1', 'EX', QR_SIGN_IN_MAX_LIFE_SEC, 'NX')
@@ -371,10 +435,11 @@ export async function answerQrSignIn(
// slower than the code's two minutes: it lives out its whole life instead, with nothing to extend.
const next: QrRecord = { ...r, status: 'approved', userId: answer.userId, email: answer.email }
const left = Math.max(1, qrLifeLeft(r))
- await pub.multi()
+ const tx = pub.multi()
.set(qrKey(codeHash), JSON.stringify(next), 'EX', left, 'XX')
.expire(qrPollKey(r.pollHash), left)
- .exec()
+ if (r.spokenCode) tx.expire(qrSpokenKey(r.spokenCode), left)
+ await tx.exec()
return 'ok'
}
@@ -384,7 +449,9 @@ export async function cancelQrSignIn(pollToken: string): Promise<void> {
if (!codeHash) return
const r = await readQr(codeHash)
if (!r || r.pollHash !== harnessTokenHash(pollToken)) return
- await pub.multi().del(qrKey(codeHash)).del(qrPollKey(r.pollHash)).set(qrLockKey(codeHash), '1', 'EX', QR_SIGN_IN_MAX_LIFE_SEC).exec()
+ const tx = pub.multi().del(qrKey(codeHash)).del(qrPollKey(r.pollHash)).set(qrLockKey(codeHash), '1', 'EX', QR_SIGN_IN_MAX_LIFE_SEC)
+ if (r.spokenCode) tx.del(qrSpokenKey(r.spokenCode))
+ await tx.exec()
}
export type QrSignInPoll =
@@ -416,7 +483,9 @@ export async function extendQrSignIn(pollToken: string): Promise<number | null>
// An approved code already lives out its whole life (answerQrSignIn); extending would shorten it.
if (r.status === 'approved') return left
const ttl = Math.min(QR_SIGN_IN_TTL_SEC, left)
- await pub.multi().expire(qrKey(codeHash), ttl).expire(qrPollKey(r.pollHash), ttl).exec()
+ const tx = pub.multi().expire(qrKey(codeHash), ttl).expire(qrPollKey(r.pollHash), ttl)
+ if (r.spokenCode) tx.expire(qrSpokenKey(r.spokenCode), ttl)
+ await tx.exec()
return ttl
}
@@ -434,6 +503,7 @@ export async function claimQrSignIn(pollToken: string): Promise<(HarnessTokens &
let r: QrRecord
try { r = JSON.parse(read[1]) as QrRecord } catch { return null }
await pub.del(qrPollKey(r.pollHash))
+ if (r.spokenCode) await pub.del(qrSpokenKey(r.spokenCode))
if (r.pollHash !== harnessTokenHash(pollToken) || r.status !== 'approved' || !r.userId || !r.email) return null
const tokens = await createSession(r.userId, r.label, r.kind)
return tokens ? { ...tokens, email: r.email, kind: r.kind } : null
diff --git a/backend/src/routes/qrSignIn.test.ts b/backend/src/routes/qrSignIn.test.ts
index a95db12da..844a5c573 100644
--- a/backend/src/routes/qrSignIn.test.ts
+++ b/backend/src/routes/qrSignIn.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import Fastify, { type FastifyInstance } from 'fastify'
// In-memory Redis and sessions, so the real QR sign-in, session and authentication code runs.
@@ -19,6 +19,16 @@ const fakes = vi.hoisted(() => {
return 'OK'
}
const pub = {
+ // The quota scripts: INCR every key, arming its expiry (ms) on first use; the counts in KEYS order.
+ eval: vi.fn(async (_script: string, n: number, ...args: unknown[]) => {
+ const keys = args.slice(0, n) as string[]
+ return keys.map((key, i) => {
+ const next = Number(redis.get(key) ?? 0) + 1
+ redis.set(key, String(next))
+ if (next === 1) ttls.set(key, Math.ceil(Number(args[n + i]) / 1000))
+ return next
+ })
+ }),
set: vi.fn(async (key: string, value: string, ...opts: unknown[]) => set(key, value, ...opts)),
get: vi.fn(async (key: string) => redis.get(key) ?? null),
del: vi.fn(async (key: string) => (redis.delete(key) ? 1 : 0)),
@@ -58,7 +68,7 @@ vi.mock('../services/UserService.js', () => ({
vi.mock('../services/index.js', () => ({ userService: { get: fakes.get, toPublic: (u: unknown) => u } }))
import { authenticateAccessToken, SsoAuthError } from '../lib/ssoAuth.js'
-import { redeemHandoff, startHandoff, BOX_TICKET_TTL_SEC, QR_SIGN_IN_MAX_LIFE_SEC } from '../lib/harnessSession.js'
+import { redeemHandoff, startHandoff, BOX_TICKET_TTL_SEC, QR_SIGN_IN_MAX_LIFE_SEC, SPOKEN_CODE_MISSES_PER_HOUR } from '../lib/harnessSession.js'
import { qrSignInRoutes } from './qrSignIn.js'
import { authRoutes } from './auth.js'
import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'
@@ -178,6 +188,86 @@ describe('sign a computer in by scanning its QR', () => {
expect((await post('/api/auth/handoff', {}, { authorization: `Bearer ${phone}` })).statusCode).toBe(403)
})
+ // A device with no screen (lampOS's lamp, #1410) cannot show a QR: it says a short code aloud and the
+ // person types it into Harness on their phone. The same QR sign-in underneath, with the same
+ // "Sign in as <email>?" on the device, so a stranger who hears the code still cannot use it.
+ describe('a spoken code', () => {
+ // Each start from its own address: the start limit is per address and per process, across tests.
+ let device = 0
+ // And each test in a minute of its own: the phone half's 20/min is per account and per process too.
+ let minute = 0
+ beforeEach(() => { vi.spyOn(Date, 'now').mockReturnValue(Date.UTC(2030, 0, 1) + ++minute * 61_000) })
+ afterEach(() => { vi.restoreAllMocks() })
+ const startSpoken = async () =>
+ (await post('/api/auth/qr/start', { label: 'Lamp', kind: 'computer', computerId: COMPUTER_ID, spokenCode: true }, { 'cf-connecting-ip': `10.0.0.${++device}` })).json().data as { code: string; pollToken: string; spokenCode: string }
+
+ it('signs a device in with eight digits typed on the phone, spaced however the person likes', async () => {
+ const { pollToken, spokenCode } = await startSpoken()
+ expect(spokenCode).toMatch(/^\d{8}$/)
+ const typed = `${spokenCode.slice(0, 4)} ${spokenCode.slice(4)}`
+ expect((await post('/api/auth/qr/lookup', { code: typed }, asPhone())).json().data).toMatchObject({ label: 'Lamp', kind: 'computer', status: 'pending' })
+ expect((await post('/api/auth/qr/approve', { code: typed }, asPhone())).statusCode).toBe(200)
+ expect((await post('/api/auth/qr/poll', { pollToken })).json().data).toEqual({ status: 'approved', email: '[email protected]' })
+ expect((await post('/api/auth/qr/claim', { pollToken })).json().data).toMatchObject({ email: '[email protected]', kind: 'computer' })
+ })
+
+ it('is made only when the device asks, so a QR sign-in gains no guessable handle', async () => {
+ const plain = await start()
+ expect(plain).not.toHaveProperty('spokenCode')
+ expect([...fakes.redis.keys()].filter((k) => k.startsWith('hnauth:qrspoken:'))).toEqual([])
+ })
+
+ it('lives and dies with its sign-in', async () => {
+ const { code, pollToken, spokenCode } = await startSpoken()
+ const key = `hnauth:qrspoken:${spokenCode}`
+ expect(fakes.ttls.get(key)).toBe(120)
+ expect((await post('/api/auth/qr/extend', { pollToken })).statusCode).toBe(200)
+ expect(fakes.ttls.get(key)).toBe(120)
+ expect((await post('/api/auth/qr/approve', { code: spokenCode }, asPhone())).statusCode).toBe(200)
+ expect(fakes.ttls.get(key)).toBeGreaterThan(QR_SIGN_IN_MAX_LIFE_SEC - 5)
+ expect((await post('/api/auth/qr/deny', { code }, asPhone())).statusCode).toBe(409)
+ expect((await post('/api/auth/qr/claim', { pollToken })).statusCode).toBe(200)
+ expect(fakes.redis.has(key)).toBe(false)
+ })
+
+ it('is gone once the device takes it back', async () => {
+ const { pollToken, spokenCode } = await startSpoken()
+ await post('/api/auth/qr/cancel', { pollToken })
+ expect((await post('/api/auth/qr/approve', { code: spokenCode }, asPhone())).statusCode).toBe(404)
+ })
+
+ it('lets an account miss only a few spoken codes an hour, whichever replica it reaches', async () => {
+ const { spokenCode } = await startSpoken()
+ const wrong = spokenCode === '00000000' ? '00000001' : '00000000'
+ for (let i = 0; i < SPOKEN_CODE_MISSES_PER_HOUR; i++) {
+ expect((await post('/api/auth/qr/lookup', { code: wrong }, asPhone())).statusCode).toBe(404)
+ }
+ // Out of guesses: even the right code waits, so a hit cannot follow a run of misses.
+ expect((await post('/api/auth/qr/approve', { code: spokenCode }, asPhone())).statusCode).toBe(429)
+ expect((await post('/api/auth/qr/lookup', { code: spokenCode }, asPhone())).statusCode).toBe(429)
+ // Counted in Redis, so every replica sees the same misses.
+ expect([...fakes.redis.keys()].some((k) => k.startsWith('hnauth:spokenmiss:'))).toBe(true)
+ })
+
+ it('a deny by spoken code reaches the device', async () => {
+ const { pollToken, spokenCode } = await startSpoken()
+ expect((await post('/api/auth/qr/deny', { code: spokenCode }, asPhone())).statusCode).toBe(200)
+ expect((await post('/api/auth/qr/poll', { pollToken })).json().data).toEqual({ status: 'denied' })
+ })
+
+ it('is only for a device signing itself in, never an app', async () => {
+ const r = await post('/api/auth/qr/start', { label: 'x', kind: 'viewer', spokenCode: true }, { 'cf-connecting-ip': '10.9.9.9' })
+ expect(r.statusCode).toBe(400)
+ })
+
+ it('a code that matches nothing, or is not eight digits, is not found', async () => {
+ await startSpoken()
+ for (const code of ['00000000', '1234567', '123456789', 'abcd efgh']) {
+ expect((await post('/api/auth/qr/lookup', { code }, asPhone())).statusCode).toBe(404)
+ }
+ })
+ })
+
describe('a box ticket', () => {
const ticket = async () => (await post('/api/auth/box/ticket', {}, asPhone())).json().data as { ticket: string; expiresIn: number }
diff --git a/backend/src/routes/qrSignIn.ts b/backend/src/routes/qrSignIn.ts
index cf922b521..b86b0f1e4 100644
--- a/backend/src/routes/qrSignIn.ts
+++ b/backend/src/routes/qrSignIn.ts
@@ -1,7 +1,8 @@
import type { FastifyInstance, FastifyReply } from 'fastify'
import { z } from 'zod'
import {
- answerQrSignIn, cancelQrSignIn, claimQrSignIn, extendQrSignIn, issueBoxTicket, lookupQrSignIn, pollQrSignIn, startQrSignIn,
+ answerQrSignIn, cancelQrSignIn, claimQrSignIn, extendQrSignIn, isSpokenCode, issueBoxTicket, lookupQrSignIn, pollQrSignIn,
+ recordSpokenCodeMiss, spokenCodeGuessesLeft, startQrSignIn,
} from '../lib/harnessSession.js'
import { clientIpFromHeaders, countryCodeFromHeaders } from '../lib/clientGeo.js'
import { validateBody } from '../middlewares/validation.js'
@@ -19,6 +20,8 @@ const start = z.object({
kind: z.enum(['computer', 'viewer']),
// A computer names the computer it is, so the session it gets is one; an app does not.
computerId: z.string().regex(/^[0-9a-fA-F-]{16,64}$/).optional(),
+ // A device with no screen asks for a code it can say aloud (lib/harnessSession.ts).
+ spokenCode: z.boolean().optional(),
}).strict()
const byCode = z.object({ code: z.string().min(1).max(128) }).strict()
const byPoll = z.object({ pollToken: z.string().min(1).max(128) }).strict()
@@ -47,6 +50,14 @@ const unavailable = (reply: FastifyReply, e: unknown, what: string) => {
return sendError(reply, 'Authentication service unavailable', 'AUTH_SERVICE_UNAVAILABLE', 503)
}
const tooMany = (reply: FastifyReply) => sendError(reply, 'Too many tries. Wait a minute.', 'RATE_LIMITED', 429)
+const tooManyWrongCodes = (reply: FastifyReply) =>
+ sendError(reply, 'Too many wrong codes. Try again in an hour.', 'SPOKEN_CODE_LIMITED', 429)
+/** A spoken code that matches nothing: said as a typo, never "scan again", and counted against the account. */
+const noSuchCode = async (reply: FastifyReply, userId: string, code: string) => {
+ if (!isSpokenCode(code)) return sendError(reply, 'That code has expired. Scan the new one.', 'QR_INVALID', 404)
+ await recordSpokenCodeMiss(userId)
+ return sendError(reply, 'No device is waiting with that code. Check the digits, or ask the device for a new one.', 'QR_INVALID', 404)
+}
export async function qrSignInRoutes(app: FastifyInstance): Promise<void> {
app.post<{ Body: z.infer<typeof start> }>('/api/auth/qr/start', { preHandler: validateBody(start) }, async (req, reply) => {
@@ -55,6 +66,10 @@ export async function qrSignInRoutes(app: FastifyInstance): Promise<void> {
if (req.body.kind === 'computer' && !req.body.computerId) {
return sendError(reply, 'A computer names itself to sign in.', 'COMPUTER_ID_REQUIRED', 400)
}
+ // A spoken code is for a device with no screen signing itself in; an app always has a screen for a QR.
+ if (req.body.spokenCode && req.body.kind !== 'computer') {
+ return sendError(reply, 'Only a device signing itself in can ask for a spoken code.', 'SPOKEN_CODE_COMPUTER_ONLY', 400)
+ }
try {
return sendSuccess(reply, await startQrSignIn(req.body, { ...(ip ? { ip } : {}), ...(countryCodeFromHeaders(req.headers) ? { country: countryCodeFromHeaders(req.headers) } : {}) }))
} catch (e) { return unavailable(reply, e, 'start') }
@@ -90,11 +105,13 @@ export async function qrSignInRoutes(app: FastifyInstance): Promise<void> {
// The phone's half.
app.post<{ Body: z.infer<typeof byCode> }>('/api/auth/qr/lookup', { preHandler: validateBody(byCode) }, async (req, reply) => {
- if (!answerLimit(req.user!.sub)) return tooMany(reply)
+ const userId = req.user!.sub
+ if (!answerLimit(userId)) return tooMany(reply)
try {
+ if (isSpokenCode(req.body.code) && !(await spokenCodeGuessesLeft(userId))) return tooManyWrongCodes(reply)
const ip = clientIpFromHeaders(req.headers, req.socket.remoteAddress)
const found = await lookupQrSignIn(req.body.code, ip ? { ip } : {})
- if (!found) return sendError(reply, 'That code has expired. Scan the new one.', 'QR_INVALID', 404)
+ if (!found) return await noSuchCode(reply, userId, req.body.code)
return sendSuccess(reply, found)
} catch (e) { return unavailable(reply, e, 'lookup') }
})
@@ -103,8 +120,9 @@ export async function qrSignInRoutes(app: FastifyInstance): Promise<void> {
const user = req.user!
if (!answerLimit(user.sub)) return tooMany(reply)
try {
+ if (isSpokenCode(req.body.code) && !(await spokenCodeGuessesLeft(user.sub))) return tooManyWrongCodes(reply)
const out = await answerQrSignIn(req.body.code, approve ? { approve: true, userId: user.sub, email: user.email } : { approve: false })
- if (out === 'gone') return sendError(reply, 'That code has expired. Scan the new one.', 'QR_INVALID', 404)
+ if (out === 'gone') return await noSuchCode(reply, user.sub, req.body.code)
if (out === 'answered') return sendError(reply, 'This code was already answered.', 'QR_ANSWERED', 409)
logger.info(`qr sign-in ${approve ? 'approved' : 'denied'}`, { userId: user.sub })
return sendSuccess(reply, { ok: true })
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index c75469342..b51b70d6a 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -115,6 +115,9 @@ Machine:
harness login --google sign in with Google in your browser, without asking
harness login --apple sign in with Apple in your browser, without asking
harness login --qr sign in by scanning a QR with Harness on your phone, without asking
+ harness login --code for a device with no screen: say a short code the person types into Harness
+ (phone: Settings ▸ Sign in a computer ▸ Type a code instead; desktop or web:
+ Machines ▸ Approve a device); with --json the code is an event
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)
@@ -381,6 +384,8 @@ interface SignInHooks {
onStarted?: (cancel: () => Promise<void>) => void
/** The person said yes / the browser came back: finish the sign-in, do not abandon it. */
onCommitted?: () => void
+ /** `--code`: say a short code instead of showing the QR (a device with no screen, #1410). */
+ spoken?: boolean
}
/**
@@ -488,8 +493,8 @@ async function loginCommand(
}
const signIn = async (): Promise<SignInOutcome> => {
try {
- return method === 'qr'
- ? await qrSignInCommand(json, emit, (email) => succeed(false, email), { driver, onStarted: (cancel) => { takeBack = cancel }, onCommitted: () => setWaiting(false) })
+ return method === 'qr' || method === 'code'
+ ? await qrSignInCommand(json, emit, (email) => succeed(false, email), { driver, spoken: method === 'code', onStarted: (cancel) => { takeBack = cancel }, onCommitted: () => setWaiting(false) })
: await browserSignIn(json, emit, () => succeed(false), { entryPoint, provider: method }, { onCommitted: () => setWaiting(false) })
} finally {
setWaiting(false)
@@ -600,6 +605,10 @@ function askLine(question: string): Promise<string> {
* 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.
+ *
+ * [SignInHooks.spoken] (`--code`): a device with no screen says a short code instead of the QR —
+ * `{"type":"code","code","expiresIn"}` under --json, sent again whenever the code is kept alive — and
+ * the person types it into Harness on their phone. The confirm question stays, to be asked aloud.
*/
async function qrSignInCommand(
json: boolean,
@@ -614,6 +623,15 @@ async function qrSignInCommand(
...(hooks.onStarted ? { onStarted: hooks.onStarted } : {}),
label: hostname().slice(0, 80),
computerId: computerId(),
+ ...(hooks.spoken ? {
+ showCode: (code: string, expiresIn: number) => {
+ if (json) { emit({ type: 'code', code, expiresIn }); return }
+ if (shown) return
+ shown = true
+ console.log(`\n On your phone, open Harness ▸ Settings ▸ Sign in a computer ▸ Type a code instead (or Machines ▸ Approve a device on a computer), and enter:\n\n ${code.slice(0, 4)} ${code.slice(4)}\n`)
+ console.log(' Waiting for your phone…')
+ },
+ } : {}),
show: (link, expiresIn) => {
if (json) { emit({ type: 'qr', url: link, expiresIn }); return }
if (shown) return
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index b7faa9413..3e8c7dae7 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -1981,6 +1981,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
onAgentSettingsRead: () => agentSettings.settingsRead(),
onAgentSettingsWrite: (body) => agentSettings.settingsWrite(body),
onProductFeedback: (body) => proxyBackend('POST', '/api/product-usage/feedback', body),
+ onSignInAnswer: (action, body) => proxyBackend('POST', `/api/auth/qr/${action}`, body),
onProductUsageReport: (body) => proxyBackend('POST', '/api/product-usage/report', body),
onProductUsageRead: () => proxyBackend('GET', '/api/product-usage/settings'),
onProductUsageWrite: (body) => proxyBackend('POST', '/api/product-usage/settings', body),
diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.ts
index 37fa1f4f7..db17f598d 100644
--- a/cli/src/hookServer.spec.ts
+++ b/cli/src/hookServer.spec.ts
@@ -355,6 +355,34 @@ describe('the Agent Messages proxy', () => {
})
})
+// The desktop and web apps approve a device that says its code aloud (a lamp, #1410), as the phone does:
+// the daemon passes the phone half of a sign-in through with its own session, and nothing else.
+describe('sign-in approval proxy', () => {
+ it('passes lookup, approve and deny through with the code only, guarded from cross-origin requests', async () => {
+ const send = vi.fn(async () => ({ status: 200, body: { success: true, data: { ok: true } } }))
+ const { base } = await start({ onSignInAnswer: send })
+ const headers = { 'x-adapter-local': '1', 'content-type': 'application/json' }
+ for (const h of [{}, { ...headers, origin: 'https://untrusted.example' }]) {
+ expect((await fetch(`${base}/api/auth/qr/approve`, { method: 'POST', headers: h, body: JSON.stringify({ code: '12345678' }) })).status).toBe(403)
+ }
+ for (const invalid of [{}, { code: '' }, { code: 5 }, { code: 'x'.repeat(129) }, { code: '12345678', userId: 'u2' }]) {
+ expect((await fetch(`${base}/api/auth/qr/approve`, { method: 'POST', headers, body: JSON.stringify(invalid) })).status).toBe(400)
+ }
+ expect((await fetch(`${base}/api/auth/qr/claim`, { method: 'POST', headers, body: JSON.stringify({ code: '12345678' }) })).status).toBe(404)
+ expect(send).not.toHaveBeenCalled()
+ for (const action of ['lookup', 'approve', 'deny'] as const) {
+ expect((await fetch(`${base}/api/auth/qr/${action}`, { method: 'POST', headers, body: JSON.stringify({ code: '1234 5678' }) })).status).toBe(200)
+ expect(send).toHaveBeenLastCalledWith(action, { code: '1234 5678' })
+ }
+ })
+
+ it('is unavailable on a daemon that cannot reach the backend for it', async () => {
+ const { base } = await start({})
+ const r = await fetch(`${base}/api/auth/qr/lookup`, { method: 'POST', headers: { 'x-adapter-local': '1', 'content-type': 'application/json' }, body: JSON.stringify({ code: '12345678' }) })
+ expect(r.status).toBe(503)
+ })
+})
+
describe('account Experimental settings proxy', () => {
it('proxies only voluntary fixed-choice feedback and guards it from cross-origin requests', async () => {
const send = vi.fn(async () => ({ status: 200, body: { success: true, data: { accepted: true } } }))
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index d718bbe48..dd0f7067b 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -185,6 +185,9 @@ export interface HookServerHandlers {
onExperimentalRead?: () => Promise<PairOutcome>
onExperimentalWrite?: (body: unknown) => Promise<PairOutcome>
onProductFeedback?: (body: unknown) => Promise<PairOutcome>
+ /** The phone half of a sign-in (backend routes/qrSignIn.ts) for the desktop and web apps: approve a device
+ * that says its code aloud (a lamp, #1410) with this computer's own session, as the phone does. */
+ onSignInAnswer?: (action: 'lookup' | 'approve' | 'deny', body: { code: string }) => Promise<PairOutcome>
onProductUsageReport?: (body: unknown) => Promise<PairOutcome>
onProductUsageRead?: () => Promise<PairOutcome>
onProductUsageWrite?: (body: unknown) => Promise<PairOutcome>
@@ -1080,6 +1083,21 @@ export function startHookServer(
} catch { json(502, { success: false, error: { code: 'USAGE_UNAVAILABLE', message: 'Product usage unavailable' } }) }
return
}
+ const signInAnswer = req.method === 'POST' ? /^\/api\/auth\/qr\/(lookup|approve|deny)$/.exec(url) : null
+ if (signInAnswer) {
+ if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }
+ if (!handlers.onSignInAnswer) { json(503, { error: 'UNAVAILABLE' }); return }
+ let body: unknown
+ try { body = JSON.parse(await readBody(req)) } catch { json(400, { error: 'BAD_REQUEST' }); return }
+ // The code and nothing else: whose account approves is this computer's session, never the caller's.
+ const code = (body as { code?: unknown } | null)?.code
+ if (!body || typeof body !== 'object' || Object.keys(body).length !== 1
+ || typeof code !== 'string' || code.length < 1 || code.length > 128) {
+ json(400, { error: 'BAD_REQUEST' }); return
+ }
+ const action = signInAnswer[1] as 'lookup' | 'approve' | 'deny'
+ await proxied(() => handlers.onSignInAnswer!(action, { code })); return
+ }
if (req.method === 'POST' && url === '/api/product-usage/feedback') {
if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }
if (!handlers.onProductFeedback) { json(503, { error: 'UNAVAILABLE' }); return }
diff --git a/cli/src/lib/qrSignIn.spec.ts b/cli/src/lib/qrSignIn.spec.ts
index 77318d567..843cee89b 100644
--- a/cli/src/lib/qrSignIn.spec.ts
+++ b/cli/src/lib/qrSignIn.spec.ts
@@ -3,12 +3,18 @@ import { claimTicket, qrSignIn, qrSignInLink, type QrSignInDeps } from './qrSign
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' } = {}) {
+function backend(polls: Array<{ status: string; email?: string }>, opts: { extend?: 'ok' | 'fail'; claim?: 'ok' | 'fail'; spoken?: 'unsupported' | 'rejected' } = {}) {
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/start') {
+ if ((body as { spokenCode?: boolean }).spokenCode && opts.spoken === 'rejected') {
+ throw Object.assign(new Error('Unrecognized key(s) in object: \'spokenCode\''), { status: 400 })
+ }
+ const spoken = (body as { spokenCode?: boolean }).spokenCode && opts.spoken !== 'unsupported'
+ return { code: 'hnq_code', pollToken: 'hnp_poll', expiresIn: 120, ...(spoken ? { spokenCode: '12345678' } : {}) }
+ }
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.')
@@ -97,6 +103,55 @@ describe('qrSignIn', () => {
})
})
+// A device with no screen (lampOS's lamp, #1410): it says a short code aloud instead of showing a QR,
+// and still asks its person "Sign in as <email>?" before any session exists.
+describe('qrSignIn with a spoken code', () => {
+ const spokenDeps = (b: ReturnType<typeof backend>, confirm = true) => {
+ const said: Array<[string, number]> = []
+ const d = { ...b.deps(confirm), showCode: (code: string, expiresIn: number) => { said.push([code, expiresIn]) } }
+ return { d, said }
+ }
+
+ it('asks for a spoken code, says it instead of the QR, and confirms before claiming', async () => {
+ const b = backend([{ status: 'approved', email: '[email protected]' }])
+ const { d, said } = spokenDeps(b)
+ const r = await qrSignIn(d)
+ expect(r).toMatchObject({ ok: true })
+ expect(b.calls[0].body).toEqual({ label: 'MacBook Pro', kind: 'computer', computerId: 'c-1', spokenCode: true })
+ expect(said).toEqual([['12345678', 120]])
+ expect(d.shown).toEqual([])
+ expect(d.confirm).toHaveBeenCalledWith('[email protected]')
+ })
+
+ it('says the same code again each time it is kept alive', async () => {
+ const polls: Array<{ status: string; email?: string }> = Array.from({ length: 50 }, () => ({ status: 'pending' }))
+ const b = backend([...polls, { status: 'approved', email: '[email protected]' }])
+ const { d, said } = spokenDeps(b)
+ await qrSignIn(d)
+ expect(said.length).toBeGreaterThan(1)
+ expect(new Set(said.map(([code]) => code))).toEqual(new Set(['12345678']))
+ })
+
+ it('says plainly that an older backend, which refuses the field, has no spoken codes', async () => {
+ const b = backend([], { spoken: 'rejected' })
+ const { d } = spokenDeps(b)
+ expect(await qrSignIn(d)).toEqual({ ok: false, code: 'BACKEND_ERROR', message: 'This Harness backend cannot give a spoken code yet.' })
+ })
+
+ it('names the way back that gives a new spoken code when this one runs out', async () => {
+ const b = backend(Array.from({ length: 60 }, () => ({ status: 'pending' })), { extend: 'fail' })
+ const { d } = spokenDeps(b)
+ expect(await qrSignIn(d)).toMatchObject({ ok: false, code: 'EXPIRED', message: 'The code expired. Run `harness login --code` again.' })
+ })
+
+ it('stops at once, and takes the sign-in back, when the backend gives no spoken code', async () => {
+ const b = backend([], { spoken: 'unsupported' })
+ const { d } = spokenDeps(b)
+ expect(await qrSignIn(d)).toMatchObject({ ok: false, code: 'BACKEND_ERROR' })
+ expect(b.paths()).toEqual(['/api/auth/qr/start', '/api/auth/qr/cancel'])
+ })
+})
+
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')
diff --git a/cli/src/lib/qrSignIn.ts b/cli/src/lib/qrSignIn.ts
index 77cd6efec..7888a70e1 100644
--- a/cli/src/lib/qrSignIn.ts
+++ b/cli/src/lib/qrSignIn.ts
@@ -35,6 +35,9 @@ export interface QrSignInDeps {
post: <T>(path: string, body: unknown) => Promise<T>
/** A new (or the same, extended) code to show. */
show: (link: string, expiresIn: number) => void
+ /** For a device with no screen (a lamp, #1410): ask the backend for a short code to say aloud, and
+ * say it — again each time it is kept alive — instead of showing the QR. */
+ showCode?: (code: string, expiresIn: number) => void
/** Ask the person whether to sign in as [email]. */
confirm: (email: string) => Promise<boolean>
label: string
@@ -46,6 +49,8 @@ export interface QrSignInDeps {
onStarted?: (cancel: () => Promise<void>) => void
}
+const NO_SPOKEN_CODE = 'This Harness backend cannot give a spoken code yet.'
+
/** Extend the code this long before it runs out, so an approval given at the last moment counts. */
const EXTEND_BEFORE_MS = 30_000
@@ -53,17 +58,35 @@ 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 }
+ const spoken = deps.showCode !== undefined
+ let started: { code: string; pollToken: string; expiresIn: number; spokenCode?: string }
try {
- started = await deps.post('/api/auth/qr/start', { label: deps.label, kind: 'computer', computerId: deps.computerId })
+ started = await deps.post('/api/auth/qr/start', {
+ label: deps.label, kind: 'computer', computerId: deps.computerId, ...(spoken ? { spokenCode: true } : {}),
+ })
} catch (err) {
+ // A backend from before spoken codes refuses the field outright (its body schema is strict).
+ if (spoken && (err as { status?: number }).status === 400) {
+ return { ok: false, code: 'BACKEND_ERROR', message: NO_SPOKEN_CODE }
+ }
return { ok: false, code: 'BACKEND_ERROR', message: (err as Error).message }
}
const { pollToken } = started
+ const expired = `The code expired. Run \`harness login${spoken ? ' --code' : ''}\` again.`
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(() => {}) }
+ const spokenCode = started.spokenCode
+ if (spoken && !spokenCode) {
+ // A backend from before spoken codes: there is nothing this device could say, so do not wait.
+ await cancel()
+ return { ok: false, code: 'BACKEND_ERROR', message: NO_SPOKEN_CODE }
+ }
+ const display = (expiresIn: number): void => {
+ if (spokenCode) deps.showCode!(spokenCode, expiresIn)
+ else deps.show(link, expiresIn)
+ }
+ let expiresAt = now() + started.expiresIn * 1000
+ display(started.expiresIn)
deps.onStarted?.(cancel)
for (;;) {
await sleep(every)
@@ -71,9 +94,9 @@ export async function qrSignIn(deps: QrSignInDeps): Promise<QrSignInResult> {
try {
const { expiresIn } = await deps.post<{ expiresIn: number }>('/api/auth/qr/extend', { pollToken })
expiresAt = now() + expiresIn * 1000
- deps.show(link, expiresIn)
+ display(expiresIn)
} catch {
- return { ok: false, code: 'EXPIRED', message: 'The code expired. Run `harness login` again.' }
+ return { ok: false, code: 'EXPIRED', message: expired }
}
}
let state: { status: string; email?: string }
@@ -85,7 +108,7 @@ export async function qrSignIn(deps: QrSignInDeps): Promise<QrSignInResult> {
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.' }
+ return { ok: false, code: 'EXPIRED', message: expired }
}
if (!(await deps.confirm(state.email))) {
await cancel()
diff --git a/cli/src/lib/signInMethodPicker.spec.ts b/cli/src/lib/signInMethodPicker.spec.ts
index 7145769a3..7af34b6f3 100644
--- a/cli/src/lib/signInMethodPicker.spec.ts
+++ b/cli/src/lib/signInMethodPicker.spec.ts
@@ -68,6 +68,8 @@ describe('signInMethodFlag', () => {
expect(signInMethodFlag(['--force', '--google'])).toBe('google')
expect(signInMethodFlag(['--apple', '--json'])).toBe('apple')
expect(signInMethodFlag(['--qr'])).toBe('qr')
+ // A device with no screen says a short code aloud (#1410); never offered by the picker.
+ expect(signInMethodFlag(['--code', '--json'])).toBe('code')
})
it('names nothing without one — `--sso` included, which is no longer a method', () => {
diff --git a/cli/src/lib/signInMethodPicker.ts b/cli/src/lib/signInMethodPicker.ts
index 19700761c..962d0be3c 100644
--- a/cli/src/lib/signInMethodPicker.ts
+++ b/cli/src/lib/signInMethodPicker.ts
@@ -2,7 +2,8 @@ import { emitKeypressEvents } from 'node:readline'
/** The accounts a browser sign-in goes straight to (backend `SIGN_IN_PROVIDERS`). */
export type SignInProvider = 'google' | 'apple'
-export type SignInMethod = SignInProvider | 'qr'
+/** `code`: a short code said aloud, for a device with no screen (#1410) — a flag only, never picked. */
+export type SignInMethod = SignInProvider | 'qr' | 'code'
const OPTIONS: Array<{ method: SignInMethod; label: string }> = [
{ method: 'google', label: 'Google in your browser' },
@@ -10,9 +11,9 @@ const OPTIONS: Array<{ method: SignInMethod; label: string }> = [
{ method: 'qr', label: 'Scan a QR with Harness on your phone' },
]
-/** `harness login --google|--apple|--qr`: the method a flag names, so nothing is asked. */
+/** `harness login --google|--apple|--qr|--code`: the method a flag names, so nothing is asked. */
export const signInMethodFlag = (flags: readonly string[]): SignInMethod | undefined =>
- OPTIONS.find((option) => flags.includes(`--${option.method}`))?.method
+ OPTIONS.find((option) => flags.includes(`--${option.method}`))?.method ?? (flags.includes('--code') ? 'code' : undefined)
/** How a provider is written for a person: `Google`, `Apple`. */
export const signInProviderName = (provider: SignInProvider): string =>
diff --git a/desktop/lib/api/api_client.dart b/desktop/lib/api/api_client.dart
index 6bf816573..640bc55e1 100644
--- a/desktop/lib/api/api_client.dart
+++ b/desktop/lib/api/api_client.dart
@@ -202,6 +202,40 @@ class ApiClient {
return Map<String, dynamic>.from(unwrapApiResponse(response) as Map);
}
+ // -- the phone half of a sign-in (backend routes/qrSignIn.ts): approving a device that says its code aloud
+ // (a lamp, #1410). Natively the daemon passes these through with this computer's session; a viewer
+ // sends them with its own. --
+
+ /// What is asking to sign in with [code]: its name, kind, network and status.
+ Future<Map<String, dynamic>> signInLookup(String code) async {
+ final res = await _dio.post(
+ '/api/auth/qr/lookup',
+ data: {'code': code},
+ options: Options(headers: {'x-adapter-local': '1'}),
+ );
+ 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},
+ options: Options(headers: {'x-adapter-local': '1'}),
+ ),
+ );
+ }
+
+ Future<void> denySignIn(String code) async {
+ unwrapApiResponse(
+ await _dio.post(
+ '/api/auth/qr/deny',
+ data: {'code': code},
+ options: Options(headers: {'x-adapter-local': '1'}),
+ ),
+ );
+ }
+
Future<Map<String, dynamic>?> me() async {
final res = await _dio.get('/api/auth/me');
return unwrapApiResponse(res) as Map<String, dynamic>?;
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index bca2703ee..827c86127 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -36,6 +36,7 @@ import '../widgets/resting_section.dart'
import '../widgets/session_close_dialog.dart';
import '../notify/system_notifications.dart';
import '../widgets/account_device_detail.dart';
+import '../widgets/approve_device_code.dart';
import '../settings/settings_screen.dart';
import '../settings/settings_section.dart';
import 'login_screen.dart' show showSignInSheet;
@@ -3424,6 +3425,15 @@ class _SwarmScreenState extends State<SwarmScreen> {
_closeSearch(restoreFocus: false);
unawaited(_addPhone());
},
+ onApproveDevice: () async {
+ _pickerModalChanged(true);
+ try {
+ await approveDeviceByCode(context, app);
+ } finally {
+ _pickerModalChanged(false);
+ if (mounted && _search != null) _focusSearch();
+ }
+ },
);
void _openResourcePicker(String prefix) {
diff --git a/desktop/lib/widgets/approve_device_code.dart b/desktop/lib/widgets/approve_device_code.dart
new file mode 100644
index 000000000..1affde452
--- /dev/null
+++ b/desktop/lib/widgets/approve_device_code.dart
@@ -0,0 +1,320 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import '../api/api_client.dart' show ApiException, describeApiError;
+import '../core/viewer_mode.dart' show kViewerMode;
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_dialog.dart';
+import '../state/app_state.dart';
+
+/// Machines ▸ Approve a device: sign in a device with no screen — a lamp (#1410), `harness login --code`
+/// — that says eight digits aloud instead of showing a QR. The same approval the phone gives
+/// (backend routes/qrSignIn.ts), made with this computer's session or, in a browser, the page's.
+///
+/// Approving hands that device the account's terminals, so the prompt says what is asking and from
+/// where before anything is sent, and the device then asks its own person whose account it is joining.
+Future<void> approveDeviceByCode(BuildContext context, AppNotifier notifier) async {
+ final code = await showAppDialog<String>(
+ context: context,
+ builder: (_) => const _TypeCodeDialog(),
+ );
+ if (code == null || !context.mounted) return;
+ final Map<String, dynamic> asking;
+ try {
+ asking = await notifier.api.signInLookup(code);
+ } catch (error) {
+ if (!context.mounted) return;
+ // A daemon from before this route answers its own bare 404, not the backend's sentence.
+ final oldDaemon = !kViewerMode && error is ApiException && error.status == 404 && error.message.startsWith('Request failed');
+ await _tell(
+ context,
+ "Couldn't find that code",
+ oldDaemon ? 'Update Harness on this computer to approve devices from here.' : _sentence(describeApiError(error)),
+ );
+ return;
+ }
+ if (!context.mounted) return;
+ if (asking['status'] != 'pending') {
+ // The device's own "Sign in as …?" is all that stands between a stranger who heard the code and
+ // the account: say so while the person can still answer it.
+ await _tell(
+ context,
+ 'Already answered',
+ "Someone else already answered this code. If the device asks to sign in with an account that isn't yours, say no.",
+ );
+ return;
+ }
+ final label = asking['label'] is String ? (asking['label'] as String).trim() : '';
+ final approve = await showAppDialog<bool>(
+ context: context,
+ builder: (_) => _ApproveDialog(
+ label: label.isEmpty ? null : label,
+ 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 (approve == null || !context.mounted) return;
+ try {
+ if (approve) {
+ await notifier.api.approveSignIn(code);
+ if (context.mounted) {
+ await _tell(context, 'Approved', 'Confirm the account on the device to finish signing it in.');
+ }
+ } else {
+ await notifier.api.denySignIn(code);
+ }
+ } catch (error) {
+ if (context.mounted) await _tell(context, "Couldn't answer", _sentence(describeApiError(error)));
+ }
+}
+
+/// [describeApiError] words its reasons to follow a colon; here they start a sentence.
+String _sentence(String text) {
+ final trimmed = text.trim();
+ if (trimmed.isEmpty) return 'Something went wrong. Try again.';
+ return '${trimmed[0].toUpperCase()}${trimmed.substring(1)}';
+}
+
+Future<void> _tell(BuildContext context, String title, String message) => showAppDialog<void>(
+ context: context,
+ builder: (context) => AlertDialog(
+ title: Text(title),
+ content: SizedBox(width: 360, child: Text(message, style: grid.AppType.body(height: 1.4))),
+ actions: [
+ FilledButton(
+ key: const Key('approve-sign-in-ok'),
+ onPressed: () => Navigator.pop(context),
+ child: const Text('OK'),
+ ),
+ ],
+ ),
+);
+
+/// The eight digits, typed with any spacing. Owns its controller, so nothing rebuilds over a disposed
+/// one while the dialog animates out.
+class _TypeCodeDialog extends StatefulWidget {
+ const _TypeCodeDialog();
+
+ @override
+ State<_TypeCodeDialog> createState() => _TypeCodeDialogState();
+}
+
+class _TypeCodeDialogState extends State<_TypeCodeDialog> {
+ final _controller = TextEditingController();
+
+ String get _digits => _controller.text.replaceAll(RegExp(r'\D'), '');
+ bool get _complete => _digits.length == 8;
+
+ void _submit() {
+ if (_complete) Navigator.pop(context, _digits);
+ }
+
+ @override
+ void dispose() {
+ _controller.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return AlertDialog(
+ title: const Text('Approve a device'),
+ content: SizedBox(
+ width: 360,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ 'Type the eight digits the device says aloud.',
+ style: grid.AppType.body(height: 1.4),
+ ),
+ const SizedBox(height: 6),
+ Text(
+ 'Never type a code someone sent you — only one a device in front of you is saying.',
+ style: grid.AppType.body(height: 1.4, color: grid.AppPalette.textSecondary),
+ ),
+ const SizedBox(height: 14),
+ TextField(
+ key: const Key('sign-in-code-field'),
+ controller: _controller,
+ autofocus: true,
+ keyboardType: TextInputType.number,
+ textAlign: TextAlign.center,
+ style: grid.AppType.mono(letterSpacing: 4).copyWith(fontSize: 22),
+ inputFormatters: [
+ FilteringTextInputFormatter.allow(RegExp(r'[0-9 ]')),
+ LengthLimitingTextInputFormatter(9),
+ ],
+ decoration: const InputDecoration(hintText: '1234 5678'),
+ onChanged: (_) => setState(() {}),
+ onSubmitted: (_) => _submit(),
+ ),
+ ],
+ ),
+ ),
+ actions: [
+ TextButton(
+ key: const Key('sign-in-code-cancel'),
+ onPressed: () => Navigator.pop(context),
+ style: TextButton.styleFrom(
+ foregroundColor: grid.AppPalette.textSecondary,
+ overlayColor: grid.AppSurface.hoverFill,
+ ),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ key: const Key('sign-in-code-continue'),
+ onPressed: _complete ? _submit : null,
+ child: const Text('Continue'),
+ ),
+ ],
+ );
+ }
+}
+
+/// What is asking, and from where; true approves, false denies.
+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;
+
+ String get _title => switch (label) {
+ final label? => 'Sign in $label?',
+ null => computer ? 'Sign in a device?' : 'Sign in an app?',
+ };
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final body = grid.AppType.body(height: 1.4);
+ return AlertDialog(
+ title: Text(_title, key: const Key('approve-sign-in-title')),
+ content: SizedBox(
+ width: 360,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ computer
+ ? 'A device, to your account — it will run your agents and reach your other computers.'
+ : 'An app, to your account — it will reach your computers.',
+ style: body,
+ ),
+ const SizedBox(height: 10),
+ Text(
+ sameNetwork
+ ? '✓ On the same network as this computer.'
+ : '⚠ On another network${where.isEmpty ? '' : ' ($where)'}. Only approve a device you can see.',
+ key: const Key('approve-sign-in-network'),
+ style: body.copyWith(color: sameNetwork ? grid.AppPalette.textSecondary : grid.AppPalette.dangerFill),
+ ),
+ ],
+ ),
+ ),
+ actions: [
+ TextButton(
+ key: const Key('approve-sign-in-deny'),
+ onPressed: () => Navigator.pop(context, false),
+ style: TextButton.styleFrom(
+ foregroundColor: grid.AppPalette.textSecondary,
+ overlayColor: grid.AppSurface.hoverFill,
+ ),
+ child: Text(sameNetwork ? 'Deny' : 'Not me'),
+ ),
+ if (sameNetwork)
+ FilledButton(
+ key: const Key('approve-sign-in-approve'),
+ onPressed: () => Navigator.pop(context, true),
+ child: const Text('Approve'),
+ )
+ else
+ _HoldToApprove(
+ key: const Key('approve-sign-in-approve'),
+ onApproved: () => Navigator.pop(context, true),
+ ),
+ ],
+ );
+ }
+}
+
+/// Approve for a device on another network: a two-second hold, as on the phone. A code is easily read
+/// out over a call or a chat, and a click given out of habit would hand that stranger the account.
+class _HoldToApprove extends StatefulWidget {
+ const _HoldToApprove({super.key, required this.onApproved});
+
+ final VoidCallback onApproved;
+
+ @override
+ State<_HoldToApprove> createState() => _HoldToApproveState();
+}
+
+class _HoldToApproveState extends State<_HoldToApprove> with SingleTickerProviderStateMixin {
+ late final _hold = AnimationController(vsync: this, duration: const Duration(seconds: 2))
+ ..addStatusListener((status) {
+ if (status == AnimationStatus.completed) widget.onApproved();
+ });
+
+ void _release() {
+ if (!_hold.isCompleted) _hold.reverse();
+ }
+
+ @override
+ void dispose() {
+ _hold.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final fill = grid.AppPalette.dangerFill;
+ return Listener(
+ onPointerDown: (_) => _hold.forward(),
+ onPointerUp: (_) => _release(),
+ onPointerCancel: (_) => _release(),
+ child: AnimatedBuilder(
+ animation: _hold,
+ builder: (context, _) => ClipRRect(
+ borderRadius: BorderRadius.circular(8),
+ child: Container(
+ constraints: const BoxConstraints(minWidth: 150, minHeight: 36),
+ decoration: BoxDecoration(color: fill.withValues(alpha: 0.18)),
+ child: Stack(
+ alignment: Alignment.center,
+ children: [
+ Positioned.fill(
+ child: FractionallySizedBox(
+ alignment: Alignment.centerLeft,
+ widthFactor: _hold.value,
+ child: ColoredBox(color: fill),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
+ child: Text('Hold to approve', style: grid.AppType.body(color: grid.AppPalette.textPrimary)),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/widgets/machine_picker_extras.dart b/desktop/lib/widgets/machine_picker_extras.dart
index 9dbfec2af..0cd4bc68b 100644
--- a/desktop/lib/widgets/machine_picker_extras.dart
+++ b/desktop/lib/widgets/machine_picker_extras.dart
@@ -18,6 +18,7 @@ class MachinePickerHooks {
required this.confirm,
required this.onHistory,
this.onAddPhone,
+ this.onApproveDevice,
});
/// Asks a yes/no question over the workspace (the picker steps aside while it is up).
@@ -28,6 +29,9 @@ class MachinePickerHooks {
/// Opens Add Phone. Null where a phone cannot be added from here.
final VoidCallback? onAddPhone;
+
+ /// Approves a device that says its code aloud (a lamp, `harness login --code`). Null hides it.
+ final VoidCallback? onApproveDevice;
}
/// The top of the Machines picker: which computer's tabs this window shows, and what the account's
@@ -341,6 +345,14 @@ class MachinePickerFooter extends StatelessWidget {
compact: true,
onPressed: addPhone,
),
+ if (hooks.onApproveDevice case final approve?)
+ DesktopPill(
+ key: const Key('machine-picker-approve-device'),
+ label: 'Approve a device',
+ compact: true,
+ tooltip: 'Type the code a device with no screen says aloud.',
+ onPressed: approve,
+ ),
DesktopPill(
key: const Key('account-devices-history'),
label: 'History…',
diff --git a/desktop/test/machine_devices_picker_test.dart b/desktop/test/machine_devices_picker_test.dart
index 3bc6b849a..39443e5bd 100644
--- a/desktop/test/machine_devices_picker_test.dart
+++ b/desktop/test/machine_devices_picker_test.dart
@@ -81,6 +81,26 @@ class _AddPhoneApi extends ApiClient {
Future<Map<String, dynamic>?> daemonDevices() async => null;
}
+/// The phone half of a sign-in, canned: a lamp on this network asking, and what this computer said.
+class _ApproveApi extends ApiClient {
+ _ApproveApi({this.sameNetwork = true, this.status = 'pending'})
+ : super(config: AppConfig.dev, session: AuthSession());
+ final bool sameNetwork;
+ final String status;
+ final looked = <String>[];
+ final answers = <String>[];
+ @override
+ Future<Map<String, dynamic>> signInLookup(String code) async {
+ looked.add(code);
+ return {'label': 'Lamp', 'kind': 'computer', 'sameNetwork': sameNetwork, 'status': status, 'country': 'VN', 'ipHint': '9.8.7.x'};
+ }
+
+ @override
+ Future<void> approveSignIn(String code) async => answers.add('approve:$code');
+ @override
+ Future<void> denySignIn(String code) async => answers.add('deny:$code');
+}
+
AccountDevice _device(
String pub, {
required String label,
@@ -334,6 +354,72 @@ void main() {
expect(find.text('Device history'), findsOneWidget);
});
+ // A device with no screen (a lamp, #1410) says eight digits aloud; this computer approves it as a
+ // phone would, with the same "Sign in …?" before anything is sent.
+ testWidgets('Approve a device takes the code a device says, and asks before approving', (tester) async {
+ final api = _ApproveApi();
+ app.api = api;
+ await mount(tester);
+ await openPicker(tester);
+ await tester.tap(find.byKey(const Key('machine-picker-approve-device')));
+ await tester.pumpAndSettle();
+ final next = find.byKey(const Key('sign-in-code-continue'));
+ await tester.enterText(find.byKey(const Key('sign-in-code-field')), '1234 567');
+ await tester.pump();
+ expect(tester.widget<FilledButton>(next).onPressed, isNull);
+ await tester.enterText(find.byKey(const Key('sign-in-code-field')), '1234 5678');
+ await tester.pump();
+ await tester.tap(next);
+ await tester.pumpAndSettle();
+ expect(api.looked, ['12345678']);
+ expect(find.text('Sign in Lamp?'), findsOneWidget);
+ expect(api.answers, isEmpty);
+ await tester.tap(find.byKey(const Key('approve-sign-in-approve')));
+ await tester.pumpAndSettle();
+ expect(api.answers, ['approve:12345678']);
+ });
+
+ Future<void> typeCode(WidgetTester tester, String code) async {
+ await tester.tap(find.byKey(const Key('machine-picker-approve-device')));
+ await tester.pumpAndSettle();
+ expect(find.textContaining('Never type a code someone sent you'), findsOneWidget);
+ await tester.enterText(find.byKey(const Key('sign-in-code-field')), code);
+ await tester.pump();
+ await tester.tap(find.byKey(const Key('sign-in-code-continue')));
+ await tester.pumpAndSettle();
+ }
+
+ // A code is easily read out over a call or a chat: a device on another network takes a deliberate
+ // hold, as on the phone, never one click.
+ testWidgets('a device on another network is approved only by holding', (tester) async {
+ final api = _ApproveApi(sameNetwork: false);
+ app.api = api;
+ await mount(tester);
+ await openPicker(tester);
+ await typeCode(tester, '12345678');
+ expect(find.textContaining('On another network (VN · 9.8.7.x)'), findsOneWidget);
+ final hold = find.byKey(const Key('approve-sign-in-approve'));
+ await tester.tap(hold);
+ await tester.pump(const Duration(milliseconds: 300));
+ expect(api.answers, isEmpty, reason: 'a click is not a hold');
+ final gesture = await tester.startGesture(tester.getCenter(hold));
+ await tester.pump(); // the hold's clock starts on the first frame after the press
+ await tester.pump(const Duration(milliseconds: 2100));
+ await gesture.up();
+ await tester.pumpAndSettle();
+ expect(api.answers, ['approve:12345678']);
+ });
+
+ testWidgets('a code someone else answered warns before the device asks', (tester) async {
+ final api = _ApproveApi(status: 'approved');
+ app.api = api;
+ await mount(tester);
+ await openPicker(tester);
+ await typeCode(tester, '12345678');
+ expect(find.textContaining('Someone else already answered this code'), findsOneWidget);
+ expect(api.answers, isEmpty);
+ });
+
testWidgets('Show in this window narrows the window to one computer', (
tester,
) async {
diff --git a/mobile/lib/phone/approve_sign_in.dart b/mobile/lib/phone/approve_sign_in.dart
index a617282b8..19c1b2710 100644
--- a/mobile/lib/phone/approve_sign_in.dart
+++ b/mobile/lib/phone/approve_sign_in.dart
@@ -24,12 +24,122 @@ import 'welcome/scan_to_connect.dart';
/// 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.
+///
+/// A device with no screen — a lamp (#1410), `harness login --code` — says eight digits aloud instead
+/// of showing a QR: "Type a code instead" under the camera takes them, and they go on to the same
+/// approval. The device still asks its own person whose account it is joining.
Future<void> signInAComputer(BuildContext context, AppNotifier notifier, {Widget? camera}) async {
- final code = await scanForSignIn(context, camera: camera);
+ var typeCode = false;
+ final scanned = await scanForSignIn(context, camera: camera, onTypeCode: () => typeCode = true);
+ if (!context.mounted) return;
+ final code = scanned ?? (typeCode ? await typeSignInCode(context) : null);
if (code == null || !context.mounted) return;
await approveComputerSignIn(context, notifier, code);
}
+/// The eight digits a device with no screen says aloud. Null when the person dropped it.
+Future<SignInCode?> typeSignInCode(BuildContext context) =>
+ showAppDialog<SignInCode>(context: context, builder: (_) => const _TypeCodeDialog());
+
+/// Owns its controller, so nothing rebuilds over a disposed one while the dialog animates out.
+class _TypeCodeDialog extends StatefulWidget {
+ const _TypeCodeDialog();
+
+ @override
+ State<_TypeCodeDialog> createState() => _TypeCodeDialogState();
+}
+
+class _TypeCodeDialogState extends State<_TypeCodeDialog> {
+ final _controller = TextEditingController();
+
+ /// The digits typed, whatever spacing the person used to keep their place.
+ String get _digits => _controller.text.replaceAll(RegExp(r'\D'), '');
+ bool get _complete => _digits.length == 8;
+
+ void _submit() {
+ if (_complete) Navigator.of(context).pop(SignInCode(_digits));
+ }
+
+ @override
+ void dispose() {
+ _controller.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final accent = AppPalette.accentOnSurface;
+ 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: [
+ Text(
+ 'Type the code',
+ style: TextStyle(color: AppPalette.textPrimary, fontSize: 17, fontWeight: AppFont.semibold, height: 1.3),
+ ),
+ const SizedBox(height: 10),
+ Text(
+ 'The eight digits the device says aloud.',
+ style: TextStyle(color: AppPalette.textSecondary, fontSize: 15, height: 1.45),
+ ),
+ const SizedBox(height: 6),
+ Text(
+ 'Never type a code someone sent you — only one a device in front of you is saying.',
+ style: TextStyle(color: AppPalette.textSecondary, fontSize: 13, height: 1.4),
+ ),
+ const SizedBox(height: 16),
+ TextField(
+ key: const Key('sign-in-code-field'),
+ controller: _controller,
+ autofocus: true,
+ keyboardType: TextInputType.number,
+ textAlign: TextAlign.center,
+ style: TextStyle(color: AppPalette.textPrimary, fontSize: 24, letterSpacing: 4),
+ inputFormatters: [
+ FilteringTextInputFormatter.allow(RegExp(r'[0-9 ]')),
+ LengthLimitingTextInputFormatter(9),
+ ],
+ decoration: const InputDecoration(hintText: '1234 5678'),
+ onChanged: (_) => setState(() {}),
+ onSubmitted: (_) => _submit(),
+ ),
+ const SizedBox(height: 22),
+ Row(
+ children: [
+ Expanded(
+ child: FilledButton(
+ key: const Key('sign-in-code-cancel'),
+ style: appDialogButtonStyle(background: AppSurface.recess, foreground: AppPalette.textPrimary),
+ onPressed: () => Navigator.of(context).pop(),
+ child: const Text('Cancel'),
+ ),
+ ),
+ const SizedBox(width: 10),
+ Expanded(
+ child: FilledButton(
+ key: const Key('sign-in-code-continue'),
+ style: appDialogButtonStyle(background: accent, foreground: Colors.white),
+ onPressed: _complete ? _submit : null,
+ child: const Text('Continue'),
+ ),
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
+
/// The prompt and the answer for one scanned [code].
///
/// [scanAgain], when given, follows the reason a code could not be read: where to scan a fresh one.
@@ -56,7 +166,11 @@ Future<void> approveComputerSignIn(
await _tell(
context,
'Already answered',
- scanAgain == null
+ // A typed code was heard, and could have been heard by someone else: the device's own
+ // "Sign in as …?" is then all that stands in their way, so say so while it can be answered.
+ _typed(code)
+ ? "Someone else already answered this code. If the device asks to sign in with an account that isn't yours, say no."
+ : scanAgain == null
? 'That code was already answered. Scan the new one.'
: 'That code was already answered. $scanAgain',
);
@@ -91,6 +205,9 @@ Future<void> approveComputerSignIn(
}
}
+/// A code typed from a device's voice (eight digits) rather than read from a QR.
+bool _typed(SignInCode code) => RegExp(r'^\d{8}$').hasMatch(code.code);
+
/// Why a request failed, as a sentence for the person.
///
/// ⚠️ **Never the exception's own text.** `'$error'` put "DioException [connection error]: The
diff --git a/mobile/lib/phone/welcome/scan_to_connect.dart b/mobile/lib/phone/welcome/scan_to_connect.dart
index 81a729876..9ed854357 100644
--- a/mobile/lib/phone/welcome/scan_to_connect.dart
+++ b/mobile/lib/phone/welcome/scan_to_connect.dart
@@ -480,7 +480,11 @@ Future<ConnectCode?> scanForCode(
///
/// The steps name the terminal's way only: the desktop app signs in on its own page and no longer
/// shows a QR, so this is for a server or a computer without the app, `harness login --qr`.
-Future<SignInCode?> scanForSignIn(BuildContext context, {Widget? camera}) async {
+///
+/// [onTypeCode], when given, takes the button under the camera: "Type a code instead", for a device
+/// with no screen that says its code aloud (`harness login --code`). It is called once the page is
+/// gone; back still leaves.
+Future<SignInCode?> scanForSignIn(BuildContext context, {Widget? camera, VoidCallback? onTypeCode}) async {
SignInCode? scanned;
await Navigator.of(context).push(
phoneRoute(
@@ -491,14 +495,17 @@ Future<SignInCode?> scanForSignIn(BuildContext context, {Widget? camera}) async
camera: camera,
title: 'Scan the code in the terminal',
step: 'On a server, run harness login --qr',
- fallbackLabel: 'Not now',
+ fallbackLabel: onTypeCode == null ? 'Not now' : 'Type a code instead',
acceptConnectCodes: false,
onCode: (_) {},
onSignInCode: (code) {
scanned = code;
Navigator.of(page).pop();
},
- onUseEmail: () => Navigator.of(page).pop(),
+ onUseEmail: () {
+ Navigator.of(page).pop();
+ onTypeCode?.call();
+ },
onBack: () => Navigator.of(page).pop(),
),
),
diff --git a/mobile/test/approve_sign_in_test.dart b/mobile/test/approve_sign_in_test.dart
index 5b15fd57c..8dd917116 100644
--- a/mobile/test/approve_sign_in_test.dart
+++ b/mobile/test/approve_sign_in_test.dart
@@ -117,13 +117,13 @@ void main() {
group('Settings ▸ Sign in a computer', () {
/// Settings' row opening the camera — [signInAComputer] with no real camera behind it.
- Future<_Api> open(WidgetTester tester, {Size size = const Size(430, 932)}) async {
+ Future<_Api> open(WidgetTester tester, {Size size = const Size(430, 932), String status = 'pending'}) async {
tester.view.devicePixelRatio = 1;
tester.view.physicalSize = size;
addTearDown(tester.view.reset);
final app = AppNotifier(config: AppConfig.dev, authSession: AuthSession(), configStore: null);
addTearDown(app.dispose);
- final api = _Api({'label': 'build-box', 'kind': 'computer', 'sameNetwork': true, 'status': 'pending'});
+ final api = _Api({'label': 'build-box', 'kind': 'computer', 'sameNetwork': true, 'status': status});
app.api = api;
await tester.pumpWidget(
MaterialApp(
@@ -170,13 +170,58 @@ void main() {
expect(api.answers, ['approve:$_code']);
});
- testWidgets('Not now goes back and asks nothing', (tester) async {
+ testWidgets('Back goes back and asks nothing', (tester) async {
final api = await open(tester);
- await tester.tap(find.text('Not now'));
+ tester.widget<ScanToConnectPage>(find.byType(ScanToConnectPage)).onBack();
await tester.pumpAndSettle();
expect(find.byType(ScanToConnectPage), findsNothing);
expect(api.looked, isEmpty);
expect(api.answers, isEmpty);
});
+
+ // A device with no screen (a lamp, #1410) says eight digits aloud instead of showing a QR.
+ testWidgets('Type a code instead takes the eight digits a device says, on to the approval', (tester) async {
+ final api = await open(tester);
+ await tester.tap(find.text('Type a code instead'));
+ await tester.pumpAndSettle();
+ expect(find.byType(ScanToConnectPage), findsNothing);
+ final field = find.byKey(const Key('sign-in-code-field'));
+ final next = find.byKey(const Key('sign-in-code-continue'));
+ await tester.enterText(field, '1234 567');
+ await tester.pump();
+ expect(tester.widget<FilledButton>(next).onPressed, isNull);
+ await tester.enterText(field, '1234 5678');
+ await tester.pump();
+ await tester.tap(next);
+ await tester.pumpAndSettle();
+ expect(api.looked, ['12345678']);
+ expect(find.text('Sign in build-box?'), findsOneWidget);
+ await tester.tap(find.byKey(const Key('approve-sign-in-approve')));
+ await tester.pumpAndSettle();
+ expect(api.answers, ['approve:12345678']);
+ });
+
+ testWidgets('a typed code someone else answered warns before the device asks', (tester) async {
+ final api = await open(tester, status: 'approved');
+ await tester.tap(find.text('Type a code instead'));
+ await tester.pumpAndSettle();
+ expect(find.textContaining('Never type a code someone sent you'), findsOneWidget);
+ await tester.enterText(find.byKey(const Key('sign-in-code-field')), '12345678');
+ await tester.pump();
+ await tester.tap(find.byKey(const Key('sign-in-code-continue')));
+ await tester.pumpAndSettle();
+ expect(find.textContaining('Someone else already answered this code'), findsOneWidget);
+ expect(api.answers, isEmpty);
+ });
+
+ testWidgets('a typed code can be dropped without asking anything', (tester) async {
+ final api = await open(tester);
+ await tester.tap(find.text('Type a code instead'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const Key('sign-in-code-cancel')));
+ await tester.pumpAndSettle();
+ expect(find.byKey(const Key('sign-in-code-field')), findsNothing);
+ expect(api.looked, isEmpty);
+ });
});
}