: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(hog): log in with the OAuth device grant (#127819)
Rafael Audibert743d75097a6a
diff --git a/hog/README.md b/hog/README.mdindex 9381d04bdfe0..dce19fd3e1e2 100644--- a/hog/README.md+++ b/hog/README.md@@ -184,7 +184,7 @@ hog uploads the same bytes and content hashes as posthog-cli, so either CLI can1. `HOG_PERSONAL_API_KEY` and `HOG_PROJECT_ID` in the environment, plus an optional `HOG_HOST`. The key is a personal API key: it acts as you, with your access.2. The same variables in the file `--dotenv-file` or `HOG_DOTENV_FILE` names. A missing file prints a warning and hog moves on to the next source.-3. What `hog auth login` stored, one login per host: the system keychain (Keychain on macOS, Credential Manager on Windows, Secret Service on Linux), or `credentials.json` in hog's folder when hog can't use the keychain, such as over SSH or in a container. Only you can read that file.+3. What `hog auth login` stored, one login per host: a short-lived OAuth token for one project, or a personal API key you pasted. It lives in the system keychain (Keychain on macOS, Credential Manager on Windows, Secret Service on Linux), or `credentials.json` in hog's folder when hog can't use the keychain, such as over SSH or in a container. Only you can read that file.hog doesn't read `~/.posthog/credentials.json`, the file `posthog-cli login` writes (`HOG_HOME` moves the folder). Run `hog auth migrate` once to move its key into hog's store.@@ -196,10 +196,13 @@ hog's folder is `~/Library/Application Support/hog` on macOS, `$XDG_CONFIG_HOME/### 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.-- Each login checks that hog can use the keychain, and records where it stored the key in `settings.json` in hog's folder, so other commands don't check again. The keychain, or the credentials file, keeps only the secret. The rest of the login, such as the project, is in `settings.json`. When the keychain shows a dialog, choose "Always Allow".+- On the approval page you check the code, pick a project and see what hog will be able to do. The token only works in that project; to use another one, log in again. hog renews the token by itself.+- `hog auth login --read-only` asks only for read access. To change something later, run `hog auth login` again without the flag.+- 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 token. Running `hog auth login` again before the code expires returns the same link.+- Each login checks that hog can use the keychain, and records where it stored the token in `settings.json` in hog's folder, so other commands don't check again. The keychain, or the credentials file, keeps only the secrets. The rest of the login, such as the project and the scopes, is in `settings.json`. When the keychain shows a dialog, choose "Always Allow".+- Self-hosted PostHog has to reach posthog.com to log hog in, because hog's OAuth client is described there. Without that, set the environment variables above.- In CI, skip login and set the environment variables above.-- `hog auth status` checks the key against PostHog and names where it comes from. `hog auth logout` removes hog's login to the current host, and `hog auth logout --all` removes every login hog stored. Both warn when an environment variable still holds a key.+- `hog auth status` checks the credentials against PostHog, and names where they come from, their scopes and when the token expires. `hog auth logout` revokes the login on this machine in PostHog and removes it from this machine. `hog auth logout --all` does the same for every login hog stored. Both warn when an environment variable still holds a key.## Developdiff --git a/hog/src/commands/api/access.ts b/hog/src/commands/api/access.tsindex 2818cc190b5d..cfa755ce5f0b 100644--- a/hog/src/commands/api/access.ts+++ b/hog/src/commands/api/access.ts@@ -4,7 +4,7 @@ import { defineCommand } from '@/core/command'import type { Context } from '@/core/context'import { plural } from '@/core/text'import { ApiError } from '@/posthog/api'-import { apiConnection, groupSlug, unwrap } from '@/posthog/api-tools'+import { apiConnection, credentialAccess, groupSlug, unwrap } from '@/posthog/api-tools'const TOP_SCOPES = 10@@ -39,14 +39,14 @@ async function reachesProject(}export default defineCommand({- description: 'Show what the personal API key can reach, and the scopes that would unlock more tools',+ description: 'Show what your credentials can reach, and the scopes that would unlock more tools',notes: 'Each missing scope counts the tools it blocks. A tool can need more than one scope.',examples: ['hog api access', 'hog api access -o json'],async run({ ctx }) {const library = await ctx.apiTools()const connection = await apiConnection(ctx)- const access = unwrap(await library.keyAccess(connection))+ const access = unwrap(await credentialAccess(ctx, library, connection))const projectId = connection.projectId ?? ''const blocked = new Map<string, { tools: number; groups: Set<string> }>()let usable = 0diff --git a/hog/src/commands/api/api.test.ts b/hog/src/commands/api/api.test.tsindex 09d13c90d20b..5f581c7378fd 100644--- a/hog/src/commands/api/api.test.ts+++ b/hog/src/commands/api/api.test.ts@@ -213,4 +213,25 @@ describe('hog api', () => {],})})++ test('access answers for an OAuth login from its scopes, because the key lookup refuses OAuth tokens', async () => {+ const EU = 'https://eu.posthog.com'+ const record = {+ store: 'keychain',+ type: 'oauth',+ projectId: '42',+ host: EU,+ expiresAt: Date.UTC(2026, 0, 8),+ scopes: ['feature_flag:read', 'feature_flag:write'],+ loginId: 'login-1',+ }+ const result = await runHog(['api', 'access'], {+ env: { CLAUDECODE: '1' },+ files: { '/home/test/.config/hog/settings.json': JSON.stringify({ logins: { [EU]: record }, host: EU }) },+ keychain: { [EU]: JSON.stringify({ accessToken: 'pha_token', refreshToken: 'phr_token' }) },+ apiTools: fakeLibrary([], { lookupFails: true }),+ })++ expect(result.json()).toMatchObject({ usable: 2, tools: 3, projectAllowed: true })+ })})diff --git a/hog/src/commands/auth/auth.test.ts b/hog/src/commands/auth/auth.test.tsindex ab6b36f04993..7c9d322b9055 100644--- a/hog/src/commands/auth/auth.test.ts+++ b/hog/src/commands/auth/auth.test.ts@@ -1,44 +1,63 @@import { describe, expect, test } from 'bun:test'import type { Secrets } from '@/core/runtime'+import { LOGIN_SCOPES } from '@/posthog/device-auth'+import { HOG_CLIENT_ID } from '@/posthog/oauth'import { runHog } from '@/testing'+const EU = 'https://eu.posthog.com'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/.config/hog/pending-auth-login.json'const DEVICE_CODE = 'device-secret-123'+// Tokens as long as the ones PostHog issues, so the size check below is realistic.+const ACCESS_TOKEN = `pha_${'a'.repeat(43)}`+const REFRESH_TOKEN = `phr_${'r'.repeat(43)}`+// The answers layers of the OAuth server give: RFC 8628 device authorization, then the token+// endpoint's RFC 8628 errors, then a token scoped to the project the person picked.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,+ user_code: 'BCDF-GHJK',+ verification_uri: `${EU}/device`,+ verification_uri_complete: `${EU}/device?code=BCDF-GHJK`,+ expires_in: 1800,interval: 5,}const APPROVED = {- status: 'authorized',- personal_api_key: 'phx_secret',- project_id: '42',- scopes: ['query:read'],+ access_token: ACCESS_TOKEN,+ token_type: 'Bearer',+ expires_in: 604800,+ refresh_token: REFRESH_TOKEN,+ scope: LOGIN_SCOPES.join(' '),+ scoped_teams: [42],+ scoped_organizations: [],}const PENDING = JSON.stringify({- host: 'https://eu.posthog.com',+ host: EU,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,+ userCode: 'BCDF-GHJK',+ url: `${EU}/device?code=BCDF-GHJK`,+ expiresAt: Date.UTC(2026, 0, 1) + 1_800_000,intervalSeconds: 5,+ scopes: LOGIN_SCOPES,})// 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 = 0return (url: string) => {- if (url.endsWith('/api/cli-auth/device-code/')) {+ if (url.endsWith('/oauth/device-authorization/')) {return { status: 200, body: DEVICE }}- return polls++ < pendingPolls ? { status: 202, body: { status: 'pending' } } : final+ if (url.endsWith('/oauth/revoke/')) {+ return { status: 200, body: {} }+ }+ if (url.endsWith('/api/personal_api_keys/@current/')) {+ return { status: 200, body: { scopes: ['query:read'] } }+ }+ return polls++ < pendingPolls ? { status: 400, body: { error: 'authorization_pending' } } : final}}@@ -52,26 +71,53 @@ describe('hog auth login', () => {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',+ code: 'BCDF-GHJK',+ url: `${EU}/device?code=BCDF-GHJK`,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/',+ expect(result.requests).toEqual([+ {+ method: 'POST',+ url: `${EU}/oauth/device-authorization/`,+ body: { client_id: HOG_CLIENT_ID, scope: LOGIN_SCOPES.join(' ') },+ },])})+ test('--read-only asks for read access only', async () => {+ const result = await runHog(['auth', 'login', '--region', 'eu', '--read-only'], {+ env: { CLAUDECODE: '1' },+ respond: deviceFlow(0),+ })++ const requested = String((result.requests[0]?.body as { scope?: string } | undefined)?.scope ?? '').split(' ')+ expect(requested).toContain('insight:read')+ expect(requested).toContain('openid')+ expect(requested.filter((scope) => scope.endsWith(':write'))).toEqual([])+ })++ test('an approval link on another origin than the host is replaced with the page on the host', async () => {+ const result = await runHog(['auth', 'login', '--region', 'eu'], {+ env: { CLAUDECODE: '1' },+ respond: () => ({+ status: 200,+ body: {+ ...DEVICE,+ verification_uri: 'https://phish.example.com/device',+ verification_uri_complete: 'https://phish.example.com/device?code=BCDF-GHJK',+ },+ }),+ })++ expect(result.json()).toMatchObject({ status: 'pending', url: `${EU}/device?code=BCDF-GHJK` })+ })+test.each([- ['a posthog.json Cloud host picks the region', [], 'https://eu.posthog.com', 'https://eu.posthog.com'],- [- '--region beats the posthog.json host',- ['--region', 'eu'],- 'https://us.posthog.com',- 'https://eu.posthog.com',- ],+ ['a posthog.json Cloud host picks the region', [], EU, EU],+ ['--region beats the posthog.json host', ['--region', 'eu'], 'https://us.posthog.com', EU],])('%s', async (_name, flags, configHost, loginHost) => {const result = await runHog(['auth', 'login', ...flags], {env: { CLAUDECODE: '1' },@@ -80,7 +126,7 @@ describe('hog auth login', () => {})expect(result.exitCode).toBe(0)- expect(result.requests.map((request) => request.url)).toEqual([`${loginHost}/api/cli-auth/device-code/`])+ expect(result.requests.map((request) => request.url)).toEqual([`${loginHost}/oauth/device-authorization/`])})test('a posthog.json host outside PostHog Cloud never starts a login', async () => {@@ -100,7 +146,7 @@ describe('hog auth login', () => {files: { [PENDING_FILE]: PENDING },respond: deviceFlow(0),})- expect(result.json()).toMatchObject({ status: 'pending', code: 'ABCD-1234' })+ expect(result.json()).toMatchObject({ status: 'pending', code: 'BCDF-GHJK' })expect(result.requests).toEqual([])})@@ -108,13 +154,21 @@ describe('hog auth login', () => {['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'],+ [+ '--read-only with --wait',+ ['auth', 'login', '--wait', '--read-only'],+ { CLAUDECODE: '1' },+ { [PENDING_FILE]: PENDING },+ 2,+ 'read_only_with_wait',+ ],])('%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 keychain once the person approves', async () => {+ test('--wait stores the token for the approved project in the keychain', async () => {const result = await runHog(['auth', 'login', '--wait'], {env: { CLAUDECODE: '1' },files: { [PENDING_FILE]: PENDING },@@ -122,25 +176,38 @@ describe('hog auth login', () => {})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')- // The keychain keeps only the secret. What isn't secret is in settings.json.- expect(JSON.parse(result.keychain['https://eu.posthog.com'] ?? '{}')).toEqual({ apiKey: 'phx_secret' })+ expect(result.json()).toMatchObject({+ status: 'logged_in',+ host: EU,+ projectId: '42',+ scopes: LOGIN_SCOPES,+ expiresAt: expect.any(String),+ })+ expect(result.stdout).not.toContain(ACCESS_TOKEN)+ // The keychain keeps only the tokens. What isn't secret is in settings.json.+ expect(JSON.parse(result.keychain[EU] ?? '{}')).toEqual({+ accessToken: ACCESS_TOKEN,+ refreshToken: REFRESH_TOKEN,+ })+ // Windows Credential Manager refuses an item over 2,560 bytes, and Bun stores it as UTF-8.+ expect(Buffer.byteLength(result.keychain[EU] ?? '')).toBeLessThanOrEqual(2560)expect(JSON.parse(result.files[SETTINGS_FILE] ?? '{}')).toEqual({logins: {- 'https://eu.posthog.com': {+ [EU]: {store: 'keychain',- type: 'personal_api_key',+ type: 'oauth',projectId: '42',- host: 'https://eu.posthog.com',+ host: EU,+ expiresAt: expect.any(Number),+ scopes: LOGIN_SCOPES,+ loginId: expect.any(String),},},- host: 'https://eu.posthog.com',+ host: EU,})expect(result.files[LEGACY_CLI_FILE]).toBeUndefined()expect(result.files[PENDING_FILE]).toBeUndefined()- // Only polls: a key PostHog just issued skips the key check.- expect(result.requests.map((request) => request.url.endsWith('/poll/'))).toEqual([true, true, true])+ expect(result.requests.filter((request) => request.url.endsWith('/oauth/token/'))).toHaveLength(3)})const denied = Object.assign(new Error('User canceled'), { code: 'ERR_SECRETS_USER_CANCELED' })@@ -154,7 +221,7 @@ describe('hog auth login', () => {// An item an older hog build saved can ask again even though a new probe item works.["denies the host's item after the probe passes", denied, true],])(- 'a login saves the key in a private file, and says so, when the keychain %s',+ 'a login saves the token in a private file, and says so, when the keychain %s',async (_name, failure, probeWorks) => {const items = new Map<string, string>()const check = (name: string): void => {@@ -190,7 +257,7 @@ describe('hog auth login', () => {keychainError: expect.stringContaining('keychain'),})expect(JSON.parse(result.files[HOG_CREDENTIALS_FILE] ?? '{}')).toEqual({- 'https://eu.posthog.com': { apiKey: 'phx_secret' },+ [EU]: { accessToken: ACCESS_TOKEN, refreshToken: REFRESH_TOKEN },})expect(JSON.parse(result.files[SETTINGS_FILE] ?? '{}')).toMatchObject({logins: { 'https://eu.posthog.com': { store: 'file', projectId: '42' } },@@ -201,37 +268,53 @@ describe('hog auth login', () => {test.each([['stops when the code expires and forgets it',- { status: 400, body: { status: 'expired' } },- 'login_expired',+ { status: 400, body: { error: 'expired_token' } },+ { code: 'login_expired' },+ false,+ ],+ [+ 'stops when the person denies it and forgets it',+ { status: 400, body: { error: 'access_denied' } },+ { code: 'login_rejected' },+ false,+ ],+ [+ "stops with PostHog's reason when it refuses the client, and forgets it",+ {+ status: 400,+ body: { error: 'unauthorized_client', error_description: "PostHog hasn't verified this app." },+ },+ { code: 'login_unavailable', message: expect.stringContaining("hasn't verified this app") },false,],['retries a server that keeps failing, then keeps the login to resume',{ status: 503, body: 'Service Unavailable' },- 'login_interrupted',+ { code: 'login_interrupted' },true,],- ])('--wait %s', async (_name, final, code, keepsPending) => {+ ])('--wait %s', async (_name, final, expected, 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.error()).toMatchObject(expected)expect(result.files[PENDING_FILE] !== undefined).toBe(keepsPending)expect(result.keychain).toEqual({})})test.each([- ['approving in the browser', ['eu'], true, 'https://eu.posthog.com'],+ ['approving in the browser', ['eu'], true, EU, { accessToken: ACCESS_TOKEN }],['pasting a personal API key',['key', 'https://ph.example.com/', '42', 'phx_secret'],false,'https://ph.example.com',+ { apiKey: 'phx_secret' },],- ])('a person at a terminal logs in by %s', async (_name, answers, opensBrowser, host) => {+ ])('a person at a terminal logs in by %s', async (_name, answers, opensBrowser, host, secret) => {const result = await runHog(['auth', 'login'], {stdoutIsTTY: true,env: { NO_COLOR: '1' },@@ -244,7 +327,21 @@ describe('hog auth login', () => {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.keychain[host] ?? '{}')).toEqual({ apiKey: 'phx_secret' })+ expect(JSON.parse(result.keychain[host] ?? '{}')).toMatchObject(secret)+ expect(result.stdout).toContain('Try it: hog query run')+ })++ test('a pasted personal API key that PostHog rejects is not saved', async () => {+ const result = await runHog(['auth', 'login'], {+ stdoutIsTTY: true,+ env: { NO_COLOR: '1' },+ answers: ['key', 'https://ph.example.com/', '42', 'phx_deleted'],+ respond: () => ({ status: 401, body: { detail: 'Invalid personal API key.' } }),+ })++ expect(result.exitCode).toBe(1)+ expect(result.stderr).toContain('https://ph.example.com rejected the personal API key')+ expect(result.keychain).toEqual({})})const STORED = JSON.stringify({ host: 'https://eu.posthog.com', token: 'phx_secret', env_id: '42' })@@ -264,6 +361,25 @@ describe('hog auth login', () => {},keychain: { 'https://eu.posthog.com': JSON.stringify({ apiKey: 'phx_secret' }) },}+ const OAUTH_LOGIN = {+ files: {+ [SETTINGS_FILE]: JSON.stringify({+ logins: {+ [EU]: {+ store: 'keychain',+ type: 'oauth',+ projectId: '42',+ host: EU,+ expiresAt: Date.UTC(2026, 0, 2),+ scopes: ['openid', 'insight:read'],+ loginId: 'login-1',+ },+ },+ host: EU,+ }),+ },+ keychain: { [EU]: JSON.stringify({ accessToken: ACCESS_TOKEN, refreshToken: REFRESH_TOKEN }) },+ }test.each([[@@ -289,8 +405,21 @@ describe('hog auth login', () => {expect(result.stdout).not.toContain('phx_secret')})- test.each([['a hog login', KEYCHAIN_LOGIN, { source: 'store', store: 'keychain', credentialsPath: null }]])(- 'status names where the key of %s comes from',+ test.each([+ ['a hog login', KEYCHAIN_LOGIN, { source: 'store', store: 'keychain', credentialsPath: null }],+ [+ 'an OAuth login',+ OAUTH_LOGIN,+ {+ kind: 'oauth',+ source: 'store',+ store: 'keychain',+ scopes: ['openid', 'insight:read'],+ expiresAt: '2026-01-02T00:00:00.000Z',+ },+ ],+ ])(+ 'status names where the credentials of %s come from, and what they can do',async (_name, { files, keychain }, expected) => {const result = await runHog(['auth', 'status'], {env: { CLAUDECODE: '1' },@@ -406,6 +535,7 @@ describe('hog auth login', () => {files,keychain: KEYCHAIN_LOGIN.keychain,})+ expect(result.requests).toEqual([])expect(result.exitCode).toBe(0)expect(result.json()).toMatchObject({ status, revokeUrl, stillSet })expect(result.keychain).toEqual(files[SETTINGS_FILE] ? {} : KEYCHAIN_LOGIN.keychain)@@ -414,6 +544,27 @@ describe('hog auth login', () => {})+ test.each([+ ['revokes an OAuth login in PostHog before it removes it', 200, true],+ ['says when PostHog could not revoke the login, and still removes it', 503, false],+ ])('logout %s', async (_name, status, revoked) => {+ const result = await runHog(['auth', 'logout'], {+ env: { CLAUDECODE: '1' },+ ...OAUTH_LOGIN,+ respond: () => ({ status, body: {} }),+ })++ expect(result.json()).toMatchObject({ status: 'logged_out', revoked, revokeUrl: null })+ expect(result.requests).toEqual([+ {+ method: 'POST',+ url: `${EU}/oauth/revoke/`,+ body: { token: REFRESH_TOKEN, token_type_hint: 'refresh_token', client_id: HOG_CLIENT_ID },+ },+ ])+ expect(result.keychain).toEqual({})+ })+test('a file login that replaced a keychain login takes the old keychain item with it on logout', async () => {const oldItem = JSON.stringify({ apiKey: 'phx_old' })const items = new Map([['https://eu.posthog.com', oldItem]])diff --git a/hog/src/commands/auth/login.ts b/hog/src/commands/auth/login.tsindex 4eb3586e8410..044134f720e3 100644--- a/hog/src/commands/auth/login.ts+++ b/hog/src/commands/auth/login.ts@@ -4,17 +4,17 @@ import type { Context } from '@/core/context'import { EXIT_USAGE, HogError } from '@/core/errors'import { escapeControls } from '@/core/output'import type { Prompts } from '@/core/prompts'-import { PersonalAPIKey } from '@/posthog/access-key'+import { PersonalAPIKey, type AccessKey } from '@/posthog/access-key'import type { StoreChoice } from '@/posthog/credential-store/types'import { checkApiKey, checkHost, checkProjectId } from '@/posthog/credentials'-import type { Approval } from '@/posthog/device-auth'+import { LOGIN_SCOPES, READ_ONLY_LOGIN_SCOPES } from '@/posthog/device-auth'import { trimHost } from '@/posthog/host'-import { loginFlow, saveLogin, type LoggedIn } from '@/posthog/login/flow'+import { loginFlow, loginWait, saveLogin, type LoggedIn } from '@/posthog/login/flow'const REGIONS = { us: 'https://us.posthog.com', eu: 'https://eu.posthog.com' } as const-// A posthog.json comes with the repository, so it only picks between the PostHog Cloud regions.-// A login to any other host needs --host, because the key it gets is saved for every project.+// A posthog.json comes with the repository, so it only picks between the PostHog Cloud regions. A+// login to any other host needs --host, so a repository can't send a person's login elsewhere.function cloudRegion(host: string | undefined): string | undefined {if (host === undefined) {return undefined@@ -37,23 +37,36 @@ type LoginResult =store: StoreChoicecredentialsPath: string | nullkeychainError: string | null+ // What the login may do, as PostHog reports it.+ scopes: string[] | null+ // ISO 8601, for an OAuth login. hog renews the token before then.+ expiresAt: string | nullnext: string}-function nextCommand(scopes: readonly string[]): string {- const canQuery = scopes.some((scope) => scope === '*' || scope.startsWith('query:'))+function nextCommand(scopes: readonly string[] | null): string {+ const canQuery = scopes?.some((scope) => scope === '*' || scope.startsWith('query:')) ?? falsereturn canQuery ? 'hog query run "select event, count() from events group by event"' : 'hog --help'}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) }+ const { host, projectId, store, credentialsPath, keychainError, status } = loggedIn+ const { scopes, expiresAt } = status+ return {+ status: 'logged_in',+ host,+ projectId,+ store,+ credentialsPath,+ keychainError,+ scopes,+ expiresAt: expiresAt === null ? null : new Date(expiresAt).toISOString(),+ next: nextCommand(scopes),+ }}-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 finish(ctx: Context, key: AccessKey): Promise<LoginResult> {+ return loggedInResult(await saveLogin(ctx.runtime, key))}async function keyLogin(ctx: Context, prompts: Prompts): Promise<LoginResult> {@@ -61,11 +74,11 @@ async function keyLogin(ctx: Context, prompts: Prompts): Promise<LoginResult> {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 })const key = new PersonalAPIKey({ host: trimHost(host), projectId, apiKey })- return loggedInResult(await saveLogin(ctx.runtime, key))+ return finish(ctx, key)}export default defineCommand({- description: 'Log in to PostHog',+ description: 'Log in to PostHog in the browser',writes: true,options: {region: {@@ -77,22 +90,36 @@ export default defineCommand({},wait: {type: 'boolean',- description: 'Wait for the login an agent or script started, and save the key once a person approves it',+ description: 'Wait for the login an agent or script started, and save the token once a person approves it',+ },+ readOnly: {+ type: 'boolean',+ description:+ 'Ask only for read access. To change something later, run `hog auth login` again without this flag',},},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`.',- 'hog stores the key in the system keychain. If no keychain is available, such as over SSH, it stores the key in a file only you can read.',+ 'The person picks one project, and the token only works there. To use another project, log in again. hog renews the token by itself.',+ 'hog stores the token in the system keychain. If no keychain is available, such as over SSH, it stores the token in a file only you can read.','In CI, skip login and set HOG_PERSONAL_API_KEY, HOG_PROJECT_ID and HOG_HOST.',].join('\n'),- examples: ['hog auth login', 'hog auth login --region eu', 'hog auth login --wait'],+ examples: ['hog auth login', 'hog auth login --region eu', 'hog auth login --read-only', 'hog auth login --wait'],async run({ options, ctx }): Promise<LoginResult> {const prompts = ctx.prompts+ if (options.wait && options.readOnly) {+ throw new HogError(+ 'read_only_with_wait',+ '--read-only sets what a new login asks for, and --wait finishes the login that already started.',+ 'Run `hog auth login --read-only` to start a read-only login, then `hog auth login --wait`.',+ EXIT_USAGE+ )+ }if (options.wait) {- return finish(ctx, await resumeApproval(ctx, loginFlow(ctx.runtime)))+ return finish(ctx, await resumeApproval(ctx, loginWait(ctx.runtime)))}if (!prompts && ctx.mode.agent === undefined && ctx.mode.ci) {@@ -132,12 +159,21 @@ export default defineCommand({})if (choice === 'key') {+ if (options.readOnly) {+ throw new HogError(+ 'read_only_with_key',+ "--read-only can't limit a personal API key: the key keeps the scopes it has in PostHog.",+ 'Approve a read-only login in the browser instead, or create a key with read scopes only.',+ EXIT_USAGE+ )+ }return keyLogin(ctx, prompts)}host = REGIONS[choice]}- const result = await runApproval(ctx, loginFlow(ctx.runtime, host))+ const scopes = options.readOnly ? READ_ONLY_LOGIN_SCOPES : LOGIN_SCOPES+ const result = await runApproval(ctx, loginFlow(ctx.runtime, host, scopes))return result.status === 'pending' ? { ...result, host } : finish(ctx, result.value)},diff --git a/hog/src/commands/auth/logout.ts b/hog/src/commands/auth/logout.tsindex f5e361fa6f8c..307086059d0c 100644--- a/hog/src/commands/auth/logout.ts+++ b/hog/src/commands/auth/logout.ts@@ -22,9 +22,12 @@ interface LogoutResult {}export default defineCommand({- description: 'Remove the personal API key hog stored on this machine',+ description: 'Log out of PostHog and remove the login hog stored on this machine',writes: true,- notes: 'The key itself stays valid until you delete it in PostHog under Settings > Personal API keys.',+ notes: [+ 'hog revokes the login on this machine in PostHog. Your hog logins on other machines keep working.',+ 'A personal API key you pasted stays valid until you delete it in PostHog under Settings > Personal API keys.',+ ].join('\n'),options: {all: { type: 'boolean', description: 'Log out of every PostHog host hog has a login for' },},@@ -60,7 +63,7 @@ export default defineCommand({human({ result, out }) {const loggedOut = result.hosts ?? (result.host && result.status === 'logged_out' ? [result] : [])if (loggedOut.length === 0) {- out.line('hog had no stored key to remove.')+ out.line('hog had no stored login to remove.')}for (const { host, revoked, revokeUrl, keychainLeftover } of loggedOut) {out.line(`${out.style('Logged out', 'green', 'bold')} of ${escapeControls(host ?? '')}.`)diff --git a/hog/src/commands/auth/status.ts b/hog/src/commands/auth/status.tsindex 2fb8bfa8b273..79d3559d1b39 100644--- a/hog/src/commands/auth/status.ts+++ b/hog/src/commands/auth/status.ts@@ -16,8 +16,8 @@ function sourceLabel(source: CredentialSource, store: StoreChoice | null, path:}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.',+ description: 'Show whether hog is logged in, where its credentials come from, and what they can do',+ notes: 'Exits with code 1 when hog has no working credentials, so scripts and agents can branch on it.',examples: ['hog auth status', 'hog auth status -o json'],run: ({ ctx }) => checkAuthStatus(ctx),@@ -33,7 +33,14 @@ export default defineCommand({out.line(`${out.style('Logged in', 'green', 'bold')} to ${escapeControls(result.host)}${who}.`)const name = result.projectName ? escapeControls(result.projectName) : nullout.line(`Project: ${name ? `${name} (${result.projectId})` : result.projectId}`)- out.line(out.style(`Key from ${sourceLabel(result.source, result.store, result.credentialsPath)}`, 'dim'))+ const what = result.kind === 'oauth' ? 'Token' : 'Personal API key'+ out.line(out.style(`${what} from ${sourceLabel(result.source, result.store, result.credentialsPath)}`, 'dim'))+ if (result.scopes) {+ out.line(out.style(`Scopes: ${result.scopes.join(', ')}`, 'dim'))+ }+ if (result.expiresAt) {+ out.line(out.style(`Expires ${result.expiresAt}. hog renews it before then.`, 'dim'))+ }},exitCode: (result) => (result.authenticated ? 0 : 1),diff --git a/hog/src/posthog/access-key.ts b/hog/src/posthog/access-key.tsindex 884e80253357..880aa72b4067 100644--- a/hog/src/posthog/access-key.ts+++ b/hog/src/posthog/access-key.ts@@ -1,3 +1,5 @@+import type { ApiKeyAccess } from '@posthog/mcp/src/cli/library-types'+import { HogError } from '@/core/errors'import type { Runtime } from '@/core/runtime'import type { StoreChoice, StoredSecret } from '@/posthog/credential-store/types'@@ -14,6 +16,8 @@ export interface AccessKeyStatus {scopes: string[] | null// Epoch milliseconds. Null for a key that doesn't expire.expiresAt: number | null+ // What hog says when PostHog rejects the key.+ rejected: string}export interface LogoutOutcome {@@ -44,6 +48,8 @@ export interface AccessKey {// The key as PostHog sees it, before hog stores it. Throws when PostHog rejects it.verify(runtime: Runtime): Promise<AccessKey>status(): AccessKeyStatus+ // What the key can reach, when hog knows. Null when only PostHog can say.+ access(): ApiKeyAccess | nulllogout(runtime: Runtime): Promise<LogoutOutcome>// The credential store keeps the secret, and settings.json keeps the record.secret(): StoredSecret@@ -79,7 +85,16 @@ export class PersonalAPIKey implements AccessKey {}status(): AccessKeyStatus {- return { kind: 'personal_api_key', scopes: this.scopes, expiresAt: null }+ return {+ kind: 'personal_api_key',+ scopes: this.scopes,+ expiresAt: null,+ rejected: 'PostHog rejected the key. Someone may have deleted it.',+ }+ }++ access(): null {+ return null}// A key someone deleted, or one pasted only in part, would otherwise fail only at the firstdiff --git a/hog/src/posthog/api-tools.ts b/hog/src/posthog/api-tools.tsindex b4fee2915304..298498571a00 100644--- a/hog/src/posthog/api-tools.ts+++ b/hog/src/posthog/api-tools.ts@@ -1,5 +1,6 @@import type {ApiConnection,+ ApiKeyAccess,ApiToolError,ApiToolLibrary,ApiToolResult,@@ -195,6 +196,18 @@ export function unwrap<T>(result: ApiToolResult<T>, tool?: string): T {const SCOPE_LOOKUP_MS = 10_000+// What the credentials can reach. PostHog's key lookup only answers for a personal API key, so a+// credential that knows its own access answers first.+export async function credentialAccess(+ ctx: Context,+ library: ApiToolLibrary,+ connection: ApiConnection,+ options?: { signal?: AbortSignal }+): Promise<ApiToolResult<ApiKeyAccess>> {+ const access = (await ctx.credentials()).key.access()+ return access ? { ok: true, value: access } : library.keyAccess(connection, options)+}+// Undefined when the scopes are unknown, so browsing still works on a failed or stalled lookup.export async function grantedScopes(ctx: Context, library: ApiToolLibrary): Promise<string[] | undefined> {let connection: ApiConnection@@ -215,9 +228,9 @@ export async function grantedScopes(ctx: Context, library: ApiToolLibrary): Promresolve(undefined)}, SCOPE_LOOKUP_MS)})- const lookup = library- .keyAccess(connection, { signal: deadline.signal })- .then((result) => (result.ok ? result.value.scopes : undefined))+ const lookup = credentialAccess(ctx, library, connection, { signal: deadline.signal }).then((result) =>+ result.ok ? result.value.scopes : undefined+ )try {return await Promise.race([lookup, stalled])} finally {diff --git a/hog/src/posthog/auth-status.ts b/hog/src/posthog/auth-status.tsindex 651d9c38fd9b..5a5242be22ce 100644--- a/hog/src/posthog/auth-status.ts+++ b/hog/src/posthog/auth-status.ts@@ -19,10 +19,15 @@ export type AuthStatus =host: stringprojectId: stringprojectName: string | null+ kind: 'personal_api_key' | 'oauth'source: CredentialSource// Set when the source is the store.store: StoreChoice | nullcredentialsPath: string | null+ // What an OAuth login may do and when its access token expires (ISO 8601). Null for a+ // personal API key, which has no expiry and whose scopes PostHog doesn't report.+ scopes: string[] | null+ expiresAt: 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}@@ -35,10 +40,14 @@ export async function checkAuthStatus(ctx: Context): Promise<AuthStatus> {if (error instanceof HogError && error.code === 'not_authenticated') {return { authenticated: false, next: 'hog auth login' }}+ if (error instanceof HogError && error.code === 'session_expired') {+ return { authenticated: false, error: error.message, next: 'hog auth login' }+ }throw error}- const { host, projectId } = credentials.key- const { source } = credentials+ const { key, source } = credentials+ const { host, projectId } = key+ const { kind, scopes, expiresAt, rejected } = key.status()const api = await ctx.posthog()const [user, project] = await Promise.allSettled([api.get<{ email: string; first_name?: string }>('/api/users/@me/'),@@ -51,7 +60,7 @@ export async function checkAuthStatus(ctx: Context): Promise<AuthStatus> {host,projectId,source,- error: 'PostHog rejected the key. Someone may have deleted it.',+ error: rejected,next: 'hog auth login',}}@@ -65,9 +74,12 @@ export async function checkAuthStatus(ctx: Context): Promise<AuthStatus> {host,projectId,projectName: project.status === 'fulfilled' ? project.value.name : null,+ kind,source,store: credentials.source === 'store' ? credentials.store : null,credentialsPath: credentials.source === 'env' ? null : credentials.path,+ scopes,+ expiresAt: expiresAt === null ? null : new Date(expiresAt).toISOString(),user: user.status === 'fulfilled' ? { email: user.value.email, name: user.value.first_name || null } : null,}}diff --git a/hog/src/posthog/device-auth.ts b/hog/src/posthog/device-auth.tsindex 155542a447d6..8868daf86968 100644--- a/hog/src/posthog/device-auth.ts+++ b/hog/src/posthog/device-auth.ts@@ -1,100 +1,221 @@import type { PendingApproval, PollOutcome } from '@/core/approval'import { HogError } from '@/core/errors'+import { escapeControls } from '@/core/output'import type { Runtime } from '@/core/runtime'-import { sendRequest, type HttpResponse } from './api'+import { hostKey, hostUrl } from './host'+import { HOG_CLIENT_ID, OAuthLogin, oauthPost, type TokenResponse } from './oauth'-// 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 DEVICE_CODE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code'-const REQUEST_TIMEOUT_MS = 30_000+// What a new login asks for. hog sends this list explicitly, because a request without `scope`+// gets every scope hog's client may hold.+// TODO: add `ci_trust_policy_request:write` once PostHog has that scope, so `hog ci setup` works+// without a step-up.+const LOGIN_WRITE_SCOPES = [+ 'action',+ 'alert',+ 'annotation',+ 'cohort',+ 'dashboard',+ 'data_catalog',+ 'endpoint',+ 'error_tracking',+ 'event_definition',+ 'experiment',+ 'external_data_source',+ 'feature_flag',+ 'heatmap',+ 'hog_flow',+ 'hog_function',+ 'insight',+ 'insight_variable',+ 'llm_skill',+ 'marketing_analytics',+ 'notebook',+ 'person',+ 'product_enablement',+ 'project',+ 'property_definition',+ 'replay_scanner',+ 'session_recording_playlist',+ 'signal_scout',+ 'subscription',+ 'survey',+ 'task',+ 'warehouse_view',+]+const LOGIN_READ_SCOPES = [+ 'activity_log',+ 'batch_export',+ 'billing',+ 'business_knowledge',+ 'dashboard_template',+ 'early_access_feature',+ 'evaluation',+ 'experiment_saved_metric',+ 'group',+ 'health_issue',+ 'integration',+ 'llm_prompt',+ 'logs',+ 'mcp_analytics',+ 'organization',+ 'organization_member',+ 'query',+ 'session_recording',+ 'ticket',+ 'tracing',+ 'user',+ 'warehouse_table',+ 'web_analytics',+]+const LOGIN_IDENTITY_SCOPES = ['openid', 'profile', 'email']+export const LOGIN_SCOPES: readonly string[] = [+ ...LOGIN_IDENTITY_SCOPES,+ ...LOGIN_WRITE_SCOPES.map((object) => `${object}:write`),+ ...LOGIN_READ_SCOPES.map((object) => `${object}:read`),+]-// A login the person still has to approve in the browser. `deviceCode` retrieves the key once+// What `hog auth login --read-only` asks for: the same objects, read access only.+export const READ_ONLY_LOGIN_SCOPES: readonly string[] = [+ ...LOGIN_IDENTITY_SCOPES,+ ...[...LOGIN_WRITE_SCOPES, ...LOGIN_READ_SCOPES].map((object) => `${object}:read`),+]++// A login the person still has to approve in the browser. `deviceCode` redeems the tokens once// they approve, so it stays in a private file and never reaches the output.export interface PendingLogin extends PendingApproval {host: stringdeviceCode: stringuserCode: string-}--export interface Approval {- host: string- apiKey: string- projectId: stringscopes: string[]}-interface DeviceCodeResponse {- device_code: string- user_code: string- verification_uri_complete: string- expires_in: number- interval: number+// PostHog refuses a client it hasn't verified with `unauthorized_client`, and its description says why.+function unauthorizedClient(host: string, body: { error?: string; error_description?: unknown }): HogError | undefined {+ if (body.error !== 'unauthorized_client' || typeof body.error_description !== 'string') {+ return undefined+ }+ return new HogError(+ 'login_unavailable',+ `${host} won't log hog in: ${escapeControls(body.error_description)}`,+ 'Set HOG_PERSONAL_API_KEY and HOG_PROJECT_ID instead.'+ )}-interface PollResponse {- status?: 'pending' | 'authorized' | 'expired'- personal_api_key?: string- project_id?: string | number- scopes?: string[]+interface DeviceAuthorizationResponse {+ device_code?: string+ user_code?: string+ verification_uri?: string+ verification_uri_complete?: string+ expires_in?: number+ interval?: number}-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 })+// hog opens the approval page only on the host it logs in to. A server that names another origin could+// send the person to a look-alike page, and the code check wouldn't catch it: that server chose the code.+function approvalUrl(host: string, userCode: string, named: string): string {+ if (URL.canParse(named) && hostKey(named) === hostKey(host)) {+ return named+ }+ const url = hostUrl(host, 'device')+ url.searchParams.set('code', userCode)+ return url.toString()}-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) {+export async function startDeviceLogin(+ runtime: Runtime,+ host: string,+ scopes: readonly string[]+): Promise<PendingLogin> {+ const response = await oauthPost(runtime, host, 'oauth/device-authorization/', {+ client_id: HOG_CLIENT_ID,+ scope: scopes.join(' '),+ })+ if (response.status === 429) {+ throw new HogError(+ 'login_rate_limited',+ `${host} refused to start another login for now.`,+ 'Wait a minute, then run `hog auth login` again.'+ )+ }+ const body = (response.json ?? {}) as DeviceAuthorizationResponse & { error?: string; error_description?: unknown }+ const refused = unauthorizedClient(host, body)+ if (refused) {+ throw refused+ }+ if (!response.ok || !body.device_code || !body.user_code || !body.verification_uri || !body.expires_in) {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.'+ 'Check the host. A self-hosted PostHog must be able to reach posthog.com to log hog in. Otherwise set HOG_PERSONAL_API_KEY and HOG_PROJECT_ID.')}- 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(),+ url: approvalUrl(host, body.user_code, body.verification_uri_complete ?? body.verification_uri),expiresAt: runtime.now() + body.expires_in * 1000,- intervalSeconds: body.interval,+ intervalSeconds: body.interval ?? 5,+ scopes: [...scopes],}}+// One poll of the token endpoint, read the way RFC 8628 section 3.5 describes.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)+): Promise<PollOutcome<OAuthLogin>> {+ const response = await oauthPost(+ runtime,+ pending.host,+ 'oauth/token/',+ { grant_type: DEVICE_CODE_GRANT, device_code: pending.deviceCode, client_id: HOG_CLIENT_ID },+ timeoutMs+ )+ // A rate limit asks for slower polling, the same as RFC 8628's slow_down.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) {+ const body = (response.json ?? {}) as TokenResponse & { error?: string; error_description?: unknown }+ if (response.ok) {+ const projectId = body.scoped_teams?.[0]+ if (projectId === undefined || !body.refresh_token) {+ throw new HogError(+ 'unexpected_response',+ 'PostHog approved the login, but its answer had no project or no refresh token.',+ 'Run `hog auth login` to start again.'+ )+ }return {state: 'approved',- value: {+ value: OAuthLogin.fromTokens(runtime, body, {host: pending.host,- apiKey: body.personal_api_key,- projectId: String(body.project_id),- scopes: body.scopes ?? [],- },+ projectId: String(projectId),+ refreshToken: body.refresh_token,+ scopes: pending.scopes,+ }),}}- if (body.status === 'expired') {- return { state: 'expired' }+ switch (body.error) {+ case 'authorization_pending':+ return { state: 'pending' }+ case 'slow_down':+ return { state: 'slow_down' }+ case 'access_denied':+ return { state: 'rejected' }+ case 'expired_token':+ return { state: 'expired' }+ }+ const refused = unauthorizedClient(pending.host, body)+ if (refused) {+ throw refused}throw new HogError('login_failed',diff --git a/hog/src/posthog/login/flow.ts b/hog/src/posthog/login/flow.tsindex f6dfb86f6f42..82f26fc7ce02 100644--- a/hog/src/posthog/login/flow.ts+++ b/hog/src/posthog/login/flow.ts@@ -1,13 +1,13 @@-import { clearPending, type ApprovalFlow } from '@/core/approval'+import { clearPending, type ApprovalFlow, type ApprovalWait } from '@/core/approval'import { HogError } from '@/core/errors'import type { Runtime } from '@/core/runtime'-import type { AccessKey } from '@/posthog/access-key'+import type { AccessKey, AccessKeyStatus } 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 { pollDeviceLogin, startDeviceLogin, type Approval, type PendingLogin } from '@/posthog/device-auth'-import { withLoginLock } from '@/posthog/oauth'+import { pollDeviceLogin, startDeviceLogin, type PendingLogin } from '@/posthog/device-auth'+import { withLoginLock, type OAuthLogin } from '@/posthog/oauth'import { loginFor, readSettings } from '@/posthog/settings'import { writeLogin } from './stored'@@ -22,26 +22,32 @@ export interface LoggedIn {credentialsPath: string | null// Why hog couldn't use the keychain, when it stored the credentials in a file.keychainError: string | null- scopes: string[]+ status: AccessKeyStatus}-// 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> {+// What `hog auth login --wait` needs to finish the login a previous run started.+export function loginWait(runtime: Runtime): ApprovalWait<PendingLogin, OAuthLogin> {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),}}+// An agent that retries `hog auth login` for the same host gets the same code back, so the link it+// already shared keeps working.+export function loginFlow(+ runtime: Runtime,+ host: string,+ scopes: readonly string[]+): ApprovalFlow<PendingLogin, OAuthLogin> {+ return {+ ...loginWait(runtime),+ start: () => startDeviceLogin(runtime, host, scopes),+ reuse: (existing) => existing.host === host && existing.scopes?.join(' ') === scopes.join(' '),+ }+}+// Each login probes the keychain again, so a login at the desk moves credentials out of the file a// login over SSH had to use. Clears any pending login too, so a later `--wait` can't replace these// credentials with an older approval.@@ -80,6 +86,6 @@ export async function saveLogin(runtime: Runtime, unverified: AccessKey): Promisstore: store.kind,credentialsPath: store.path,keychainError,- scopes: [],+ status: key.status(),}}diff --git a/hog/src/posthog/oauth.ts b/hog/src/posthog/oauth.tsindex 6d44b8e43f1e..5a4ae3d44824 100644--- a/hog/src/posthog/oauth.ts+++ b/hog/src/posthog/oauth.ts@@ -1,5 +1,7 @@import { createHash, randomUUID } from 'node:crypto'+import type { ApiKeyAccess } from '@posthog/mcp/src/cli/library-types'+import { HogError } from '@/core/errors'import { withFileLock } from '@/core/file-lock'import type { Runtime } from '@/core/runtime'@@ -197,7 +199,17 @@ export class OAuthLogin implements AccessKey {}status(): AccessKeyStatus {- return { kind: 'oauth', scopes: this.scopes, expiresAt: this.expiresAt }+ return {+ kind: 'oauth',+ scopes: this.scopes,+ expiresAt: this.expiresAt,+ rejected: 'PostHog rejected the token. Someone may have revoked it.',+ }+ }++ // A login works in the one project it was approved for.+ access(): ApiKeyAccess {+ return { scopes: this.scopes, scopedTeams: [Number(this.projectId)], scopedOrganizations: [] }}// Revoking the refresh token ends this login: PostHog revokes its access tokens with it.