MCPcopy
hub / github.com/codeaashu/claude-code / getAnthropicApiKeyWithSource

Function getAnthropicApiKeyWithSource

src/utils/auth.ts:226–348  ·  view source on GitHub ↗
(
  opts: { skipRetrievingKeyFromApiKeyHelper?: boolean } = {},
)

Source from the content-addressed store, hash-verified

224}
225
226export function getAnthropicApiKeyWithSource(
227 opts: { skipRetrievingKeyFromApiKeyHelper?: boolean } = {},
228): {
229 key: null | string
230 source: ApiKeySource
231} {
232 // --bare: hermetic auth. Only ANTHROPIC_API_KEY env or apiKeyHelper from
233 // the --settings flag. Never touches keychain, config file, or approval
234 // lists. 3P (Bedrock/Vertex/Foundry) uses provider creds, not this path.
235 if (isBareMode()) {
236 if (process.env.ANTHROPIC_API_KEY) {
237 return { key: process.env.ANTHROPIC_API_KEY, source: 'ANTHROPIC_API_KEY' }
238 }
239 if (getConfiguredApiKeyHelper()) {
240 return {
241 key: opts.skipRetrievingKeyFromApiKeyHelper
242 ? null
243 : getApiKeyFromApiKeyHelperCached(),
244 source: 'apiKeyHelper',
245 }
246 }
247 return { key: null, source: 'none' }
248 }
249
250 // On homespace, don't use ANTHROPIC_API_KEY (use Console key instead)
251 // https://anthropic.slack.com/archives/C08428WSLKV/p1747331773214779
252 const apiKeyEnv = isRunningOnHomespace()
253 ? undefined
254 : process.env.ANTHROPIC_API_KEY
255
256 // Always check for direct environment variable when the user ran claude --print.
257 // This is useful for CI, etc.
258 if (preferThirdPartyAuthentication() && apiKeyEnv) {
259 return {
260 key: apiKeyEnv,
261 source: 'ANTHROPIC_API_KEY',
262 }
263 }
264
265 if (isEnvTruthy(process.env.CI) || process.env.NODE_ENV === 'test') {
266 // Check for API key from file descriptor first
267 const apiKeyFromFd = getApiKeyFromFileDescriptor()
268 if (apiKeyFromFd) {
269 return {
270 key: apiKeyFromFd,
271 source: 'ANTHROPIC_API_KEY',
272 }
273 }
274
275 if (
276 !apiKeyEnv &&
277 !process.env.CLAUDE_CODE_OAUTH_TOKEN &&
278 !process.env.CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR
279 ) {
280 throw new Error(
281 'ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN env var is required',
282 )
283 }

Callers 13

isAnthropicAuthEnabledFunction · 0.85
getAnthropicApiKeyFunction · 0.85
hasAnthropicApiKeyAuthFunction · 0.85
getAccountInformationFunction · 0.85
buildSystemInitMessageFunction · 0.85
authStatusFunction · 0.85
isPolicyLimitsEligibleFunction · 0.85
getAuthHeadersFunction · 0.85

Calls 9

isBareModeFunction · 0.85
isRunningOnHomespaceFunction · 0.85
isEnvTruthyFunction · 0.85
getGlobalConfigFunction · 0.85
normalizeApiKeyForConfigFunction · 0.85

Tested by

no test coverage detected