:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(cli): return an error instead of panicking without a home directory (#127426)
posthog[bot]5d6bc49b8642
diff --git a/cli/.sampo/changesets/calm-homeless-credentials.md b/cli/.sampo/changesets/calm-homeless-credentials.mdnew file mode 100644index 000000000000..5fca9a1a072d--- /dev/null+++ b/cli/.sampo/changesets/calm-homeless-credentials.md@@ -0,0 +1,5 @@+---+cargo/posthog-cli: patch+---++Return a credentials error that names `POSTHOG_HOME` and the env credential variables, instead of panicking, when no home directory can be founddiff --git a/cli/src/experimental/tui/query.rs b/cli/src/experimental/tui/query.rsindex 96cef62bf02a..690a3c66bd97 100644--- a/cli/src/experimental/tui/query.rs+++ b/cli/src/experimental/tui/query.rs@@ -98,7 +98,7 @@ impl QueryTui {if !self.state_dirty {return Ok(());}- let home_dir = posthog_home_dir();+ let home_dir = posthog_home_dir()?;let editor_state_path = home_dir.join("editor_state.json");let state = PersistedEditorState {lines,@@ -111,7 +111,7 @@ impl QueryTui {}fn load_editor_state(&mut self) -> Result<Vec<String>, Error> {- let home_dir = posthog_home_dir();+ let home_dir = posthog_home_dir()?;let editor_state_path = home_dir.join("editor_state.json");if !editor_state_path.exists() {return Ok(vec![]);diff --git a/cli/src/utils/auth.rs b/cli/src/utils/auth.rsindex 741b55e10992..d56149be896e 100644--- a/cli/src/utils/auth.rs+++ b/cli/src/utils/auth.rs@@ -33,7 +33,7 @@ pub struct HomeDirProvider;impl CredentialProvider for HomeDirProvider {fn get_credentials(&self) -> Result<Token, Error> {- let home = posthog_home_dir();+ let home = posthog_home_dir()?;let file = home.join("credentials.json");let token = std::fs::read_to_string(file.clone()).context(format!("While trying to read credentials from file {file:?}"@@ -43,7 +43,7 @@ impl CredentialProvider for HomeDirProvider {}fn store_credentials(&self, token: Token) -> Result<(), Error> {- let home = posthog_home_dir();+ let home = posthog_home_dir()?;ensure_homedir_exists()?;let file = home.join("credentials.json");let token = serde_json::to_string(&token).context("While trying to serialize token")?;@@ -54,10 +54,10 @@ impl CredentialProvider for HomeDirProvider {}fn report_location(&self) -> String {- posthog_home_dir()- .join("credentials.json")- .to_string_lossy()- .to_string()+ match posthog_home_dir() {+ Ok(home) => home.join("credentials.json").to_string_lossy().to_string(),+ Err(_) => "an unknown location (no home directory)".to_string(),+ }}}diff --git a/cli/src/utils/homedir.rs b/cli/src/utils/homedir.rsindex dfc59e5b40c7..49cd40997a15 100644--- a/cli/src/utils/homedir.rs+++ b/cli/src/utils/homedir.rs@@ -1,24 +1,46 @@-use std::path::PathBuf;+use std::{ffi::OsString, path::PathBuf};use anyhow::{Context, Error};// IF `POSTHOG_HOME` is set, use that, otherwise use $HOME/.posthogpub fn posthog_home_dir_if_available() -> Option<PathBuf> {- if let Some(home) = std::env::var_os("POSTHOG_HOME") {- return Some(PathBuf::from(home));- }+ posthog_home_dir().ok()+}- let mut home = dirs::home_dir()?;- home.push(".posthog");- Some(home)+pub fn posthog_home_dir() -> Result<PathBuf, Error> {+ resolve_posthog_home(std::env::var_os("POSTHOG_HOME"), dirs::home_dir())}-pub fn posthog_home_dir() -> PathBuf {- posthog_home_dir_if_available().expect("Could not find home directory")+fn resolve_posthog_home(+ posthog_home: Option<OsString>,+ home: Option<PathBuf>,+) -> Result<PathBuf, Error> {+ if let Some(posthog_home) = posthog_home {+ return Ok(PathBuf::from(posthog_home));+ }++ let mut home = home.context(+ "Could not find a home directory. Set POSTHOG_HOME to a writable directory, \+ or set POSTHOG_CLI_API_KEY and POSTHOG_CLI_PROJECT_ID to authenticate without one",+ )?;+ home.push(".posthog");+ Ok(home)}pub fn ensure_homedir_exists() -> Result<(), Error> {- let home = posthog_home_dir();+ let home = posthog_home_dir()?;std::fs::create_dir_all(&home).context(format!("While trying to create directory {home:?}"))?;Ok(())}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn resolve_posthog_home_errors_with_hint_when_no_home_is_found() {+ let err = resolve_posthog_home(None, None).unwrap_err().to_string();+ assert!(err.contains("POSTHOG_HOME"));+ assert!(err.contains("POSTHOG_CLI_API_KEY"));+ }+}diff --git a/hog/src/core/runtime.ts b/hog/src/core/runtime.tsindex 3a3c2e394526..e132972bf8a2 100644--- a/hog/src/core/runtime.ts+++ b/hog/src/core/runtime.ts@@ -92,7 +92,10 @@ export function processRuntime(): Runtime {sleep: (ms) => Bun.sleep(ms),homeDir: () => {try {- return homedir()+ const home = homedir()+ // When HOME is unset and the user has no passwd entry, Node throws but Bun returns "/".+ // A "/" that came from HOME itself is a real choice, so it still counts.+ return !home || (home === '/' && !process.env.HOME) ? undefined : home} catch {return undefined}diff --git a/hog/src/posthog/credentials.test.ts b/hog/src/posthog/credentials.test.tsindex 129ed505d77a..30b4e19a524f 100644--- a/hog/src/posthog/credentials.test.ts+++ b/hog/src/posthog/credentials.test.ts@@ -125,4 +125,15 @@ describe('resolveCredentials', () => {const error = await resolveCredentials(runtime, { dotenvFile: '/x/.env' }).catch((caught: unknown) => caught)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 () => {+ 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('HOG_API_KEY')+ })})diff --git a/hog/src/posthog/credentials.ts b/hog/src/posthog/credentials.tsindex 6088e79e360e..9ba72ea66c18 100644--- a/hog/src/posthog/credentials.ts+++ b/hog/src/posthog/credentials.ts@@ -79,6 +79,9 @@ async function readDotenv(runtime: Runtime, path: string): Promise<string | unde}}+const NO_HOME_HINT =+ 'Set HOG_HOME to a folder hog can write to, or set HOG_API_KEY and HOG_PROJECT_ID to skip logging in.'+function posthogHomeDir(env: Env, homeDir: string | undefined): string | undefined {if (env.HOG_HOME) {return env.HOG_HOME@@ -92,7 +95,7 @@ export function posthogFile(runtime: Runtime, name: string): string {throw new HogError('no_home_directory',"hog couldn't find your home folder to store credentials in.",- 'Set HOG_HOME to the folder to use.'+ NO_HOME_HINT)}return join(home, name)@@ -191,21 +194,26 @@ export async function resolveCredentials(}const home = posthogHomeDir(runtime.env, runtime.homeDir())- if (home !== undefined) {- 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,- }- return withHost(raw, 'credentials-file')+ 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,}+ return withHost(raw, 'credentials-file')}throw new HogError(