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): add auth login, logout and status with agent-aware login (#124474)

Rafael Audibertbd6f0eef8ebb
diff --git a/hog/AGENTS.md b/hog/AGENTS.md
index 0fcabe4a2f3f..4521349be5b5 100644
--- a/hog/AGENTS.md
+++ b/hog/AGENTS.md
@@ -51,6 +51,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`.
- `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/README.md b/hog/README.md
index 62b839b87b74..1d6424a902e5 100644
--- a/hog/README.md
+++ b/hog/README.md
@@ -11,12 +11,15 @@ It is not published yet.
`hog` has no `exp` namespace.
The commands `posthog-cli` keeps under `exp` (`query`, `endpoints`, `logs`, `tasks`, `schema`) are top-level commands in `hog`.
-| Command | Status |
-| ------------------------- | --------------------------------------------------------------------------------------------------------------- |
-| `hog query run <query>` | Runs a HogQL query. `-` reads the query from stdin. |
-| `hog query check <query>` | Checks a query without running it. Exits with code 1 when the query has errors. |
-| `hog commands` | Lists every command, its arguments, options and scopes. |
-| Everything else | Not ported yet. Exits with code 1 and prints the `posthog-cli` command to run instead, with the same arguments. |
+| Command | Status |
+| ------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
+| `hog auth login` | Logs in through the browser and saves a personal API key. Agents finish with `hog auth login --wait`. |
+| `hog auth status` | Shows whether hog is logged in, whose key it is, and where the key comes from. Exits with code 1 without a working key. |
+| `hog auth logout` | Removes the stored key. The key stays valid in PostHog until you delete it there. |
+| `hog query run <query>` | Runs a HogQL query. `-` reads the query from stdin. |
+| `hog query check <query>` | Checks a query without running it. Exits with code 1 when the query has errors. |
+| `hog commands` | Lists every command, its arguments, options and scopes. |
+| Everything else | Not ported yet. Exits with code 1 and prints the `posthog-cli` command to run instead, with the same arguments. |
## Agents, people and pipes
@@ -38,10 +41,17 @@ Exit codes: 0 on success, 1 when a command fails, 2 for a usage error.
1. `POSTHOG_CLI_API_KEY` and `POSTHOG_CLI_PROJECT_ID` in the environment, plus an optional `POSTHOG_CLI_HOST`
2. The same variables in the file `--dotenv-file` or `POSTHOG_CLI_DOTENV_FILE` names. A missing file prints a warning and hog moves on to the next source.
-3. `~/.posthog/credentials.json`, which `posthog-cli login` writes (`POSTHOG_HOME` moves the folder)
+3. `~/.posthog/credentials.json`, which `hog auth login` and `posthog-cli login` write (`POSTHOG_HOME` moves the folder). `hog auth login` makes it readable only by you.
`--host` overrides the host from any of these.
+### Logging in and out
+
+- At a terminal, `hog auth login` asks where your PostHog account is hosted, opens the browser, and waits for you to approve. The address PostHog opens at, us.posthog.com or eu.posthog.com, tells you which to pick.
+- An agent or a script cannot answer prompts, so `hog auth login --region us` returns at once with a link and a code for a person to approve. `hog auth login --wait` then saves the key. Running `hog auth login` again before the code expires returns the same link.
+- In CI, skip login and set the environment variables above.
+- `hog auth status` checks the key against PostHog. `hog auth logout` warns when an environment variable still holds a key.
+
## Develop
Each command is one file under `src/commands/`, and declares what people and agents see separately.
diff --git a/hog/package.json b/hog/package.json
index 9b72affdfc4b..b1a462d3fc08 100644
--- a/hog/package.json
+++ b/hog/package.json
@@ -14,6 +14,7 @@
"unit": "bun test"
},
"dependencies": {
+ "@clack/prompts": "1.8.1",
"cli-table3": "0.6.5",
"commander": "15.0.0"
},
diff --git a/hog/src/cli.test.ts b/hog/src/cli.test.ts
index 50159c22611c..2820c597acac 100644
--- a/hog/src/cli.test.ts
+++ b/hog/src/cli.test.ts
@@ -65,6 +65,12 @@ describe('hog', () => {
expect(result.error()).toMatchObject({ code })
})
+ test('a command that moved into a group points to its full name', async () => {
+ const result = await runHog(['login'])
+ expect(result.exitCode).toBe(2)
+ expect(result.error().message).toContain('Did you mean `hog auth login`?')
+ })
+
test('a person sees errors as text', async () => {
const result = await runHog(['qury'], { stdoutIsTTY: true, env: { NO_COLOR: '1' } })
expect(result.stderr).toBe(
@@ -78,12 +84,15 @@ describe('hog', () => {
const manifest = result.json()
expect(manifest).toMatchObject({ cli: 'hog', agent: 'claude-code' })
expect(manifest.globalOptions).toContainEqual(expect.objectContaining({ flags: '-o, --output <format>' }))
- expect(manifest.commands[0]).toMatchObject({
+ expect(manifest.commands.find((command: { name: string }) => command.name === 'query run')).toMatchObject({
name: 'query run',
arguments: [{ name: 'query', required: true, stdin: true }],
scopes: ['query:read'],
})
expect(manifest.commands.map((command: { name: string }) => command.name)).toEqual([
+ 'auth login',
+ 'auth logout',
+ 'auth status',
'query run',
'query check',
'query editor',
diff --git a/hog/src/cli.ts b/hog/src/cli.ts
index ea17ad9d1e56..88b677c66377 100644
--- a/hog/src/cli.ts
+++ b/hog/src/cli.ts
@@ -22,7 +22,7 @@ import { VERSION } from '@/version'
const ROOT_HELP = `
hog prints JSON when an agent such as Claude Code or Codex runs it, or when stdout is not a terminal.
-Run \`hog commands -o json\` to list every command, its arguments and its options.`
+Run \`hog auth login\` to log in, and \`hog commands -o json\` to list every command, its arguments and its options.`
const LEGACY_HELP_GROUP = 'Not ported yet (each one prints the posthog-cli command to run):'
@@ -251,6 +251,17 @@ function findLegacy(tokens: Token[]): LegacyRoute | undefined {
return undefined
}
+// Full names of commands in groups whose last word is `name`, so `hog login` can point to `hog auth login`.
+function nestedMatches(tree: CommandTree, name: string, prefix = ''): string[] {
+ return Object.entries(tree).flatMap(([key, node]) => {
+ const path = prefix ? `${prefix} ${key}` : key
+ if (node.kind === 'group') {
+ return nestedMatches(node.commands, name, path)
+ }
+ return prefix && key === name ? [path] : []
+ })
+}
+
function toHogError(caught: unknown): HogError {
if (caught instanceof HogError) {
return caught
@@ -259,9 +270,12 @@ function toHogError(caught: unknown): HogError {
const message = caught.message.replace(/^error: /, '')
const sentence = message.charAt(0).toUpperCase() + message.slice(1)
if (caught.code === 'commander.unknownCommand') {
+ const name = /unknown command '([^']+)'/.exec(caught.message)?.[1] ?? ''
+ const [match] = nestedMatches(COMMANDS, name)
+ const message = match ? `Unknown command '${name}'. Did you mean \`hog ${match}\`?` : sentence
return new HogError(
'unknown_command',
- sentence,
+ message,
'Run `hog --help` to see the available commands.',
EXIT_USAGE
)
diff --git a/hog/src/commands/auth/auth.test.ts b/hog/src/commands/auth/auth.test.ts
new file mode 100644
index 000000000000..3ec2121ecffa
--- /dev/null
+++ b/hog/src/commands/auth/auth.test.ts
@@ -0,0 +1,237 @@
+import { describe, expect, test } from 'bun:test'
+
+import { runHog } from '@/testing'
+
+const CREDENTIALS_FILE = '/home/test/.posthog/credentials.json'
+const PENDING_FILE = '/home/test/.posthog/login-pending.json'
+const DEVICE_CODE = 'device-secret-123'
+
+const DEVICE = {
+ device_code: DEVICE_CODE,
+ user_code: 'ABCD-1234',
+ verification_uri_complete: 'https://eu.posthog.com/cli/authorize?code=ABCD-1234',
+ expires_in: 600,
+ interval: 5,
+}
+const APPROVED = {
+ status: 'authorized',
+ personal_api_key: 'phx_secret',
+ project_id: '42',
+ scopes: ['query:read'],
+}
+const PENDING = JSON.stringify({
+ host: 'https://eu.posthog.com',
+ deviceCode: DEVICE_CODE,
+ userCode: 'ABCD-1234',
+ url: 'https://eu.posthog.com/cli/authorize?code=ABCD-1234&use_cases=agent-cli',
+ expiresAt: Date.UTC(2026, 0, 1) + 600_000,
+ intervalSeconds: 5,
+})
+
+// The device flow: a device code, then `pendingPolls` answers of "keep waiting", then `final`.
+function deviceFlow(pendingPolls: number, final = { status: 200, body: APPROVED as unknown }) {
+ let polls = 0
+ return (url: string) => {
+ if (url.endsWith('/api/cli-auth/device-code/')) {
+ return { status: 200, body: DEVICE }
+ }
+ return polls++ < pendingPolls ? { status: 202, body: { status: 'pending' } } : final
+ }
+}
+
+describe('hog auth login', () => {
+ test('an agent gets a link to hand over, without blocking or seeing the device code', async () => {
+ const result = await runHog(['auth', 'login', '--region', 'eu'], {
+ env: { CLAUDECODE: '1' },
+ respond: deviceFlow(0),
+ })
+
+ expect(result.exitCode).toBe(0)
+ expect(result.json()).toMatchObject({
+ status: 'pending',
+ code: 'ABCD-1234',
+ url: 'https://eu.posthog.com/cli/authorize?code=ABCD-1234&use_cases=agent-cli',
+ next: 'hog auth login --wait',
+ })
+ expect(result.stdout).not.toContain(DEVICE_CODE)
+ expect(JSON.parse(result.files[PENDING_FILE] ?? '{}')).toMatchObject({ deviceCode: DEVICE_CODE })
+ expect(result.opened).toEqual([])
+ expect(result.requests.map((request) => request.url)).toEqual([
+ 'https://eu.posthog.com/api/cli-auth/device-code/',
+ ])
+ })
+
+ test('an agent that retries gets the same code, so the link it shared keeps working', async () => {
+ const result = await runHog(['auth', 'login', '--region', 'eu'], {
+ env: { CLAUDECODE: '1' },
+ files: { [PENDING_FILE]: PENDING },
+ respond: deviceFlow(0),
+ })
+ expect(result.json()).toMatchObject({ status: 'pending', code: 'ABCD-1234' })
+ expect(result.requests).toEqual([])
+ })
+
+ test.each([
+ ['an agent without a region', ['auth', 'login'], { CLAUDECODE: '1' }, {}, 2, 'region_required'],
+ ['a CI job', ['auth', 'login', '--region', 'us'], { CI: 'true' }, {}, 1, 'login_needs_a_person'],
+ ['--wait with no login started', ['auth', 'login', '--wait'], { CLAUDECODE: '1' }, {}, 1, 'no_pending_login'],
+ ])('%s fails with a hint', async (_name, argv, env, files, exitCode, code) => {
+ const result = await runHog(argv, { env, files, respond: deviceFlow(0) })
+ expect(result.exitCode).toBe(exitCode)
+ expect(result.error()).toMatchObject({ code, hint: expect.any(String) })
+ })
+
+ test('--wait saves the key in the file posthog-cli reads once the person approves', async () => {
+ const result = await runHog(['auth', 'login', '--wait'], {
+ env: { CLAUDECODE: '1' },
+ files: { [PENDING_FILE]: PENDING },
+ respond: deviceFlow(2),
+ })
+
+ expect(result.exitCode).toBe(0)
+ expect(result.json()).toMatchObject({ status: 'logged_in', host: 'https://eu.posthog.com', projectId: '42' })
+ expect(result.stdout).not.toContain('phx_secret')
+ expect(JSON.parse(result.files[CREDENTIALS_FILE] ?? '{}')).toEqual({
+ host: 'https://eu.posthog.com',
+ token: 'phx_secret',
+ env_id: '42',
+ })
+ expect(result.files[PENDING_FILE]).toBeUndefined()
+ expect(result.requests.filter((request) => request.url.endsWith('/poll/'))).toHaveLength(3)
+ })
+
+ test.each([
+ [
+ 'stops when the code expires and forgets it',
+ { status: 400, body: { status: 'expired' } },
+ 'login_expired',
+ false,
+ ],
+ [
+ 'retries a server that keeps failing, then keeps the login to resume',
+ { status: 503, body: 'Service Unavailable' },
+ 'login_interrupted',
+ true,
+ ],
+ ])('--wait %s', async (_name, final, code, keepsPending) => {
+ const result = await runHog(['auth', 'login', '--wait'], {
+ env: { CLAUDECODE: '1' },
+ files: { [PENDING_FILE]: PENDING },
+ respond: deviceFlow(1, final),
+ })
+ expect(result.exitCode).toBe(1)
+ expect(result.error()).toMatchObject({ code })
+ expect(result.files[PENDING_FILE] !== undefined).toBe(keepsPending)
+ expect(result.files[CREDENTIALS_FILE]).toBeUndefined()
+ })
+
+ test.each([
+ ['approving in the browser', ['eu'], true, 'https://eu.posthog.com'],
+ [
+ 'pasting a personal API key',
+ ['key', 'https://ph.example.com/', '42', 'phx_secret'],
+ false,
+ 'https://ph.example.com',
+ ],
+ ])('a person at a terminal logs in by %s', async (_name, answers, opensBrowser, host) => {
+ const result = await runHog(['auth', 'login'], {
+ stdoutIsTTY: true,
+ env: { NO_COLOR: '1' },
+ files: { [PENDING_FILE]: PENDING },
+ answers,
+ respond: deviceFlow(1),
+ })
+
+ expect(result.exitCode).toBe(0)
+ expect(result.stdout).toContain(`Logged in to ${host}, project 42.`)
+ expect(result.opened).toHaveLength(opensBrowser ? 1 : 0)
+ expect(result.files[PENDING_FILE]).toBeUndefined()
+ expect(JSON.parse(result.files[CREDENTIALS_FILE] ?? '{}')).toMatchObject({
+ host,
+ token: 'phx_secret',
+ env_id: '42',
+ })
+ })
+
+ const STORED = JSON.stringify({ host: 'https://eu.posthog.com', token: 'phx_secret', env_id: '42' })
+
+ test.each([
+ [
+ 'a working key',
+ 200,
+ 200,
+ 0,
+ { authenticated: true, user: { email: '[email protected]' }, projectName: 'Shop' },
+ ],
+ ['a key without user:read', 403, 200, 0, { authenticated: true, user: null, projectName: 'Shop' }],
+ ['a deleted key', 401, 401, 1, { authenticated: false, error: expect.any(String), next: 'hog auth login' }],
+ ])('status reports %s', async (_name, userStatus, projectStatus, exitCode, expected) => {
+ const result = await runHog(['auth', 'status'], {
+ env: { CLAUDECODE: '1' },
+ files: { [CREDENTIALS_FILE]: STORED },
+ respond: (url) =>
+ url.endsWith('/api/users/@me/')
+ ? { status: userStatus, body: { email: '[email protected]' } }
+ : { status: projectStatus, body: { name: 'Shop' } },
+ })
+ expect(result.exitCode).toBe(exitCode)
+ expect(result.json()).toMatchObject({ host: 'https://eu.posthog.com', projectId: '42', ...expected })
+ expect(result.stdout).not.toContain('phx_secret')
+ })
+
+ test('status escapes terminal control characters in the project name', async () => {
+ const result = await runHog(['auth', 'status'], {
+ stdoutIsTTY: true,
+ env: { NO_COLOR: '1' },
+ files: { [CREDENTIALS_FILE]: STORED },
+ respond: (url) =>
+ url.endsWith('/api/users/@me/')
+ ? { status: 200, body: { email: '[email protected]' } }
+ : { status: 200, body: { name: '\u001b]52;c;eA==\u0007Shop' } },
+ })
+ expect(result.stdout).toContain('Project: \\x1b]52;c;eA==\\x07Shop (42)')
+ expect(result.stdout).not.toContain('\u001b')
+ })
+
+ test('status fails when one request lacks a scope and the other fails', async () => {
+ const result = await runHog(['auth', 'status'], {
+ env: { CLAUDECODE: '1' },
+ files: { [CREDENTIALS_FILE]: STORED },
+ respond: (url) => (url.endsWith('/api/users/@me/') ? { status: 403, body: {} } : { status: 500, body: {} }),
+ })
+ expect(result.exitCode).toBe(1)
+ expect(result.error()).toMatchObject({ code: 'http_500' })
+ })
+
+ test('status without a key exits 1 and points to login', async () => {
+ const result = await runHog(['auth', 'status'], { env: { CLAUDECODE: '1' } })
+ expect(result.exitCode).toBe(1)
+ expect(result.json()).toEqual({ authenticated: false, next: 'hog auth login' })
+ })
+
+ test.each([
+ [
+ 'a stored key',
+ { [CREDENTIALS_FILE]: STORED, [PENDING_FILE]: PENDING },
+ {},
+ 'logged_out',
+ 'https://eu.posthog.com/settings/user-api-keys',
+ [],
+ ],
+ ['no stored key', {}, {}, 'not_logged_in', null, []],
+ [
+ 'a key in the environment',
+ { [CREDENTIALS_FILE]: STORED },
+ { POSTHOG_CLI_API_KEY: 'phx_env' },
+ 'logged_out',
+ 'https://eu.posthog.com/settings/user-api-keys',
+ ['POSTHOG_CLI_API_KEY'],
+ ],
+ ])('logout with %s removes what hog stored', async (_name, files, env, status, revokeUrl, stillSet) => {
+ const result = await runHog(['auth', 'logout'], { env: { CLAUDECODE: '1', ...env }, files })
+ expect(result.exitCode).toBe(0)
+ expect(result.json()).toMatchObject({ status, revokeUrl, stillSet })
+ expect(result.files[CREDENTIALS_FILE]).toBeUndefined()
+ expect(result.files[PENDING_FILE]).toBeUndefined()
+ })
+})
diff --git a/hog/src/commands/auth/index.ts b/hog/src/commands/auth/index.ts
new file mode 100644
index 000000000000..b46670be86ea
--- /dev/null
+++ b/hog/src/commands/auth/index.ts
@@ -0,0 +1,10 @@
+import { defineGroup } from '@/core/command'
+
+import login from './login'
+import logout from './logout'
+import status from './status'
+
+export default defineGroup({
+ description: 'Log in to PostHog, log out, and check who hog is logged in as',
+ commands: { login, logout, status },
+})
diff --git a/hog/src/commands/auth/login.ts b/hog/src/commands/auth/login.ts
new file mode 100644
index 000000000000..c9a16533e547
--- /dev/null
+++ b/hog/src/commands/auth/login.ts
@@ -0,0 +1,177 @@
+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 { checkApiKey, checkHost, checkProjectId } from '@/posthog/credentials'
+import type { PendingLogin } from '@/posthog/device-auth'
+import { completeLogin, readPendingLogin, saveLogin, startLogin, type LoggedIn } from '@/posthog/login'
+
+const REGIONS = { us: 'https://us.posthog.com', eu: 'https://eu.posthog.com' } as const
+
+type LoginResult =
+ | {
+ status: 'pending'
+ host: string
+ url: string
+ code: string
+ expiresAt: string
+ instructions: string
+ next: string
+ }
+ | { status: 'logged_in'; host: string; projectId: string; credentialsPath: string; next: string }
+
+function isTruthy(value: string | undefined): boolean {
+ return value !== undefined && value !== '' && value !== '0' && value.toLowerCase() !== 'false'
+}
+
+function nextCommand(scopes: readonly string[]): string {
+ const canQuery = scopes.some((scope) => scope === '*' || scope.startsWith('query:'))
+ 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, credentialsPath, scopes } = loggedIn
+ return { status: 'logged_in', host, projectId, credentialsPath, 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 keyLogin(ctx: Context, prompts: Prompts): Promise<LoginResult> {
+ const host = await prompts.text('PostHog host', { initialValue: REGIONS.us, validate: checkHost })
+ const projectId = await prompts.text('Project ID, the number in your project URL', { validate: checkProjectId })
+ const apiKey = await prompts.password('Personal API key', { validate: checkApiKey })
+ return loggedInResult(await saveLogin(ctx.runtime, { apiKey, projectId, host: host.replace(/\/+$/, '') }))
+}
+
+export default defineCommand({
+ description: 'Log in to PostHog and store a personal API key on this machine',
+ options: {
+ region: {
+ type: 'string',
+ choices: ['us', 'eu'],
+ placeholder: 'region',
+ description:
+ 'Where your PostHog account is hosted, as in the us.posthog.com or eu.posthog.com address. Use --host for self-hosted PostHog',
+ },
+ wait: {
+ type: 'boolean',
+ description: 'Wait for the login an agent or script started, and save the key once a person approves it',
+ },
+ },
+ notes: [
+ 'At a terminal, hog asks where your PostHog account is hosted and opens the browser to approve the login.',
+ 'Agents and scripts get a link and a code to hand to a person, then finish with `hog auth login --wait`.',
+ 'In CI, skip login and set POSTHOG_CLI_API_KEY, POSTHOG_CLI_PROJECT_ID and POSTHOG_CLI_HOST.',
+ ].join('\n'),
+ 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'))
+ }
+
+ if (!prompts && ctx.mode.agent === undefined && isTruthy(env.CI)) {
+ throw new HogError(
+ 'login_needs_a_person',
+ 'hog auth login needs a person to approve it in a browser, so it does not run in CI.',
+ 'Set POSTHOG_CLI_API_KEY, POSTHOG_CLI_PROJECT_ID and POSTHOG_CLI_HOST instead.'
+ )
+ }
+
+ let host = ctx.globals.host?.replace(/\/+$/, '') ?? (options.region ? REGIONS[options.region] : undefined)
+ if (!host) {
+ if (!prompts) {
+ throw new HogError(
+ 'region_required',
+ 'hog auth login needs to know where your PostHog account is hosted.',
+ 'Ask the user where their PostHog account is hosted. When they open PostHog in a browser, the address starts with us.posthog.com or eu.posthog.com. Then run `hog auth login --region us` or `hog auth login --region eu`. For self-hosted PostHog, pass --host.',
+ EXIT_USAGE
+ )
+ }
+ const choice = await prompts.select(
+ 'Where is your PostHog account hosted?',
+ [
+ { value: 'us', label: 'US Cloud', hint: 'us.posthog.com' },
+ { value: 'eu', label: 'EU Cloud', hint: 'eu.posthog.com' },
+ {
+ value: 'key',
+ label: 'Paste a personal API key',
+ hint: 'for self-hosted PostHog, or without a browser',
+ },
+ ],
+ {
+ help: 'Open PostHog in your browser and check the address: it starts with us.posthog.com or eu.posthog.com.',
+ }
+ )
+ if (choice === 'key') {
+ return keyLogin(ctx, prompts)
+ }
+ 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'
+ )
+ )
+ },
+
+ 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')}.`)
+ return
+ }
+ out.line(`${out.style('Logged in', 'green', 'bold')} to ${result.host}, project ${result.projectId}.`)
+ out.line(out.style(`Credentials saved to ${result.credentialsPath}`, 'dim'))
+ out.line(`Try it: ${result.next}`)
+ },
+})
diff --git a/hog/src/commands/auth/logout.ts b/hog/src/commands/auth/logout.ts
new file mode 100644
index 000000000000..5a0e7dad3947
--- /dev/null
+++ b/hog/src/commands/auth/logout.ts
@@ -0,0 +1,54 @@
+import { defineCommand } from '@/core/command'
+import { API_KEY_ENV_VARS, posthogFile } from '@/posthog/credentials'
+import { clearPendingLogin } from '@/posthog/login'
+
+interface LogoutResult {
+ status: 'logged_out' | 'not_logged_in'
+ credentialsPath: string
+ revokeUrl: string | null
+ // Variables that still give hog a key after logout.
+ stillSet: string[]
+}
+
+export default defineCommand({
+ description: 'Remove the personal API key hog stored on this machine',
+ notes: 'The key itself stays valid until you delete it in PostHog under Settings > Personal API keys.',
+ examples: ['hog auth logout'],
+
+ async run({ ctx }): Promise<LogoutResult> {
+ const { runtime } = ctx
+ const credentialsPath = posthogFile(runtime, 'credentials.json')
+ let host: string | undefined
+ let stored = false
+ try {
+ host = (JSON.parse(await runtime.readFile(credentialsPath)) as { host?: string }).host
+ stored = true
+ } catch {
+ stored = false
+ }
+ await runtime.removeFile(credentialsPath)
+ await clearPendingLogin(runtime)
+ return {
+ status: stored ? 'logged_out' : 'not_logged_in',
+ credentialsPath,
+ revokeUrl: host ? new URL('settings/user-api-keys', `${host.replace(/\/+$/, '')}/`).toString() : null,
+ stillSet: API_KEY_ENV_VARS.filter((name) => runtime.env[name]),
+ }
+ },
+
+ human({ result, out }) {
+ out.line(
+ result.status === 'logged_out'
+ ? `${out.style('Logged out', 'green', 'bold')}. Removed ${result.credentialsPath}.`
+ : 'hog had no stored key to remove.'
+ )
+ if (result.revokeUrl) {
+ out.line(out.style(`The key still works until you delete it at ${result.revokeUrl}`, 'dim'))
+ }
+ if (result.stillSet.length > 0) {
+ out.line(
+ `${out.style('Still logged in', 'yellow', 'bold')} through ${result.stillSet.join(' and ')}. Unset it to log out fully.`
+ )
+ }
+ },
+})
diff --git a/hog/src/commands/auth/status.ts b/hog/src/commands/auth/status.ts
new file mode 100644
index 000000000000..22fdeb1793fa
--- /dev/null
+++ b/hog/src/commands/auth/status.ts
@@ -0,0 +1,34 @@
+import { defineCommand } from '@/core/command'
+import { escapeControls } from '@/core/output'
+import { checkAuthStatus } from '@/posthog/auth-status'
+import type { CredentialSource } from '@/posthog/credentials'
+
+const SOURCE_LABELS: Record<CredentialSource, string> = {
+ env: 'the POSTHOG_CLI_API_KEY environment variable',
+ 'dotenv-file': 'the --dotenv-file file',
+ 'credentials-file': 'the credentials file',
+}
+
+export default defineCommand({
+ description: 'Show whether hog is logged in, where its key comes from, and whose key it is',
+ notes: 'Exits with code 1 when hog has no working key, so scripts and agents can branch on it.',
+ examples: ['hog auth status', 'hog auth status -o json'],
+
+ run: ({ ctx }) => checkAuthStatus(ctx),
+
+ human({ result, out }) {
+ if (!result.authenticated) {
+ out.line(out.style(result.error ? `Not logged in: ${result.error}` : 'Not logged in.', 'yellow', 'bold'))
+ out.line(`Run ${out.style(result.next, 'bold')} to log in.`)
+ return
+ }
+ // The email and project name come from PostHog, and anyone who can rename the project sets the name.
+ const who = result.user ? ` as ${out.style(escapeControls(result.user.email), 'bold')}` : ''
+ out.line(`${out.style('Logged in', 'green', 'bold')} to ${escapeControls(result.host)}${who}.`)
+ const name = result.projectName ? escapeControls(result.projectName) : null
+ out.line(`Project: ${name ? `${name} (${result.projectId})` : result.projectId}`)
+ out.line(out.style(`Key from ${result.credentialsPath ?? SOURCE_LABELS[result.source]}`, 'dim'))
+ },
+
+ exitCode: (result) => (result.authenticated ? 0 : 1),
+})
diff --git a/hog/src/commands/index.ts b/hog/src/commands/index.ts
index c6e0ec3a19ec..c064f9843232 100644
--- a/hog/src/commands/index.ts
+++ b/hog/src/commands/index.ts
@@ -1,10 +1,12 @@
-import query from '@/commands/query'
import type { CommandTree } from '@/core/command'
+import auth from './auth'
import commands from './commands'
import { LEGACY_COMMANDS } from './legacy'
+import query from './query'
export const COMMANDS: CommandTree = {
+ auth,
query,
commands,
...LEGACY_COMMANDS,
diff --git a/hog/src/commands/legacy.ts b/hog/src/commands/legacy.ts
index 61bae4ed288c..2281a24ff8ce 100644
--- a/hog/src/commands/legacy.ts
+++ b/hog/src/commands/legacy.ts
@@ -1,10 +1,6 @@
import { defineLegacy, type CommandTree } from '@/core/command'
export const LEGACY_COMMANDS: CommandTree = {
- login: defineLegacy({
- description: 'Log in to PostHog and store a personal API key on this machine',
- use: 'posthog-cli login',
- }),
api: defineLegacy({ description: 'Agent-first PostHog API tools', use: 'posthog-cli api' }),
endpoints: defineLegacy({ description: 'Manage PostHog endpoints', use: 'posthog-cli exp endpoints' }),
logs: defineLegacy({
diff --git a/hog/src/core/context.ts b/hog/src/core/context.ts
index ab1f52953af1..ba642ccb30d3 100644
--- a/hog/src/core/context.ts
+++ b/hog/src/core/context.ts
@@ -1,8 +1,9 @@
import { PostHogApi } from '@/posthog/api'
-import { resolveCredentials } from '@/posthog/credentials'
+import { resolveCredentials, type ResolvedCredentials } from '@/posthog/credentials'
import type { Mode } from './agent'
import type { CommandTree, OptionSpec, OptionValues } from './command'
+import type { Prompts } from './prompts'
import type { Runtime } from './runtime'
export const GLOBAL_OPTIONS = {
@@ -35,6 +36,7 @@ export type GlobalOptions = OptionValues<typeof GLOBAL_OPTIONS>
// purpose: `run` returns data, and the command's `human` and `agent` views print it.
export class Context {
private api?: PostHogApi
+ private resolved?: ResolvedCredentials
constructor(
readonly runtime: Runtime,
@@ -43,13 +45,23 @@ export class Context {
readonly tree: CommandTree
) {}
+ // Undefined unless a person is at the terminal, so a command can ask questions only when
+ // someone can answer them. Agents, pipes and `-o json` never get prompts.
+ get prompts(): Prompts | undefined {
+ const person = this.mode.format === 'text' && this.mode.agent === undefined
+ return person && this.runtime.stdinIsTTY && this.runtime.stdoutIsTTY ? this.runtime.prompts : undefined
+ }
+
// The PostHog API client. Credentials resolve on first use, so commands that never call
// the API work without them.
async posthog(): Promise<PostHogApi> {
- if (!this.api) {
- const credentials = await resolveCredentials(this.runtime, this.globals)
- this.api = new PostHogApi(credentials, this.runtime.fetch)
- }
+ this.api ??= new PostHogApi(await this.credentials(), this.runtime.fetch)
return this.api
}
+
+ // Throws `not_authenticated` when there are none.
+ async credentials(): Promise<ResolvedCredentials> {
+ this.resolved ??= await resolveCredentials(this.runtime, this.globals)
+ return this.resolved
+ }
}
diff --git a/hog/src/core/prompts.ts b/hog/src/core/prompts.ts
new file mode 100644
index 000000000000..75e72d589b9f
--- /dev/null
+++ b/hog/src/core/prompts.ts
@@ -0,0 +1,80 @@
+import * as clack from '@clack/prompts'
+import { styleText } from 'node:util'
+
+import { HogError } from './errors'
+
+export interface Choice<Value extends string> {
+ value: Value
+ label: string
+ hint?: string
+}
+
+export type Validate = (value: string) => string | undefined
+
+export interface Spinner {
+ stop(message: string): void
+ error(message: string): void
+}
+
+export interface Prompts {
+ // `help` is a dimmed line under the question that tells the person how to find the answer.
+ select<Value extends string>(
+ message: string,
+ choices: readonly Choice<Value>[],
+ options?: { help?: string }
+ ): Promise<Value>
+ text(message: string, options?: { initialValue?: string; validate?: Validate }): Promise<string>
+ password(message: string, options?: { validate?: Validate }): Promise<string>
+ note(message: string, title: string): void
+ spinner(message: string): Spinner
+}
+
+// Ctrl-C at a prompt. 130 is the exit code shells report for SIGINT.
+const cancelled = (): HogError => new HogError('cancelled', 'Cancelled.', undefined, 130)
+
+function answer<Value>(value: Value): Exclude<Value, symbol> {
+ if (clack.isCancel(value)) {
+ throw cancelled()
+ }
+ return value as Exclude<Value, symbol>
+}
+
+export function clackPrompts(): Prompts {
+ return {
+ async select<Value extends string>(
+ message: string,
+ choices: readonly Choice<Value>[],
+ { help }: { help?: string } = {}
+ ): Promise<Value> {
+ const options = choices.map((choice) => ({ ...choice })) as Parameters<
+ typeof clack.select<Value>
+ >[0]['options']
+ const question = help ? `${message}\n${styleText('dim', help)}` : message
+ return answer(await clack.select<Value>({ message: question, options }))
+ },
+ async text(message, options = {}) {
+ const validate = options.validate
+ return answer(
+ await clack.text({
+ message,
+ initialValue: options.initialValue,
+ validate: validate ? (value) => validate(value ?? '') : undefined,
+ })
+ )
+ },
+ async password(message, options = {}) {
+ const validate = options.validate
+ return answer(
+ await clack.password({ message, validate: validate ? (value) => validate(value ?? '') : undefined })
+ )
+ },
+ note(message, title) {
+ clack.note(message, title)
+ },
+ spinner(message) {
+ const spin = clack.spinner()
+ spin.start(message)
+ return { stop: (text) => spin.stop(text), error: (text) => spin.error(text) }
+ },
+ }
+}
diff --git a/hog/src/core/runtime.ts b/hog/src/core/runtime.ts
index 7bfd8f07239f..526850841a97 100644
--- a/hog/src/core/runtime.ts
+++ b/hog/src/core/runtime.ts
@@ -1,5 +1,9 @@
-import { readFile } from 'node:fs/promises'
+import { randomUUID } from 'node:crypto'
+import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
import { homedir } from 'node:os'
+import { dirname } from 'node:path'
+
+import { clackPrompts, type Prompts } from './prompts'
export type Env = Readonly<Record<string, string | undefined>>
@@ -7,20 +11,43 @@ export type Env = Readonly<Record<string, string | undefined>>
// so no command reads `process` or the network directly.
export interface Runtime {
env: Env
+ stdinIsTTY: boolean
stdoutIsTTY: boolean
stdoutHasColors: boolean
stdoutColumns: number | undefined
writeStdout: (text: string) => void
writeStderr: (text: string) => void
fetch: typeof fetch
+ now: () => number
+ sleep: (ms: number) => Promise<void>
homeDir: () => string | undefined
readFile: (path: string) => Promise<string>
+ writePrivateFile: (path: string, contents: string) => Promise<void>
+ removeFile: (path: string) => Promise<void>
readStdin: () => Promise<string>
+ // Resolves to false when no browser could be started, for example on a server without one.
+ openUrl: (url: string) => Promise<boolean>
+ prompts: Prompts
+}
+
+const BROWSER_LAUNCH_MS = 1000
+
+function browserCommand(url: string): string[] {
+ switch (process.platform) {
+ case 'darwin':
+ return ['open', url]
+ case 'win32':
+ // Not `cmd /c start`: cmd treats the `&` in a URL's query string as a command separator.
+ return ['rundll32', 'url.dll,FileProtocolHandler', url]
+ default:
+ return ['xdg-open', url]
+ }
}
export function processRuntime(): Runtime {
return {
env: process.env,
+ stdinIsTTY: process.stdin.isTTY === true,
stdoutIsTTY: process.stdout.isTTY === true,
stdoutHasColors: process.stdout.isTTY === true && process.stdout.hasColors(),
stdoutColumns: process.stdout.columns || undefined,
@@ -31,6 +58,8 @@ export function processRuntime(): Runtime {
process.stderr.write(text)
},
fetch: globalThis.fetch,
+ now: () => Date.now(),
+ sleep: (ms) => Bun.sleep(ms),
homeDir: () => {
try {
return homedir()
@@ -39,6 +68,36 @@ export function processRuntime(): Runtime {
}
},
readFile: (path) => readFile(path, 'utf8'),
+ // A rename is atomic, so a crash never leaves a half-written file. The temporary name is
+ // random and `wx` refuses an existing path, so nobody can plant a symlink there first.
+ writePrivateFile: async (path, contents) => {
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 })
+ const temporary = `${path}.${randomUUID()}.tmp`
+ try {
+ await writeFile(temporary, contents, { mode: 0o600, flag: 'wx' })
+ await rename(temporary, path)
+ } catch (error) {
+ await rm(temporary, { force: true })
+ throw error
+ }
+ },
+ removeFile: (path) => rm(path, { force: true }),
readStdin: () => new Response(Bun.stdin.stream()).text(),
+ openUrl: async (url) => {
+ if (!URL.canParse(url) || !['http:', 'https:'].includes(new URL(url).protocol)) {
+ return false
+ }
+ try {
+ const child = Bun.spawn(browserCommand(url), { stdin: 'ignore', stdout: 'ignore', stderr: 'ignore' })
+ child.unref()
+ // Some openers, like xdg-open, stay attached to the browser they start. Waiting for
+ // them to exit would hold up polling, so hog only waits long enough to see a failed launch.
+ const code = await Promise.race([child.exited, Bun.sleep(BROWSER_LAUNCH_MS).then(() => undefined)])
+ return code === undefined || code === 0
+ } catch {
+ return false
+ }
+ },
+ prompts: clackPrompts(),
}
}
diff --git a/hog/src/posthog/api.ts b/hog/src/posthog/api.ts
index c237bb04f966..e30b7676bb7f 100644
--- a/hog/src/posthog/api.ts
+++ b/hog/src/posthog/api.ts
@@ -4,12 +4,59 @@ import { VERSION } from '@/version'
import type { Credentials } from './credentials'
-const USER_AGENT = `hog/${VERSION}`
+export const USER_AGENT = `hog/${VERSION}`
// Generous, because a HogQL query can run for minutes. It only stops a connection that hangs.
const REQUEST_TIMEOUT_MS = 10 * 60 * 1000
type Method = 'GET' | 'POST' | 'PATCH' | 'DELETE'
+export interface HttpRequest {
+ method: Method
+ body?: unknown
+ apiKey?: string
+ timeoutMs?: number
+}
+
+export interface HttpResponse {
+ status: number
+ ok: boolean
+ json: unknown
+ text: string
+}
+
+// Sends one JSON request to PostHog. Any failure before the whole body arrives, including the
+// deadline, is a `network_error`, so callers handle a dropped connection in one place.
+export async function sendRequest(fetchFn: typeof fetch, url: URL, request: HttpRequest): Promise<HttpResponse> {
+ const headers: Record<string, string> = { 'Content-Type': 'application/json', 'User-Agent': USER_AGENT }
+ if (request.apiKey) {
+ headers.Authorization = `Bearer ${request.apiKey}`
+ }
+ let response: Response
+ let text: string
+ try {
+ response = await fetchFn(url, {
+ method: request.method,
+ headers,
+ body: request.body === undefined ? undefined : JSON.stringify(request.body),
+ signal: AbortSignal.timeout(request.timeoutMs ?? REQUEST_TIMEOUT_MS),
+ })
+ text = await response.text()
+ } catch (error) {
+ throw new HogError(
+ 'network_error',
+ `hog couldn't reach ${url.origin}: ${error instanceof Error ? error.message : String(error)}`,
+ 'Check the host and your network connection.'
+ )
+ }
+ let json: unknown
+ try {
+ json = text ? parseLossless(text) : undefined
+ } catch {
+ json = undefined
+ }
+ return { status: response.status, ok: response.ok, json, text }
+}
+
// A non-2xx answer from PostHog. `type` is the DRF error type, such as `validation_error`.
export class ApiError extends HogError {
constructor(
@@ -29,9 +76,13 @@ export class PostHogApi {
private readonly fetchFn: typeof fetch
) {}
- // Paths are relative to the project, so `query` is /api/environments/<project id>/query.
- private environmentUrl(path: string): URL {
- return new URL(path, new URL(`api/environments/${this.credentials.projectId}/`, this.credentials.host))
+ // Paths are relative to the project, so `query` is /api/environments/<project id>/query. A path
+ // that starts with `/`, like `/api/users/@me/`, is relative to the host instead.
+ private url(path: string): URL {
+ const base = path.startsWith('/')
+ ? this.credentials.host
+ : new URL(`api/environments/${this.credentials.projectId}/`, this.credentials.host)
+ return new URL(path, base)
}
get<T>(path: string): Promise<T> {
@@ -51,32 +102,12 @@ export class PostHogApi {
}
private async request<T>(method: Method, path: string, body?: unknown): Promise<T> {
- let response: Response
- let text: string
- try {
- response = await this.fetchFn(this.environmentUrl(path), {
- method,
- headers: {
- Authorization: `Bearer ${this.credentials.apiKey}`,
- 'Content-Type': 'application/json',
- 'User-Agent': USER_AGENT,
- },
- body: body === undefined ? undefined : JSON.stringify(body),
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
- })
- text = await response.text()
- } catch (error) {
- throw new HogError(
- 'network_error',
- `hog couldn't reach ${this.credentials.host}: ${error instanceof Error ? error.message : String(error)}`,
- 'Check the host and your network connection.'
- )
- }
-
- let parsed: unknown
- try {
- parsed = text ? parseLossless(text) : undefined
- } catch {
+ const response = await sendRequest(this.fetchFn, this.url(path), {
+ method,
+ body,
+ apiKey: this.credentials.apiKey,
+ })
+ if (response.text && response.json === undefined) {
throw new HogError(
'unexpected_response',
`PostHog answered with HTTP ${response.status} and a body that isn't JSON.`,
@@ -84,9 +115,9 @@ export class PostHogApi {
)
}
if (!response.ok) {
- throw this.failure(response.status, parsed)
+ throw this.failure(response.status, response.json)
}
- return parsed as T
+ return response.json as T
}
private failure(status: number, body: unknown): ApiError {
diff --git a/hog/src/posthog/auth-status.ts b/hog/src/posthog/auth-status.ts
new file mode 100644
index 000000000000..e0fde90a5f56
--- /dev/null
+++ b/hog/src/posthog/auth-status.ts
@@ -0,0 +1,68 @@
+import type { Context } from '@/core/context'
+import { HogError } from '@/core/errors'
+
+import { ApiError } from './api'
+import { posthogFile, type CredentialSource } from './credentials'
+
+export type AuthStatus =
+ | {
+ authenticated: false
+ next: string
+ error?: string
+ host?: string
+ projectId?: string
+ source?: CredentialSource
+ }
+ | {
+ authenticated: true
+ host: string
+ projectId: string
+ projectName: string | null
+ source: CredentialSource
+ credentialsPath: string | null
+ // Null when the key lacks the user:read scope, so hog can't tell whose key it is.
+ user: { email: string; name: string | null } | null
+ }
+
+export async function checkAuthStatus(ctx: Context): Promise<AuthStatus> {
+ let credentials
+ try {
+ credentials = await ctx.credentials()
+ } catch (error) {
+ if (error instanceof HogError && error.code === 'not_authenticated') {
+ return { authenticated: false, next: 'hog auth login' }
+ }
+ throw error
+ }
+ const { host, projectId, source } = credentials
+ const api = await ctx.posthog()
+ const [user, project] = await Promise.allSettled([
+ api.get<{ email: string; first_name?: string }>('/api/users/@me/'),
+ api.get<{ name: string }>(''),
+ ])
+ const failures = [user, project].flatMap((outcome) => (outcome.status === 'rejected' ? [outcome.reason] : []))
+ if (failures.some((failure) => failure instanceof ApiError && failure.status === 401)) {
+ return {
+ authenticated: false,
+ host,
+ projectId,
+ source,
+ error: 'PostHog rejected the key. Someone may have deleted it.',
+ next: 'hog auth login',
+ }
+ }
+ // A 403 means the key lacks the scope for that detail, not that it doesn't work.
+ const fatal = failures.find((failure) => !(failure instanceof ApiError && failure.status === 403))
+ if (fatal !== undefined) {
+ throw fatal
+ }
+ return {
+ authenticated: true,
+ host,
+ projectId,
+ projectName: project.status === 'fulfilled' ? project.value.name : null,
+ source,
+ credentialsPath: source === 'credentials-file' ? posthogFile(ctx.runtime, 'credentials.json') : null,
+ user: user.status === 'fulfilled' ? { email: user.value.email, name: user.value.first_name || null } : null,
+ }
+}
diff --git a/hog/src/posthog/credentials.ts b/hog/src/posthog/credentials.ts
index 450122cbc38c..ca6103810852 100644
--- a/hog/src/posthog/credentials.ts
+++ b/hog/src/posthog/credentials.ts
@@ -12,16 +12,22 @@ export interface Credentials {
host: string
}
+export type CredentialSource = 'env' | 'dotenv-file' | 'credentials-file'
+
+export type ResolvedCredentials = Credentials & { source: CredentialSource }
+
interface RawCredentials {
apiKey: string
projectId: string
host: string | undefined
}
+export const API_KEY_ENV_VARS = ['POSTHOG_CLI_API_KEY', 'POSTHOG_CLI_TOKEN'] as const
+
// Same variables and aliases as posthog-cli. The host only counts when it comes from the
// same source as the key, so a stray host cannot redirect a key from somewhere else.
function fromLookup(lookup: (name: string) => string | undefined): RawCredentials | undefined {
- const apiKey = lookup('POSTHOG_CLI_API_KEY') ?? lookup('POSTHOG_CLI_TOKEN')
+ const apiKey = lookup(API_KEY_ENV_VARS[0]) ?? lookup(API_KEY_ENV_VARS[1])
const projectId = lookup('POSTHOG_CLI_PROJECT_ID') ?? lookup('POSTHOG_CLI_ENV_ID')
if (!apiKey || !projectId) {
return undefined
@@ -80,40 +86,76 @@ function posthogHomeDir(env: Env, homeDir: string | undefined): string | undefin
return homeDir === undefined ? undefined : join(homeDir, '.posthog')
}
+export function posthogFile(runtime: Runtime, name: string): string {
+ const home = posthogHomeDir(runtime.env, runtime.homeDir())
+ if (home === undefined) {
+ throw new HogError(
+ 'no_home_directory',
+ "hog couldn't find your home folder to store credentials in.",
+ 'Set POSTHOG_HOME to the folder to use.'
+ )
+ }
+ return join(home, name)
+}
+
+export function checkApiKey(apiKey: string): string | undefined {
+ return apiKey.startsWith('phx_') ? undefined : "The personal API key doesn't look right: it must start with 'phx_'."
+}
+
+export function checkProjectId(projectId: string): string | undefined {
+ return /^\d+$/.test(projectId) ? undefined : `The project ID must be a number, but it is "${projectId}".`
+}
+
+export function checkHost(host: string): string | undefined {
+ return URL.canParse(host) ? undefined : `The host must be a valid URL, but it is "${host}".`
+}
+
function validate(raw: RawCredentials, host: string): Credentials {
- if (!raw.apiKey.startsWith('phx_')) {
+ const keyError = checkApiKey(raw.apiKey)
+ if (keyError) {
throw new HogError(
'invalid_credentials',
- "The personal API key doesn't look right: it must start with 'phx_'.",
+ keyError,
'Create a personal API key in PostHog under Settings > Personal API keys.'
)
}
- if (!/^\d+$/.test(raw.projectId)) {
+ const projectError = checkProjectId(raw.projectId)
+ if (projectError) {
throw new HogError(
'invalid_credentials',
- `The project ID must be a number, but it is "${raw.projectId}".`,
+ projectError,
'Use the number in your project URL, like the 2 in https://us.posthog.com/project/2.'
)
}
- try {
- new URL(host)
- } catch {
- throw new HogError('invalid_credentials', `The host must be a valid URL, but it is "${host}".`)
+ const hostError = checkHost(host)
+ if (hostError) {
+ throw new HogError('invalid_credentials', hostError)
}
return { apiKey: raw.apiKey, projectId: raw.projectId, host }
}
+// Same file and fields as posthog-cli, so either CLI can use a login made by the other.
+export async function saveCredentials(runtime: Runtime, credentials: Credentials): Promise<string> {
+ const path = posthogFile(runtime, 'credentials.json')
+ const stored = { host: credentials.host, token: credentials.apiKey, env_id: credentials.projectId }
+ await runtime.writePrivateFile(path, JSON.stringify(stored))
+ return path
+}
+
// Lookup order matches posthog-cli: process env, then --dotenv-file, then the credentials
-// file `posthog-cli login` writes. --host overrides whichever host the source carried.
+// file `hog auth login` and `posthog-cli login` write. --host overrides whichever host the source carried.
export async function resolveCredentials(
runtime: Runtime,
options: { host?: string; dotenvFile?: string }
-): Promise<Credentials> {
- const withHost = (raw: RawCredentials): Credentials => validate(raw, options.host ?? raw.host ?? DEFAULT_HOST)
+): Promise<ResolvedCredentials> {
+ const withHost = (raw: RawCredentials, source: CredentialSource): ResolvedCredentials => ({
+ ...validate(raw, options.host ?? raw.host ?? DEFAULT_HOST),
+ source,
+ })
const fromEnv = fromLookup((name) => runtime.env[name] || undefined)
if (fromEnv) {
- return withHost(fromEnv)
+ return withHost(fromEnv, 'env')
}
const dotenvFile = options.dotenvFile ?? (runtime.env.POSTHOG_CLI_DOTENV_FILE || undefined)
@@ -129,7 +171,7 @@ export async function resolveCredentials(
'Add both variables to the file, or remove --dotenv-file.'
)
}
- return withHost(fromFile)
+ return withHost(fromFile, 'dotenv-file')
}
}
@@ -147,13 +189,13 @@ export async function resolveCredentials(
projectId: String(stored.env_id),
host: typeof stored.host === 'string' ? stored.host : undefined,
}
- return withHost(raw)
+ return withHost(raw, 'credentials-file')
}
}
throw new HogError(
'not_authenticated',
"hog couldn't find PostHog credentials.",
- 'Run `posthog-cli login`, or set POSTHOG_CLI_API_KEY and POSTHOG_CLI_PROJECT_ID.'
+ 'Run `hog auth login`, or set POSTHOG_CLI_API_KEY and POSTHOG_CLI_PROJECT_ID.'
)
}
diff --git a/hog/src/posthog/device-auth.ts b/hog/src/posthog/device-auth.ts
new file mode 100644
index 000000000000..69a3f37d1798
--- /dev/null
+++ b/hog/src/posthog/device-auth.ts
@@ -0,0 +1,137 @@
+import { HogError } from '@/core/errors'
+import type { Runtime } from '@/core/runtime'
+
+import { sendRequest, type HttpResponse } from './api'
+
+// The `agent-cli` use case asks for the scope set the MCP and agent tools need, so a fresh login
+// 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 {
+ host: string
+ deviceCode: string
+ userCode: string
+ url: string
+ // Epoch milliseconds after which PostHog forgets the code.
+ expiresAt: number
+ intervalSeconds: number
+}
+
+export interface Approval {
+ apiKey: string
+ projectId: string
+ scopes: string[]
+}
+
+interface DeviceCodeResponse {
+ device_code: string
+ user_code: string
+ verification_uri_complete: string
+ expires_in: number
+ interval: number
+}
+
+interface PollResponse {
+ status?: 'pending' | 'authorized' | 'expired'
+ personal_api_key?: string
+ project_id?: string | number
+ scopes?: string[]
+}
+
+function post(runtime: Runtime, host: string, path: string, body: unknown, timeoutMs: number): Promise<HttpResponse> {
+ return sendRequest(runtime.fetch, new URL(`api/cli-auth/${path}/`, host), { method: 'POST', body, timeoutMs })
+}
+
+export async function startDeviceLogin(runtime: Runtime, host: string): Promise<PendingLogin> {
+ const response = await post(runtime, host, 'device-code', undefined, REQUEST_TIMEOUT_MS)
+ const body = response.json as DeviceCodeResponse | undefined
+ if (!response.ok || !body?.device_code) {
+ throw new HogError(
+ 'login_unavailable',
+ `${host} didn't start a login: it answered with HTTP ${response.status}.`,
+ 'Check the host. Self-hosted PostHog needs a version that supports CLI login.'
+ )
+ }
+ const url = new URL(body.verification_uri_complete)
+ url.searchParams.set('use_cases', USE_CASES)
+ return {
+ host,
+ deviceCode: body.device_code,
+ userCode: body.user_code,
+ url: url.toString(),
+ expiresAt: runtime.now() + body.expires_in * 1000,
+ intervalSeconds: body.interval,
+ }
+}
+
+// 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
+ }
+ throw new HogError(
+ 'login_failed',
+ `PostHog rejected the login with HTTP ${response.status}.`,
+ 'Run `hog auth login` to start again.'
+ )
+ }
+ 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.'
+ )
+}
diff --git a/hog/src/posthog/login.ts b/hog/src/posthog/login.ts
new file mode 100644
index 000000000000..fc3ce301ea5d
--- /dev/null
+++ b/hog/src/posthog/login.ts
@@ -0,0 +1,63 @@
+import { HogError } from '@/core/errors'
+import type { Runtime } from '@/core/runtime'
+
+import { posthogFile, saveCredentials, type Credentials } from './credentials'
+import { startDeviceLogin, waitForApproval, type PendingLogin } from './device-auth'
+
+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 interface LoggedIn {
+ host: string
+ projectId: string
+ credentialsPath: string
+ 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
+ }
+ const loggedIn = await saveLogin(runtime, { ...approval, host: pending.host })
+ return { ...loggedIn, scopes: approval.scopes }
+}
+
+// Clears any pending login too, so a later `--wait` can't replace these credentials with an older approval.
+export async function saveLogin(runtime: Runtime, credentials: Credentials): Promise<LoggedIn> {
+ const credentialsPath = await saveCredentials(runtime, credentials)
+ await clearPendingLogin(runtime)
+ return { host: credentials.host, projectId: credentials.projectId, credentialsPath, scopes: [] }
+}
diff --git a/hog/src/testing.ts b/hog/src/testing.ts
index fdee24d80116..c1cb77c278c1 100644
--- a/hog/src/testing.ts
+++ b/hog/src/testing.ts
@@ -1,3 +1,4 @@
+import type { Prompts } from '@/core/prompts'
import type { Env, Runtime } from '@/core/runtime'
import { run } from './cli'
@@ -8,6 +9,8 @@ export interface FakeRuntimeOptions {
columns?: number
files?: Record<string, string>
stdin?: string
+ // Answers to prompts, in the order hog asks them. A prompt with no answer left fails the test.
+ answers?: string[]
// Answers every API request. Without it, requests fail with HTTP 500. A string body is sent
// as is, for JSON that JSON.stringify can't produce.
respond?: (url: string, body: unknown) => { status: number; body: unknown }
@@ -17,15 +20,38 @@ export interface FakeRuntime extends Runtime {
stdout: () => string
stderr: () => string
requests: { method: string; url: string; body: unknown }[]
+ files: Record<string, string>
+ opened: string[]
+}
+
+function fakePrompts(answers: string[]): Prompts {
+ const next = async (message: string): Promise<string> => {
+ const value = answers.shift()
+ if (value === undefined) {
+ throw new Error(`No answer for the prompt "${message}"`)
+ }
+ return value
+ }
+ return {
+ select: (message) => next(message) as never,
+ text: (message) => next(message),
+ password: (message) => next(message),
+ note: () => {},
+ spinner: () => ({ stop: () => {}, error: () => {} }),
+ }
}
export function fakeRuntime(options: FakeRuntimeOptions = {}): FakeRuntime {
let stdout = ''
let stderr = ''
const requests: FakeRuntime['requests'] = []
- const files = options.files ?? {}
+ const files = { ...options.files }
+ const opened: string[] = []
+ // A clock that only moves when hog sleeps, so polling runs instantly.
+ let clock = Date.UTC(2026, 0, 1)
return {
env: options.env ?? {},
+ stdinIsTTY: options.stdoutIsTTY ?? false,
stdoutIsTTY: options.stdoutIsTTY ?? false,
stdoutHasColors: options.stdoutIsTTY ?? false,
stdoutColumns: options.columns,
@@ -43,6 +69,10 @@ export function fakeRuntime(options: FakeRuntimeOptions = {}): FakeRuntime {
const text = typeof reply.body === 'string' ? reply.body : JSON.stringify(reply.body)
return new Response(text, { status: reply.status })
}) as typeof fetch,
+ now: () => clock,
+ sleep: async (ms) => {
+ clock += ms
+ },
homeDir: () => '/home/test',
readFile: async (path) => {
const contents = files[path]
@@ -51,10 +81,23 @@ export function fakeRuntime(options: FakeRuntimeOptions = {}): FakeRuntime {
}
return contents
},
+ writePrivateFile: async (path, contents) => {
+ files[path] = contents
+ },
+ removeFile: async (path) => {
+ delete files[path]
+ },
readStdin: async () => options.stdin ?? '',
+ openUrl: async (url) => {
+ opened.push(url)
+ return true
+ },
+ prompts: fakePrompts([...(options.answers ?? [])]),
stdout: () => stdout,
stderr: () => stderr,
requests,
+ files,
+ opened,
}
}
@@ -71,6 +114,8 @@ export interface HogRun {
stdout: string
stderr: string
requests: FakeRuntime['requests']
+ files: Record<string, string>
+ opened: string[]
json: () => any
error: () => any
}
@@ -83,6 +128,8 @@ export async function runHog(argv: string[], options: FakeRuntimeOptions = {}):
stdout: runtime.stdout(),
stderr: runtime.stderr(),
requests: runtime.requests,
+ files: runtime.files,
+ opened: runtime.opened,
json: () => JSON.parse(runtime.stdout()),
error: () => JSON.parse(runtime.stderr()).error,
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d9e52736abd3..4df44333b766 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1520,6 +1520,9 @@ importers:
hog:
dependencies:
+ '@clack/prompts':
+ specifier: 1.8.1
+ version: 1.8.1
cli-table3:
specifier: 0.6.5
version: 0.6.5
@@ -7476,6 +7479,14 @@ packages:
'@chevrotain/[email protected]':
resolution: {integrity: sha512-U+HFai5+zmJCkK86QsaJtoITlboZHBqrVketcO2ROv865xfCMSFpELQoz1GkX5GzME8pTa+3kbKrZHQtI0gdbw==}
+ '@clack/[email protected]':
+ resolution: {integrity: sha512-iHTrHA8MtVuLl2TfZySmcKv1qO2PoyC9Z7pfSDozEuV5vtY3/wcOPKJXlqJ5Oq2Cx5DDGQGAMVx6HZfRRoVEbQ==}
+ engines: {node: '>= 20.12.0'}
+
+ '@clack/[email protected]':
+ resolution: {integrity: sha512-dlT1m5e/0yUL0kRNcQn7yGLVThkgbB0Ga/1AmfDDC/8ik6AIiSf2QLQO2zPYvefsHP0aFgxO93cVLCCfDp7kzQ==}
+ engines: {node: '>= 20.12.0'}
+
'@clickhouse/[email protected]':
resolution: {integrity: sha512-cyI4n7u9jK30d9q1q0ceQ7IwJ/MtTs5HxoQfc8yHpN+ok5wqaU2jAtq5hpa1z7C7sS1pDy/ZOFmOzg1v1F683g==}
deprecated: 'Deprecated: import from @clickhouse/client or @clickhouse/client-web instead.'
@@ -26612,6 +26623,18 @@ snapshots:
'@chevrotain/[email protected]': {}
+ '@clack/[email protected]':
+ dependencies:
+ fast-wrap-ansi: 0.2.2
+ sisteransi: 1.0.5
+
+ '@clack/[email protected]':
+ dependencies:
+ '@clack/core': 1.5.1
+ fast-string-width: 3.0.2
+ fast-wrap-ansi: 0.2.2
+ sisteransi: 1.0.5
+
'@clickhouse/[email protected]': {}
'@clickhouse/[email protected]':