Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(hog): share one way to wait for a browser approval (#127800)

Rafael Audibert6a5fff5e8ff2
diff --git a/hog/AGENTS.md b/hog/AGENTS.md
index 917d31b397db..1a19000d632b 100644
--- a/hog/AGENTS.md
+++ b/hog/AGENTS.md
@@ -54,7 +54,7 @@ export default defineCommand({
- Agent output is JSON only, on stdout, with no color and no prose. Prefer `out.jsonLines` for lists, so an agent can stream them.
- `out.table` colors each column by kind (number, date, boolean, JSON) and fits the terminal width. Pass a `kind` when the API declares column types, as `hog query run` does with ClickHouse types. Otherwise the kind comes from the values.
- A failure throws a `HogError` with a stable `code` and a `hint` that names the next step. `cli.ts` prints it as text or as JSON on stderr. Do not catch errors to print them yourself.
-- Ask questions only through `ctx.prompts`. It is undefined for agents, pipes and `-o json`, so a command that needs an answer must take it as an option there, or fail with a hint that names the option. Never block an agent on a person: split the work into a call that returns at once and a call that finishes it, like `hog auth login` and `hog auth login --wait`.
+- Ask questions only through `ctx.prompts`. It is undefined for agents, pipes and `-o json`, so a command that needs an answer must take it as an option there, or fail with a hint that names the option. Never block an agent on a person: split the work into a call that returns at once and a call that finishes it, like `hog auth login` and `hog auth login --wait`. A command that waits for a person to approve something in a browser uses `runApproval` and `resumeApproval` from `src/core/approval.ts`, so every such command starts, waits and resumes the same way.
- `exitCode` is for results that are not failures but that a script must branch on, like `hog query check` finding errors.
- `--raw` is global: it prints the result of `run` as JSON and skips both views. Do not add per-command `--raw` or `--debug` flags; return enough data from `run` instead.
- An argument with `stdin: true` reads stdin when the caller passes `-`, and fails when it is empty. `hog commands` tells agents which arguments accept it.
diff --git a/hog/src/commands/auth/auth.test.ts b/hog/src/commands/auth/auth.test.ts
index 6044200e4532..ab6b36f04993 100644
--- a/hog/src/commands/auth/auth.test.ts
+++ b/hog/src/commands/auth/auth.test.ts
@@ -6,7 +6,7 @@ import { runHog } from '@/testing'
const LEGACY_CLI_FILE = '/home/test/.posthog/credentials.json'
const SETTINGS_FILE = '/home/test/.config/hog/settings.json'
const HOG_CREDENTIALS_FILE = '/home/test/.config/hog/credentials.json'
-const PENDING_FILE = '/home/test/.posthog/login-pending.json'
+const PENDING_FILE = '/home/test/.config/hog/pending-auth-login.json'
const DEVICE_CODE = 'device-secret-123'
const DEVICE = {
diff --git a/hog/src/commands/auth/login.ts b/hog/src/commands/auth/login.ts
index 59fcff4dcc2d..4eb3586e8410 100644
--- a/hog/src/commands/auth/login.ts
+++ b/hog/src/commands/auth/login.ts
@@ -1,14 +1,15 @@
+import { printPending, resumeApproval, runApproval, type ApprovalResult } from '@/core/approval'
import { defineCommand } from '@/core/command'
import type { Context } from '@/core/context'
import { EXIT_USAGE, HogError } from '@/core/errors'
import { escapeControls } from '@/core/output'
-import type { Prompts, Spinner } from '@/core/prompts'
+import type { Prompts } from '@/core/prompts'
import { PersonalAPIKey } from '@/posthog/access-key'
import type { StoreChoice } from '@/posthog/credential-store/types'
import { checkApiKey, checkHost, checkProjectId } from '@/posthog/credentials'
-import type { PendingLogin } from '@/posthog/device-auth'
+import type { Approval } from '@/posthog/device-auth'
import { trimHost } from '@/posthog/host'
-import { completeLogin, readPendingLogin, saveLogin, startLogin, type LoggedIn } from '@/posthog/login/flow'
+import { loginFlow, saveLogin, type LoggedIn } from '@/posthog/login/flow'
const REGIONS = { us: 'https://us.posthog.com', eu: 'https://eu.posthog.com' } as const
@@ -28,15 +29,7 @@ function cloudRegion(host: string | undefined): string | undefined {
}
type LoginResult =
- | {
- status: 'pending'
- host: string
- url: string
- code: string
- expiresAt: string
- instructions: string
- next: string
- }
+ | (Extract<ApprovalResult<never>, { status: 'pending' }> & { host: string })
| {
status: 'logged_in'
host: string
@@ -52,33 +45,15 @@ function nextCommand(scopes: readonly string[]): string {
return canQuery ? 'hog query run "select event, count() from events group by event"' : 'hog --help'
}
-function pendingResult(pending: PendingLogin): LoginResult {
- return {
- status: 'pending',
- host: pending.host,
- url: pending.url,
- code: pending.userCode,
- expiresAt: new Date(pending.expiresAt).toISOString(),
- instructions: `Ask the user to open ${pending.url} and approve the code ${pending.userCode}. Then run \`hog auth login --wait\`, which returns once they approve. If it times out, run it again.`,
- next: 'hog auth login --wait',
- }
-}
-
function loggedInResult(loggedIn: LoggedIn): LoginResult {
const { host, projectId, store, credentialsPath, keychainError, scopes } = loggedIn
return { status: 'logged_in', host, projectId, store, credentialsPath, keychainError, next: nextCommand(scopes) }
}
-async function finish(ctx: Context, pending: PendingLogin, spinner?: Spinner): Promise<LoginResult> {
- let loggedIn
- try {
- loggedIn = await completeLogin(ctx.runtime, pending)
- } catch (error) {
- spinner?.error("The login didn't finish")
- throw error
- }
- spinner?.stop('Approved')
- return loggedInResult(loggedIn)
+async function finish(ctx: Context, approval: Approval): Promise<LoginResult> {
+ const { host, apiKey, projectId, scopes } = approval
+ const loggedIn = await saveLogin(ctx.runtime, new PersonalAPIKey({ host, projectId, apiKey, scopes }))
+ return loggedInResult({ ...loggedIn, scopes })
}
async function keyLogin(ctx: Context, prompts: Prompts): Promise<LoginResult> {
@@ -114,19 +89,10 @@ export default defineCommand({
examples: ['hog auth login', 'hog auth login --region eu', 'hog auth login --wait'],
async run({ options, ctx }): Promise<LoginResult> {
- const { env } = ctx.runtime
const prompts = ctx.prompts
if (options.wait) {
- const pending = await readPendingLogin(ctx.runtime)
- if (!pending) {
- throw new HogError(
- 'no_pending_login',
- 'No login is waiting for approval.',
- 'Run `hog auth login` to start one.'
- )
- }
- return finish(ctx, pending, prompts?.spinner('Waiting for the login to be approved in the browser'))
+ return finish(ctx, await resumeApproval(ctx, loginFlow(ctx.runtime)))
}
if (!prompts && ctx.mode.agent === undefined && ctx.mode.ci) {
@@ -171,31 +137,13 @@ export default defineCommand({
host = REGIONS[choice]
}
- const pending = await startLogin(ctx.runtime, host)
-
- if (!prompts) {
- return pendingResult(pending)
- }
- prompts.note(`${pending.url}\n\nCode: ${escapeControls(pending.userCode)}`, 'Approve the login in your browser')
- // Over SSH, a browser would open on the remote machine, where nobody sees it.
- const overSsh = env.SSH_CONNECTION !== undefined || env.SSH_TTY !== undefined
- const opened = !overSsh && (await ctx.runtime.openUrl(pending.url))
- return finish(
- ctx,
- pending,
- prompts.spinner(
- opened ? 'Waiting for you to approve in the browser' : 'Open the link above to approve. Waiting'
- )
- )
+ const result = await runApproval(ctx, loginFlow(ctx.runtime, host))
+ return result.status === 'pending' ? { ...result, host } : finish(ctx, result.value)
},
human({ result, out }) {
if (result.status === 'pending') {
- out.line(
- `Open this link to approve the login, and check that it shows the code ${out.style(escapeControls(result.code), 'bold')}:`
- )
- out.line(` ${result.url}`)
- out.line(`Then run ${out.style(result.next, 'bold')}.`)
+ printPending(out, result)
return
}
out.line(`${out.style('Logged in', 'green', 'bold')} to ${result.host}, project ${result.projectId}.`)
diff --git a/hog/src/commands/auth/logout.ts b/hog/src/commands/auth/logout.ts
index eac33f716ecb..f13712bde2fa 100644
--- a/hog/src/commands/auth/logout.ts
+++ b/hog/src/commands/auth/logout.ts
@@ -1,7 +1,8 @@
+import { clearPending } from '@/core/approval'
import { defineCommand } from '@/core/command'
import { escapeControls } from '@/core/output'
import { PERSONAL_API_KEY_ENV_VAR } from '@/posthog/credentials'
-import { clearPendingLogin } from '@/posthog/login/flow'
+import { LOGIN_COMMAND } from '@/posthog/login/flow'
import { logout, logoutAll, type LoggedOutHost } from '@/posthog/login/stored'
import { readSettings } from '@/posthog/settings'
@@ -31,7 +32,7 @@ export default defineCommand({
const stillSet = runtime.env[PERSONAL_API_KEY_ENV_VAR] ? [PERSONAL_API_KEY_ENV_VAR] : []
if (options.all) {
const hosts = await logoutAll(runtime)
- await clearPendingLogin(runtime)
+ await clearPending(runtime, LOGIN_COMMAND)
const status = hosts.length > 0 ? 'logged_out' : 'not_logged_in'
return { status, host: null, revokeUrl: null, keychainLeftover: null, hosts, stillSet }
}
@@ -41,7 +42,7 @@ export default defineCommand({
const configHost = (await ctx.config().catch(() => undefined))?.config.host
const host = ctx.globals.host ?? configHost ?? settings.host
const outcome = host ? await logout(runtime, host) : undefined
- await clearPendingLogin(runtime)
+ await clearPending(runtime, LOGIN_COMMAND)
return {
status: outcome ? 'logged_out' : 'not_logged_in',
host: host ?? null,
diff --git a/hog/src/core/approval.test.ts b/hog/src/core/approval.test.ts
new file mode 100644
index 000000000000..47239db3a828
--- /dev/null
+++ b/hog/src/core/approval.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, test } from 'bun:test'
+
+import { COMMANDS } from '@/commands'
+import { fakeRuntime } from '@/testing'
+
+import { resumeApproval, type ApprovalFlow, type PendingApproval, type PollOutcome } from './approval'
+import { Context } from './context'
+import { HogError } from './errors'
+import type { GlobalOptions } from './globals'
+
+const PENDING_FILE = '/home/test/.config/hog/pending-thing-start.json'
+const START = Date.UTC(2026, 0, 1)
+const PENDING: PendingApproval = {
+ url: 'https://ph.example.com/approve',
+ expiresAt: START + 600_000,
+ intervalSeconds: 5,
+}
+
+describe('resumeApproval', () => {
+ test.each([
+ [
+ 'polls five seconds slower after each slow_down',
+ [{ state: 'slow_down' }, { state: 'slow_down' }, { state: 'pending' }, { state: 'approved', value: 'ok' }],
+ 'ok',
+ [5_000, 15_000, 30_000, 45_000],
+ ],
+ ['forgets a request the person rejected', [{ state: 'rejected' }], 'thing_rejected', [5_000]],
+ ] as const)('%s', async (_name, outcomes, expected, pollTimes) => {
+ const runtime = fakeRuntime({ files: { [PENDING_FILE]: JSON.stringify(PENDING) } })
+ const ctx = new Context(
+ runtime,
+ {} as GlobalOptions,
+ { agent: 'test', agentReason: '', format: 'json', color: false, columns: undefined, ci: false },
+ COMMANDS
+ )
+ const remaining: PollOutcome<string>[] = [...outcomes]
+ const polledAt: number[] = []
+ const flow: ApprovalFlow<PendingApproval, string> = {
+ command: 'hog thing start',
+ noun: 'thing',
+ start: async () => PENDING,
+ poll: async () => {
+ polledAt.push(runtime.now() - START)
+ return remaining.shift() ?? { state: 'pending' }
+ },
+ }
+
+ const outcome = await resumeApproval(ctx, flow).catch((error: unknown) =>
+ error instanceof HogError ? error.code : error
+ )
+
+ expect(outcome).toBe(expected)
+ expect(polledAt).toEqual([...pollTimes])
+ // An approval stays pending until the caller stores its value. A rejection ends it.
+ expect(runtime.files[PENDING_FILE] !== undefined).toBe(expected === 'ok')
+ })
+})
diff --git a/hog/src/core/approval.ts b/hog/src/core/approval.ts
new file mode 100644
index 000000000000..11a3875a844f
--- /dev/null
+++ b/hog/src/core/approval.ts
@@ -0,0 +1,253 @@
+import type { Context } from './context'
+import { HogError } from './errors'
+import { escapeControls, type Output } from './output'
+import { hogFile } from './paths'
+import type { Spinner } from './prompts'
+import type { Runtime } from './runtime'
+
+// Something a person approves in a browser, saved in hog's folder while hog waits for them.
+export interface PendingApproval {
+ url: string
+ // The code the approval page shows, so the person can check it is the request they started.
+ userCode?: string
+ // Epoch milliseconds after which PostHog forgets the request.
+ expiresAt: number
+ intervalSeconds: number
+}
+
+export type PollOutcome<Value> =
+ | { state: 'pending' }
+ // RFC 8628 `slow_down`: poll less often from now on.
+ | { state: 'slow_down' }
+ // A failure that can pass, such as a 429 or a 5xx.
+ | { state: 'retry'; reason: string }
+ | { state: 'approved'; value: Value }
+ | { state: 'rejected' }
+ | { state: 'expired' }
+
+// One command that waits for a person. Every such command goes through `runApproval`, so they all
+// start, wait, resume and give up the same way.
+export interface ApprovalFlow<Pending extends PendingApproval, Value> {
+ // The command that starts it, like `hog auth login`. `<command> --wait` resumes it.
+ command: string
+ // What the person approves, in copy and in error codes, like `login`.
+ noun: string
+ start: () => Promise<Pending>
+ // Whether a pending item from an earlier run can stand in for a new one, so an agent that
+ // retries hands the person the link it already shared.
+ reuse?: (existing: Pending) => boolean
+ // `timeoutMs` is how long the poll request may take before the request expires.
+ poll: (pending: Pending, timeoutMs: number) => Promise<PollOutcome<Value>>
+}
+
+// What resuming a pending item needs. It can't start a new one.
+export type ApprovalWait<Pending extends PendingApproval, Value> = Pick<
+ ApprovalFlow<Pending, Value>,
+ 'command' | 'noun' | 'poll'
+>
+
+export type ApprovalResult<Value> =
+ | {
+ status: 'pending'
+ url: string
+ code: string | null
+ expiresAt: string
+ instructions: string
+ next: string
+ }
+ | { status: 'approved'; value: Value }
+
+const MAX_RETRIES = 3
+const REQUEST_TIMEOUT_MS = 30_000
+// RFC 8628 asks clients to poll this much slower after each `slow_down`.
+const SLOW_DOWN_SECONDS = 5
+// Reusing a request this close to expiry would hand the person a link that dies while they open it.
+// Approving takes a few seconds, so the margin stays short.
+const REUSE_MARGIN_MS = 20_000
+
+function pendingPath(runtime: Runtime, command: string): string {
+ return hogFile(runtime, `pending-${command.replace(/^hog /, '').replaceAll(' ', '-')}.json`)
+}
+
+async function readPending<Pending extends PendingApproval>(
+ runtime: Runtime,
+ command: string
+): Promise<Pending | undefined> {
+ try {
+ return JSON.parse(await runtime.readFile(pendingPath(runtime, command))) as Pending
+ } catch {
+ return undefined
+ }
+}
+
+export async function clearPending(runtime: Runtime, command: string): Promise<void> {
+ await runtime.removeFile(pendingPath(runtime, command))
+}
+
+// A new start replaces the command's pending item, unless the flow can reuse it.
+async function startPending<Pending extends PendingApproval, Value>(
+ runtime: Runtime,
+ flow: ApprovalFlow<Pending, Value>
+): Promise<Pending> {
+ const existing = await readPending<Pending>(runtime, flow.command)
+ if (existing && existing.expiresAt - runtime.now() > REUSE_MARGIN_MS && flow.reuse?.(existing)) {
+ return existing
+ }
+ const pending = await flow.start()
+ // The pending item can hold a secret, like a device code, so only its owner may read it.
+ await runtime.writePrivateFile(pendingPath(runtime, flow.command), JSON.stringify(pending))
+ return pending
+}
+
+// Polls until the person approves, rejects or lets the request expire, and forgets the pending item
+// in each case. When hog loses contact with PostHog the item stays, so `--wait` can resume it.
+async function waitFor<Pending extends PendingApproval, Value>(
+ runtime: Runtime,
+ flow: ApprovalWait<Pending, Value>,
+ pending: Pending
+): Promise<Value> {
+ const interrupted = (reason: string): HogError =>
+ new HogError(
+ `${flow.noun}_interrupted`,
+ `hog lost contact with PostHog while waiting for the ${flow.noun}: ${reason}`,
+ `Run \`${flow.command} --wait\` to keep waiting. The link stays the same.`
+ )
+ const fail = async (error: HogError): Promise<never> => {
+ await clearPending(runtime, flow.command)
+ throw error
+ }
+
+ let failures = 0
+ let intervalSeconds = pending.intervalSeconds
+ while (runtime.now() < pending.expiresAt) {
+ await runtime.sleep(intervalSeconds * 1000)
+ const remaining = pending.expiresAt - runtime.now()
+ if (remaining <= 0) {
+ break
+ }
+ let outcome: PollOutcome<Value>
+ try {
+ outcome = await flow.poll(pending, Math.min(REQUEST_TIMEOUT_MS, remaining))
+ } catch (error) {
+ if (!(error instanceof HogError)) {
+ throw error
+ }
+ if (error.code !== 'network_error') {
+ return fail(error)
+ }
+ outcome = { state: 'retry', reason: error.message }
+ }
+ switch (outcome.state) {
+ case 'retry':
+ if (++failures > MAX_RETRIES) {
+ throw interrupted(outcome.reason)
+ }
+ continue
+ case 'slow_down':
+ intervalSeconds += SLOW_DOWN_SECONDS
+ continue
+ case 'pending':
+ failures = 0
+ continue
+ case 'approved':
+ // The caller clears the pending approval once it has stored the value, so a failed
+ // save can still be retried with `--wait`.
+ return outcome.value
+ case 'rejected':
+ return fail(
+ new HogError(
+ `${flow.noun}_rejected`,
+ `The ${flow.noun} was rejected in the browser.`,
+ `Run \`${flow.command}\` to start again.`
+ )
+ )
+ case 'expired':
+ return fail(expired(flow))
+ }
+ }
+ return fail(expired(flow))
+}
+
+function expired(flow: { noun: string; command: string }): HogError {
+ return new HogError(
+ `${flow.noun}_expired`,
+ `The ${flow.noun} request expired before it was approved.`,
+ `Run \`${flow.command}\` to start a new one.`
+ )
+}
+
+function pendingResult(flow: { command: string }, pending: PendingApproval): ApprovalResult<never> {
+ const code = pending.userCode ?? null
+ const approve = code ? `open ${pending.url} and approve the code ${code}` : `open ${pending.url} and approve it`
+ return {
+ status: 'pending',
+ url: pending.url,
+ code,
+ expiresAt: new Date(pending.expiresAt).toISOString(),
+ instructions: `Ask the user to ${approve}. Then run \`${flow.command} --wait\`, which returns once they approve. If it times out, run it again.`,
+ next: `${flow.command} --wait`,
+ }
+}
+
+async function withSpinner<Value>(spinner: Spinner | undefined, noun: string, wait: Promise<Value>): Promise<Value> {
+ try {
+ const value = await wait
+ spinner?.stop('Approved')
+ return value
+ } catch (error) {
+ spinner?.error(`The ${noun} didn't finish`)
+ throw error
+ }
+}
+
+// Starts a command that waits for a person. At a terminal it shows the link, opens the browser when it
+// can, and waits; Ctrl-C keeps the pending item for `--wait`. Agents and scripts get the link and the
+// `--wait` command to run next, without waiting.
+export async function runApproval<Pending extends PendingApproval, Value>(
+ ctx: Context,
+ flow: ApprovalFlow<Pending, Value>
+): Promise<ApprovalResult<Value>> {
+ const { runtime } = ctx
+ const prompts = ctx.prompts
+ const pending = await startPending(runtime, flow)
+ if (!prompts) {
+ return pendingResult(flow, pending)
+ }
+ const code = pending.userCode ? `\n\nCode: ${escapeControls(pending.userCode)}` : ''
+ prompts.note(`${escapeControls(pending.url)}${code}`, `Approve the ${flow.noun} in your browser`)
+ // Over SSH, a browser would open on the remote machine, where nobody sees it.
+ const overSsh = runtime.env.SSH_CONNECTION !== undefined || runtime.env.SSH_TTY !== undefined
+ const opened = !overSsh && (await runtime.openUrl(pending.url))
+ const spinner = prompts.spinner(
+ opened ? 'Waiting for you to approve in the browser' : 'Open the link above to approve. Waiting'
+ )
+ return { status: 'approved', value: await withSpinner(spinner, flow.noun, waitFor(runtime, flow, pending)) }
+}
+
+// `<command> --wait`: resumes the command's pending item. It takes no ID, because the item is on disk.
+export async function resumeApproval<Pending extends PendingApproval, Value>(
+ ctx: Context,
+ flow: ApprovalWait<Pending, Value>
+): Promise<Value> {
+ const pending = await readPending<Pending>(ctx.runtime, flow.command)
+ if (!pending) {
+ throw new HogError(
+ `no_pending_${flow.noun}`,
+ `No ${flow.noun} is waiting for approval.`,
+ `Run \`${flow.command}\` to start one.`
+ )
+ }
+ const spinner = ctx.prompts?.spinner(`Waiting for the ${flow.noun} to be approved in the browser`)
+ return withSpinner(spinner, flow.noun, waitFor(ctx.runtime, flow, pending))
+}
+
+// What a person sees when an agent or a script started the request.
+export function printPending(out: Output, result: Extract<ApprovalResult<unknown>, { status: 'pending' }>): void {
+ out.line(
+ result.code
+ ? `Open this link to approve, and check that it shows the code ${out.style(escapeControls(result.code), 'bold')}:`
+ : 'Open this link to approve:'
+ )
+ out.line(` ${escapeControls(result.url)}`)
+ out.line(`Then run ${out.style(result.next, 'bold')}.`)
+}
diff --git a/hog/src/posthog/device-auth.ts b/hog/src/posthog/device-auth.ts
index 69a3f37d1798..155542a447d6 100644
--- a/hog/src/posthog/device-auth.ts
+++ b/hog/src/posthog/device-auth.ts
@@ -1,3 +1,4 @@
+import type { PendingApproval, PollOutcome } from '@/core/approval'
import { HogError } from '@/core/errors'
import type { Runtime } from '@/core/runtime'
@@ -7,24 +8,18 @@ import { sendRequest, type HttpResponse } from './api'
// can run any command without authorizing again.
const USE_CASES = 'agent-cli'
-const MAX_RETRIES = 3
const REQUEST_TIMEOUT_MS = 30_000
-// RFC 8628 asks clients to poll this much slower after each `slow_down`.
-const SLOW_DOWN_SECONDS = 5
// A login the person still has to approve in the browser. `deviceCode` retrieves the key once
// they approve, so it stays in a private file and never reaches the output.
-export interface PendingLogin {
+export interface PendingLogin extends PendingApproval {
host: string
deviceCode: string
userCode: string
- url: string
- // Epoch milliseconds after which PostHog forgets the code.
- expiresAt: number
- intervalSeconds: number
}
export interface Approval {
+ host: string
apiKey: string
projectId: string
scopes: string[]
@@ -71,67 +66,39 @@ export async function startDeviceLogin(runtime: Runtime, host: string): Promise<
}
}
-// A network failure, a 429 or a 5xx can pass, so the poll retries them. When they don't pass,
-// the error is `login_interrupted` and the pending login stays, so `--wait` can resume it.
-export async function waitForApproval(runtime: Runtime, pending: PendingLogin): Promise<Approval> {
- let failures = 0
- let intervalSeconds = pending.intervalSeconds
- while (runtime.now() < pending.expiresAt) {
- await runtime.sleep(intervalSeconds * 1000)
- const remaining = pending.expiresAt - runtime.now()
- if (remaining <= 0) {
- break
- }
- let response: HttpResponse
- try {
- response = await post(
- runtime,
- pending.host,
- 'poll',
- { device_code: pending.deviceCode },
- Math.min(REQUEST_TIMEOUT_MS, remaining)
- )
- } catch (error) {
- if (++failures > MAX_RETRIES) {
- throw interrupted(error instanceof Error ? error.message : String(error))
- }
- continue
- }
- if (response.status === 429 || response.status >= 500) {
- if (++failures > MAX_RETRIES) {
- throw interrupted(`PostHog answered with HTTP ${response.status}.`)
- }
- intervalSeconds += response.status === 429 ? SLOW_DOWN_SECONDS : 0
- continue
- }
- failures = 0
- if (response.status === 202) {
- continue
- }
- const body = (response.json ?? {}) as PollResponse
- if (response.ok && body.status === 'authorized' && body.personal_api_key && body.project_id !== undefined) {
- return { apiKey: body.personal_api_key, projectId: String(body.project_id), scopes: body.scopes ?? [] }
- }
- if (body.status === 'expired') {
- break
+export async function pollDeviceLogin(
+ runtime: Runtime,
+ pending: PendingLogin,
+ timeoutMs: number
+): Promise<PollOutcome<Approval>> {
+ const response = await post(runtime, pending.host, 'poll', { device_code: pending.deviceCode }, timeoutMs)
+ if (response.status === 429) {
+ return { state: 'slow_down' }
+ }
+ if (response.status >= 500) {
+ return { state: 'retry', reason: `PostHog answered with HTTP ${response.status}.` }
+ }
+ if (response.status === 202) {
+ return { state: 'pending' }
+ }
+ const body = (response.json ?? {}) as PollResponse
+ if (response.ok && body.status === 'authorized' && body.personal_api_key && body.project_id !== undefined) {
+ return {
+ state: 'approved',
+ value: {
+ host: pending.host,
+ apiKey: body.personal_api_key,
+ projectId: String(body.project_id),
+ scopes: body.scopes ?? [],
+ },
}
- throw new HogError(
- 'login_failed',
- `PostHog rejected the login with HTTP ${response.status}.`,
- 'Run `hog auth login` to start again.'
- )
+ }
+ if (body.status === 'expired') {
+ return { state: 'expired' }
}
throw new HogError(
- 'login_expired',
- 'The login code expired before it was approved.',
- 'Run `hog auth login` to get a new code.'
- )
-}
-
-function interrupted(reason: string): HogError {
- return new HogError(
- 'login_interrupted',
- `hog lost contact with PostHog while waiting for the login: ${reason}`,
- 'Run `hog auth login --wait` to keep waiting. The link stays the same.'
+ 'login_failed',
+ `PostHog rejected the login with HTTP ${response.status}.`,
+ 'Run `hog auth login` to start again.'
)
}
diff --git a/hog/src/posthog/login/flow.ts b/hog/src/posthog/login/flow.ts
index b434c279eef0..88c618d72d65 100644
--- a/hog/src/posthog/login/flow.ts
+++ b/hog/src/posthog/login/flow.ts
@@ -1,20 +1,17 @@
+import { clearPending, type ApprovalFlow } from '@/core/approval'
import { HogError } from '@/core/errors'
import type { Runtime } from '@/core/runtime'
-import { PersonalAPIKey, type AccessKey } from '@/posthog/access-key'
+import type { AccessKey } from '@/posthog/access-key'
import { FileStore } from '@/posthog/credential-store/file'
import { probeKeychain } from '@/posthog/credential-store/keychain'
import { openStore } from '@/posthog/credential-store/open'
import type { StoreChoice } from '@/posthog/credential-store/types'
-import { posthogFile } from '@/posthog/credentials'
-import { startDeviceLogin, waitForApproval, type PendingLogin } from '@/posthog/device-auth'
+import { pollDeviceLogin, startDeviceLogin, type Approval, type PendingLogin } from '@/posthog/device-auth'
import { loginFor, readSettings } from '@/posthog/settings'
import { writeLogin } from './stored'
-const PENDING_LOGIN_FILE = 'login-pending.json'
-
-// Reusing a code this close to expiry would hand the person a link that dies while they open it.
-const REUSE_MARGIN_MS = 60_000
+export const LOGIN_COMMAND = 'hog auth login'
export interface LoggedIn {
host: string
@@ -27,45 +24,21 @@ export interface LoggedIn {
scopes: string[]
}
-export async function readPendingLogin(runtime: Runtime): Promise<PendingLogin | undefined> {
- try {
- return JSON.parse(await runtime.readFile(posthogFile(runtime, PENDING_LOGIN_FILE))) as PendingLogin
- } catch {
- return undefined
- }
-}
-
-export async function clearPendingLogin(runtime: Runtime): Promise<void> {
- await runtime.removeFile(posthogFile(runtime, PENDING_LOGIN_FILE))
-}
-
-// Retrying agents get the same code back, so the link they already shared keeps working.
-export async function startLogin(runtime: Runtime, host: string): Promise<PendingLogin> {
- const existing = await readPendingLogin(runtime)
- const pending =
- existing?.host === host && existing.expiresAt - runtime.now() > REUSE_MARGIN_MS
- ? existing
- : await startDeviceLogin(runtime, host)
- await runtime.writePrivateFile(posthogFile(runtime, PENDING_LOGIN_FILE), JSON.stringify(pending))
- return pending
-}
-
-// Waits for the person to approve, then saves the key. A login that can't succeed any more is
-// forgotten. One that lost contact with PostHog stays, so `hog auth login --wait` can resume it.
-export async function completeLogin(runtime: Runtime, pending: PendingLogin): Promise<LoggedIn> {
- let approval
- try {
- approval = await waitForApproval(runtime, pending)
- } catch (error) {
- if (error instanceof HogError && error.code !== 'login_interrupted') {
- await clearPendingLogin(runtime)
- }
- throw error
+// An agent that retries `hog auth login` for the same host gets the same code back, so the link it
+// already shared keeps working. `host` is only needed to start a new login.
+export function loginFlow(runtime: Runtime, host?: string): ApprovalFlow<PendingLogin, Approval> {
+ return {
+ command: LOGIN_COMMAND,
+ noun: 'login',
+ start: () => {
+ if (host === undefined) {
+ throw new Error('A new login needs a host')
+ }
+ return startDeviceLogin(runtime, host)
+ },
+ reuse: (existing) => existing.host === host,
+ poll: (pending, timeoutMs) => pollDeviceLogin(runtime, pending, timeoutMs),
}
- const { projectId, apiKey, scopes } = approval
- const key = new PersonalAPIKey({ host: pending.host, projectId, apiKey, scopes })
- const loggedIn = await saveLogin(runtime, key)
- return { ...loggedIn, scopes: approval.scopes }
}
// Each login probes the keychain again, so a login at the desk moves credentials out of the file a
@@ -95,7 +68,7 @@ export async function saveLogin(runtime: Runtime, unverified: AccessKey): Promis
if (loginFor(previous, host)?.store === 'file' && store.kind === 'keychain') {
await new FileStore(runtime).remove(host)
}
- await clearPendingLogin(runtime)
+ await clearPending(runtime, LOGIN_COMMAND)
return {
host,
projectId,