package claude import ( "context" "encoding/json" "log" "os" "os/exec" "strings" "sync" "time" "git.a-wan.net/alan/pipelines/internal/workenv" ) // secureStorageEnvKey points Claude Code's credential lookup at a config // directory. With it set to the ordinary ~/.claude, Claude Code reads the // login file a terminal sign-in keeps there instead of a keychain entry. const secureStorageEnvKey = "CLAUDE_SECURESTORAGE_CONFIG_DIR" // authStatus runs `claude auth status` with [env] and reports loggedIn. type authStatus func(ctx context.Context, binary string, env []string) bool func cliLoggedIn(ctx context.Context, binary string, env []string) bool { ctx, cancel := context.WithTimeout(ctx, 20*time.Second) defer cancel() cmd := exec.CommandContext(ctx, binary, "auth", "status") cmd.Env = env out, err := cmd.Output() if err != nil { return false } var status struct { LoggedIn bool `json:"loggedIn"` } return json.Unmarshal(out, &status) == nil && status.LoggedIn } // authEnv chooses how Claude Code processes started by the server sign in. // A server running as a background service can see a stale keychain entry // where the operator's terminal sees a valid login file; when the default is // not signed in but the login file is, the server uses the login file. type authEnv struct { once sync.Once extra []string status authStatus } func (a *authEnv) resolve(ctx context.Context, binary string, base []string) []string { a.once.Do(func() { status := a.status if status == nil { status = cliLoggedIn } if hasEnv(base, secureStorageEnvKey) || hasEnv(base, "CLAUDE_CONFIG_DIR") || hasEnv(base, "CLAUDE_CODE_OAUTH_TOKEN") || hasEnv(base, "ANTHROPIC_API_KEY") { return } if status(ctx, binary, base) { return } dir := ConfigDir() if dir == "" { return } candidate := append(append([]string{}, base...), secureStorageEnvKey+"="+dir) if status(ctx, binary, candidate) { a.extra = []string{secureStorageEnvKey + "=" + dir} } }) return append(append([]string{}, base...), a.extra...) } // SignedIn reports whether Claude Code started with env is signed in, trying // the same sources the server uses for the processes it starts: the default // login, then the login file in ConfigDir, then the private service token. The // second result names the source that worked. func SignedIn(ctx context.Context, binary string, env []string) (bool, string) { if cliLoggedIn(ctx, binary, env) { return true, "Claude Code login" } if dir := ConfigDir(); dir != "" && !hasEnv(env, secureStorageEnvKey) && !hasEnv(env, "CLAUDE_CONFIG_DIR") { if cliLoggedIn(ctx, binary, append(append([]string{}, env...), secureStorageEnvKey+"="+dir)) { return true, "login file in " + dir } } if HasServiceToken() && !hasEnv(env, "CLAUDE_CODE_OAUTH_TOKEN") { if cliLoggedIn(ctx, binary, withServiceToken(append([]string{}, env...))) { return true, "service token " + serviceTokenPath() } } return false, "" } // A chat directory whose own environment (direnv, mise) sets or unsets any of // workenv.AccountEnvKeys owns the account: the server's fallbacks (service // token, login file) are not added and inherited credentials are dropped, // exactly as a terminal opened in that directory would behave. Pipeline stages // apply the same rule through workenv.Environment. // processEnv is the environment for a CLI process started in directory: the // server's environment, then the directory's own environment, then the // server's sign-in fallbacks only when the directory does not choose an // account. The second result holds operator-facing warnings. func (c *Chat) processEnv(ctx context.Context, directory string) ([]string, []string) { return c.processEnvFrom(ctx, directory, os.Environ()) } func (c *Chat) processEnvFrom(ctx context.Context, directory string, base []string) ([]string, []string) { var dir workenv.Result if c.dirEnv != nil { dir = c.dirEnv.Resolve(ctx, directory, base) } for _, warning := range dir.Warnings { log.Printf("claude chat directory %s: %s", directory, warning) } var env []string if dir.OwnsAccount() { kept, _ := dir.WithoutInheritedCredentials(base) env = dir.Apply(kept) } else { env = c.auth.resolve(c.ctx, c.binary, withServiceToken(dir.Apply(base))) } if value, ok := envValue(env, "CLAUDE_CONFIG_DIR"); ok { rememberConfigDir(value) } return workenv.WithPWD(env, directory), dir.Warnings } // HintDirectory tells the adapter the recorded directory of a session it has // not opened in this server process, so a transcript kept in that // directory's own CLAUDE_CONFIG_DIR is found after a restart. func (c *Chat) HintDirectory(ctx context.Context, id, directory string) { if id == "" || strings.TrimSpace(directory) == "" || c.session(id) != nil { return } if _, done := c.hinted.LoadOrStore(id, true); done { return } if c.dirEnv == nil { return } if value, ok := c.dirEnv.Resolve(ctx, directory, os.Environ()).Value("CLAUDE_CONFIG_DIR"); ok { rememberConfigDir(value) } } func envValue(env []string, key string) (string, bool) { for i := len(env) - 1; i >= 0; i-- { if k, v, ok := strings.Cut(env[i], "="); ok && k == key { return v, true } } return "", false } // ServiceTokenPath is the token file the server reads. func ServiceTokenPath() string { return serviceTokenPath() } func hasEnv(env []string, key string) bool { for _, item := range env { if strings.HasPrefix(item, key+"=") { return true } } return false }