package claude import ( "os" "path/filepath" "strings" ) // ServiceTokenEnvKey names a file holding a long-lived Claude Code token // (`claude setup-token`). Default: ~/.config/pipelines/claude-token. const ServiceTokenEnvKey = "PIPELINES_CLAUDE_TOKEN_FILE" // serviceTokenPath is the private token file the server hands to the Claude // Code processes it starts. A server running as a background service (launchd, // systemd) cannot rely on the interactive login a terminal uses, so a token // made for this purpose keeps its chats signed in. func serviceTokenPath() string { if path := strings.TrimSpace(os.Getenv(ServiceTokenEnvKey)); path != "" { return path } home, err := os.UserHomeDir() if err != nil { return "" } return filepath.Join(home, ".config", "pipelines", "claude-token") } // readServiceToken returns the token from a private (owner-only) regular // file, or "" when there is none. func readServiceToken(path string) string { if path == "" { return "" } info, err := os.Lstat(path) if err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0o077 != 0 { return "" } data, err := os.ReadFile(path) if err != nil { return "" } return strings.TrimSpace(string(data)) } // withServiceToken adds the service token to [env] unless the environment // already names one. func withServiceToken(env []string) []string { for _, item := range env { if strings.HasPrefix(item, "CLAUDE_CODE_OAUTH_TOKEN=") { return env } } token := readServiceToken(serviceTokenPath()) if token == "" { return env } return append(env, "CLAUDE_CODE_OAUTH_TOKEN="+token) } // HasServiceToken reports whether a usable service token is configured, for // the server's startup report. func HasServiceToken() bool { return readServiceToken(serviceTokenPath()) != "" }