(
opts: { skipRetrievingKeyFromApiKeyHelper?: boolean } = {},
)
| 290 | } |
| 291 | |
| 292 | export function getAnthropicApiKeyWithSource( |
| 293 | opts: { skipRetrievingKeyFromApiKeyHelper?: boolean } = {}, |
| 294 | ): { |
| 295 | key: null | string |
| 296 | source: ApiKeySource |
| 297 | } { |
| 298 | // --bare: hermetic static-key auth. Only direct env keys or apiKeyHelper from |
| 299 | // the --settings flag are read. Never touches keychain, config file, or |
| 300 | // approval lists. 3P (Bedrock/Vertex/Foundry) uses provider creds, not this |
| 301 | // path. |
| 302 | if (isBareMode()) { |
| 303 | const directApiKey = getDirectApiKeyEnvValue() |
| 304 | if (directApiKey) { |
| 305 | return { |
| 306 | key: directApiKey, |
| 307 | source: getDirectApiKeyEnvVarName() ?? 'ANTHROPIC_API_KEY', |
| 308 | } |
| 309 | } |
| 310 | if (getConfiguredApiKeyHelper()) { |
| 311 | return { |
| 312 | key: opts.skipRetrievingKeyFromApiKeyHelper |
| 313 | ? null |
| 314 | : getApiKeyFromApiKeyHelperCached(), |
| 315 | source: 'apiKeyHelper', |
| 316 | } |
| 317 | } |
| 318 | return { key: null, source: 'none' } |
| 319 | } |
| 320 | |
| 321 | // On homespace, don't use direct API-key env overrides (use Console key instead) |
| 322 | // https://anthropic.slack.com/archives/C08428WSLKV/p1747331773214779 |
| 323 | const apiKeyEnv = isRunningOnHomespace() |
| 324 | ? undefined |
| 325 | : getDirectApiKeyEnvValue() |
| 326 | const directApiKeySource = getDirectApiKeyEnvVarName() ?? 'ANTHROPIC_API_KEY' |
| 327 | |
| 328 | // Always check for direct environment variable when the user ran claude --print. |
| 329 | // This is useful for CI, etc. |
| 330 | if (preferThirdPartyAuthentication() && apiKeyEnv) { |
| 331 | return { |
| 332 | key: apiKeyEnv, |
| 333 | source: directApiKeySource, |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | if (isEnvTruthy(process.env.CI) || process.env.NODE_ENV === 'test') { |
| 338 | // Check for API key from file descriptor first |
| 339 | const apiKeyFromFd = getApiKeyFromFileDescriptor() |
| 340 | if (apiKeyFromFd) { |
| 341 | return { |
| 342 | key: apiKeyFromFd, |
| 343 | source: 'ANTHROPIC_API_KEY', |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | if ( |
| 348 | !apiKeyEnv && |
| 349 | !process.env.NCODE_OAUTH_TOKEN && |
no test coverage detected