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): keep credentials in the system keychain (#127796)

Rafael Audibert40e2a3e187e3
diff --git a/hog/MIGRATING.md b/hog/MIGRATING.md
index 828c8596941e..9d81c7f489e3 100644
--- a/hog/MIGRATING.md
+++ b/hog/MIGRATING.md
@@ -8,7 +8,7 @@ Most moves take three steps: install hog, rename the environment variables, and
## What stays the same
-- **Your login.** Both CLIs read and write `~/.posthog/credentials.json`, so `posthog-cli login` works for hog, and `hog auth login` works for posthog-cli.
+- **Your login.** Run `hog auth migrate` once. It moves the key `posthog-cli login` saved in `~/.posthog/credentials.json` into hog's store, so you don't have to log in again. It checks the key with PostHog first, and a key PostHog rejects stays out of hog's store. hog doesn't read that file otherwise and never changes it.
- **Uploads.** hog sends the same bytes and content hashes, so either CLI can re-upload what the other uploaded. Chunk IDs and releases don't change.
- **posthog.json.** hog reads the `languages` entries `posthog-cli exp schema` writes, and the endpoint YAML files `posthog-cli exp endpoints` writes.
- **Global flags.** `--host`, `--dotenv-file`, `--no-fail`, `--skip-ssl-verification` and `--rate-limit` work as before, before or after the command.
diff --git a/hog/README.md b/hog/README.md
index 7fe430764770..9381d04bdfe0 100644
--- a/hog/README.md
+++ b/hog/README.md
@@ -16,6 +16,7 @@ The commands `posthog-cli` keeps under `exp` (`query`, `endpoints`, `logs`, `tas
| `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 auth migrate` | Moves the key `posthog-cli login` saved into hog's store, so you don't have to log in again. |
| `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 api groups`, `hog api tools [group]` | List the PostHog MCP tools by group, with the scopes the key is missing for each. |
@@ -179,20 +180,26 @@ hog uploads the same bytes and content hashes as posthog-cli, so either CLI can
## Credentials
-`hog` reads credentials in the same order as `posthog-cli`, with `HOG_` variable names:
+`hog` reads credentials from these sources, in order:
1. `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. `~/.posthog/credentials.json`, which `hog auth login` and `posthog-cli login` write (`HOG_HOME` moves the folder). `hog auth login` makes it readable only by you.
+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.
-`--host` and `HOG_HOST` override the host from any of these.
+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.
+
+`--host` and `HOG_HOST` override the host from any of these, and pick which stored login to use.
+A `host` in `posthog.json` also picks a stored login, but never sends a key to a host it wasn't made for.
+
+hog's folder is `~/Library/Application Support/hog` on macOS, `$XDG_CONFIG_HOME/hog` or `~/.config/hog` on Linux, and `%LOCALAPPDATA%\hog` on Windows.
### 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".
- 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.
+- `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.
## Develop
@@ -208,4 +215,4 @@ pnpm --filter @posthog/hog typecheck # check types
pnpm --filter @posthog/hog compile # build dist/hog for this machine
```
-hog reads credentials only from the sources above, like posthog-cli. Bun would otherwise load a `.env` or `bunfig.toml` from the working folder, so the scripts turn that off. Older Bun versions ignore those flags, hence the minimum version.
+hog reads credentials only from the sources above. Runs from source keep their keychain items under their own name, so they never read or replace an installed hog's login. Bun would otherwise load a `.env` or `bunfig.toml` from the working folder, so the scripts turn that off. Older Bun versions ignore those flags, hence the minimum version.
diff --git a/hog/src/cli.test.ts b/hog/src/cli.test.ts
index 608f31277b3d..02a64e49ca51 100644
--- a/hog/src/cli.test.ts
+++ b/hog/src/cli.test.ts
@@ -96,6 +96,7 @@ describe('hog', () => {
expect(manifest.commands.map((command: { name: string }) => command.name)).toEqual([
'auth login',
'auth logout',
+ 'auth migrate',
'auth status',
'query run',
'query check',
diff --git a/hog/src/cli.ts b/hog/src/cli.ts
index fb55fc7d8369..03ce4f196602 100644
--- a/hog/src/cli.ts
+++ b/hog/src/cli.ts
@@ -178,7 +178,10 @@ function createProgram(runtime: Runtime, mode: Mode, state: RunState, telemetry:
if (globals.noTelemetry) {
telemetry.disable()
}
- telemetry.credentials = () => resolveCredentials({ ...runtime, writeStderr: () => {} }, globals)
+ let ctx: Context | undefined
+ telemetry.credentials = () =>
+ ctx?.requestedCredentials ??
+ resolveCredentials({ ...runtime, writeStderr: () => {} }, { ...globals, skipStore: true })
const commandRuntime = networkRuntime(runtime, globals)
const options = self.opts()
if (envFlag(runtime.env, DRY_RUN_ENV)) {
@@ -200,7 +203,7 @@ function createProgram(runtime: Runtime, mode: Mode, state: RunState, telemetry:
args[name] = spec.stdin && value !== undefined ? await readArgument(runtime, name, value) : value
}
- const ctx = new Context(commandRuntime, globals, mode, COMMANDS, config, telemetry)
+ ctx = new Context(commandRuntime, globals, mode, COMMANDS, config, telemetry)
let result: unknown
try {
result = await node.run({ args, options, ctx })
diff --git a/hog/src/commands/auth/auth.test.ts b/hog/src/commands/auth/auth.test.ts
index 1ef27a138299..6044200e4532 100644
--- a/hog/src/commands/auth/auth.test.ts
+++ b/hog/src/commands/auth/auth.test.ts
@@ -1,8 +1,11 @@
import { describe, expect, test } from 'bun:test'
+import type { Secrets } from '@/core/runtime'
import { runHog } from '@/testing'
-const CREDENTIALS_FILE = '/home/test/.posthog/credentials.json'
+const LEGACY_CLI_FILE = '/home/test/.posthog/credentials.json'
+const SETTINGS_FILE = '/home/test/.config/hog/settings.json'
+const HOG_CREDENTIALS_FILE = '/home/test/.config/hog/credentials.json'
const PENDING_FILE = '/home/test/.posthog/login-pending.json'
const DEVICE_CODE = 'device-secret-123'
@@ -111,7 +114,7 @@ describe('hog auth login', () => {
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 () => {
+ test('--wait saves the key in the keychain once the person approves', async () => {
const result = await runHog(['auth', 'login', '--wait'], {
env: { CLAUDECODE: '1' },
files: { [PENDING_FILE]: PENDING },
@@ -121,15 +124,80 @@ 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')
- expect(JSON.parse(result.files[CREDENTIALS_FILE] ?? '{}')).toEqual({
+ // 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(JSON.parse(result.files[SETTINGS_FILE] ?? '{}')).toEqual({
+ logins: {
+ 'https://eu.posthog.com': {
+ store: 'keychain',
+ type: 'personal_api_key',
+ projectId: '42',
+ host: 'https://eu.posthog.com',
+ },
+ },
host: 'https://eu.posthog.com',
- token: 'phx_secret',
- env_id: '42',
})
+ expect(result.files[LEGACY_CLI_FILE]).toBeUndefined()
expect(result.files[PENDING_FILE]).toBeUndefined()
- expect(result.requests.filter((request) => request.url.endsWith('/poll/'))).toHaveLength(3)
+ // Only polls: a key PostHog just issued skips the key check.
+ expect(result.requests.map((request) => request.url.endsWith('/poll/'))).toEqual([true, true, true])
})
+ const denied = Object.assign(new Error('User canceled'), { code: 'ERR_SECRETS_USER_CANCELED' })
+ test.each([
+ [
+ 'is unavailable',
+ Object.assign(new Error('no Secret Service'), { code: 'ERR_SECRETS_PLATFORM_ERROR' }),
+ false,
+ ],
+ ['is denied', denied, false],
+ // 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',
+ async (_name, failure, probeWorks) => {
+ const items = new Map<string, string>()
+ const check = (name: string): void => {
+ if (!probeWorks || name.startsWith('https://')) {
+ throw failure
+ }
+ }
+ const broken: Secrets = {
+ get: async (name) => {
+ check(name)
+ return items.get(name) ?? null
+ },
+ set: async (name, value) => {
+ check(name)
+ items.set(name, value)
+ },
+ delete: async (name) => {
+ check(name)
+ return items.delete(name)
+ },
+ }
+ const result = await runHog(['auth', 'login', '--wait'], {
+ env: { CLAUDECODE: '1' },
+ files: { [PENDING_FILE]: PENDING },
+ respond: deviceFlow(0),
+ secrets: () => broken,
+ })
+
+ expect(result.exitCode).toBe(0)
+ expect(result.json()).toMatchObject({
+ store: 'file',
+ credentialsPath: HOG_CREDENTIALS_FILE,
+ keychainError: expect.stringContaining('keychain'),
+ })
+ expect(JSON.parse(result.files[HOG_CREDENTIALS_FILE] ?? '{}')).toEqual({
+ 'https://eu.posthog.com': { apiKey: 'phx_secret' },
+ })
+ expect(JSON.parse(result.files[SETTINGS_FILE] ?? '{}')).toMatchObject({
+ logins: { 'https://eu.posthog.com': { store: 'file', projectId: '42' } },
+ })
+ }
+ )
+
test.each([
[
'stops when the code expires and forgets it',
@@ -152,7 +220,7 @@ describe('hog auth login', () => {
expect(result.exitCode).toBe(1)
expect(result.error()).toMatchObject({ code })
expect(result.files[PENDING_FILE] !== undefined).toBe(keepsPending)
- expect(result.files[CREDENTIALS_FILE]).toBeUndefined()
+ expect(result.keychain).toEqual({})
})
test.each([
@@ -176,14 +244,26 @@ 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.files[CREDENTIALS_FILE] ?? '{}')).toMatchObject({
- host,
- token: 'phx_secret',
- env_id: '42',
- })
+ expect(JSON.parse(result.keychain[host] ?? '{}')).toEqual({ apiKey: 'phx_secret' })
})
const STORED = JSON.stringify({ host: 'https://eu.posthog.com', token: 'phx_secret', env_id: '42' })
+ const KEYCHAIN_LOGIN = {
+ files: {
+ [SETTINGS_FILE]: JSON.stringify({
+ logins: {
+ 'https://eu.posthog.com': {
+ store: 'keychain',
+ type: 'personal_api_key',
+ projectId: '42',
+ host: 'https://eu.posthog.com',
+ },
+ },
+ host: 'https://eu.posthog.com',
+ }),
+ },
+ keychain: { 'https://eu.posthog.com': JSON.stringify({ apiKey: 'phx_secret' }) },
+ }
test.each([
[
@@ -198,7 +278,7 @@ describe('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 },
+ ...KEYCHAIN_LOGIN,
respond: (url) =>
url.endsWith('/api/users/@me/')
? { status: userStatus, body: { email: '[email protected]' } }
@@ -209,11 +289,24 @@ 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',
+ async (_name, { files, keychain }, expected) => {
+ const result = await runHog(['auth', 'status'], {
+ env: { CLAUDECODE: '1' },
+ files,
+ keychain,
+ respond: () => ({ status: 200, body: { email: '[email protected]', name: 'Shop' } }),
+ })
+ expect(result.json()).toMatchObject({ authenticated: true, ...expected })
+ }
+ )
+
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 },
+ ...KEYCHAIN_LOGIN,
respond: (url) =>
url.endsWith('/api/users/@me/')
? { status: 200, body: { email: '[email protected]' } }
@@ -226,7 +319,7 @@ describe('hog auth login', () => {
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 },
+ ...KEYCHAIN_LOGIN,
respond: (url) => (url.endsWith('/api/users/@me/') ? { status: 403, body: {} } : { status: 500, body: {} }),
})
expect(result.exitCode).toBe(1)
@@ -242,7 +335,7 @@ describe('hog auth login', () => {
test.each([
[
'a stored key',
- { [CREDENTIALS_FILE]: STORED, [PENDING_FILE]: PENDING },
+ { ...KEYCHAIN_LOGIN.files, [PENDING_FILE]: PENDING },
{},
'logged_out',
'https://eu.posthog.com/settings/user-api-keys',
@@ -250,18 +343,232 @@ describe('hog auth login', () => {
],
['no stored key', {}, {}, 'not_logged_in', null, []],
[
- 'a key in the environment',
- { [CREDENTIALS_FILE]: STORED },
+ 'a file login whose file entry is gone, but whose old keychain item is still there',
+ {
+ [SETTINGS_FILE]: JSON.stringify({
+ logins: {
+ 'https://eu.posthog.com': {
+ store: 'file',
+ type: 'personal_api_key',
+ projectId: '42',
+ host: 'https://eu.posthog.com',
+ keychainLeftover: true,
+ },
+ },
+ host: 'https://eu.posthog.com',
+ }),
+ },
+ {},
+ 'logged_out',
+ null,
+ [],
+ ],
+ [
+ 'a posthog.json host that is not the last login',
+ {
+ [SETTINGS_FILE]: JSON.stringify({
+ logins: {
+ 'https://eu.posthog.com': {
+ store: 'keychain',
+ type: 'personal_api_key',
+ projectId: '42',
+ host: 'https://eu.posthog.com',
+ },
+ 'https://us.posthog.com': {
+ store: 'keychain',
+ type: 'personal_api_key',
+ projectId: '42',
+ host: 'https://us.posthog.com',
+ },
+ },
+ host: 'https://us.posthog.com',
+ }),
+ '/work/posthog.json': JSON.stringify({ host: 'https://eu.posthog.com' }),
+ },
+ {},
+ 'logged_out',
+ 'https://eu.posthog.com/settings/user-api-keys',
+ [],
+ ],
+ [
+ "a key in the environment and posthog-cli's file, which hog leaves alone",
+ { ...KEYCHAIN_LOGIN.files, [LEGACY_CLI_FILE]: STORED },
{ HOG_PERSONAL_API_KEY: 'phx_env' },
'logged_out',
'https://eu.posthog.com/settings/user-api-keys',
['HOG_PERSONAL_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 })
+ ])(
+ 'logout with %s removes what hog stored',
+ async (_name, files: Record<string, string>, env, status, revokeUrl, stillSet) => {
+ const result = await runHog(['auth', 'logout'], {
+ env: { CLAUDECODE: '1', ...env },
+ files,
+ keychain: KEYCHAIN_LOGIN.keychain,
+ })
+ expect(result.exitCode).toBe(0)
+ expect(result.json()).toMatchObject({ status, revokeUrl, stillSet })
+ expect(result.keychain).toEqual(files[SETTINGS_FILE] ? {} : KEYCHAIN_LOGIN.keychain)
+ expect(result.files[PENDING_FILE]).toBeUndefined()
+ expect(result.files[LEGACY_CLI_FILE]).toBe(files[LEGACY_CLI_FILE])
+ }
+ )
+
+ 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]])
+ const keychainWorks = { now: false }
+ const secrets: Secrets = {
+ get: async (name) => items.get(name) ?? null,
+ set: async (name, value) => {
+ if (!keychainWorks.now) {
+ throw Object.assign(new Error('denied'), { code: 'ERR_SECRETS_USER_CANCELED' })
+ }
+ items.set(name, value)
+ },
+ delete: async (name) => {
+ if (!keychainWorks.now) {
+ throw Object.assign(new Error('denied'), { code: 'ERR_SECRETS_USER_CANCELED' })
+ }
+ return items.delete(name)
+ },
+ }
+ const login = await runHog(['auth', 'login', '--wait'], {
+ env: { CLAUDECODE: '1' },
+ files: { ...KEYCHAIN_LOGIN.files, [PENDING_FILE]: PENDING },
+ respond: deviceFlow(0),
+ secrets: () => secrets,
+ })
+ expect(login.json()).toMatchObject({ store: 'file' })
+
+ const denied = await runHog(['auth', 'logout'], {
+ env: { CLAUDECODE: '1' },
+ files: login.files,
+ secrets: () => secrets,
+ })
+ expect(denied.json()).toMatchObject({
+ status: 'logged_out',
+ keychainLeftover: expect.stringContaining('keychain'),
+ })
+ expect(items.get('https://eu.posthog.com')).toBe(oldItem)
+
+ keychainWorks.now = true
+ const removed = await runHog(['auth', 'logout'], {
+ env: { CLAUDECODE: '1' },
+ files: login.files,
+ secrets: () => secrets,
+ })
+ expect(removed.json()).toMatchObject({ status: 'logged_out', keychainLeftover: null })
+ expect(items.size).toBe(0)
+ })
+
+ test('logout --all removes every login, and the leftovers settings.json no longer names', async () => {
+ const record = (host: string, store: string): Record<string, string> => ({
+ store,
+ type: 'personal_api_key',
+ projectId: '42',
+ host,
+ })
+ const result = await runHog(['auth', 'logout', '--all'], {
+ env: { CLAUDECODE: '1' },
+ files: {
+ [SETTINGS_FILE]: JSON.stringify({
+ logins: {
+ 'https://eu.posthog.com': record('https://eu.posthog.com', 'keychain'),
+ 'https://us.posthog.com': {
+ ...record('https://us.posthog.com', 'file'),
+ keychainLeftover: true,
+ },
+ },
+ host: 'https://us.posthog.com',
+ }),
+ [HOG_CREDENTIALS_FILE]: JSON.stringify({
+ 'https://us.posthog.com': { apiKey: 'phx_us' },
+ 'https://posthog.example.com': { apiKey: 'phx_orphan' },
+ }),
+ [PENDING_FILE]: PENDING,
+ },
+ keychain: {
+ ...KEYCHAIN_LOGIN.keychain,
+ 'https://us.posthog.com': JSON.stringify({ apiKey: 'phx_before_fallback' }),
+ 'https://posthog.example.com': JSON.stringify({ apiKey: 'phx_before_settings_were_lost' }),
+ },
+ })
+
expect(result.exitCode).toBe(0)
- expect(result.json()).toMatchObject({ status, revokeUrl, stillSet })
- expect(result.files[CREDENTIALS_FILE]).toBeUndefined()
+ expect(result.json()).toMatchObject({
+ status: 'logged_out',
+ hosts: [
+ { host: 'https://eu.posthog.com', revokeUrl: 'https://eu.posthog.com/settings/user-api-keys' },
+ { host: 'https://us.posthog.com', revokeUrl: 'https://us.posthog.com/settings/user-api-keys' },
+ { host: 'https://posthog.example.com', revokeUrl: null },
+ ],
+ })
+ expect(result.keychain).toEqual({})
+ expect(result.files[HOG_CREDENTIALS_FILE]).toBeUndefined()
+ expect(JSON.parse(result.files[SETTINGS_FILE] ?? '{}')).toEqual({ logins: {} })
expect(result.files[PENDING_FILE]).toBeUndefined()
})
+
+ test.each([
+ [
+ "a key posthog-cli saved moves into the keychain, and posthog-cli's file stays",
+ { [LEGACY_CLI_FILE]: STORED },
+ 200,
+ 0,
+ { status: 'migrated', host: 'https://eu.posthog.com', projectId: '42', store: 'keychain' },
+ ],
+ [
+ 'nothing to move points to login',
+ {},
+ 200,
+ 0,
+ { status: 'nothing_to_migrate', legacyFile: LEGACY_CLI_FILE, next: 'hog auth login' },
+ ],
+ [
+ 'a broken file fails with a hint',
+ { [LEGACY_CLI_FILE]: JSON.stringify({ token: 'abc', env_id: '42' }) },
+ 200,
+ 1,
+ { code: 'invalid_legacy_credentials', hint: expect.any(String) },
+ ],
+ [
+ 'a self-hosted key is checked under the path PostHog sits under',
+ {
+ [LEGACY_CLI_FILE]: JSON.stringify({
+ host: 'https://example.com/posthog',
+ token: 'phx_secret',
+ env_id: '42',
+ }),
+ },
+ 200,
+ 0,
+ { status: 'migrated', host: 'https://example.com/posthog', store: 'keychain' },
+ ],
+ [
+ 'a key PostHog rejects stays out of the store',
+ { [LEGACY_CLI_FILE]: STORED },
+ 401,
+ 1,
+ { code: 'key_rejected', hint: expect.stringContaining('hog auth login') },
+ ],
+ ])('migrate: %s', async (_name, files: Record<string, string>, keyStatus, exitCode, expected) => {
+ const result = await runHog(['auth', 'migrate'], {
+ env: { CLAUDECODE: '1' },
+ files,
+ respond: (url) =>
+ [
+ 'https://eu.posthog.com/api/personal_api_keys/@current/',
+ 'https://example.com/posthog/api/personal_api_keys/@current/',
+ ].includes(url)
+ ? { status: keyStatus, body: keyStatus === 200 ? { scopes: ['query:read'] } : {} }
+ : { status: 404, body: {} },
+ })
+
+ expect(result.exitCode).toBe(exitCode)
+ expect(exitCode === 0 ? result.json() : result.error()).toMatchObject(expected)
+ expect(result.files[LEGACY_CLI_FILE]).toBe(files[LEGACY_CLI_FILE])
+ const migrated = exitCode === 0 && files[LEGACY_CLI_FILE] !== undefined
+ expect(Object.values(result.keychain)).toEqual(migrated ? [JSON.stringify({ apiKey: 'phx_secret' })] : [])
+ })
})
diff --git a/hog/src/commands/auth/index.ts b/hog/src/commands/auth/index.ts
index b46670be86ea..b0c26fe90f10 100644
--- a/hog/src/commands/auth/index.ts
+++ b/hog/src/commands/auth/index.ts
@@ -2,9 +2,10 @@ import { defineGroup } from '@/core/command'
import login from './login'
import logout from './logout'
+import migrate from './migrate'
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 },
+ commands: { login, logout, migrate, status },
})
diff --git a/hog/src/commands/auth/login.ts b/hog/src/commands/auth/login.ts
index f0eb31866356..59fcff4dcc2d 100644
--- a/hog/src/commands/auth/login.ts
+++ b/hog/src/commands/auth/login.ts
@@ -3,9 +3,12 @@ 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 { PersonalAPIKey } from '@/posthog/access-key'
+import type { StoreChoice } from '@/posthog/credential-store/types'
import { checkApiKey, checkHost, checkProjectId } from '@/posthog/credentials'
import type { PendingLogin } from '@/posthog/device-auth'
-import { completeLogin, readPendingLogin, saveLogin, startLogin, type LoggedIn } from '@/posthog/login'
+import { trimHost } from '@/posthog/host'
+import { completeLogin, readPendingLogin, saveLogin, startLogin, type LoggedIn } from '@/posthog/login/flow'
const REGIONS = { us: 'https://us.posthog.com', eu: 'https://eu.posthog.com' } as const
@@ -34,11 +37,15 @@ type LoginResult =
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'
-}
+ | {
+ status: 'logged_in'
+ host: string
+ projectId: string
+ store: StoreChoice
+ credentialsPath: string | null
+ keychainError: string | null
+ next: string
+ }
function nextCommand(scopes: readonly string[]): string {
const canQuery = scopes.some((scope) => scope === '*' || scope.startsWith('query:'))
@@ -58,8 +65,8 @@ function pendingResult(pending: PendingLogin): LoginResult {
}
function loggedInResult(loggedIn: LoggedIn): LoginResult {
- const { host, projectId, credentialsPath, scopes } = loggedIn
- return { status: 'logged_in', host, projectId, credentialsPath, next: nextCommand(scopes) }
+ const { host, projectId, store, credentialsPath, keychainError, scopes } = loggedIn
+ return { status: 'logged_in', host, projectId, store, credentialsPath, keychainError, next: nextCommand(scopes) }
}
async function finish(ctx: Context, pending: PendingLogin, spinner?: Spinner): Promise<LoginResult> {
@@ -78,11 +85,12 @@ 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(/\/+$/, '') }))
+ const key = new PersonalAPIKey({ host: trimHost(host), projectId, apiKey })
+ return loggedInResult(await saveLogin(ctx.runtime, key))
}
export default defineCommand({
- description: 'Log in to PostHog and store a personal API key on this machine',
+ description: 'Log in to PostHog',
writes: true,
options: {
region: {
@@ -100,6 +108,7 @@ export default defineCommand({
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.',
'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'],
@@ -120,7 +129,7 @@ export default defineCommand({
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)) {
+ if (!prompts && ctx.mode.agent === undefined && ctx.mode.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.',
@@ -190,7 +199,17 @@ export default defineCommand({
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'))
+ switch (result.store) {
+ case 'keychain':
+ out.line(out.style('Credentials saved to the system keychain', 'dim'))
+ break
+ case 'file':
+ if (result.keychainError) {
+ out.line(out.style(`${escapeControls(result.keychainError).replace(/\.$/, '')}.`, 'yellow'))
+ }
+ out.line(out.style(`Credentials saved to ${result.credentialsPath}, which only you can read`, 'dim'))
+ break
+ }
out.line(`Try it: ${result.next}`)
},
})
diff --git a/hog/src/commands/auth/logout.ts b/hog/src/commands/auth/logout.ts
index 5cc32d2ef8ed..eac33f716ecb 100644
--- a/hog/src/commands/auth/logout.ts
+++ b/hog/src/commands/auth/logout.ts
@@ -1,11 +1,18 @@
import { defineCommand } from '@/core/command'
-import { PERSONAL_API_KEY_ENV_VAR, posthogFile } from '@/posthog/credentials'
-import { clearPendingLogin } from '@/posthog/login'
+import { escapeControls } from '@/core/output'
+import { PERSONAL_API_KEY_ENV_VAR } from '@/posthog/credentials'
+import { clearPendingLogin } from '@/posthog/login/flow'
+import { logout, logoutAll, type LoggedOutHost } from '@/posthog/login/stored'
+import { readSettings } from '@/posthog/settings'
interface LogoutResult {
status: 'logged_out' | 'not_logged_in'
- credentialsPath: string
+ host: string | null
revokeUrl: string | null
+ // Why hog couldn't remove the keychain item a file login left behind. Null when there was none.
+ keychainLeftover: string | null
+ // Every host `--all` logged out of. Null without `--all`.
+ hosts: LoggedOutHost[] | null
// Variables that still give hog a key after logout.
stillSet: string[]
}
@@ -14,37 +21,55 @@ export default defineCommand({
description: 'Remove the personal API key hog stored on this machine',
writes: true,
notes: 'The key itself stays valid until you delete it in PostHog under Settings > Personal API keys.',
- examples: ['hog auth logout'],
+ options: {
+ all: { type: 'boolean', description: 'Log out of every PostHog host hog has a login for' },
+ },
+ examples: ['hog auth logout', 'hog auth logout --host https://eu.posthog.com', 'hog auth logout --all'],
- async run({ ctx }): Promise<LogoutResult> {
+ async run({ options, 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
+ const stillSet = runtime.env[PERSONAL_API_KEY_ENV_VAR] ? [PERSONAL_API_KEY_ENV_VAR] : []
+ if (options.all) {
+ const hosts = await logoutAll(runtime)
+ await clearPendingLogin(runtime)
+ const status = hosts.length > 0 ? 'logged_out' : 'not_logged_in'
+ return { status, host: null, revokeUrl: null, keychainLeftover: null, hosts, stillSet }
}
- await runtime.removeFile(credentialsPath)
+ const settings = await readSettings(runtime)
+ // The same host order commands use, so logout removes the login they would send. A broken
+ // posthog.json must not stop a logout.
+ const configHost = (await ctx.config().catch(() => undefined))?.config.host
+ const host = ctx.globals.host ?? configHost ?? settings.host
+ const outcome = host ? await logout(runtime, host) : undefined
await clearPendingLogin(runtime)
return {
- status: stored ? 'logged_out' : 'not_logged_in',
- credentialsPath,
- revokeUrl: host ? new URL('settings/user-api-keys', `${host.replace(/\/+$/, '')}/`).toString() : null,
- stillSet: runtime.env[PERSONAL_API_KEY_ENV_VAR] ? [PERSONAL_API_KEY_ENV_VAR] : [],
+ status: outcome ? 'logged_out' : 'not_logged_in',
+ host: host ?? null,
+ revokeUrl: outcome?.revokeUrl ?? null,
+ keychainLeftover: outcome?.keychainLeftover ?? null,
+ hosts: null,
+ stillSet,
}
},
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'))
+ const loggedOut = result.hosts ?? (result.host && result.status === 'logged_out' ? [result] : [])
+ if (loggedOut.length === 0) {
+ out.line('hog had no stored key to remove.')
+ }
+ for (const { host, revokeUrl, keychainLeftover } of loggedOut) {
+ out.line(`${out.style('Logged out', 'green', 'bold')} of ${escapeControls(host ?? '')}.`)
+ if (keychainLeftover) {
+ out.line(
+ out.style(
+ `hog couldn't remove an older copy of the key from the keychain: ${keychainLeftover} Remove the hog item for ${escapeControls(host ?? '')} from the keychain yourself.`,
+ 'yellow'
+ )
+ )
+ }
+ if (revokeUrl) {
+ out.line(out.style(`The key still works until you delete it at ${revokeUrl}`, 'dim'))
+ }
}
if (result.stillSet.length > 0) {
out.line(
diff --git a/hog/src/commands/auth/migrate.ts b/hog/src/commands/auth/migrate.ts
new file mode 100644
index 000000000000..dc3187c6de25
--- /dev/null
+++ b/hog/src/commands/auth/migrate.ts
@@ -0,0 +1,82 @@
+import { defineCommand } from '@/core/command'
+import { HogError } from '@/core/errors'
+import { escapeControls } from '@/core/output'
+import { PersonalAPIKey } from '@/posthog/access-key'
+import { parseJson } from '@/posthog/credential-store/helpers'
+import type { StoreChoice } from '@/posthog/credential-store/types'
+import { checkApiKey, checkHost, checkProjectId, DEFAULT_HOST, posthogFile } from '@/posthog/credentials'
+import { trimHost } from '@/posthog/host'
+import { saveLogin } from '@/posthog/login/flow'
+
+type MigrateResult =
+ | {
+ status: 'migrated'
+ host: string
+ projectId: string
+ store: StoreChoice
+ credentialsPath: string | null
+ keychainError: string | null
+ // The file the key came from, which hog leaves as it was.
+ legacyFile: string
+ }
+ | { status: 'nothing_to_migrate'; legacyFile: string; next: string }
+
+// TODO(v1.1): drop this command. It exists so people moving from posthog-cli keep their key
+// without logging in again, and hog reads the old file nowhere else.
+export default defineCommand({
+ description: 'Move the personal API key posthog-cli saved into hog',
+ writes: true,
+ notes: [
+ 'Reads ~/.posthog/credentials.json, the file `posthog-cli login` writes, and saves its key the way `hog auth login` saves one.',
+ 'hog never reads that file otherwise, and leaves it as it is.',
+ ].join('\n'),
+ examples: ['hog auth migrate'],
+
+ async run({ ctx }): Promise<MigrateResult> {
+ const { runtime } = ctx
+ const legacyFile = posthogFile(runtime, 'credentials.json')
+ let text: string
+ try {
+ text = await runtime.readFile(legacyFile)
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
+ return { status: 'nothing_to_migrate', legacyFile, next: 'hog auth login' }
+ }
+ throw error
+ }
+ const stored = parseJson(text) as { token?: unknown; env_id?: unknown; host?: unknown } | null | undefined
+ const apiKey = typeof stored?.token === 'string' ? stored.token : ''
+ const projectId = stored?.env_id === undefined ? '' : String(stored.env_id)
+ const host = trimHost(typeof stored?.host === 'string' ? stored.host : DEFAULT_HOST)
+ const problem = checkApiKey(apiKey) ?? checkProjectId(projectId) ?? checkHost(host)
+ if (problem) {
+ throw new HogError(
+ 'invalid_legacy_credentials',
+ `hog couldn't move the key in ${legacyFile}. ${problem}`,
+ 'Run `hog auth login` to log in instead.'
+ )
+ }
+ const key = new PersonalAPIKey({ host, projectId, apiKey })
+ const loggedIn = await saveLogin(runtime, key)
+ const { store, credentialsPath, keychainError } = loggedIn
+ return { status: 'migrated', host, projectId, store, credentialsPath, keychainError, legacyFile }
+ },
+
+ human({ result, out }) {
+ if (result.status === 'nothing_to_migrate') {
+ out.line(`There is nothing to move: ${result.legacyFile} doesn't exist.`)
+ out.line(`Run ${out.style(result.next, 'bold')} to log in.`)
+ return
+ }
+ const where = result.store === 'keychain' ? 'the system keychain' : (result.credentialsPath ?? '')
+ out.line(
+ `${out.style('Moved', 'green', 'bold')} the personal API key for ${escapeControls(result.host)}, project ${result.projectId}, into ${where}.`
+ )
+ if (result.keychainError) {
+ out.line(out.style(`${escapeControls(result.keychainError).replace(/\.$/, '')}.`, 'yellow'))
+ }
+ out.line(
+ out.style(`hog no longer reads ${result.legacyFile}. Delete it once posthog-cli doesn't need it.`, 'dim')
+ )
+ },
+})
diff --git a/hog/src/commands/auth/status.ts b/hog/src/commands/auth/status.ts
index 58cfbda38b0f..2fb8bfa8b273 100644
--- a/hog/src/commands/auth/status.ts
+++ b/hog/src/commands/auth/status.ts
@@ -1,12 +1,18 @@
import { defineCommand } from '@/core/command'
import { escapeControls } from '@/core/output'
import { checkAuthStatus } from '@/posthog/auth-status'
+import type { StoreChoice } from '@/posthog/credential-store/types'
import type { CredentialSource } from '@/posthog/credentials'
-const SOURCE_LABELS: Record<CredentialSource, string> = {
- env: 'the HOG_PERSONAL_API_KEY environment variable',
- 'dotenv-file': 'the --dotenv-file file',
- 'credentials-file': 'the credentials file',
+function sourceLabel(source: CredentialSource, store: StoreChoice | null, path: string | null): string {
+ switch (source) {
+ case 'env':
+ return 'the HOG_PERSONAL_API_KEY environment variable'
+ case 'dotenv-file':
+ return `HOG_PERSONAL_API_KEY in ${path}`
+ case 'store':
+ return store === 'keychain' ? 'the system keychain' : `${path}`
+ }
}
export default defineCommand({
@@ -27,7 +33,7 @@ export default defineCommand({
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'))
+ out.line(out.style(`Key from ${sourceLabel(result.source, result.store, result.credentialsPath)}`, 'dim'))
},
exitCode: (result) => (result.authenticated ? 0 : 1),
diff --git a/hog/src/commands/endpoints/list.ts b/hog/src/commands/endpoints/list.ts
index af2d1802a3ad..931606158224 100644
--- a/hog/src/commands/endpoints/list.ts
+++ b/hog/src/commands/endpoints/list.ts
@@ -11,7 +11,7 @@ export default defineCommand({
async run({ ctx }) {
const api = await ctx.posthog()
- return { projectId: (await ctx.credentials()).projectId, endpoints: await listEndpoints(api) }
+ return { projectId: (await ctx.credentials()).key.projectId, endpoints: await listEndpoints(api) }
},
human({ result, out }) {
diff --git a/hog/src/commands/error-tracking/download.ts b/hog/src/commands/error-tracking/download.ts
index d8cd2e25fa94..8a91e2da4379 100644
--- a/hog/src/commands/error-tracking/download.ts
+++ b/hog/src/commands/error-tracking/download.ts
@@ -33,7 +33,7 @@ export default defineCommand({
],
async run({ args, options, ctx }) {
- const client = new SymbolSetClient(ctx.runtime, await ctx.credentials())
+ const client = new SymbolSetClient(ctx.runtime, (await ctx.credentials()).key)
const byId = !options.ref && isSymbolSetId(args.symbolSet)
const id = byId ? args.symbolSet : await resolveRef(client, args.symbolSet)
const data = await downloadSymbolSet(client, id, ctx.runtime.fetch)
diff --git a/hog/src/commands/error-tracking/release.ts b/hog/src/commands/error-tracking/release.ts
index 3764a755503c..4f4535988795 100644
--- a/hog/src/commands/error-tracking/release.ts
+++ b/hog/src/commands/error-tracking/release.ts
@@ -45,7 +45,7 @@ export default defineCommand({
if (!resolved) {
return null
}
- const client = new SymbolSetClient(ctx.runtime, await ctx.credentials())
+ const client = new SymbolSetClient(ctx.runtime, (await ctx.credentials()).key)
if (options.dryRun) {
const existing = await findRelease(client, resolved.name, resolved.version)
const { id, hash_id, version, project } = existing ?? {
diff --git a/hog/src/core/agent.ts b/hog/src/core/agent.ts
index e16f4faed9e2..4ab81fc88cb5 100644
--- a/hog/src/core/agent.ts
+++ b/hog/src/core/agent.ts
@@ -35,6 +35,8 @@ export interface Mode {
format: OutputFormat
color: boolean
columns: number | undefined
+ // Set from the CI variable most CI services export.
+ ci: boolean
}
export interface Terminal {
@@ -66,6 +68,10 @@ function detectAgent(env: Env): { agent: string | undefined; reason: string } {
return { agent: undefined, reason: 'no agent env var is set' }
}
+function isTruthy(value: string | undefined): boolean {
+ return value !== undefined && value !== '' && value !== '0' && value.toLowerCase() !== 'false'
+}
+
export function resolveMode(env: Env, terminal: Terminal, requestedFormat: OutputFormat | undefined): Mode {
const { agent, reason } = detectAgent(env)
// Agents and pipes get JSON by default, people at a terminal get text.
@@ -73,5 +79,5 @@ export function resolveMode(env: Env, terminal: Terminal, requestedFormat: Outpu
const colorForced = env.FORCE_COLOR !== undefined && env.FORCE_COLOR !== '0'
const color =
colorForced || (format === 'text' && terminal.hasColors && agent === undefined && env.NO_COLOR === undefined)
- return { agent, agentReason: reason, format, color, columns: terminal.columns }
+ return { agent, agentReason: reason, format, color, columns: terminal.columns, ci: isTruthy(env.CI) }
}
diff --git a/hog/src/core/context.ts b/hog/src/core/context.ts
index bbaecdc7cb21..ae17fef99c10 100644
--- a/hog/src/core/context.ts
+++ b/hog/src/core/context.ts
@@ -1,7 +1,7 @@
import type { ApiToolLibrary } from '@posthog/mcp/src/cli/library-types'
import { PostHogApi } from '@/posthog/api'
-import { resolveCredentials, type ResolvedCredentials } from '@/posthog/credentials'
+import { resolveCredentials, type Credentials } from '@/posthog/credentials'
import type { Mode } from './agent'
import type { CommandTree } from './command'
@@ -15,7 +15,7 @@ import { Telemetry } from './telemetry'
// purpose: `run` returns data, and the command's `human` and `agent` views print it.
export class Context {
private api?: PostHogApi
- private resolved?: ResolvedCredentials
+ private credentialsRequest?: Promise<Credentials>
private loaded?: Promise<LoadedConfig | undefined>
private tools?: Promise<ApiToolLibrary>
@@ -40,7 +40,7 @@ export class Context {
// The PostHog API client. Credentials resolve on first use, so commands that never call
// the API work without them.
async posthog(): Promise<PostHogApi> {
- this.api ??= new PostHogApi(await this.credentials(), this.runtime.fetch)
+ this.api ??= new PostHogApi((await this.credentials()).key, this.runtime.fetch)
return this.api
}
@@ -57,11 +57,15 @@ export class Context {
}
// Throws `not_authenticated` when there are none.
- async credentials(): Promise<ResolvedCredentials> {
- this.resolved ??= await resolveCredentials(this.runtime, {
- ...this.globals,
- configHost: (await this.config())?.config.host,
- })
- return this.resolved
+ credentials(): Promise<Credentials> {
+ this.credentialsRequest ??= this.config().then((loaded) =>
+ resolveCredentials(this.runtime, { ...this.globals, configHost: loaded?.config.host })
+ )
+ return this.credentialsRequest
+ }
+
+ // The credentials the command already asked for, so telemetry doesn't read the keychain a second time.
+ get requestedCredentials(): Promise<Credentials> | undefined {
+ return this.credentialsRequest
}
}
diff --git a/hog/src/core/globals.test.ts b/hog/src/core/globals.test.ts
index fc3d3fe75a0a..10d07cb79424 100644
--- a/hog/src/core/globals.test.ts
+++ b/hog/src/core/globals.test.ts
@@ -2,6 +2,21 @@ import { describe, expect, test } from 'bun:test'
import { runHog, TEST_CREDENTIALS } from '@/testing'
+// hog logins for each host, the first one the last login.
+function storedLogins(...hosts: string[]): { files: Record<string, string>; keychain: Record<string, string> } {
+ const logins = Object.fromEntries(
+ hosts.map((host) => [host, { store: 'keychain', type: 'personal_api_key', projectId: '7', host }])
+ )
+ return {
+ files: { '/home/test/.config/hog/settings.json': JSON.stringify({ logins, host: hosts[0] }) },
+ keychain: Object.fromEntries(hosts.map((host) => [host, JSON.stringify({ apiKey: 'phx_test' })])),
+ }
+}
+
+function withConfig(stored: ReturnType<typeof storedLogins>, configHost: string): ReturnType<typeof storedLogins> {
+ return { ...stored, files: { ...stored.files, '/work/posthog.json': JSON.stringify({ host: configHost }) } }
+}
+
const AGENT = { CLAUDECODE: '1' }
const ENDPOINTS = 'https://ph.example.com/api/environments/7/endpoints/'
@@ -118,13 +133,10 @@ describe('global options', () => {
expect(pull.json()).toMatchObject({ status: 'would_write' })
expect(pull.files).toEqual({})
- const logout = await runHog(['auth', 'logout'], {
- env,
- files: { '/home/test/.posthog/credentials.json': '{}' },
- })
+ const logout = await runHog(['auth', 'logout'], { env, ...storedLogins('https://stored.example.com') })
expect(logout.exitCode).toBe(2)
expect(logout.error().code).toBe('dry_run_unsupported')
- expect(logout.files).toEqual({ '/home/test/.posthog/credentials.json': '{}' })
+ expect(logout.files).toEqual(storedLogins('https://stored.example.com').files)
})
test.each([
@@ -143,14 +155,7 @@ describe('global options', () => {
])('%s', async (_name, configHost, env, host) => {
const result = await runHog(['endpoints', 'list'], {
env: { ...AGENT, ...env },
- files: {
- '/work/posthog.json': JSON.stringify({ host: configHost }),
- '/home/test/.posthog/credentials.json': JSON.stringify({
- token: 'phx_test',
- env_id: '7',
- host: 'https://stored.example.com',
- }),
- },
+ ...withConfig(storedLogins('https://stored.example.com', 'https://env.example.com'), configHost),
respond: () => ({ status: 200, body: { results: [] } }),
})
@@ -160,14 +165,7 @@ describe('global options', () => {
test('a posthog.json host never receives credentials stored for another host', async () => {
const result = await runHog(['endpoints', 'list'], {
env: AGENT,
- files: {
- '/work/posthog.json': JSON.stringify({ host: 'https://config.example.com' }),
- '/home/test/.posthog/credentials.json': JSON.stringify({
- token: 'phx_test',
- env_id: '7',
- host: 'https://stored.example.com',
- }),
- },
+ ...withConfig(storedLogins('https://stored.example.com'), 'https://config.example.com'),
})
expect(result.error().code).toBe('host_mismatch')
diff --git a/hog/src/core/paths.test.ts b/hog/src/core/paths.test.ts
new file mode 100644
index 000000000000..56b777a16d30
--- /dev/null
+++ b/hog/src/core/paths.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, test } from 'bun:test'
+
+import { hogDir } from './paths'
+
+describe('hogDir', () => {
+ test.each([
+ ['macOS', 'darwin', {}, '/Users/ana/Library/Application Support/hog', false],
+ ['macOS, run from source', 'darwin', {}, '/Users/ana/Library/Application Support/hog-dev', true],
+ ['Linux', 'linux', {}, '/Users/ana/.config/hog', false],
+ ['Linux with XDG_CONFIG_HOME', 'linux', { XDG_CONFIG_HOME: '/xdg' }, '/xdg/hog', false],
+ ['Linux with a relative XDG_CONFIG_HOME', 'linux', { XDG_CONFIG_HOME: 'xdg' }, '/Users/ana/.config/hog', false],
+ [
+ 'Windows',
+ 'win32',
+ { APPDATA: 'C:\\Users\\ana\\AppData\\Roaming', LOCALAPPDATA: 'C:\\Users\\ana\\AppData\\Local' },
+ 'C:\\Users\\ana\\AppData\\Local\\hog',
+ false,
+ ],
+ ] as const)('%s', (_name, platform, env, expected, isDevelopment) => {
+ expect(hogDir({ platform, env, homeDir: () => '/Users/ana', isDevelopment })).toBe(expected)
+ })
+})
diff --git a/hog/src/core/paths.ts b/hog/src/core/paths.ts
index cb8ef7343f36..780efa572dd9 100644
--- a/hog/src/core/paths.ts
+++ b/hog/src/core/paths.ts
@@ -1,4 +1,7 @@
-import { isAbsolute, relative, resolve } from 'node:path'
+import { isAbsolute, posix, relative, resolve, win32 } from 'node:path'
+
+import { HogError } from './errors'
+import type { Runtime } from './runtime'
export function absolutePath(root: string, path: string): string {
return isAbsolute(path) ? path : resolve(root, path)
@@ -10,3 +13,41 @@ export function storedPath(root: string, path: string): string {
const rel = relative(root, path)
return isAbsolute(rel) ? path : rel
}
+
+// hog's own folder, where it keeps its settings, the approvals it waits for and, without a keychain,
+// its credentials. posthog-cli's ~/.posthog folder is not hog's: only `hog auth migrate` reads it.
+export function hogDir(runtime: Pick<Runtime, 'env' | 'platform' | 'homeDir' | 'isDevelopment'>): string {
+ const { env, platform } = runtime
+ const home = runtime.homeDir()
+ const name = runtime.isDevelopment ? 'hog-dev' : 'hog'
+ let folder: string | undefined
+ if (platform === 'win32') {
+ // Local, not Roaming: a domain profile copies Roaming to a server and to every machine the
+ // person signs in to, and this folder can hold credentials.
+ folder = env.LOCALAPPDATA
+ ? win32.join(env.LOCALAPPDATA, name)
+ : home && win32.join(home, 'AppData', 'Local', name)
+ } else if (platform === 'darwin') {
+ folder = home && posix.join(home, 'Library', 'Application Support', name)
+ } else {
+ // The XDG spec says to ignore a relative XDG_CONFIG_HOME.
+ const xdg = env.XDG_CONFIG_HOME && posix.isAbsolute(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : undefined
+ folder = xdg ? posix.join(xdg, name) : home && posix.join(home, '.config', name)
+ }
+ if (!folder) {
+ throw new HogError(
+ 'no_home_directory',
+ "hog couldn't find your home folder to keep its settings in.",
+ platform === 'win32' ? 'Set LOCALAPPDATA to your local app data folder.' : 'Set HOME to your home folder.'
+ )
+ }
+ return folder
+}
+
+export function hogFile(
+ runtime: Pick<Runtime, 'env' | 'platform' | 'homeDir' | 'isDevelopment'>,
+ name: string
+): string {
+ const folder = hogDir(runtime)
+ return runtime.platform === 'win32' ? win32.join(folder, name) : posix.join(folder, name)
+}
diff --git a/hog/src/core/runtime.ts b/hog/src/core/runtime.ts
index e132972bf8a2..c7ee6b643878 100644
--- a/hog/src/core/runtime.ts
+++ b/hog/src/core/runtime.ts
@@ -1,7 +1,7 @@
import { randomUUID } from 'node:crypto'
import { access, mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
import { homedir } from 'node:os'
-import { dirname } from 'node:path'
+import { basename, dirname } from 'node:path'
import type { ApiToolLibrary } from '@posthog/mcp/src/cli/library-types'
@@ -18,10 +18,24 @@ export type RuntimeFetch = (
init?: RequestInit & { timeoutMs?: number; skipRateLimit?: boolean }
) => Promise<Response>
+// The operating system's secret store: Keychain on macOS, Credential Manager on Windows and Secret
+// Service on Linux. Every item belongs to hog's own service, so `name` only has to be unique within hog.
+export interface Secrets {
+ // Resolves to null when there is no item with this name.
+ get: (name: string) => Promise<string | null>
+ set: (name: string, value: string) => Promise<void>
+ // Resolves to false when there was no item to delete.
+ delete: (name: string) => Promise<boolean>
+}
+
// Everything a command touches outside its own arguments. Tests build one by hand,
// so no command reads `process` or the network directly.
export interface Runtime {
env: Env
+ platform: NodeJS.Platform
+ // True for `bun src/index.ts`, false for a compiled hog. A run from source keeps its credentials
+ // and settings apart, so it never reads or replaces those of an installed hog.
+ isDevelopment: boolean
stdinIsTTY: boolean
stdoutIsTTY: boolean
stdoutHasColors: boolean
@@ -30,7 +44,8 @@ export interface Runtime {
writeStderr: (text: string) => void
fetch: RuntimeFetch
now: () => number
- sleep: (ms: number) => Promise<void>
+ // Resolves early when `signal` aborts, so a timer that lost a race doesn't keep hog running.
+ sleep: (ms: number, signal?: AbortSignal) => Promise<void>
homeDir: () => string | undefined
cwd: () => string
exists: (path: string) => Promise<boolean>
@@ -48,6 +63,7 @@ export interface Runtime {
// Resolves to false when no browser could be started, for example on a server without one.
openUrl: (url: string) => Promise<boolean>
prompts: Prompts
+ secrets: Secrets
// The project token for anonymous usage events. Undefined turns them off, as in tests.
telemetryToken: string | undefined
// Accepts any TLS certificate from here on, for every request, including the API tools' own.
@@ -70,9 +86,57 @@ function browserCommand(url: string): string[] {
}
}
+// `bun src/index.ts` runs as the bun executable, a compiled hog as itself.
+const FROM_SOURCE = basename(process.execPath).replace(/\.exe$/i, '') === 'bun'
+
+// Keychain calls that haven't settled. A call hog stopped waiting for, such as one behind a dialog
+// nobody answers, keeps the process alive, so the entry point ends the process when this is not zero.
+let pendingSecretCalls = 0
+
+export function hasPendingSecretCalls(): boolean {
+ return pendingSecretCalls > 0
+}
+
+async function tracked<T>(call: () => Promise<T>): Promise<T> {
+ pendingSecretCalls += 1
+ try {
+ return await call()
+ } finally {
+ pendingSecretCalls -= 1
+ }
+}
+
+function bunSecrets(service: string): Secrets {
+ return {
+ get: (name) => tracked(() => Bun.secrets.get({ service, name })),
+ set: (name, value) => tracked(() => Bun.secrets.set({ service, name, value })),
+ delete: (name) => tracked(() => Bun.secrets.delete({ service, name })),
+ }
+}
+
+function sleep(ms: number, signal?: AbortSignal): Promise<void> {
+ return new Promise((resolve) => {
+ if (signal?.aborted) {
+ resolve()
+ return
+ }
+ const timer = setTimeout(resolve, ms)
+ signal?.addEventListener(
+ 'abort',
+ () => {
+ clearTimeout(timer)
+ resolve()
+ },
+ { once: true }
+ )
+ })
+}
+
export function processRuntime(): Runtime {
return {
env: process.env,
+ platform: process.platform,
+ isDevelopment: FROM_SOURCE,
stdinIsTTY: process.stdin.isTTY === true,
stdoutIsTTY: process.stdout.isTTY === true,
stdoutHasColors: process.stdout.isTTY === true && process.stdout.hasColors(),
@@ -89,7 +153,7 @@ export function processRuntime(): Runtime {
timeoutMs === undefined ? init : { ...init, signal: AbortSignal.timeout(timeoutMs) }
),
now: () => Date.now(),
- sleep: (ms) => Bun.sleep(ms),
+ sleep,
homeDir: () => {
try {
const home = homedir()
@@ -156,6 +220,7 @@ export function processRuntime(): Runtime {
}
},
prompts: clackPrompts(),
+ secrets: bunSecrets(FROM_SOURCE ? 'com.posthog.hog.dev' : 'com.posthog.hog'),
telemetryToken: DEFAULT_TELEMETRY_TOKEN,
skipTlsVerification: () => {
// Runs only for --skip-ssl-verification, posthog-cli's opt-in flag for self-hosted certificates.
diff --git a/hog/src/core/telemetry.test.ts b/hog/src/core/telemetry.test.ts
index fb41e598d8b7..2434a731b248 100644
--- a/hog/src/core/telemetry.test.ts
+++ b/hog/src/core/telemetry.test.ts
@@ -209,4 +209,38 @@ describe('telemetry', () => {
])
expect(uploads[1]!.properties).toMatchObject({ success: true, skipped_already_present: 1, uploaded: 0 })
})
+
+ test('a command that needs no credentials never opens the keychain for telemetry', async () => {
+ let keychainReads = 0
+ const result = await runHog(['commands'], {
+ ...ON,
+ env: { CLAUDECODE: '1' },
+ files: {
+ '/home/test/.config/hog/settings.json': JSON.stringify({
+ logins: {
+ 'https://us.posthog.com': {
+ store: 'keychain',
+ type: 'personal_api_key',
+ projectId: '1',
+ host: 'https://us.posthog.com',
+ },
+ },
+ host: 'https://us.posthog.com',
+ }),
+ },
+ secrets: () => ({
+ get: async () => {
+ keychainReads++
+ return null
+ },
+ set: async () => {},
+ delete: async () => true,
+ }),
+ respond: () => ({ status: 200, body: {} }),
+ })
+
+ expect(result.exitCode).toBe(0)
+ expect(events(result).length).toBeGreaterThan(0)
+ expect(keychainReads).toBe(0)
+ })
})
diff --git a/hog/src/core/telemetry.ts b/hog/src/core/telemetry.ts
index b3368961d3e2..b640543e8180 100644
--- a/hog/src/core/telemetry.ts
+++ b/hog/src/core/telemetry.ts
@@ -1,5 +1,6 @@
import { createHash, randomUUID } from 'node:crypto'
+import type { AccessKey } from '@/posthog/access-key'
import { posthogFile, type Credentials } from '@/posthog/credentials'
import { VERSION } from '@/version'
@@ -139,8 +140,8 @@ export class Telemetry {
if (!this.enabled || this.queue.length === 0) {
return
}
- const credentials = await this.credentials?.().catch(() => undefined)
- const identity = credentials ? await this.identity(credentials) : undefined
+ const key = (await this.credentials?.().catch(() => undefined))?.key
+ const identity = key ? await this.identity(key) : undefined
const installId = await this.installId()
const distinctId = identity?.distinctId ?? installId
const groups = Object.fromEntries(
@@ -152,7 +153,7 @@ export class Telemetry {
...this.commonProperties(),
install_id: installId,
// A self-hosted project ID means nothing in PostHog Cloud and would tie the install to that instance.
- env_id: credentials && isCloudHost(credentials.host) ? credentials.projectId : null,
+ env_id: key && isCloudHost(key.host) ? key.projectId : null,
...(identity?.distinctId ? {} : { $process_person_profile: false }),
...(Object.keys(groups).length > 0 ? { $groups: groups } : {}),
}
@@ -205,8 +206,8 @@ export class Telemetry {
// Looks the user up once per key and keeps the answer for 30 days, or a day when PostHog had
// none, so most runs send no extra request. A key without the scopes stays anonymous.
- private async identity(credentials: Credentials): Promise<Identity | undefined> {
- if (!isCloudHost(credentials.host)) {
+ private async identity(key: AccessKey): Promise<Identity | undefined> {
+ if (!isCloudHost(key.host)) {
return undefined
}
let path: string
@@ -215,9 +216,7 @@ export class Telemetry {
} catch {
return undefined
}
- const key = createHash('sha256')
- .update(`${credentials.host}\n${credentials.projectId}\n${credentials.apiKey}`)
- .digest('hex')
+ const cacheKey = createHash('sha256').update(`${key.host}\n${key.projectId}\n${key.token}`).digest('hex')
let cache: Record<string, CachedIdentity> = {}
try {
const parsed: unknown = JSON.parse(await this.runtime.readFile(path))
@@ -228,13 +227,13 @@ export class Telemetry {
} catch {
// No cache yet.
}
- const cached = cache[key]
+ const cached = cache[cacheKey]
const now = this.runtime.now()
if (cached && now - cached.checkedAt < (cached.distinctId ? 30 : 1) * DAY_MS) {
return cached
}
- const identity = await this.lookup(credentials)
- cache[key] = { ...identity, checkedAt: now }
+ const identity = await this.lookup(key)
+ cache[cacheKey] = { ...identity, checkedAt: now }
try {
await this.runtime.writePrivateFile(path, JSON.stringify(cache))
} catch {
@@ -243,11 +242,11 @@ export class Telemetry {
return identity
}
- private async lookup(credentials: Credentials): Promise<Identity> {
+ private async lookup(key: AccessKey): Promise<Identity> {
const get = async (path: string): Promise<Record<string, any> | undefined> => {
try {
- const response = await this.runtime.fetch(new URL(path, credentials.host), {
- headers: { Authorization: `Bearer ${credentials.apiKey}` },
+ const response = await this.runtime.fetch(new URL(path, key.host), {
+ headers: { Authorization: `Bearer ${key.token}` },
signal: AbortSignal.timeout(LOOKUP_TIMEOUT_MS),
})
return response.ok ? ((await response.json()) as Record<string, any>) : undefined
@@ -255,10 +254,7 @@ export class Telemetry {
return undefined
}
}
- const [user, project] = await Promise.all([
- get('/api/users/@me/'),
- get(`/api/projects/${credentials.projectId}/`),
- ])
+ const [user, project] = await Promise.all([get('/api/users/@me/'), get(`/api/projects/${key.projectId}/`)])
return {
distinctId: text(user?.distinct_id),
organization: text(project?.organization) ?? text(user?.organization?.id),
diff --git a/hog/src/error-tracking/run.ts b/hog/src/error-tracking/run.ts
index b78ea2a30907..4c3cb7013364 100644
--- a/hog/src/error-tracking/run.ts
+++ b/hog/src/error-tracking/run.ts
@@ -154,8 +154,8 @@ export class Session {
this.client ??= this.ctx
.credentials()
.then(
- (credentials) =>
- new SymbolSetClient(this.ctx.runtime, credentials, () =>
+ ({ key }) =>
+ new SymbolSetClient(this.ctx.runtime, key, () =>
this.ctx.telemetry.capture('error_tracking_cli_sourcemaps_upload_endpoint_fallback')
)
)
diff --git a/hog/src/error-tracking/upload.ts b/hog/src/error-tracking/upload.ts
index 65b97277bb44..13eae74b69b5 100644
--- a/hog/src/error-tracking/upload.ts
+++ b/hog/src/error-tracking/upload.ts
@@ -1,7 +1,7 @@
import { HogError } from '@/core/errors'
import type { Runtime } from '@/core/runtime'
+import type { AccessKey } from '@/posthog/access-key'
import { USER_AGENT } from '@/posthog/api'
-import type { Credentials } from '@/posthog/credentials'
import { contentHash } from './container'
@@ -145,7 +145,7 @@ export class SymbolSetClient {
constructor(
private readonly runtime: Runtime,
- private readonly credentials: Credentials,
+ private readonly key: AccessKey,
private readonly onFallback: () => void = () => {}
) {
this.throttle = new Throttle(runtime, RATE_LIMIT_PER_MINUTE)
@@ -153,7 +153,7 @@ export class SymbolSetClient {
// Project-scoped API URL, resolved the way posthog-cli's `Url::join` does.
projectUrl(path: string): URL {
- return new URL(path, new URL(`api/projects/${this.credentials.projectId}/`, this.credentials.host))
+ return new URL(path, new URL(`api/projects/${this.key.projectId}/`, this.key.host))
}
async api(method: 'GET' | 'POST', path: string, body?: unknown): Promise<unknown> {
@@ -164,7 +164,7 @@ export class SymbolSetClient {
response = await this.runtime.fetch(url, {
method,
headers: {
- Authorization: `Bearer ${this.credentials.apiKey}`,
+ Authorization: `Bearer ${this.key.token}`,
'Content-Type': 'application/json',
'User-Agent': USER_AGENT,
},
diff --git a/hog/src/index.ts b/hog/src/index.ts
index 5dcb9913469a..82f181b1460f 100644
--- a/hog/src/index.ts
+++ b/hog/src/index.ts
@@ -1,9 +1,14 @@
#!/usr/bin/env -S bun --no-env-file
-import { processRuntime } from '@/core/runtime'
+import { hasPendingSecretCalls, processRuntime } from '@/core/runtime'
import { run } from './cli'
// A promise chain rather than top-level await, which `bun build --bytecode` does not support.
void run(process.argv.slice(2), processRuntime()).then((code) => {
process.exitCode = code
+ if (hasPendingSecretCalls()) {
+ // A keychain call that timed out still waits on its dialog. Exit once stdout drains, so an
+ // agent isn't left waiting on a person.
+ process.stdout.write('', () => process.exit(code))
+ }
})
diff --git a/hog/src/posthog/access-key.ts b/hog/src/posthog/access-key.ts
new file mode 100644
index 000000000000..151f4292342e
--- /dev/null
+++ b/hog/src/posthog/access-key.ts
@@ -0,0 +1,123 @@
+import { HogError } from '@/core/errors'
+import type { Runtime } from '@/core/runtime'
+import type { StoreChoice, StoredSecret } from '@/posthog/credential-store/types'
+
+import { sendRequest } from './api'
+import { hostUrl } from './host'
+import type { LoginRecord } from './settings'
+
+export interface LogoutOutcome {
+ // Whether PostHog revoked the login. Null for a key hog can't revoke.
+ revoked: boolean | null
+ // Where to delete a key that keeps working after logout.
+ revokeUrl: string | null
+}
+
+// How a stored key reaches its stored copy, so a renewal can read the latest one and save the new one.
+export interface AccessKeyStorage {
+ reread(): Promise<AccessKey | undefined>
+ save(key: AccessKey): Promise<void>
+}
+
+// A key hog sends to PostHog. Each kind owns how it authenticates, renews, logs out and is stored,
+// so callers never branch on the kind.
+export interface AccessKey {
+ readonly host: string
+ readonly projectId: string
+ // What PostHog takes as the bearer token.
+ readonly token: string
+ // A key that works for the rest of the command, renewed if it is about to expire.
+ fresh(runtime: Runtime, storage: AccessKeyStorage): Promise<AccessKey>
+ // The key as PostHog sees it, before hog stores it. Throws when PostHog rejects it.
+ verify(runtime: Runtime): Promise<AccessKey>
+ logout(runtime: Runtime): Promise<LogoutOutcome>
+ // The credential store keeps the secret, and settings.json keeps the record.
+ secret(): StoredSecret
+ record(store: StoreChoice): LoginRecord
+}
+
+const KEY_CHECK_TIMEOUT_MS = 30_000
+
+export class PersonalAPIKey implements AccessKey {
+ readonly host: string
+ readonly projectId: string
+ readonly apiKey: string
+ // Null until `verify` asks PostHog, because only PostHog knows a key's scopes.
+ readonly scopes: string[] | null
+
+ constructor(fields: { host: string; projectId: string; apiKey: string; scopes?: string[] }) {
+ this.host = fields.host
+ this.projectId = fields.projectId
+ this.apiKey = fields.apiKey
+ this.scopes = fields.scopes ?? null
+ }
+
+ get token(): string {
+ return this.apiKey
+ }
+
+ async fresh(): Promise<AccessKey> {
+ return this
+ }
+
+ // A key someone deleted, or one pasted only in part, would otherwise fail only at the first
+ // command that uses it. A key PostHog just issued already came with its scopes, so it skips the
+ // check: its approval is short-lived and a slow check could lose it.
+ async verify(runtime: Runtime): Promise<PersonalAPIKey> {
+ if (this.scopes !== null) {
+ return this
+ }
+ const response = await sendRequest(runtime.fetch, hostUrl(this.host, 'api/personal_api_keys/@current/'), {
+ method: 'GET',
+ apiKey: this.apiKey,
+ timeoutMs: KEY_CHECK_TIMEOUT_MS,
+ })
+ if (response.status === 401) {
+ throw new HogError(
+ 'key_rejected',
+ `${this.host} rejected the personal API key. The key may belong to another PostHog region or instance, or someone deleted it.`,
+ 'Check the host, or create a personal API key in PostHog under Settings > Personal API keys and run `hog auth login`.'
+ )
+ }
+ if (!response.ok) {
+ throw new HogError(
+ 'unexpected_response',
+ `PostHog answered the key check with HTTP ${response.status}.`,
+ 'Check the host, then run the command again.'
+ )
+ }
+ const scopes = (response.json as { scopes?: unknown } | undefined)?.scopes
+ const { host, projectId, apiKey } = this
+ return new PersonalAPIKey({
+ host,
+ projectId,
+ apiKey,
+ scopes: Array.isArray(scopes) ? scopes.filter((scope) => typeof scope === 'string') : [],
+ })
+ }
+
+ // A personal API key can't be revoked from hog, so logout says where to delete it.
+ async logout(): Promise<LogoutOutcome> {
+ return {
+ revoked: null,
+ revokeUrl: hostUrl(this.host, 'settings/user-api-keys').toString(),
+ }
+ }
+
+ secret(): StoredSecret {
+ return { apiKey: this.apiKey }
+ }
+
+ record(store: StoreChoice): LoginRecord {
+ return { store, type: 'personal_api_key', projectId: this.projectId, host: this.host }
+ }
+}
+
+// The one place that reads the stored kind. A secret of the wrong kind for its record, such as one
+// an older hog wrote, reads as no login.
+export function accessKeyFromStorage(record: LoginRecord, secret: StoredSecret): AccessKey | undefined {
+ if (record.type === 'personal_api_key' && 'apiKey' in secret) {
+ return new PersonalAPIKey({ host: record.host, projectId: record.projectId, apiKey: secret.apiKey })
+ }
+ return undefined
+}
diff --git a/hog/src/posthog/api-tools.ts b/hog/src/posthog/api-tools.ts
index 186d1d5aec30..b0b791bb1658 100644
--- a/hog/src/posthog/api-tools.ts
+++ b/hog/src/posthog/api-tools.ts
@@ -107,12 +107,12 @@ export async function apiConnection(
throw new HogError('invalid_input', `${flag} is empty.`, `Pass an ID, or leave out ${flag}.`, EXIT_USAGE)
}
}
- const credentials = await ctx.credentials()
+ const { key } = await ctx.credentials()
// The saved project can belong to another organization, so an organization override drops it.
- const projectId = scope.projectId ?? (scope.organizationId ? undefined : credentials.projectId)
+ const projectId = scope.projectId ?? (scope.organizationId ? undefined : key.projectId)
return {
- apiKey: credentials.apiKey,
- host: credentials.host,
+ apiKey: key.token,
+ host: key.host,
...(projectId ? { projectId } : {}),
...(scope.organizationId ? { organizationId: scope.organizationId } : {}),
clientName: 'hog',
diff --git a/hog/src/posthog/api.ts b/hog/src/posthog/api.ts
index d589eca37e17..8bcdf1c903d0 100644
--- a/hog/src/posthog/api.ts
+++ b/hog/src/posthog/api.ts
@@ -3,7 +3,7 @@ import { parseLossless } from '@/core/raw-json'
import type { RuntimeFetch } from '@/core/runtime'
import { VERSION } from '@/version'
-import type { Credentials } from './credentials'
+import type { AccessKey } from './access-key'
export const USER_AGENT = `hog/${VERSION}`
// Generous, because a HogQL query can run for minutes. It only stops a connection that hangs.
@@ -77,7 +77,7 @@ export class ApiError extends HogError {
export class PostHogApi {
constructor(
- private readonly credentials: Credentials,
+ private readonly key: AccessKey,
private readonly fetchFn: RuntimeFetch
) {}
@@ -85,8 +85,8 @@ export class PostHogApi {
// 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)
+ ? this.key.host
+ : new URL(`api/environments/${this.key.projectId}/`, this.key.host)
return new URL(path, base)
}
@@ -110,7 +110,7 @@ export class PostHogApi {
const response = await sendRequest(this.fetchFn, this.url(path), {
method,
body,
- apiKey: this.credentials.apiKey,
+ apiKey: this.key.token,
})
if (response.text && response.json === undefined) {
throw new HogError(
diff --git a/hog/src/posthog/auth-status.ts b/hog/src/posthog/auth-status.ts
index e0fde90a5f56..651d9c38fd9b 100644
--- a/hog/src/posthog/auth-status.ts
+++ b/hog/src/posthog/auth-status.ts
@@ -1,8 +1,9 @@
import type { Context } from '@/core/context'
import { HogError } from '@/core/errors'
+import type { StoreChoice } from '@/posthog/credential-store/types'
import { ApiError } from './api'
-import { posthogFile, type CredentialSource } from './credentials'
+import type { CredentialSource } from './credentials'
export type AuthStatus =
| {
@@ -19,6 +20,8 @@ export type AuthStatus =
projectId: string
projectName: string | null
source: CredentialSource
+ // Set when the source is the store.
+ store: StoreChoice | null
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
@@ -34,7 +37,8 @@ export async function checkAuthStatus(ctx: Context): Promise<AuthStatus> {
}
throw error
}
- const { host, projectId, source } = credentials
+ const { host, projectId } = credentials.key
+ const { source } = credentials
const api = await ctx.posthog()
const [user, project] = await Promise.allSettled([
api.get<{ email: string; first_name?: string }>('/api/users/@me/'),
@@ -62,7 +66,8 @@ export async function checkAuthStatus(ctx: Context): Promise<AuthStatus> {
projectId,
projectName: project.status === 'fulfilled' ? project.value.name : null,
source,
- credentialsPath: source === 'credentials-file' ? posthogFile(ctx.runtime, 'credentials.json') : null,
+ store: credentials.source === 'store' ? credentials.store : null,
+ credentialsPath: credentials.source === 'env' ? null : credentials.path,
user: user.status === 'fulfilled' ? { email: user.value.email, name: user.value.first_name || null } : null,
}
}
diff --git a/hog/src/posthog/credential-store/credential-store.test.ts b/hog/src/posthog/credential-store/credential-store.test.ts
new file mode 100644
index 000000000000..5c7744e2e7c6
--- /dev/null
+++ b/hog/src/posthog/credential-store/credential-store.test.ts
@@ -0,0 +1,122 @@
+import { describe, expect, test } from 'bun:test'
+
+import { HogError } from '@/core/errors'
+import type { Secrets } from '@/core/runtime'
+import { fakeRuntime, type FakeRuntime } from '@/testing'
+
+import { FileStore } from './file'
+import { KeychainStore } from './keychain'
+import { MemoryStore } from './memory'
+import type { CredentialStore, StoredSecret } from './types'
+
+const EU = 'https://eu.posthog.com'
+const US = 'https://us.posthog.com'
+
+function secret(apiKey: string): StoredSecret {
+ return { apiKey }
+}
+
+// A keychain that answers after `delayMs` of fake time, or never, or fails the way Bun reports a
+// denied dialog.
+function dialogSecrets(behavior: number | 'never' | 'denied'): (runtime: FakeRuntime) => Secrets {
+ return (runtime) => {
+ const answer = async <T>(value: T): Promise<T> => {
+ if (behavior === 'never') {
+ return new Promise<T>(() => {})
+ }
+ if (behavior === 'denied') {
+ throw Object.assign(new Error('User canceled the operation.'), { code: 'ERR_SECRETS_USER_CANCELED' })
+ }
+ await runtime.sleep(behavior)
+ return value
+ }
+ return {
+ get: () => answer(JSON.stringify(secret('phx_slow'))),
+ set: () => answer(undefined),
+ delete: () => answer(true),
+ }
+ }
+}
+
+describe('credential stores', () => {
+ describe.each([
+ ['memory', (): CredentialStore => new MemoryStore()],
+ ['file', (): CredentialStore => new FileStore(fakeRuntime())],
+ ['keychain', (): CredentialStore => new KeychainStore(fakeRuntime())],
+ ])('%s', (_kind, makeStore) => {
+ test('keeps one secret per host, overwrites it and removes it', async () => {
+ const store = makeStore()
+
+ expect(await store.read(EU)).toBeUndefined()
+ expect(await store.remove(EU)).toBe(false)
+
+ await store.write(EU, secret('phx_first'))
+ await store.write(US, secret('phx_us'))
+ await store.write(`${EU}/`, secret('phx_second'))
+
+ expect(await store.read(EU)).toEqual(secret('phx_second'))
+ expect(await store.read(US)).toEqual(secret('phx_us'))
+
+ expect(await store.remove(EU)).toBe(true)
+
+ expect(await store.read(EU)).toBeUndefined()
+ expect(await store.read(US)).toEqual(secret('phx_us'))
+ })
+ })
+
+ test("the file store writes a file only its owner can read, in hog's folder", async () => {
+ const runtime = fakeRuntime()
+ const privateFiles: string[] = []
+ const write = runtime.writePrivateFile
+ runtime.writePrivateFile = async (path, contents) => {
+ privateFiles.push(path)
+ await write(path, contents)
+ }
+
+ await new FileStore(runtime).write(EU, secret('phx_file'))
+
+ expect(privateFiles).toEqual(['/home/test/.config/hog/credentials.json'])
+ })
+
+ test.each([
+ ['answers at once', 0, 'phx_slow', false, 0],
+ ['answers while a dialog is open', 5000, 'phx_slow', true, 5000],
+ ['never answers', 'never' as const, 'keychain_access_timeout', true, 60_000],
+ ['is denied', 'denied' as const, 'keychain_access_denied', false, 0],
+ ])('a keychain that %s', async (_name, behavior, expected, warns, elapsedMs) => {
+ const runtime = fakeRuntime({ secrets: dialogSecrets(behavior) })
+ const start = runtime.now()
+
+ const outcome = await new KeychainStore(runtime).read(EU).then(
+ (stored) => stored?.apiKey,
+ (error: unknown) => (error instanceof HogError ? error.code : error)
+ )
+
+ expect(outcome).toBe(expected)
+ expect(runtime.stderr().includes('Waiting for access to the keychain')).toBe(warns)
+ expect(runtime.now() - start).toBe(elapsedMs)
+ })
+
+ test.each([
+ ['removed again when the caller stops using the keychain', true, {}],
+ ['kept when the caller keeps using the keychain', false, { [EU]: JSON.stringify(secret('phx_late')) }],
+ ])('a keychain write that lands after hog gave up is %s', async (_name, removeIfLate, keychain) => {
+ const runtime = fakeRuntime()
+ const items = runtime.secrets
+ runtime.secrets = {
+ ...items,
+ set: async (name, value) => {
+ await runtime.sleep(90_000)
+ await items.set(name, value)
+ },
+ }
+
+ const write = await new KeychainStore(runtime)
+ .write(EU, secret('phx_late'), { removeIfLate })
+ .catch((error: unknown) => error)
+ await runtime.sleep(60_000)
+
+ expect((write as HogError).code).toBe('keychain_access_timeout')
+ expect(runtime.keychain).toEqual(keychain)
+ })
+})
diff --git a/hog/src/posthog/credential-store/file.ts b/hog/src/posthog/credential-store/file.ts
new file mode 100644
index 000000000000..0f9337579f9c
--- /dev/null
+++ b/hog/src/posthog/credential-store/file.ts
@@ -0,0 +1,62 @@
+import { hogFile } from '@/core/paths'
+import type { Runtime } from '@/core/runtime'
+import { hostKey } from '@/posthog/host'
+
+import { parseJson, parseSecret } from './helpers'
+import type { CredentialStore, StoredSecret } from './types'
+
+// One JSON file, readable only by its owner, for machines without a keychain hog can use.
+export class FileStore implements CredentialStore {
+ readonly kind = 'file'
+
+ readonly path: string
+
+ constructor(private readonly runtime: Runtime) {
+ this.path = hogFile(runtime, 'credentials.json')
+ }
+
+ private async readAll(): Promise<Record<string, unknown>> {
+ let text: string
+ try {
+ text = await this.runtime.readFile(this.path)
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
+ return {}
+ }
+ throw error
+ }
+ const parsed = parseJson(text)
+ return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)
+ ? (parsed as Record<string, unknown>)
+ : {}
+ }
+
+ async hosts(): Promise<string[]> {
+ return Object.keys(await this.readAll())
+ }
+
+ async read(host: string): Promise<StoredSecret | undefined> {
+ return parseSecret((await this.readAll())[hostKey(host)])
+ }
+
+ async write(host: string, secret: StoredSecret): Promise<void> {
+ const all = await this.readAll()
+ all[hostKey(host)] = secret
+ await this.runtime.writePrivateFile(this.path, JSON.stringify(all, null, 2))
+ }
+
+ async remove(host: string): Promise<boolean> {
+ const all = await this.readAll()
+ const key = hostKey(host)
+ if (!(key in all)) {
+ return false
+ }
+ delete all[key]
+ if (Object.keys(all).length === 0) {
+ await this.runtime.removeFile(this.path)
+ } else {
+ await this.runtime.writePrivateFile(this.path, JSON.stringify(all, null, 2))
+ }
+ return true
+ }
+}
diff --git a/hog/src/posthog/credential-store/helpers.ts b/hog/src/posthog/credential-store/helpers.ts
new file mode 100644
index 000000000000..60249cc40b41
--- /dev/null
+++ b/hog/src/posthog/credential-store/helpers.ts
@@ -0,0 +1,15 @@
+import type { StoredSecret } from './types'
+
+export function parseJson(text: string): unknown {
+ try {
+ return JSON.parse(text)
+ } catch {
+ return undefined
+ }
+}
+
+// A stored value hog doesn't recognize, such as one a later version wrote, reads as no login.
+export function parseSecret(value: unknown): StoredSecret | undefined {
+ const item = value as Record<string, unknown> | null
+ return typeof item?.apiKey === 'string' ? { apiKey: item.apiKey } : undefined
+}
diff --git a/hog/src/posthog/credential-store/keychain.ts b/hog/src/posthog/credential-store/keychain.ts
new file mode 100644
index 000000000000..7b9f3ca5b3d8
--- /dev/null
+++ b/hog/src/posthog/credential-store/keychain.ts
@@ -0,0 +1,119 @@
+import { randomUUID } from 'node:crypto'
+
+import { HogError } from '@/core/errors'
+import type { Runtime } from '@/core/runtime'
+import { hostKey } from '@/posthog/host'
+
+import { parseJson, parseSecret } from './helpers'
+import type { CredentialStore, StoredSecret } from './types'
+
+// The keychain dialog on macOS never times out by itself, and a person may not notice it, so hog
+// says what it waits for and gives up on its own.
+const KEYCHAIN_PROGRESS_MS = 2000
+const KEYCHAIN_TIMEOUT_MS = 60_000
+// A name no host can have, so the probe never touches a real login.
+const PROBE_PREFIX = 'hog-keychain-probe'
+
+function keychainError(error: unknown): HogError {
+ if (error instanceof HogError) {
+ return error
+ }
+ // Bun reports both "Deny" and "Cancel" in the macOS dialog with this code.
+ if ((error as { code?: unknown } | null)?.code === 'ERR_SECRETS_USER_CANCELED') {
+ return new HogError(
+ 'keychain_access_denied',
+ "PostHog wasn't allowed to use the keychain.",
+ 'Run the command again and allow PostHog to use the keychain. Choose "Always Allow" so it doesn\'t ask again.'
+ )
+ }
+ return new HogError(
+ 'keychain_unavailable',
+ `hog couldn't use the keychain: ${error instanceof Error ? error.message : String(error)}`,
+ 'Unlock the keychain and run the command again, or run `hog auth login` to store your credentials in a file.'
+ )
+}
+
+// Runs one keychain call. After a moment it tells the person a dialog may be waiting for them, and
+// after KEYCHAIN_TIMEOUT_MS it stops waiting. The dialog can still be answered after that, so `undo`
+// reverts a call that lands late.
+async function keychainCall<T>(
+ runtime: Runtime,
+ operation: () => Promise<T>,
+ undo?: () => Promise<unknown>
+): Promise<T> {
+ const settled = new AbortController()
+ void runtime.sleep(KEYCHAIN_PROGRESS_MS, settled.signal).then(() => {
+ if (!settled.signal.aborted) {
+ runtime.writeStderr('Waiting for access to the keychain. If a dialog asks, allow PostHog to use it.\n')
+ }
+ })
+ const timeout = runtime.sleep(KEYCHAIN_TIMEOUT_MS, settled.signal).then((): never => {
+ if (settled.signal.aborted) {
+ return undefined as never
+ }
+ throw new HogError(
+ 'keychain_access_timeout',
+ `hog stopped after waiting ${KEYCHAIN_TIMEOUT_MS / 1000} seconds for access to the keychain.`,
+ 'Close the keychain dialog that is still open. Then run the command again and click "Always Allow".'
+ )
+ })
+ const pending = operation()
+ try {
+ return await Promise.race([pending, timeout])
+ } catch (error) {
+ if (undo && error instanceof HogError && error.code === 'keychain_access_timeout') {
+ void pending.then(undo).catch(() => {})
+ }
+ throw keychainError(error)
+ } finally {
+ settled.abort()
+ }
+}
+
+export class KeychainStore implements CredentialStore {
+ readonly kind = 'keychain'
+ readonly path = null
+
+ constructor(private readonly runtime: Runtime) {}
+
+ async read(host: string): Promise<StoredSecret | undefined> {
+ const value = await keychainCall(this.runtime, () => this.runtime.secrets.get(hostKey(host)))
+ return value === null ? undefined : parseSecret(parseJson(value))
+ }
+
+ async write(host: string, secret: StoredSecret, options: { removeIfLate?: boolean } = {}): Promise<void> {
+ const name = hostKey(host)
+ await keychainCall(
+ this.runtime,
+ () => this.runtime.secrets.set(name, JSON.stringify(secret)),
+ options.removeIfLate ? () => this.runtime.secrets.delete(name) : undefined
+ )
+ }
+
+ async remove(host: string): Promise<boolean> {
+ return keychainCall(this.runtime, () => this.runtime.secrets.delete(hostKey(host)))
+ }
+}
+
+type KeychainProbe = { usable: true } | { usable: false; reason: string }
+
+// Writes an item, reads it back and deletes it. Any failure, including a person who denies the
+// dialog, means hog keeps credentials in a file instead.
+export async function probeKeychain(runtime: Runtime): Promise<KeychainProbe> {
+ const value = randomUUID()
+ // Its own item for each probe, so two logins that probe at once don't change each other's item.
+ const name = `${PROBE_PREFIX}-${value}`
+ try {
+ await keychainCall(runtime, async () => {
+ await runtime.secrets.set(name, value)
+ const readBack = await runtime.secrets.get(name)
+ await runtime.secrets.delete(name)
+ if (readBack !== value) {
+ throw new Error('it returned a different value than hog stored')
+ }
+ })
+ return { usable: true }
+ } catch (error) {
+ return { usable: false, reason: error instanceof Error ? error.message : String(error) }
+ }
+}
diff --git a/hog/src/posthog/credential-store/memory.ts b/hog/src/posthog/credential-store/memory.ts
new file mode 100644
index 000000000000..75dd18cc3fed
--- /dev/null
+++ b/hog/src/posthog/credential-store/memory.ts
@@ -0,0 +1,21 @@
+import { hostKey, type HostKey } from '@/posthog/host'
+
+import type { CredentialStore, StoredSecret } from './types'
+
+export class MemoryStore implements CredentialStore {
+ readonly kind = 'memory'
+ readonly path = null
+ private readonly items = new Map<HostKey, StoredSecret>()
+
+ async read(host: string): Promise<StoredSecret | undefined> {
+ return this.items.get(hostKey(host))
+ }
+
+ async write(host: string, secret: StoredSecret): Promise<void> {
+ this.items.set(hostKey(host), secret)
+ }
+
+ async remove(host: string): Promise<boolean> {
+ return this.items.delete(hostKey(host))
+ }
+}
diff --git a/hog/src/posthog/credential-store/open.ts b/hog/src/posthog/credential-store/open.ts
new file mode 100644
index 000000000000..abee18a72e80
--- /dev/null
+++ b/hog/src/posthog/credential-store/open.ts
@@ -0,0 +1,9 @@
+import type { Runtime } from '@/core/runtime'
+
+import { FileStore } from './file'
+import { KeychainStore } from './keychain'
+import type { StoreChoice } from './types'
+
+export function openStore(runtime: Runtime, kind: StoreChoice): KeychainStore | FileStore {
+ return kind === 'keychain' ? new KeychainStore(runtime) : new FileStore(runtime)
+}
diff --git a/hog/src/posthog/credential-store/types.ts b/hog/src/posthog/credential-store/types.ts
new file mode 100644
index 000000000000..4ded33dd50b3
--- /dev/null
+++ b/hog/src/posthog/credential-store/types.ts
@@ -0,0 +1,25 @@
+// The part of a login the credential store keeps. settings.json keeps the rest, so a keychain item
+// stays small however many scopes a login gains.
+export interface PersonalAPIKeySecret {
+ apiKey: string
+}
+
+export type StoredSecret = PersonalAPIKeySecret
+
+export type StoreKind = 'keychain' | 'file' | 'memory'
+
+// The stores a login can use. The memory store exists for tests only.
+export type StoreChoice = Exclude<StoreKind, 'memory'>
+
+// Where hog keeps the secrets of the logins `hog auth login` saves, one per host.
+export interface CredentialStore {
+ readonly kind: StoreKind
+ // The file that holds the secrets. Null for a store that isn't a file.
+ readonly path: string | null
+ read(host: string): Promise<StoredSecret | undefined>
+ // `removeIfLate` is for a caller that stops using this store when the write times out: a write
+ // that still lands afterwards is removed again, so no item outlives what settings.json records.
+ write(host: string, secret: StoredSecret, options?: { removeIfLate?: boolean }): Promise<void>
+ // Resolves to false when the store held nothing for the host.
+ remove(host: string): Promise<boolean>
+}
diff --git a/hog/src/posthog/credentials.test.ts b/hog/src/posthog/credentials.test.ts
index c62cd2bc870f..eaaec007eeb7 100644
--- a/hog/src/posthog/credentials.test.ts
+++ b/hog/src/posthog/credentials.test.ts
@@ -8,6 +8,26 @@ import { DEFAULT_HOST, resolveCredentials } from './credentials'
const ENV = { HOG_PERSONAL_API_KEY: 'phx_env', HOG_PROJECT_ID: '1', HOG_HOST: 'https://env.example.com' }
const DOTENV = 'HOG_PERSONAL_API_KEY="phx_dotenv"\n# comment\nHOG_PROJECT_ID=2\n'
const STORED = JSON.stringify({ token: 'phx_stored', env_id: '3', host: 'https://stored.example.com' })
+const LEGACY_CLI_FILE = '/home/test/.posthog/credentials.json'
+const SETTINGS_FILE = '/home/test/.config/hog/settings.json'
+const EU = 'https://eu.posthog.com'
+const US = 'https://us.posthog.com'
+
+// What the store keeps for a login: only its secret.
+function login(apiKey: string): string {
+ return JSON.stringify({ apiKey })
+}
+
+// `host` is the last login. `stores` says where the login for each host is.
+function settings(host: string, stores: Record<string, 'keychain' | 'file'>): Record<string, string> {
+ const logins = Object.fromEntries(
+ Object.entries(stores).map(([login, store]) => [
+ new URL(login).origin,
+ { store, type: 'personal_api_key', projectId: '9', host: login },
+ ])
+ )
+ return { [SETTINGS_FILE]: JSON.stringify({ logins, host }) }
+}
describe('resolveCredentials', () => {
test.each([
@@ -31,53 +51,22 @@ describe('resolveCredentials', () => {
'2',
DEFAULT_HOST,
],
- [
- 'a missing dotenv file falls back to the credentials file',
- {},
- { '/home/test/.posthog/credentials.json': STORED },
- '/x/missing.env',
- undefined,
- 'phx_stored',
- '3',
- 'https://stored.example.com',
- ],
- [
- 'the credentials file is last',
- {},
- { '/home/test/.posthog/credentials.json': STORED },
- undefined,
- undefined,
- 'phx_stored',
- '3',
- 'https://stored.example.com',
- ],
- [
- 'HOG_HOME moves the credentials file',
- { HOG_HOME: '/custom' },
- { '/custom/credentials.json': STORED },
- undefined,
- undefined,
- 'phx_stored',
- '3',
- 'https://stored.example.com',
- ],
- [
- '--host overrides the stored host',
- {},
- { '/home/test/.posthog/credentials.json': STORED },
- undefined,
- 'https://flag.example.com',
- 'phx_stored',
- '3',
- 'https://flag.example.com',
- ],
] as const)('%s', async (_name, env, files, dotenvFile, host, apiKey, projectId, expectedHost) => {
const credentials = await resolveCredentials(fakeRuntime({ env, files }), { dotenvFile, host })
- expect(credentials).toMatchObject({ apiKey, projectId, host: expectedHost })
+ expect(credentials).toMatchObject({ key: { apiKey, projectId, host: expectedHost } })
})
test.each([
['nothing configured', {}, 'not_authenticated', {}, undefined],
+ // `hog auth migrate` is the only command that reads posthog-cli's file.
+ ["only posthog-cli's credentials file", {}, 'not_authenticated', { [LEGACY_CLI_FILE]: STORED }, undefined],
+ [
+ "a missing dotenv file with only posthog-cli's credentials file",
+ {},
+ 'not_authenticated',
+ { [LEGACY_CLI_FILE]: STORED },
+ '/x/missing.env',
+ ],
[
"posthog-cli's variable names",
{ POSTHOG_CLI_API_KEY: 'phx_a', POSTHOG_CLI_PROJECT_ID: '1' },
@@ -114,6 +103,96 @@ describe('resolveCredentials', () => {
expect((error as HogError).code).toBe(code)
})
+ test.each([
+ [
+ 'a hog login',
+ settings(EU, { [EU]: 'keychain' }),
+ { [EU]: login('phx_eu') },
+ {},
+ { key: { apiKey: 'phx_eu', host: EU }, source: 'store', store: 'keychain' },
+ ],
+ [
+ 'a self-hosted login keeps the path PostHog sits under',
+ settings('https://example.com', { 'https://example.com/posthog': 'keychain' }),
+ { 'https://example.com': login('phx_self') },
+ {},
+ { key: { apiKey: 'phx_self', host: 'https://example.com/posthog' } },
+ ],
+ [
+ '--host written differently for the same login',
+ settings('https://example.com', { 'https://example.com/posthog': 'keychain' }),
+ { 'https://example.com': login('phx_self') },
+ { host: 'HTTPS://Example.com:443/posthog/' },
+ { key: { apiKey: 'phx_self', host: 'https://example.com/posthog' } },
+ ],
+ [
+ '--host with another path on the same origin',
+ settings('https://example.com', { 'https://example.com/posthog': 'keychain' }),
+ { 'https://example.com': login('phx_self') },
+ { host: 'https://example.com/other-app' },
+ 'host_mismatch',
+ ],
+ [
+ 'a posthog.json path on the same origin keeps the path the login was made for',
+ settings('https://example.com', { 'https://example.com/posthog': 'keychain' }),
+ { 'https://example.com': login('phx_self') },
+ { configHost: 'https://example.com/other-app\\' },
+ { key: { apiKey: 'phx_self', host: 'https://example.com/posthog' } },
+ ],
+ [
+ 'posthog.json picks the stored login for its host',
+ settings(US, { [EU]: 'keychain', [US]: 'keychain' }),
+ { [EU]: login('phx_eu'), [US]: login('phx_us') },
+ { configHost: `${EU}/` },
+ { key: { apiKey: 'phx_eu', host: EU } },
+ ],
+ [
+ '--host picks the stored login for that host',
+ settings(US, { [EU]: 'keychain', [US]: 'keychain' }),
+ { [EU]: login('phx_eu'), [US]: login('phx_us') },
+ { host: EU },
+ { key: { apiKey: 'phx_eu', host: EU } },
+ ],
+ [
+ 'a later file login to another host keeps the keychain login',
+ settings(US, { [EU]: 'keychain', [US]: 'file' }),
+ { [EU]: login('phx_eu') },
+ { configHost: EU },
+ { key: { apiKey: 'phx_eu', host: EU }, store: 'keychain' },
+ ],
+ [
+ 'a login in the file store',
+ {
+ ...settings(EU, { [EU]: 'file' }),
+ '/home/test/.config/hog/credentials.json': JSON.stringify({ [EU]: JSON.parse(login('phx_file')) }),
+ },
+ {},
+ {},
+ {
+ key: { apiKey: 'phx_file' },
+ source: 'store',
+ store: 'file',
+ path: '/home/test/.config/hog/credentials.json',
+ },
+ ],
+ [
+ 'a posthog.json host without a login of its own',
+ settings(US, { [US]: 'keychain' }),
+ { [US]: login('phx_us') },
+ { configHost: EU },
+ 'host_mismatch',
+ ],
+ ] as const)('%s', async (_name, files, keychain, options, expected) => {
+ const outcome = await resolveCredentials(fakeRuntime({ files, keychain }), options).catch((error: unknown) =>
+ error instanceof HogError ? error.code : error
+ )
+ if (typeof expected === 'string') {
+ expect(outcome).toBe(expected)
+ } else {
+ expect(outcome).toMatchObject(expected)
+ }
+ })
+
test('fails on a dotenv file it cannot read, instead of falling back', async () => {
const runtime = fakeRuntime({ files: { '/home/test/.posthog/credentials.json': STORED } })
runtime.readFile = async (path) => {
@@ -126,14 +205,14 @@ describe('resolveCredentials', () => {
expect((error as HogError).code).toBe('invalid_dotenv_file')
})
- test('points to HOG_HOME and the env variables when there is no home folder', async () => {
+ test('points to the home folder and the env variables when there is none', async () => {
const runtime = fakeRuntime()
runtime.homeDir = () => undefined
const error = (await resolveCredentials(runtime, {}).catch((caught: unknown) => caught)) as HogError
expect(error.code).toBe('not_authenticated')
- expect(error.hint).toContain('HOG_HOME')
+ expect(error.hint).toContain('HOME')
expect(error.hint).toContain('HOG_PERSONAL_API_KEY')
})
})
diff --git a/hog/src/posthog/credentials.ts b/hog/src/posthog/credentials.ts
index 9bbedcc28dea..295307382fed 100644
--- a/hog/src/posthog/credentials.ts
+++ b/hog/src/posthog/credentials.ts
@@ -2,19 +2,25 @@ import { join } from 'node:path'
import { EXIT_USAGE, HogError } from '@/core/errors'
import type { Env, Runtime } from '@/core/runtime'
+import type { StoreChoice } from '@/posthog/credential-store/types'
+import { loginStorage, readLogin } from '@/posthog/login/stored'
+
+import { PersonalAPIKey, type AccessKey } from './access-key'
+import { hostKey, sameHost } from './host'
+import { readSettings } from './settings'
// posthog-cli falls back to this host when neither --host nor the credentials name one.
export const DEFAULT_HOST = 'https://us.i.posthog.com'
-export interface Credentials {
- apiKey: string
- projectId: string
- host: string
-}
+export type Credentials = { key: AccessKey } & (
+ | { source: 'env' }
+ | { source: 'dotenv-file'; path: string }
+ // What `hog auth login` or `hog auth migrate` saved. `path` is the file that holds the secret,
+ // and null for the keychain.
+ | { source: 'store'; store: StoreChoice; path: string | null }
+)
-export type CredentialSource = 'env' | 'dotenv-file' | 'credentials-file'
-
-export type ResolvedCredentials = Credentials & { source: CredentialSource }
+export type CredentialSource = Credentials['source']
interface RawCredentials {
apiKey: string
@@ -117,7 +123,7 @@ 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 {
+function validate(raw: RawCredentials, host: string): PersonalAPIKey {
const keyError = checkApiKey(raw.apiKey)
if (keyError) {
throw new HogError(
@@ -138,27 +144,21 @@ function validate(raw: RawCredentials, host: string): Credentials {
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
+ return new PersonalAPIKey({ host, projectId: raw.projectId, apiKey: raw.apiKey })
}
-// Lookup order matches posthog-cli: process env, then --dotenv-file, then the credentials
-// file `hog auth login` and `posthog-cli login` write. The global host overrides whichever host the
-// source carried. posthog.json comes from the repository, so its host never redirects a key: it
-// only stops the command when the key belongs to another host.
+// Every credential source, in order: HOG_PERSONAL_API_KEY in the environment, then in --dotenv-file,
+// then what `hog auth login` stored. The global host overrides the host a key in the environment
+// or --dotenv-file carried, and picks which stored login to use. posthog.json comes from the repository, so its host never
+// redirects a key: it can pick a stored login for that host, and otherwise only stops the command
+// when the key belongs to another host.
export async function resolveCredentials(
runtime: Runtime,
- options: { host?: string; dotenvFile?: string; configHost?: string }
-): Promise<ResolvedCredentials> {
- const withHost = (raw: RawCredentials, source: CredentialSource): ResolvedCredentials => {
- const host = options.host ?? raw.host ?? DEFAULT_HOST
+ // `skipStore` leaves out what `hog auth login` stored, for callers that must never open the
+ // keychain or renew a token, like telemetry for a command that needed no credentials.
+ options: { host?: string; dotenvFile?: string; configHost?: string; skipStore?: boolean }
+): Promise<Credentials> {
+ const checkConfigHost = (host: string): void => {
const { configHost } = options
if (options.host === undefined && configHost !== undefined && !sameOrigin(configHost, host)) {
throw new HogError(
@@ -168,12 +168,16 @@ export async function resolveCredentials(
EXIT_USAGE
)
}
- return { ...validate(raw, host), source }
+ }
+ const keyFrom = (raw: RawCredentials): PersonalAPIKey => {
+ const host = options.host ?? raw.host ?? DEFAULT_HOST
+ checkConfigHost(host)
+ return validate(raw, host)
}
const fromEnv = fromLookup((name) => runtime.env[name] || undefined)
if (fromEnv) {
- return withHost(fromEnv, 'env')
+ return { key: keyFrom(fromEnv), source: 'env' }
}
const dotenvFile = options.dotenvFile
@@ -189,31 +193,43 @@ export async function resolveCredentials(
'Add both variables to the file, or remove --dotenv-file.'
)
}
- return withHost(fromFile, 'dotenv-file')
+ return { key: keyFrom(fromFile), source: 'dotenv-file', path: dotenvFile }
}
}
- const home = posthogHomeDir(runtime.env, runtime.homeDir())
- if (home === undefined) {
- throw new HogError(
- 'not_authenticated',
- "hog couldn't find PostHog credentials or a home folder to read them from.",
- NO_HOME_HINT
- )
- }
- let stored: { token?: unknown; env_id?: unknown; host?: unknown } | undefined
- try {
- stored = JSON.parse(await runtime.readFile(join(home, 'credentials.json')))
- } catch {
- stored = undefined
- }
- if (stored && typeof stored.token === 'string' && stored.env_id !== undefined) {
- const raw = {
- apiKey: stored.token,
- projectId: String(stored.env_id),
- host: typeof stored.host === 'string' ? stored.host : undefined,
+ if (!options.skipStore) {
+ const settings = await readSettings(runtime).catch((error: unknown) => {
+ // Without a home folder hog has no logins, so the way in is the environment.
+ if (error instanceof HogError && error.code === 'no_home_directory') {
+ throw new HogError(
+ 'not_authenticated',
+ "hog couldn't find PostHog credentials or a home folder to read them from.",
+ `${error.hint} Or set HOG_PERSONAL_API_KEY and HOG_PROJECT_ID to skip logging in.`
+ )
+ }
+ throw error
+ })
+ const hosts = options.host !== undefined ? [options.host] : [options.configHost, settings.host]
+ for (const host of new Set(hosts)) {
+ const login = host === undefined ? undefined : await readLogin(runtime, settings, host)
+ if (!login) {
+ continue
+ }
+ // Before a renewal, so hog never renews a key it then refuses to send.
+ checkConfigHost(login.key.host)
+ // Logins are kept per origin, so another path on it is another PostHog the login isn't for.
+ if (options.host !== undefined && !sameHost(options.host, login.key.host)) {
+ throw new HogError(
+ 'host_mismatch',
+ `Your login for ${hostKey(options.host)} is for ${login.key.host}, not ${options.host}.`,
+ `Run \`hog auth login --host ${options.host}\` to log in there instead.`,
+ EXIT_USAGE
+ )
+ }
+ const key = await login.key.fresh(runtime, loginStorage(runtime, login))
+ const { store } = login
+ return { key, source: 'store', store: store.kind, path: store.path }
}
- return withHost(raw, 'credentials-file')
}
throw new HogError(
diff --git a/hog/src/posthog/host.ts b/hog/src/posthog/host.ts
new file mode 100644
index 000000000000..5ab35ccd3287
--- /dev/null
+++ b/hog/src/posthog/host.ts
@@ -0,0 +1,23 @@
+// The origin of a PostHog host: its scheme, host name and port, without a path or a trailing
+// slash, so `https://eu.posthog.com/` and `https://eu.posthog.com` are the same login. Only
+// `hostKey` makes one, so every map of logins uses the same form.
+export type HostKey = string & { readonly __brand: 'HostKey' }
+
+export function hostKey(host: string): HostKey {
+ return (URL.canParse(host) ? new URL(host).origin : host) as HostKey
+}
+
+export function trimHost(host: string): string {
+ return host.replace(/\/+$/, '')
+}
+
+// The same origin and the same path, however each is written.
+export function sameHost(a: string, b: string): boolean {
+ const path = (host: string): string => (URL.canParse(host) ? new URL(host).pathname.replace(/\/+$/, '') : '')
+ return hostKey(a) === hostKey(b) && path(a) === path(b)
+}
+
+// Keeps the path a self-hosted PostHog can sit under, such as https://example.com/posthog.
+export function hostUrl(host: string, path: string): URL {
+ return new URL(path, `${trimHost(host)}/`)
+}
diff --git a/hog/src/posthog/login.ts b/hog/src/posthog/login.ts
deleted file mode 100644
index fc3ce301ea5d..000000000000
--- a/hog/src/posthog/login.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-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/posthog/login/flow.ts b/hog/src/posthog/login/flow.ts
new file mode 100644
index 000000000000..b434c279eef0
--- /dev/null
+++ b/hog/src/posthog/login/flow.ts
@@ -0,0 +1,107 @@
+import { HogError } from '@/core/errors'
+import type { Runtime } from '@/core/runtime'
+import { PersonalAPIKey, type AccessKey } from '@/posthog/access-key'
+import { FileStore } from '@/posthog/credential-store/file'
+import { probeKeychain } from '@/posthog/credential-store/keychain'
+import { openStore } from '@/posthog/credential-store/open'
+import type { StoreChoice } from '@/posthog/credential-store/types'
+import { posthogFile } from '@/posthog/credentials'
+import { startDeviceLogin, waitForApproval, type PendingLogin } from '@/posthog/device-auth'
+import { loginFor, readSettings } from '@/posthog/settings'
+
+import { writeLogin } from './stored'
+
+const PENDING_LOGIN_FILE = 'login-pending.json'
+
+// Reusing a code this close to expiry would hand the person a link that dies while they open it.
+const REUSE_MARGIN_MS = 60_000
+
+export interface LoggedIn {
+ host: string
+ projectId: string
+ store: StoreChoice
+ // Set when the credentials are in a file.
+ credentialsPath: string | null
+ // Why hog couldn't use the keychain, when it stored the credentials in a file.
+ keychainError: string | null
+ 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 { projectId, apiKey, scopes } = approval
+ const key = new PersonalAPIKey({ host: pending.host, projectId, apiKey, scopes })
+ const loggedIn = await saveLogin(runtime, key)
+ return { ...loggedIn, scopes: approval.scopes }
+}
+
+// Each login probes the keychain again, so a login at the desk moves credentials out of the file a
+// login over SSH had to use. Clears any pending login too, so a later `--wait` can't replace these
+// credentials with an older approval.
+export async function saveLogin(runtime: Runtime, unverified: AccessKey): Promise<LoggedIn> {
+ const key = await unverified.verify(runtime)
+ const [probe, previous] = await Promise.all([probeKeychain(runtime), readSettings(runtime)])
+ let store = openStore(runtime, probe.usable ? 'keychain' : 'file')
+ let keychainError = probe.usable ? null : probe.reason
+ const { host, projectId } = key
+ try {
+ // A keychain that times out sends the login to the file below.
+ await writeLogin(runtime, store, key, { lastLogin: true, removeIfLate: true })
+ } catch (error) {
+ // The probe writes an item of its own, so the keychain can still refuse this host's item,
+ // such as one an older hog build saved.
+ if (store.kind !== 'keychain' || !(error instanceof HogError) || !error.code.startsWith('keychain_')) {
+ throw error
+ }
+ keychainError = error.message
+ store = new FileStore(runtime)
+ // The failed keychain write can still land after hog gave up on it.
+ await writeLogin(runtime, store, key, { lastLogin: true, keychainLeftover: true })
+ }
+ // Only an old file login is removed. Removing a keychain login after a failed probe would wait for the keychain again.
+ if (loginFor(previous, host)?.store === 'file' && store.kind === 'keychain') {
+ await new FileStore(runtime).remove(host)
+ }
+ await clearPendingLogin(runtime)
+ return {
+ host,
+ projectId,
+ store: store.kind,
+ credentialsPath: store.path,
+ keychainError,
+ scopes: [],
+ }
+}
diff --git a/hog/src/posthog/login/stored.ts b/hog/src/posthog/login/stored.ts
new file mode 100644
index 000000000000..eda1662a40c1
--- /dev/null
+++ b/hog/src/posthog/login/stored.ts
@@ -0,0 +1,150 @@
+import { HogError } from '@/core/errors'
+import type { Runtime } from '@/core/runtime'
+import { accessKeyFromStorage, type AccessKey, type AccessKeyStorage, type LogoutOutcome } from '@/posthog/access-key'
+import { FileStore } from '@/posthog/credential-store/file'
+import { KeychainStore } from '@/posthog/credential-store/keychain'
+import { openStore } from '@/posthog/credential-store/open'
+import { hostKey, type HostKey } from '@/posthog/host'
+import { loginFor, readSettings, withLogin, writeSettings, type HogSettings } from '@/posthog/settings'
+
+export interface LoggedOut extends LogoutOutcome {
+ // Why hog couldn't remove the keychain item a file login left behind. Null when there was none.
+ keychainLeftover: string | null
+}
+
+export interface LoggedOutHost extends LoggedOut {
+ host: string
+}
+
+export interface StoredLogin {
+ key: AccessKey
+ store: KeychainStore | FileStore
+}
+
+export async function readLogin(
+ runtime: Runtime,
+ settings: HogSettings,
+ host: string
+): Promise<StoredLogin | undefined> {
+ const record = loginFor(settings, host)
+ if (!record) {
+ return undefined
+ }
+ const store = openStore(runtime, record.store)
+ const secret = await store.read(host)
+ const key = secret && accessKeyFromStorage(record, secret)
+ return key ? { key, store } : undefined
+}
+
+export function loginStorage(runtime: Runtime, login: StoredLogin): AccessKeyStorage {
+ const { host } = login.key
+ return {
+ reread: async () => (await readLogin(runtime, await readSettings(runtime), host))?.key,
+ save: (key) => writeLogin(runtime, login.store, key),
+ }
+}
+
+// Writes the secrets first, so settings.json never names a login whose secrets aren't stored yet.
+// The settings are read again just before the write, so a change another hog process made to a
+// different host's login survives.
+export async function writeLogin(
+ runtime: Runtime,
+ store: KeychainStore | FileStore,
+ key: AccessKey,
+ options: { lastLogin?: boolean; removeIfLate?: boolean; keychainLeftover?: boolean } = {}
+): Promise<void> {
+ await store.write(key.host, key.secret(), { removeIfLate: options.removeIfLate })
+ const current = await readSettings(runtime)
+ const previous = loginFor(current, key.host)
+ const record = key.record(store.kind)
+ const keychainLeftover =
+ store.kind === 'file' &&
+ (options.keychainLeftover === true || previous?.store === 'keychain' || previous?.keychainLeftover === true)
+ const settings = withLogin(current, key.host, keychainLeftover ? { ...record, keychainLeftover } : record)
+ await writeSettings(runtime, options.lastLogin ? { ...settings, host: key.host } : settings)
+}
+
+// Resolves to false when the store held nothing for the host.
+export async function removeLogin(runtime: Runtime, host: string, store: KeychainStore | FileStore): Promise<boolean> {
+ const removed = await store.remove(host)
+ const settings = withLogin(await readSettings(runtime), host, undefined)
+ const lastLogin = settings.host !== undefined && hostKey(settings.host) === hostKey(host)
+ await writeSettings(runtime, lastLogin ? { logins: settings.logins } : settings)
+ return removed
+}
+
+// Logs this machine out of `host`: the key revokes itself where it can, and hog removes its
+// stored copy. Resolves to undefined when hog had no login to remove.
+export async function logout(runtime: Runtime, host: string): Promise<LoggedOut | undefined> {
+ const settings = await readSettings(runtime)
+ const record = loginFor(settings, host)
+ const login = await readLogin(runtime, settings, host)
+ if (!login) {
+ // The file entry can be gone while the record still names a keychain item left behind.
+ if (!record?.keychainLeftover) {
+ return undefined
+ }
+ await removeLogin(runtime, host, openStore(runtime, record.store))
+ return { revoked: null, revokeUrl: null, keychainLeftover: await removeKeychainLeftover(runtime, host) }
+ }
+ const [outcome, removed] = await Promise.all([login.key.logout(runtime), removeLogin(runtime, host, login.store)])
+ if (!removed) {
+ return undefined
+ }
+ const leftover = record?.keychainLeftover ? await removeKeychainLeftover(runtime, host) : null
+ return { ...outcome, keychainLeftover: leftover }
+}
+
+// Resolves to why the removal failed, or null once no item is left.
+async function removeKeychainLeftover(runtime: Runtime, host: string): Promise<string | null> {
+ try {
+ await new KeychainStore(runtime).remove(host)
+ return null
+ } catch (error) {
+ return error instanceof Error ? error.message : String(error)
+ }
+}
+
+// For a host settings.json names no keychain item for. A machine without a usable keychain can't
+// hold one, so only a refused or abandoned removal counts as a failure.
+async function sweepKeychain(runtime: Runtime, host: string): Promise<{ removed: boolean; error: string | null }> {
+ try {
+ return { removed: await new KeychainStore(runtime).remove(host), error: null }
+ } catch (error) {
+ if (error instanceof HogError && error.code === 'keychain_unavailable') {
+ return { removed: false, error: null }
+ }
+ return { removed: false, error: error instanceof Error ? error.message : String(error) }
+ }
+}
+
+// Logs this machine out of every host in settings.json or the credentials file. It also removes the
+// entries of the credentials file and the keychain items that settings.json doesn't name, such as a
+// keychain item from before settings.json was lost.
+export async function logoutAll(runtime: Runtime): Promise<LoggedOutHost[]> {
+ const settings = await readSettings(runtime)
+ const file = new FileStore(runtime)
+ const hosts = new Map<HostKey, string>()
+ const recorded = Object.values(settings.logins ?? {}).flatMap((record) => (record ? [record.host] : []))
+ for (const host of [...recorded, ...(await file.hosts())]) {
+ if (!hosts.has(hostKey(host))) {
+ hosts.set(hostKey(host), host)
+ }
+ }
+ const loggedOut: LoggedOutHost[] = []
+ for (const host of hosts.values()) {
+ const record = loginFor(settings, host)
+ const outcome = await logout(runtime, host)
+ const orphan = await file.remove(host)
+ // Logout already handled a keychain login and a marked leftover.
+ const swept =
+ record?.store !== 'keychain' && !record?.keychainLeftover
+ ? await sweepKeychain(runtime, host)
+ : { removed: false, error: null }
+ if (outcome || orphan || swept.removed || swept.error) {
+ const base = outcome ?? { revoked: null, revokeUrl: null, keychainLeftover: null }
+ loggedOut.push({ ...base, keychainLeftover: base.keychainLeftover ?? swept.error, host })
+ }
+ }
+ return loggedOut
+}
diff --git a/hog/src/posthog/settings.ts b/hog/src/posthog/settings.ts
new file mode 100644
index 000000000000..ec5c0869b1d1
--- /dev/null
+++ b/hog/src/posthog/settings.ts
@@ -0,0 +1,98 @@
+import { hogFile } from '@/core/paths'
+import type { Runtime } from '@/core/runtime'
+import type { StoreChoice } from '@/posthog/credential-store/types'
+
+import { hostKey, type HostKey } from './host'
+
+// What settings.json keeps about the login to one host: everything except its secrets.
+export interface LoginRecord {
+ // hog probes the keychain only at login, because a probe can open a dialog. Each host keeps its
+ // own answer, so a login over SSH that had to use the file doesn't hide a keychain login to
+ // another host.
+ store: StoreChoice
+ type: 'personal_api_key'
+ projectId: string
+ // The host the login was made for, with the path a self-hosted PostHog sits under. The login is
+ // keyed by origin, so a posthog.json path on the same origin can't send it elsewhere.
+ host: string
+ // Set on a file login that replaced a keychain login while the keychain was unusable, so the old
+ // keychain item can still be there. Logout tries to remove it.
+ keychainLeftover?: true
+}
+
+// What `hog auth login` decided, kept so later runs don't decide again. Nothing in it is secret.
+export interface HogSettings {
+ logins?: Partial<Record<HostKey, LoginRecord>>
+ // The host of the last login, which commands use when neither --host nor posthog.json names one.
+ host?: string
+}
+
+const SETTINGS_FILE = 'settings.json'
+
+function settingsPath(runtime: Runtime): string {
+ return hogFile(runtime, SETTINGS_FILE)
+}
+
+// A record hog doesn't recognize, such as one a later version wrote, reads as no login.
+function parseLoginRecord(origin: string, value: unknown): LoginRecord | undefined {
+ const item = value as Record<string, unknown> | null
+ if (
+ (item?.store === 'keychain' || item?.store === 'file') &&
+ item.type === 'personal_api_key' &&
+ typeof item.projectId === 'string' &&
+ typeof item.host === 'string' &&
+ hostKey(item.host) === hostKey(origin)
+ ) {
+ const record: LoginRecord = { store: item.store, type: item.type, projectId: item.projectId, host: item.host }
+ return item.keychainLeftover === true ? { ...record, keychainLeftover: true } : record
+ }
+ return undefined
+}
+
+// A missing or broken file means hog has no settings yet. Any other read failure stops the command,
+// because a later write would replace the logins of every host with an empty file.
+export async function readSettings(runtime: Runtime): Promise<HogSettings> {
+ let text: string
+ try {
+ text = await runtime.readFile(settingsPath(runtime))
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
+ return {}
+ }
+ throw error
+ }
+ let parsed: unknown
+ try {
+ parsed = JSON.parse(text)
+ } catch {
+ return {}
+ }
+ const raw = (typeof parsed === 'object' && parsed !== null ? parsed : {}) as Record<string, unknown>
+ const logins: Partial<Record<HostKey, LoginRecord>> = {}
+ if (typeof raw.logins === 'object' && raw.logins !== null) {
+ for (const [host, value] of Object.entries(raw.logins)) {
+ const record = parseLoginRecord(host, value)
+ if (record) {
+ logins[hostKey(host)] = record
+ }
+ }
+ }
+ return {
+ logins,
+ host: typeof raw.host === 'string' ? raw.host : undefined,
+ }
+}
+
+export function loginFor(settings: HogSettings, host: string): LoginRecord | undefined {
+ return settings.logins?.[hostKey(host)]
+}
+
+// The settings with the login for `host` replaced, or removed when `record` is undefined.
+export function withLogin(settings: HogSettings, host: string, record: LoginRecord | undefined): HogSettings {
+ const { [hostKey(host)]: _previous, ...others } = settings.logins ?? {}
+ return { ...settings, logins: record ? { ...others, [hostKey(host)]: record } : others }
+}
+
+export async function writeSettings(runtime: Runtime, settings: HogSettings): Promise<void> {
+ await runtime.writePrivateFile(settingsPath(runtime), JSON.stringify(settings, null, 2))
+}
diff --git a/hog/src/testing.ts b/hog/src/testing.ts
index 3f56555cd3bd..358a812fbcd8 100644
--- a/hog/src/testing.ts
+++ b/hog/src/testing.ts
@@ -3,7 +3,7 @@ import { existsSync, readFileSync, statSync } from 'node:fs'
import type { ApiToolLibrary } from '@posthog/mcp/src/cli/library-types'
import type { Prompts } from '@/core/prompts'
-import type { Env, Runtime } from '@/core/runtime'
+import type { Env, Runtime, Secrets } from '@/core/runtime'
import { run } from './cli'
@@ -24,6 +24,10 @@ export interface FakeRuntimeOptions {
telemetryToken?: string
// The MCP tool catalog `hog api` loads. Without it, loading the catalog fails the test.
apiTools?: ApiToolLibrary
+ // Items already in the keychain, by name.
+ keychain?: Record<string, string>
+ // Replaces the keychain, to fake one that is slow, unavailable or denied.
+ secrets?: (runtime: FakeRuntime) => Secrets
}
export interface FakeRuntime extends Runtime {
@@ -33,6 +37,7 @@ export interface FakeRuntime extends Runtime {
files: Record<string, string>
opened: string[]
tls: { verify: boolean }
+ keychain: Record<string, string>
}
function fakePrompts(answers: string[]): Prompts {
@@ -53,6 +58,71 @@ function fakePrompts(answers: string[]): Prompts {
}
}
+function memorySecrets(items: Record<string, string>): Secrets {
+ return {
+ get: async (name) => items[name] ?? null,
+ set: async (name, value) => {
+ items[name] = value
+ },
+ delete: async (name) => {
+ const existed = name in items
+ delete items[name]
+ return existed
+ },
+ }
+}
+
+// A clock that only moves when hog sleeps, so polling runs instantly. Timers fire in the order they
+// are due, and only once no other work is left, so a race between a timeout and a slow call ends as
+// it would in real time.
+function fakeClock(start: number): { now: () => number; sleep: Runtime['sleep'] } {
+ let clock = start
+ let sequence = 0
+ let scheduled = false
+ const timers: { at: number; sequence: number; fire: () => void }[] = []
+ const fireNext = (): void => {
+ scheduled = false
+ timers.sort((a, b) => a.at - b.at || a.sequence - b.sequence)
+ const next = timers.shift()
+ if (next) {
+ clock = Math.max(clock, next.at)
+ next.fire()
+ schedule()
+ }
+ }
+ const schedule = (): void => {
+ if (!scheduled && timers.length > 0) {
+ scheduled = true
+ setImmediate(fireNext)
+ }
+ }
+ return {
+ now: () => clock,
+ sleep: (ms, signal) =>
+ new Promise((resolve) => {
+ if (signal?.aborted) {
+ resolve()
+ return
+ }
+ const timer = { at: clock + ms, sequence: sequence++, fire: resolve }
+ timers.push(timer)
+ signal?.addEventListener(
+ 'abort',
+ () => {
+ // A timer that already fired is gone, and splice(-1) would drop another one.
+ const index = timers.indexOf(timer)
+ if (index >= 0) {
+ timers.splice(index, 1)
+ }
+ resolve()
+ },
+ { once: true }
+ )
+ schedule()
+ }),
+ }
+}
+
export function fakeRuntime(options: FakeRuntimeOptions = {}): FakeRuntime {
let stdout = ''
let stderr = ''
@@ -60,10 +130,12 @@ export function fakeRuntime(options: FakeRuntimeOptions = {}): FakeRuntime {
const files = { ...options.files }
const opened: string[] = []
const tls = { verify: true }
- // A clock that only moves when hog sleeps, so polling runs instantly.
- let clock = Date.UTC(2026, 0, 1)
- return {
+ const keychain = { ...options.keychain }
+ const clock = fakeClock(Date.UTC(2026, 0, 1))
+ const runtime: FakeRuntime = {
env: options.env ?? {},
+ platform: 'linux',
+ isDevelopment: false,
stdinIsTTY: options.stdoutIsTTY ?? false,
stdoutIsTTY: options.stdoutIsTTY ?? false,
stdoutHasColors: options.stdoutIsTTY ?? false,
@@ -82,10 +154,8 @@ 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
- },
+ now: clock.now,
+ sleep: clock.sleep,
homeDir: () => '/home/test',
cwd: () => options.cwd ?? '/work',
// A path exists when it is a file, or a folder some file sits under.
@@ -137,6 +207,7 @@ export function fakeRuntime(options: FakeRuntimeOptions = {}): FakeRuntime {
return true
},
prompts: fakePrompts([...(options.answers ?? [])]),
+ secrets: memorySecrets(keychain),
telemetryToken: options.telemetryToken,
skipTlsVerification: () => {
tls.verify = false
@@ -153,7 +224,12 @@ export function fakeRuntime(options: FakeRuntimeOptions = {}): FakeRuntime {
files,
opened,
tls,
+ keychain,
+ }
+ if (options.secrets) {
+ runtime.secrets = options.secrets(runtime)
}
+ return runtime
}
// Credentials that pass validation, plus NO_COLOR so text output has no escape codes.
@@ -173,6 +249,7 @@ export interface HogRun {
opened: string[]
elapsedMs: number
tls: { verify: boolean }
+ keychain: Record<string, string>
json: () => any
error: () => any
}
@@ -190,6 +267,7 @@ export async function runHog(argv: string[], options: FakeRuntimeOptions = {}):
opened: runtime.opened,
elapsedMs: runtime.now() - start,
tls: runtime.tls,
+ keychain: runtime.keychain,
json: () => JSON.parse(runtime.stdout()),
error: () => JSON.parse(runtime.stderr()).error,
}