The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(cli): harness login with Google or Apple, as the surface that asked
Dev jacobe9303ba60286
diff --git a/SECURITY.md b/SECURITY.mdindex 4d4cbd984..2de30f170 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -32,7 +32,7 @@ stranger approving yours with their phone (a QR they photographed). The phone shwhere from, and whether it is on the phone's network — another network takes a two-second hold, not atap — and the computer asks its own person whose account approved it before any session exists.A computer signed in this way can add a phone of its own; that chain is intended. Its session is-Harness's own, so billing and grid still need an SSO sign-in.+Harness's own, so billing and grid still need a Google or Apple sign-in.## For implementersdiff --git a/cli/README.md b/cli/README.mdindex f82467547..5b40b3a50 100644--- a/cli/README.md+++ b/cli/README.md@@ -74,7 +74,8 @@ bundle and writes the `~/.local/bin/harness` command, and `hn`: Harness in a teryour local daemon the first time you run it. Local use requires no login.)```bash-harness login # opens browser SSO and saves this computer's session+harness login # asks how to sign in (Google, Apple, or a QR your phone scans) and saves this computer's session+harness login --google # or --apple: straight to that account in the browser, without askingharness login --force # stop the daemon and sign in as a different SSO accountharness start # starts the local adapter; uses a saved SSO session if presentharness start -f # foreground mode for a supervisor; logs to stdout@@ -85,7 +86,7 @@ harness tui # all of Harness in this terminal — tabs, panes, every machharness logout # stop the adapter and clear this computer's SSO session```-`login` uses the browser's native loopback SSO flow. Its access token, refresh token, expiry and+`login` uses the browser's native loopback SSO flow, as the auth-service client of whoever asked — `harness-cli` from a terminal, `harness-desktop` when the desktop app runs it — and the session remembers that client, because a refresh has to name it again. Its access token, refresh token, expiry andbackend-resolved machine id are stored atomically with owner-only permissions in`~/.harness/auth/session.json`; the immutable computer id lives separately at`~/.harness/computer-id`. Later `harness start` invocations reuse and refresh that session as needed.diff --git a/cli/src/authCommand.spec.ts b/cli/src/authCommand.spec.tsindex 6009e0eb1..75d883212 100644--- a/cli/src/authCommand.spec.ts+++ b/cli/src/authCommand.spec.ts@@ -333,6 +333,53 @@ describe('harness login --json', () => {expect(lines).toEqual([{ type: 'result', status: 'error', code: 'BACKEND_ERROR', message: expect.any(String) }])})+ it('names the account the person chose and the surface that asked, and nothing it was not told', async () => {+ // `--google` / `--apple` are what the app's two buttons and the terminal picker send; a client+ // that predates them sends neither and still gets the sign-in page's own chooser. The surface+ // is the auth-service client the sign-in is made as: the terminal's, or the desktop app's.+ for (const [flags, expected] of [+ [['--google'], { provider: 'google', clientId: 'harness-cli' }],+ [['--apple', '--entry-point=desktop'], { provider: 'apple', clientId: 'harness-desktop' }],+ [[], { provider: undefined, clientId: 'harness-cli' }],+ ] as const) {+ let body: Record<string, unknown> = {}+ const { base } = await fakeBackend({+ authorizeNative: (sent) => { body = sent; return { authorizeUrl: 'https://sso.example.test/authorize?tx=abc', tx: 'tx_abc' } },+ })+ const login = jsonChild(tempRoot(), base, ['login', '--force', ...flags, '--json'])+ const page = await login.next()+ expect(page).toMatchObject({ type: 'authorize_url' })+ // This backend's page does not name the account (one from before `provider`): the page the+ // browser is sent to names it all the same.+ expect(new URL(String(page.url)).searchParams.get('provider')).toBe(expected.provider ?? null)+ expect(body.provider).toBe(expected.provider)+ expect(body.clientId).toBe(expected.clientId)+ login.child.kill()+ await login.exit+ }+ }, 30_000)++ it('keeps the client the backend exchanged as — not the one it asked for — with the session', async () => {+ // A refresh has to name the client the tokens were issued to. A backend from before the+ // clients were split exchanges as its configured one and names none: the session keeps none.+ for (const [answered, kept] of [['harness-cli', 'harness-cli'], [undefined, undefined], ['someone-else', undefined]] as const) {+ const root = tempRoot()+ let redirectUri = ''+ const { base } = await fakeBackend({+ authorizeNative: (body) => { redirectUri = body.redirectUri; return { authorizeUrl: 'https://sso.example.test/authorize?tx=abc', tx: 'tx_abc' } },+ exchange: () => ({ token: 'tok_new', refreshToken: 'refresh_new', expiresIn: 3600, autonomousEnv: 'prod', ...(answered ? { clientId: answered } : {}) }),+ resolveComputer: () => ({ machine: { machineId: 'm_new' } }),+ })+ const login = jsonChild(root, base, ['login', '--google', '--json'])+ expect(await login.next()).toMatchObject({ type: 'authorize_url' })+ await fetch(`${redirectUri}?code=code_123&state=state_456`)+ expect(await login.next()).toEqual({ type: 'result', status: 'success' })+ await login.exit+ const session = JSON.parse(readFileSync(join(root, 'auth', 'session.json'), 'utf8')) as Record<string, unknown>+ expect(session.clientId).toBe(kept)+ }+ }, 45_000)+it('drives the full loopback flow: emits authorize_url, then a success result once the callback lands', async () => {const root = tempRoot()let capturedRedirectUri = ''diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex bc2c8cb81..7fd4b23f3 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -66,13 +66,13 @@ import { ensureTmuxOnPath } from './lib/tmuxOnPath.js'import { flashCommand } from './lib/flash.js'import { readOrMintComputerId } from './lib/computerIdentity.js'import { awaitLoginCallback, extractCallbackParams, LOGIN_TIMEOUT_MESSAGE } from './lib/loginCallback.js'-import { AuthSessionError, AuthSessionManager, clearAuthSession, readAuthSession, writeAuthSession, type AuthSession } from './lib/authSession.js'+import { AuthSessionError, AuthSessionManager, clearAuthSession, knownSsoClientId, readAuthSession, ssoClientIdFor, writeAuthSession, type AuthSession } from './lib/authSession.js'import { LocalPresence, PAIR_HARNESS_DSH, ZooTurnCounter, ZooTurnReporter } from './lib/zooTurns.js'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 { pickSignInMethod, signInMethodFlag, signInProviderName, withSignInProvider, type SignInMethod, type SignInProvider } from './lib/signInMethodPicker.js'import { watchJsonDriver, type JsonDriver } from './lib/jsonDriver.js'import { terminalQr } from './lib/terminalQr.js'import { ensureGridInstalled } from './lib/gridInstall.js'@@ -414,8 +414,9 @@ ${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 (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 sign in (asks: Google or Apple in your browser, or scan a QR with your phone)+ harness login --google sign in with Google in your browser, without asking+ harness login --apple sign in with Apple in your browser, without askingharness login --qr sign in by scanning a QR with Harness on your phone, without askingharness login --force stop the daemon and sign in with a different accountharness login --json emit machine-readable NDJSON instead of opening a browser (for GUI clients)@@ -730,7 +731,7 @@ async function authStatusCommand(json: boolean): Promise<void> {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')+ if (payload.loggedIn && payload.method === 'qr') console.log(' Billing and grid need a Google or Apple sign-in: harness login --force\n')}}@@ -798,7 +799,7 @@ async function loginCommand(foreground: boolean,force: boolean,json: boolean,- opts: { chained?: boolean; entryPoint?: string; method?: 'sso' | 'qr' | 'ask' } = {},+ opts: { chained?: boolean; entryPoint?: string; method?: SignInMethod | '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@@ -818,9 +819,10 @@ async function loginCommand(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'+ // Google or Apple in the browser, or a QR the phone scans. Asked only of a person at a terminal+ // with no flag. Nothing named — a client driving --json that predates the flags, a pipe — is the+ // browser still, on the sign-in page's own chooser.+ let method: SignInMethod | undefined = opts.method === 'ask' ? undefined : opts.method// The app driving --json: its answers, and its going away. A sign-in it left behind (the app quit// or restarted) would otherwise wait on — minutes, holding the daemon spawn lock — and the app's// next sign-in would sit behind it with nothing on screen. So while it waits on a person it takes@@ -859,7 +861,7 @@ async function loginCommand(try {return method === 'qr'? await qrSignInCommand(json, emit, (email) => succeed(false, email), { driver, onStarted: (cancel) => { takeBack = cancel }, onCommitted: () => setWaiting(false) })- : await browserSignIn(json, emit, () => succeed(false), entryPoint, { onCommitted: () => setWaiting(false) })+ : await browserSignIn(json, emit, () => succeed(false), { entryPoint, provider: method }, { onCommitted: () => setWaiting(false) })} finally {setWaiting(false)}@@ -940,8 +942,8 @@ 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> {+/** `harness login` at a terminal, with no flag: which way to sign in. Enter is Google, the first row. */+async function askSignInMethod(): Promise<SignInMethod | null> {const method = await pickSignInMethod({ input: process.stdin, output: process.stdout })if (method) console.log(` (next time: harness login --${method})`)return method@@ -1028,13 +1030,15 @@ async function qrSignInCommand(* 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* an exit code (`emit`); on the human path it is thrown. `succeed` finishes the job once the- * session is on disk.+ * session is on disk. `provider` is the account the page opens on (Google, Apple); without one it+ * is the page's own chooser. The sign-in is made as [entryPoint]'s own auth-service client+ * (`ssoClientIdFor`), and the session keeps the client the backend says the tokens were issued to.*/async function browserSignIn(json: boolean,emit: (line: Record<string, unknown>) => void,succeed: () => Promise<SignInOutcome>,- entryPoint: string,+ { entryPoint, provider }: { entryPoint: string; provider?: SignInProvider },hooks: Pick<SignInHooks, 'onCommitted'> = {},): Promise<SignInOutcome> {const callback = createServer()@@ -1054,18 +1058,21 @@ async function browserSignIn(redirectUri,autonomousEnv: env.AUTONOMOUS_ENV,entryPoint,+ clientId: ssoClientIdFor(entryPoint),+ ...(provider ? { provider } : {}),})if (!start.authorizeUrl || !start.tx) throw new Error('Backend did not return an SSO authorize URL')} catch (err) {if (json) { emit({ type: 'result', status: 'error', code: 'BACKEND_ERROR', message: (err as Error).message }); process.exitCode = 1; return { signedIn: false } }throw err}+ const authorizeUrl = withSignInProvider(start.authorizeUrl, provider)if (json) {- emit({ type: 'authorize_url', url: start.authorizeUrl })+ emit({ type: 'authorize_url', url: authorizeUrl })} else {- console.log('\n Sign in to Harness in your browser:\n')- console.log(` ${start.authorizeUrl}\n`)- openInBrowser(start.authorizeUrl)+ console.log(`\n Sign in to Harness${provider ? ` with ${signInProviderName(provider)}` : ''} in your browser:\n`)+ console.log(` ${authorizeUrl}\n`)+ openInBrowser(authorizeUrl)}// A browser on this SAME machine can reach the loopback server directly. Over SSH the user's// browser is on a DIFFERENT machine — its own 127.0.0.1 has nothing listening on that port, so the@@ -1084,9 +1091,9 @@ async function browserSignIn(}// The browser came back: from here the exchange and the session write run to the end.hooks.onCommitted?.()- let exchanged: { token?: string; refreshToken?: string; expiresIn?: number; autonomousEnv?: 'prod' | 'stag' }+ let exchanged: { token?: string; refreshToken?: string; expiresIn?: number; autonomousEnv?: 'prod' | 'stag'; clientId?: string }try {- exchanged = await postJson<{ token?: string; refreshToken?: string; expiresIn?: number; autonomousEnv?: 'prod' | 'stag' }>('/api/auth/exchange', {+ exchanged = await postJson<typeof exchanged>('/api/auth/exchange', {...callbackResult,tx: start.tx,})@@ -1103,6 +1110,9 @@ async function browserSignIn(...(exchanged.expiresIn ? { expiresAt: Date.now() + exchanged.expiresIn * 1000 } : {}),autonomousEnv: exchanged.autonomousEnv ?? env.AUTONOMOUS_ENV,computerId: id,+ // What the backend says it exchanged as — never what was asked for: a backend from before+ // the clients were split signs every sign-in in as its configured one, and names none.+ ...(knownSsoClientId(exchanged.clientId) ? { clientId: knownSsoClientId(exchanged.clientId) } : {}),updatedAt: Date.now(),}writeAuthSession(session)@@ -8535,7 +8545,7 @@ switch (cmd) {// account: the desktop app reads that line and does not wait for a restart it observes anyway.loginCommand(foreground, flags.includes('--force'), flags.includes('--json'), {entryPoint: entryPointFlag(),- method: flags.includes('--qr') ? 'qr' : flags.includes('--sso') || flags.includes('--json') || !process.stdin.isTTY ? 'sso' : 'ask',+ method: signInMethodFlag(flags) ?? (flags.includes('--json') || !process.stdin.isTTY ? undefined : 'ask'),}).then((outcome) => outcome.signedIn ? restartDaemonForIdentity() : undefined).catch(onError)diff --git a/cli/src/lib/authSession.spec.ts b/cli/src/lib/authSession.spec.tsindex 31324329c..2b16b6f7f 100644--- a/cli/src/lib/authSession.spec.ts+++ b/cli/src/lib/authSession.spec.ts@@ -83,6 +83,31 @@ describe('AuthSessionManager', () => {await expect(readFile(AUTH_SESSION_FILE, 'utf8')).resolves.toContain('new-access')})+ it('refreshes as the client the session was issued to, and names none for a session that kept none', async () => {+ const fetchMock = vi.fn<typeof fetch>().mockImplementation(async () => new Response(JSON.stringify({+ success: true,+ data: { token: 'new-access', expiresIn: 3600 },+ })))+ vi.stubGlobal('fetch', fetchMock)+ const manager = new AuthSessionManager('https://api.example.test')+ const sent = (call: number) => JSON.parse(String(fetchMock.mock.calls[call]![1]?.body)) as Record<string, unknown>++ writeAuthSession({ ...baseSession(), clientId: 'harness-desktop' })+ await manager.accessToken()+ expect(sent(0)).toEqual({ refreshToken: 'refresh-1', autonomousEnv: 'prod', clientId: 'harness-desktop' })+ // The client outlives the refresh: the next one names it too.+ expect(readAuthSession()).toMatchObject({ accessToken: 'new-access', clientId: 'harness-desktop' })++ writeAuthSession(baseSession())+ await manager.accessToken()+ expect(sent(1)).toEqual({ refreshToken: 'refresh-1', autonomousEnv: 'prod' })+ })++ it('reads back only a client that is ours', async () => {+ await writeFile(AUTH_SESSION_FILE, JSON.stringify({ ...baseSession(), clientId: 'someone-else' }))+ expect(readAuthSession()).not.toHaveProperty('clientId')+ })+// `process.exit` skips `finally`: a daemon that exited mid-refresh left the lock for the next// `harness auth status` to wait out (30s), which is how long the desktop app waits for it.it('drops the refresh lock when the process exits while holding it, and only then', async () => {diff --git a/cli/src/lib/authSession.ts b/cli/src/lib/authSession.tsindex 93008394a..064c503bc 100644--- a/cli/src/lib/authSession.ts+++ b/cli/src/lib/authSession.ts@@ -14,11 +14,29 @@ export interface AuthSession {/** 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'+ /** The auth-service client these tokens were issued to, as the backend's exchange reported it.+ * A refresh has to name the same one. Absent is the backend's configured client. */+ clientId?: SsoClientIdupdatedAt: number/** Opaque local knowledge owner, learned from authenticated /auth/me, bound to this sign-in. */memoryOwner?: { key: string; binding: string }}+/**+ * auth-service's clients a computer signs in as (backend `SSO_CLIENT_IDS`): a person at a terminal,+ * or the desktop app running this CLI on their behalf.+ */+const SSO_CLIENT_IDS = { cli: 'harness-cli', desktop: 'harness-desktop' } as const+export type SsoClientId = (typeof SSO_CLIENT_IDS)[keyof typeof SSO_CLIENT_IDS]++/** The client for the surface that asked to sign in (`--entry-point`). */+export const ssoClientIdFor = (entryPoint: string): SsoClientId =>+ entryPoint === 'desktop' ? SSO_CLIENT_IDS.desktop : SSO_CLIENT_IDS.cli++/** A client id read back from the backend or the session file: one of ours, or nothing. */+export const knownSsoClientId = (raw: unknown): SsoClientId | undefined =>+ Object.values(SSO_CLIENT_IDS).find((id) => id === raw)+export class AuthSessionError extends Error {constructor(message: string, readonly code: 'MISSING' | 'INVALID_REFRESH' | 'UNAVAILABLE') {super(message)@@ -48,6 +66,7 @@ function parse(raw: string): AuthSession | null {computerId: value.computerId,...(typeof value.machineId === 'string' && value.machineId ? { machineId: value.machineId } : {}),...(value.method === 'qr' || value.method === 'sso' ? { method: value.method } : {}),+ ...(knownSsoClientId(value.clientId) ? { clientId: knownSsoClientId(value.clientId) } : {}),updatedAt: typeof value.updatedAt === 'number' ? value.updatedAt : 0,...(value.memoryOwner && /^[a-f0-9]{64}$/.test(value.memoryOwner.key)&& value.memoryOwner.binding === memoryOwnerBinding(value.accessToken, value.autonomousEnv)@@ -182,7 +201,11 @@ async function refreshRequest(baseUrl: string, current: AuthSession, timeoutMs =response = await fetch(`${baseUrl.replace(/\/$/, '')}/api/auth/refresh`, {method: 'POST',headers: { 'content-type': 'application/json' },- body: JSON.stringify({ refreshToken: current.refreshToken, autonomousEnv: current.autonomousEnv }),+ body: JSON.stringify({+ refreshToken: current.refreshToken,+ autonomousEnv: current.autonomousEnv,+ ...(current.clientId ? { clientId: current.clientId } : {}),+ }),signal: AbortSignal.timeout(timeoutMs),})} catch {diff --git a/cli/src/lib/gridHandoff.spec.ts b/cli/src/lib/gridHandoff.spec.tsindex 13782a1e7..ee207ca0f 100644--- a/cli/src/lib/gridHandoff.spec.ts+++ b/cli/src/lib/gridHandoff.spec.ts@@ -90,7 +90,7 @@ describe('handOffToGrid — which grid it runs', () => {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')+ expect(result.message).toContain('harness login --force')})it('prefers the managed runtime over a grid on PATH', async () => {diff --git a/cli/src/lib/gridHandoff.ts b/cli/src/lib/gridHandoff.tsindex 5c424cd86..3953d9007 100644--- a/cli/src/lib/gridHandoff.ts+++ b/cli/src/lib/gridHandoff.ts@@ -108,7 +108,7 @@ export async function handOffToGrid(// 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: '' }+ return { code: 'GRID_NEEDS_SSO', exitCode: 1, message: 'Grid needs a Google or Apple sign-in on this computer: harness login --force', stdout: '', stderr: '' }}const binary = gridBinaryPath()if (!binaryOnPath(binary)) {diff --git a/cli/src/lib/signInMethodPicker.spec.ts b/cli/src/lib/signInMethodPicker.spec.tsindex 324d981c5..7145769a3 100644--- a/cli/src/lib/signInMethodPicker.spec.ts+++ b/cli/src/lib/signInMethodPicker.spec.ts@@ -1,6 +1,6 @@import { PassThrough } from 'node:stream'import { describe, expect, it, vi } from 'vitest'-import { pickSignInMethod } from './signInMethodPicker.js'+import { pickSignInMethod, signInMethodFlag, withSignInProvider } from './signInMethodPicker.js'function tty() {const input = new PassThrough() as unknown as NodeJS.ReadStream & { isTTY: boolean; setRawMode: (raw: boolean) => void }@@ -19,13 +19,15 @@ function tty() {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 () => {+ it('starts on Google, so Enter alone is still the browser', async () => {const io = tty()const picked = pickSignInMethod(io)await tick()- expect(io.written()).toContain('❯ SSO in your browser')+ expect(io.written()).toContain('❯ Google in your browser')+ expect(io.written()).toContain(' Apple in your browser')+ expect(io.written()).not.toContain('SSO')io.press('enter')- expect(await picked).toBe('sso')+ expect(await picked).toBe('google')expect(io.input.setRawMode).toHaveBeenLastCalledWith(false)})@@ -35,17 +37,19 @@ describe('pickSignInMethod', () => {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(io.written().split('❯ ').at(-1)).toMatch(/^Apple in your browser/)+ io.press('j', 'k', 'up', 'up', 'enter') // apple→qr→apple→google→qrexpect(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('a row\'s number takes it at once', async () => {+ for (const [key, method] of [['1', 'google'], ['2', 'apple'], ['3', 'qr']] as const) {+ const io = tty()+ const picked = pickSignInMethod(io)+ await tick()+ io.press(key)+ expect(await picked).toBe(method)+ }})it('Esc and Ctrl-C leave with nothing chosen', async () => {@@ -58,3 +62,35 @@ describe('pickSignInMethod', () => {}})})++describe('signInMethodFlag', () => {+ it('reads the method a flag names', () => {+ expect(signInMethodFlag(['--force', '--google'])).toBe('google')+ expect(signInMethodFlag(['--apple', '--json'])).toBe('apple')+ expect(signInMethodFlag(['--qr'])).toBe('qr')+ })++ it('names nothing without one — `--sso` included, which is no longer a method', () => {+ expect(signInMethodFlag(['--force', '--json'])).toBeUndefined()+ expect(signInMethodFlag(['--sso'])).toBeUndefined()+ })+})++describe('withSignInProvider', () => {+ const page = 'https://auth.example.test/oauth2/authorize?client_id=harness-cli&redirect_uri=http%3A%2F%2F127.0.0.1%3A57969%2Fcallback&state=s1&entry_point=cli'++ it('adds the account to a page from a backend that did not', () => {+ const url = new URL(withSignInProvider(page, 'google'))+ expect(url.searchParams.get('provider')).toBe('google')+ // Nothing the backend holds for the exchange is touched.+ expect(url.searchParams.get('redirect_uri')).toBe('http://127.0.0.1:57969/callback')+ expect(url.searchParams.get('state')).toBe('s1')+ expect(url.searchParams.get('client_id')).toBe('harness-cli')+ })++ it('is the same page when the backend already named it, and when no account was chosen', () => {+ expect(new URL(withSignInProvider(`${page}&provider=apple`, 'apple')).searchParams.getAll('provider')).toEqual(['apple'])+ expect(withSignInProvider(page, undefined)).toBe(page)+ expect(withSignInProvider('not a url', 'google')).toBe('not a url')+ })+})diff --git a/cli/src/lib/signInMethodPicker.ts b/cli/src/lib/signInMethodPicker.tsindex 3b022b80b..19700761c 100644--- a/cli/src/lib/signInMethodPicker.ts+++ b/cli/src/lib/signInMethodPicker.ts@@ -1,16 +1,44 @@import { emitKeypressEvents } from 'node:readline'-export type SignInMethod = 'sso' | 'qr'+/** The accounts a browser sign-in goes straight to (backend `SIGN_IN_PROVIDERS`). */+export type SignInProvider = 'google' | 'apple'+export type SignInMethod = SignInProvider | 'qr'const OPTIONS: Array<{ method: SignInMethod; label: string }> = [- { method: 'sso', label: 'SSO in your browser' },+ { method: 'google', label: 'Google in your browser' },+ { method: 'apple', label: 'Apple in your browser' },{ 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. */+export const signInMethodFlag = (flags: readonly string[]): SignInMethod | undefined =>+ OPTIONS.find((option) => flags.includes(`--${option.method}`))?.method++/** How a provider is written for a person: `Google`, `Apple`. */+export const signInProviderName = (provider: SignInProvider): string =>+ provider === 'google' ? 'Google' : 'Apple'++/**+ * The sign-in page's address, opening on [provider]'s own sign-in.+ *+ * The backend writes `provider` into the page it hands back — but only one that knows the field+ * does, and this CLI reaches people before the backend it talks to is redeployed. The parameter is+ * the browser's to carry and changes nothing the backend holds (state, PKCE, client), so it is+ * set here as well: the same value where the backend already wrote it, the missing one where not.+ */+export function withSignInProvider(authorizeUrl: string, provider: SignInProvider | undefined): string {+ if (!provider) return authorizeUrl+ let url: URL+ try { url = new URL(authorizeUrl) } catch { return authorizeUrl }+ url.searchParams.set('provider', provider)+ return url.toString()+}+/*** `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.+ * a row's number takes it at once, Esc / q / Ctrl-C leave with null. Starts on Google, the first+ * of the two accounts. 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 }diff --git a/docs/cli.md b/docs/cli.mdindex 565565f3e..cb6d34af7 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -12,7 +12,7 @@ works the same on a headless Linux server; the app is not required on a machine,| Command | What it does ||---|---|-| `harness login [--force] [--json]` | Browser SSO; save this computer's session. `--force` signs in as a different account. `--json` emits NDJSON for GUI clients. |+| `harness login [--google\|--apple\|--qr] [--force] [--json]` | Sign in and save this computer's session: Google or Apple in the browser, or a QR a signed-in phone scans. With no flag at a terminal it asks which. `--force` signs in as a different account. `--json` emits NDJSON for GUI clients. || `harness start [-f] [--repair]` | Start the daemon from the saved session. `-f` runs in the foreground for a supervisor. `--repair` re-verifies the managed Node runtime. || `harness stop` · `harness logout` · `harness reset` | Stop the daemon · stop and clear the SSO session · stop and clear all local state. || `harness status` · `harness version` · `harness update [--force]` | Running, pid, machine id, session count · version · update now. |