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.

fix(cli): `harness login` exits after a pasted callback on a headless box

0xken154c21d50da440
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 0fa267952..5aa058e8d 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -55,7 +55,7 @@ import { stopDaemonProcess } from './lib/daemonStop.js'
import { ensureTmuxOnPath, requireTmuxAvailable } from './lib/tmuxOnPath.js'
import { flashCommand } from './lib/flash.js'
import { readOrMintComputerId } from './lib/computerIdentity.js'
-import { renderLoginSuccessHtml } from './lib/loginPage.js'
+import { awaitLoginCallback, extractCallbackParams, LOGIN_TIMEOUT_MESSAGE } from './lib/loginCallback.js'
import { AuthSessionError, AuthSessionManager, clearAuthSession, readAuthSession, writeAuthSession, type AuthSession } from './lib/authSession.js'
import { handOffToGrid } from './lib/gridHandoff.js'
import { ensureGridInstalled, type GridInstallResult } from './lib/gridInstall.js'
@@ -764,25 +764,9 @@ async function browserSignIn(
const manual = !json && process.stdin.isTTY ? promptForCallbackUrl(redirectUri) : null
let callbackResult: { code: string; state: string }
try {
- callbackResult = await new Promise<{ code: string; state: string }>((resolve, reject) => {
- const timeout = setTimeout(() => reject(new Error('SSO login timed out')), 5 * 60_000)
- callback.on('request', (req, res) => {
- const url = new URL(req.url ?? '/', redirectUri)
- const code = url.searchParams.get('code')
- const state = url.searchParams.get('state')
- const error = url.searchParams.get('error')
- res.writeHead(error || !code || !state ? 400 : 200, { 'content-type': 'text/html; charset=utf-8' })
- res.end(error || !code || !state
- ? '<h1>Harness login failed</h1><p>You can close this window.</p>'
- : renderLoginSuccessHtml())
- clearTimeout(timeout)
- if (error) reject(new Error(`SSO login failed: ${error}`))
- else if (code && state) resolve({ code, state })
- })
- manual?.promise.then(resolve, reject)
- })
+ callbackResult = await awaitLoginCallback({ server: callback, redirectUri, manual: manual?.promise ?? null, timeoutMs: 5 * 60_000 })
} catch (err) {
- const timedOut = (err as Error).message === 'SSO login timed out'
+ const timedOut = (err as Error).message === LOGIN_TIMEOUT_MESSAGE
if (json) { emit({ type: 'result', status: 'error', code: timedOut ? 'TIMEOUT' : 'CALLBACK_ERROR', message: (err as Error).message }); process.exitCode = 1; return { signedIn: false } }
throw err
} finally {
@@ -818,6 +802,9 @@ async function browserSignIn(
}
return await succeed()
} finally {
+ // A keep-alive socket the browser left open would hold `close()` until it idles out (a pinned
+ // ADAPTER_LOGIN_CALLBACK_PORT behind an SSH tunnel is where that shows up); drop it first.
+ callback.closeAllConnections?.()
await new Promise<void>((resolve) => callback.close(() => resolve()))
}
}
@@ -917,28 +904,6 @@ async function gridLogoutCommand(args: string[]): Promise<void> {
process.exitCode = outcome.exitCode
}
-/**
- * Pulls `code`/`state`/`error` out of whatever the user pasted — the full callback URL, just its query
- * string (with or without a leading `?`), or a bare `code=...&state=...` pair with no URL shape at all.
- * `new URL(input, redirectUri)` never throws (a base makes it permissive), but a bare `code=...&state=...`
- * parses as a relative PATH against that base, landing in an empty query — so a URL parse that comes up
- * empty falls back to treating the whole input as a raw query string instead.
- */
-function extractCallbackParams(input: string, redirectUri: string): {
- code: string | null
- state: string | null
- error: string | null
-} {
- const read = (params: URLSearchParams) => ({
- code: params.get('code'),
- state: params.get('state'),
- error: params.get('error'),
- })
- const viaUrl = read(new URL(input, redirectUri).searchParams)
- if (viaUrl.code || viaUrl.state || viaUrl.error) return viaUrl
- return read(new URLSearchParams(input))
-}
-
/**
* Fallback for a browser that cannot reach this machine's loopback callback (running `harness login`
* over SSH: the user's browser is on a different box, so its own 127.0.0.1 has nothing listening).
diff --git a/cli/src/lib/loginCallback.spec.ts b/cli/src/lib/loginCallback.spec.ts
new file mode 100644
index 000000000..625707704
--- /dev/null
+++ b/cli/src/lib/loginCallback.spec.ts
@@ -0,0 +1,104 @@
+import { createServer, type Server } from 'http'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { awaitLoginCallback, extractCallbackParams, LOGIN_TIMEOUT_MESSAGE } from './loginCallback.js'
+
+const REDIRECT = 'http://127.0.0.1:4321/callback'
+
+const servers: Server[] = []
+afterEach(async () => {
+ vi.restoreAllMocks()
+ vi.useRealTimers()
+ for (const server of servers.splice(0)) await new Promise<void>((resolve) => server.close(() => resolve()))
+})
+
+/**
+ * Whether the timer armed with `ms` was cleared. Counted by handle rather than `vi.getTimerCount()`:
+ * `fetch` in the neighbouring tests leaves undici's keep-alive tick (its own 1s `setTimeout`) alive in
+ * this worker, and it re-arms itself whenever the fake clock is advanced — a count would see that.
+ */
+function timerCleared(ms: number): boolean {
+ const setSpy = vi.mocked(setTimeout)
+ const clearSpy = vi.mocked(clearTimeout)
+ const call = setSpy.mock.calls.findIndex((args) => args[1] === ms)
+ if (call < 0) return false
+ const handle = setSpy.mock.results[call].value
+ return clearSpy.mock.calls.some((args) => args[0] === handle)
+}
+
+function spyTimers(): void {
+ vi.useFakeTimers()
+ vi.spyOn(globalThis, 'setTimeout')
+ vi.spyOn(globalThis, 'clearTimeout')
+}
+
+async function listening(): Promise<{ server: Server; redirectUri: string }> {
+ const server = createServer()
+ servers.push(server)
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
+ const address = server.address()
+ if (!address || typeof address === 'string') throw new Error('no port')
+ return { server, redirectUri: `http://127.0.0.1:${address.port}/callback` }
+}
+
+describe('awaitLoginCallback', () => {
+ it('leaves no timer armed once the pasted URL wins the race (issue #112)', async () => {
+ // Over SSH the browser cannot reach this loopback, so the user pastes the URL instead. The
+ // five-minute timeout used to be cleared only by the loopback request handler — on this path it
+ // stayed armed and ref'd, and `harness login` sat there after "✓ Signed in" until Ctrl+C.
+ spyTimers()
+ const server = createServer()
+ const won = await awaitLoginCallback({
+ server, redirectUri: REDIRECT, manual: Promise.resolve({ code: 'c', state: 's' }), timeoutMs: 5 * 60_000,
+ })
+ expect(won).toEqual({ code: 'c', state: 's' })
+ expect(timerCleared(5 * 60_000)).toBe(true)
+ })
+
+ it('resolves from the loopback redirect, answers the browser, and clears the timer', async () => {
+ const { server, redirectUri } = await listening()
+ const pending = awaitLoginCallback({ server, redirectUri, manual: null, timeoutMs: 60_000 })
+ const response = await fetch(`${redirectUri}?code=code_1&state=state_1`)
+ expect(response.status).toBe(200)
+ expect(await response.text()).toContain('<')
+ await expect(pending).resolves.toEqual({ code: 'code_1', state: 'state_1' })
+ // The race is over: the handler leaves with it, so a late redirect cannot reach a settled login.
+ expect(server.listenerCount('request')).toBe(0)
+ })
+
+ it('rejects on an error redirect, with a 400 for the browser', async () => {
+ const { server, redirectUri } = await listening()
+ // The rejection lands before the browser's response is read, so the expectation is attached first.
+ const rejected = expect(awaitLoginCallback({ server, redirectUri, manual: null, timeoutMs: 60_000 }))
+ .rejects.toThrow('SSO login failed: access_denied')
+ const response = await fetch(`${redirectUri}?error=access_denied`)
+ expect(response.status).toBe(400)
+ await rejected
+ })
+
+ it('rejects with the TIMEOUT message when nobody answers, and the timer never keeps the loop alive', async () => {
+ spyTimers()
+ const server = createServer()
+ const rejected = expect(awaitLoginCallback({ server, redirectUri: REDIRECT, manual: null, timeoutMs: 1_000 }))
+ .rejects.toThrow(LOGIN_TIMEOUT_MESSAGE)
+ expect(timerCleared(1_000)).toBe(false)
+ await vi.advanceTimersByTimeAsync(1_000)
+ await rejected
+ expect(timerCleared(1_000)).toBe(true)
+ })
+})
+
+describe('extractCallbackParams', () => {
+ it('reads the full URL, a bare query string, and a code=…&state=… pair alike', () => {
+ expect(extractCallbackParams(`${REDIRECT}?code=a&state=b`, REDIRECT)).toEqual({ code: 'a', state: 'b', error: null })
+ expect(extractCallbackParams('?code=a&state=b', REDIRECT)).toEqual({ code: 'a', state: 'b', error: null })
+ expect(extractCallbackParams('code=a&state=b', REDIRECT)).toEqual({ code: 'a', state: 'b', error: null })
+ expect(extractCallbackParams(`${REDIRECT}?error=denied`, REDIRECT)).toEqual({ code: null, state: null, error: 'denied' })
+ expect(extractCallbackParams('hello', REDIRECT)).toEqual({ code: null, state: null, error: null })
+ })
+
+ it('survives a paste that is not a URL at all instead of throwing out of the prompt', () => {
+ expect(extractCallbackParams('http://', REDIRECT)).toEqual({ code: null, state: null, error: null })
+ // The raw query-string fallback reads what it can; without a `code` the prompt just asks again.
+ expect(extractCallbackParams('http://ex ample/?code=a&state=b', REDIRECT)).toMatchObject({ code: null })
+ })
+})
diff --git a/cli/src/lib/loginCallback.ts b/cli/src/lib/loginCallback.ts
new file mode 100644
index 000000000..41cfab7f9
--- /dev/null
+++ b/cli/src/lib/loginCallback.ts
@@ -0,0 +1,80 @@
+import type { IncomingMessage, Server, ServerResponse } from 'http'
+import { renderLoginSuccessHtml } from './loginPage.js'
+
+export interface LoginCallbackParams { code: string; state: string }
+
+/** The exact message `harness login --json` maps to `code: 'TIMEOUT'` — keep the string stable. */
+export const LOGIN_TIMEOUT_MESSAGE = 'SSO login timed out'
+
+/**
+ * Pulls `code`/`state`/`error` out of whatever the user pasted — the full callback URL, just its query
+ * string (with or without a leading `?`), or a bare `code=...&state=...` pair with no URL shape at all.
+ * `new URL(input, redirectUri)` is permissive (the base absorbs most shapes), but a bare `code=...&state=...`
+ * parses as a relative PATH against that base, landing in an empty query — so a URL parse that comes up
+ * empty falls back to treating the whole input as a raw query string instead. It is not infallible:
+ * a mangled paste (`http://`, a space in the host) throws "Invalid URL", which inside the prompt's
+ * callback would have been an uncaught exception ending the whole login — so a throw is the same as
+ * an empty parse, and the prompt simply asks again.
+ */
+export function extractCallbackParams(input: string, redirectUri: string): {
+ code: string | null
+ state: string | null
+ error: string | null
+} {
+ const read = (params: URLSearchParams) => ({
+ code: params.get('code'),
+ state: params.get('state'),
+ error: params.get('error'),
+ })
+ try {
+ const viaUrl = read(new URL(input, redirectUri).searchParams)
+ if (viaUrl.code || viaUrl.state || viaUrl.error) return viaUrl
+ } catch { /* not a URL at all — read it as a query string below */ }
+ return read(new URLSearchParams(input))
+}
+
+/**
+ * The race `harness login` waits on: the browser's redirect landing on the loopback `server`, the
+ * user pasting that URL back in (`manual`, a TTY over SSH), or `timeoutMs` running out.
+ *
+ * The timer is unref'd AND cleared on every way out — it was only ever cleared inside the request
+ * handler, so a login completed by pasting left it armed and ref'd, and the process sat there for
+ * the remaining five minutes after printing "✓ Signed in" (issue #112, a headless VPS). A timer whose
+ * only job is to reject must never be what keeps the process alive.
+ */
+export function awaitLoginCallback(opts: {
+ server: Server
+ redirectUri: string
+ manual: Promise<LoginCallbackParams> | null
+ timeoutMs: number
+}): Promise<LoginCallbackParams> {
+ const { server, redirectUri, manual, timeoutMs } = opts
+ let timeout: NodeJS.Timeout | undefined
+ const onRequest = (req: IncomingMessage, res: ServerResponse): void => {
+ const url = new URL(req.url ?? '/', redirectUri)
+ const code = url.searchParams.get('code')
+ const state = url.searchParams.get('state')
+ const error = url.searchParams.get('error')
+ res.writeHead(error || !code || !state ? 400 : 200, { 'content-type': 'text/html; charset=utf-8' })
+ res.end(error || !code || !state
+ ? '<h1>Harness login failed</h1><p>You can close this window.</p>'
+ : renderLoginSuccessHtml())
+ if (error) reject(new Error(`SSO login failed: ${error}`))
+ else if (code && state) resolve({ code, state })
+ }
+ // Hoisted so the handler above can settle the promise, and be removed once it has: the server
+ // outlives this race (it is closed by the caller), and a late redirect must not touch a settled login.
+ let resolve!: (value: LoginCallbackParams) => void
+ let reject!: (reason: Error) => void
+ return new Promise<LoginCallbackParams>((res, rej) => {
+ resolve = res
+ reject = rej
+ timeout = setTimeout(() => reject(new Error(LOGIN_TIMEOUT_MESSAGE)), timeoutMs)
+ timeout.unref?.()
+ server.on('request', onRequest)
+ manual?.then(resolve, reject)
+ }).finally(() => {
+ clearTimeout(timeout)
+ server.off('request', onRequest)
+ })
+}