(
opts: { skipRetrievingKeyFromApiKeyHelper?: boolean } = {},
)
| 255 | } |
| 256 | |
| 257 | export function getAnthropicApiKeyWithSource( |
| 258 | opts: { skipRetrievingKeyFromApiKeyHelper?: boolean } = {}, |
| 259 | ): { |
| 260 | key: null | string |
| 261 | source: ApiKeySource |
| 262 | } { |
| 263 | if (isOpenAICompatibleProviderActive()) { |
| 264 | const configuredProviderApiKey = getConfiguredProviderApiKey() |
| 265 | if (configuredProviderApiKey) { |
| 266 | return { |
| 267 | key: configuredProviderApiKey, |
| 268 | source: 'ANTHROPIC_API_KEY', |
| 269 | } |
| 270 | } |
| 271 | return { key: null, source: 'none' } |
| 272 | } |
| 273 | |
| 274 | // --bare: hermetic auth. Only ANTHROPIC_API_KEY env or apiKeyHelper from |
| 275 | // the --settings flag. Never touches keychain, config file, or approval |
| 276 | // lists. 3P (Bedrock/Vertex/Foundry) uses provider creds, not this path. |
| 277 | if (isBareMode()) { |
| 278 | if (process.env.ANTHROPIC_API_KEY) { |
| 279 | return { key: process.env.ANTHROPIC_API_KEY, source: 'ANTHROPIC_API_KEY' } |
| 280 | } |
| 281 | if (getConfiguredApiKeyHelper()) { |
| 282 | return { |
| 283 | key: opts.skipRetrievingKeyFromApiKeyHelper |
| 284 | ? null |
| 285 | : getApiKeyFromApiKeyHelperCached(), |
| 286 | source: 'apiKeyHelper', |
| 287 | } |
| 288 | } |
| 289 | return { key: null, source: 'none' } |
| 290 | } |
| 291 | |
| 292 | // On homespace, don't use ANTHROPIC_API_KEY (use Console key instead) |
| 293 | // https://anthropic.slack.com/archives/C08428WSLKV/p1747331773214779 |
| 294 | const apiKeyEnv = isRunningOnHomespace() |
| 295 | ? undefined |
| 296 | : process.env.ANTHROPIC_API_KEY |
| 297 | |
| 298 | // Always check for direct environment variable when the user ran claude --print. |
| 299 | // This is useful for CI, etc. |
| 300 | if (preferThirdPartyAuthentication() && apiKeyEnv) { |
| 301 | return { |
| 302 | key: apiKeyEnv, |
| 303 | source: 'ANTHROPIC_API_KEY', |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | if (isEnvTruthy(process.env.CI) || process.env.NODE_ENV === 'test') { |
| 308 | // Check for API key from file descriptor first |
| 309 | const apiKeyFromFd = getApiKeyFromFileDescriptor() |
| 310 | if (apiKeyFromFd) { |
| 311 | return { |
| 312 | key: apiKeyFromFd, |
| 313 | source: 'ANTHROPIC_API_KEY', |
| 314 | } |
no test coverage detected