78 lines
2.1 KiB
Go
78 lines
2.1 KiB
Go
package claude
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"os/exec"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// 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...)
|
|
}
|
|
|
|
func hasEnv(env []string, key string) bool {
|
|
for _, item := range env {
|
|
if strings.HasPrefix(item, key+"=") {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|