@anthropic-ai/sdk 0.92.0 → 0.94.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/client.d.mts +73 -0
  3. package/client.d.mts.map +1 -1
  4. package/client.d.ts +73 -0
  5. package/client.d.ts.map +1 -1
  6. package/client.js +258 -9
  7. package/client.js.map +1 -1
  8. package/client.mjs +258 -9
  9. package/client.mjs.map +1 -1
  10. package/core/credentials.d.mts +131 -0
  11. package/core/credentials.d.mts.map +1 -0
  12. package/core/credentials.d.ts +131 -0
  13. package/core/credentials.d.ts.map +1 -0
  14. package/core/credentials.js +317 -0
  15. package/core/credentials.js.map +1 -0
  16. package/core/credentials.mjs +277 -0
  17. package/core/credentials.mjs.map +1 -0
  18. package/internal/utils/time.d.mts +3 -0
  19. package/internal/utils/time.d.mts.map +1 -0
  20. package/internal/utils/time.d.ts +3 -0
  21. package/internal/utils/time.d.ts.map +1 -0
  22. package/internal/utils/time.js +8 -0
  23. package/internal/utils/time.js.map +1 -0
  24. package/internal/utils/time.mjs +5 -0
  25. package/internal/utils/time.mjs.map +1 -0
  26. package/lib/credentials/credential-chain.d.mts +39 -0
  27. package/lib/credentials/credential-chain.d.mts.map +1 -0
  28. package/lib/credentials/credential-chain.d.ts +39 -0
  29. package/lib/credentials/credential-chain.d.ts.map +1 -0
  30. package/lib/credentials/credential-chain.js +245 -0
  31. package/lib/credentials/credential-chain.js.map +1 -0
  32. package/lib/credentials/credential-chain.mjs +208 -0
  33. package/lib/credentials/credential-chain.mjs.map +1 -0
  34. package/lib/credentials/identity-token.d.mts +11 -0
  35. package/lib/credentials/identity-token.d.mts.map +1 -0
  36. package/lib/credentials/identity-token.d.ts +11 -0
  37. package/lib/credentials/identity-token.d.ts.map +1 -0
  38. package/lib/credentials/identity-token.js +72 -0
  39. package/lib/credentials/identity-token.js.map +1 -0
  40. package/lib/credentials/identity-token.mjs +35 -0
  41. package/lib/credentials/identity-token.mjs.map +1 -0
  42. package/lib/credentials/oidc-federation.d.mts +40 -0
  43. package/lib/credentials/oidc-federation.d.mts.map +1 -0
  44. package/lib/credentials/oidc-federation.d.ts +40 -0
  45. package/lib/credentials/oidc-federation.d.ts.map +1 -0
  46. package/lib/credentials/oidc-federation.js +82 -0
  47. package/lib/credentials/oidc-federation.js.map +1 -0
  48. package/lib/credentials/oidc-federation.mjs +79 -0
  49. package/lib/credentials/oidc-federation.mjs.map +1 -0
  50. package/lib/credentials/token-cache.d.mts +54 -0
  51. package/lib/credentials/token-cache.d.mts.map +1 -0
  52. package/lib/credentials/token-cache.d.ts +54 -0
  53. package/lib/credentials/token-cache.d.ts.map +1 -0
  54. package/lib/credentials/token-cache.js +112 -0
  55. package/lib/credentials/token-cache.js.map +1 -0
  56. package/lib/credentials/token-cache.mjs +108 -0
  57. package/lib/credentials/token-cache.mjs.map +1 -0
  58. package/lib/credentials/types.d.mts +96 -0
  59. package/lib/credentials/types.d.mts.map +1 -0
  60. package/lib/credentials/types.d.ts +96 -0
  61. package/lib/credentials/types.d.ts.map +1 -0
  62. package/lib/credentials/types.js +266 -0
  63. package/lib/credentials/types.js.map +1 -0
  64. package/lib/credentials/types.mjs +224 -0
  65. package/lib/credentials/types.mjs.map +1 -0
  66. package/lib/credentials/user-oauth.d.mts +21 -0
  67. package/lib/credentials/user-oauth.d.mts.map +1 -0
  68. package/lib/credentials/user-oauth.d.ts +21 -0
  69. package/lib/credentials/user-oauth.d.ts.map +1 -0
  70. package/lib/credentials/user-oauth.js +130 -0
  71. package/lib/credentials/user-oauth.js.map +1 -0
  72. package/lib/credentials/user-oauth.mjs +94 -0
  73. package/lib/credentials/user-oauth.mjs.map +1 -0
  74. package/lib/credentials.d.mts +4 -0
  75. package/lib/credentials.d.mts.map +1 -0
  76. package/lib/credentials.d.ts +4 -0
  77. package/lib/credentials.d.ts.map +1 -0
  78. package/lib/credentials.js +8 -0
  79. package/lib/credentials.js.map +1 -0
  80. package/lib/credentials.mjs +3 -0
  81. package/lib/credentials.mjs.map +1 -0
  82. package/package.json +1 -1
  83. package/src/client.ts +342 -14
  84. package/src/core/credentials.ts +379 -0
  85. package/src/internal/utils/time.ts +4 -0
  86. package/src/lib/credentials/credential-chain.ts +292 -0
  87. package/src/lib/credentials/identity-token.ts +37 -0
  88. package/src/lib/credentials/oidc-federation.ts +140 -0
  89. package/src/lib/credentials/token-cache.ts +130 -0
  90. package/src/lib/credentials/types.ts +295 -0
  91. package/src/lib/credentials/user-oauth.ts +144 -0
  92. package/src/lib/credentials.ts +3 -0
  93. package/src/version.ts +1 -1
  94. package/version.d.mts +1 -1
  95. package/version.d.ts +1 -1
  96. package/version.js +1 -1
  97. package/version.mjs +1 -1
@@ -0,0 +1,379 @@
1
+ import { getPlatformHeaders } from '../internal/detect-platform';
2
+ import { readEnv } from '../internal/utils';
3
+
4
+ /** Current schema version written to `configs/<profile>.json`. Absent on read ⇒ "1.0". */
5
+ export const CONFIG_FILE_VERSION = '1.0';
6
+ /** Current schema version written to `credentials/<profile>.json`. Absent on read ⇒ "1.0". */
7
+ export const CREDENTIALS_FILE_VERSION = '1.0';
8
+
9
+ /**
10
+ * Authentication-mode-specific configuration. On the wire (configs/<profile>.json)
11
+ * this is a flat JSON object under the top-level `authentication` key — `type`,
12
+ * `credentials_path`, and the variant-specific fields all sit at the same level.
13
+ *
14
+ * Unknown fields are silently ignored for forward compatibility. Unknown
15
+ * authentication types are rejected because the SDK has no way to resolve
16
+ * credentials for them.
17
+ */
18
+ export type AuthenticationInfo = {
19
+ /**
20
+ * Filesystem path to the credentials JSON that stores access/refresh tokens.
21
+ * Defaults to `<config_dir>/credentials/<profile>.json` when omitted.
22
+ */
23
+ credentials_path?: string | undefined;
24
+ } & (
25
+ | {
26
+ type: 'oidc_federation';
27
+ /** Tagged ID (`fdrl_...`) of the federation rule. Required. */
28
+ federation_rule_id: string;
29
+ /** Optional `svac_...` expected-target check. */
30
+ service_account_id?: string | undefined;
31
+ identity_token?:
32
+ | {
33
+ source: 'file';
34
+ path: string;
35
+ }
36
+ | undefined;
37
+ /** Display-only; the SDK does not send this on the jwt-bearer exchange. */
38
+ scope?: string | undefined;
39
+ }
40
+ | {
41
+ type: 'user_oauth';
42
+ /** OAuth client ID for refresh. Empty → access token is treated as static. */
43
+ client_id?: string | undefined;
44
+ /** Display-only; the SDK does not send this on refresh. */
45
+ scope?: string | undefined;
46
+ /** Console URL the profile was created against. Display-only. */
47
+ console_url?: string | undefined;
48
+ }
49
+ );
50
+
51
+ export type AnthropicConfig = {
52
+ version?: string;
53
+ authentication: AuthenticationInfo;
54
+ base_url?: string | undefined;
55
+ organization_id?: string | undefined;
56
+ workspace_id?: string | undefined;
57
+ };
58
+
59
+ export type AnthropicCredentials = {
60
+ version?: string;
61
+ type: 'oauth_token';
62
+ access_token: string;
63
+ expires_at?: number;
64
+ refresh_token?: string;
65
+ scope?: string;
66
+ organization_uuid?: string;
67
+ organization_name?: string;
68
+ account_email?: string;
69
+ };
70
+
71
+ const PROFILE_NAME_PATTERN = /^[A-Za-z0-9_.-]+$/;
72
+
73
+ function validateProfileName(name: string): void {
74
+ if (!name) {
75
+ throw new Error('profile name is empty');
76
+ }
77
+ if (name === '.' || name === '..') {
78
+ throw new Error(`profile name "${name}" is not allowed`);
79
+ }
80
+ if (name.includes('/') || name.includes('\\')) {
81
+ throw new Error(`profile name "${name}" must not contain path separators`);
82
+ }
83
+ if (!PROFILE_NAME_PATTERN.test(name)) {
84
+ throw new Error(
85
+ `profile name "${name}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`,
86
+ );
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Loads the Anthropic configuration for the given (or active) profile.
92
+ *
93
+ * Returns `null` when running in a browser or no configuration can be resolved.
94
+ * Otherwise, returns the configuration based on the config file and environment variables.
95
+ *
96
+ * **Profile resolution** (first match wins):
97
+ * 1. Explicit `profile` argument
98
+ * 2. `ANTHROPIC_PROFILE` environment variable
99
+ * 3. Contents of `<config_dir>/active_config` file
100
+ * 4. `"default"`
101
+ *
102
+ * **Config resolution:**
103
+ * - If `<config_dir>/configs/<profile>.json` exists, it is loaded and
104
+ * missing fields are filled from environment variables. Values present
105
+ * in the file take precedence — env vars only fill gaps:
106
+ * - `ANTHROPIC_BASE_URL` → `base_url`
107
+ * - `ANTHROPIC_ORGANIZATION_ID` → `organization_id`
108
+ * - `ANTHROPIC_WORKSPACE_ID` → `workspace_id`
109
+ * - `ANTHROPIC_SCOPE` → `authentication.scope`
110
+ * - `ANTHROPIC_FEDERATION_RULE_ID` → `authentication.federation_rule_id` (oidc_federation)
111
+ * - `ANTHROPIC_IDENTITY_TOKEN_FILE` → `authentication.identity_token` (oidc_federation)
112
+ * - `ANTHROPIC_SERVICE_ACCOUNT_ID` → `authentication.service_account_id` (oidc_federation)
113
+ * - If no config file exists, an `oidc_federation` config is synthesized
114
+ * entirely from environment variables when both `ANTHROPIC_FEDERATION_RULE_ID`
115
+ * and `ANTHROPIC_ORGANIZATION_ID` are set.
116
+ */
117
+ export const loadConfig = async (profile?: string): Promise<AnthropicConfig | null> => {
118
+ return (await loadConfigWithSource(profile))?.config ?? null;
119
+ };
120
+
121
+ /**
122
+ * Source-tagged result of {@link loadConfigWithSource}. `fromFile` is `true`
123
+ * when `<config_dir>/configs/<profile>.json` exists on disk; `false` when the
124
+ * config was synthesized purely from environment variables.
125
+ *
126
+ * The credential chain uses this distinction to decide whether to back the
127
+ * federation exchange with a disk cache: file-backed profiles get a cache at
128
+ * `<config_dir>/credentials/<profile>.json`, env-only configs do not.
129
+ */
130
+ export type LoadedConfig = { config: AnthropicConfig; fromFile: boolean };
131
+
132
+ /**
133
+ * Same as {@link loadConfig}, but also reports whether the config was loaded
134
+ * from a profile file on disk (`fromFile: true`) or synthesized entirely from
135
+ * environment variables (`fromFile: false`).
136
+ */
137
+ export const loadConfigWithSource = async (profile?: string): Promise<LoadedConfig | null> => {
138
+ const rootConfigPath = await getRootConfigPath();
139
+ if (rootConfigPath === null) {
140
+ return null;
141
+ }
142
+
143
+ const profileName = profile ?? (await getActiveProfileName());
144
+ if (profileName === null) {
145
+ return null;
146
+ }
147
+ validateProfileName(profileName);
148
+
149
+ const fs = await import('node:fs');
150
+ const path = await import('node:path');
151
+ const configPath = path.join(rootConfigPath, 'configs', `${profileName}.json`);
152
+ let configRaw: string | null;
153
+ try {
154
+ configRaw = await fs.promises.readFile(configPath, 'utf-8');
155
+ } catch (err) {
156
+ if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') {
157
+ throw new Error(`failed to read config file ${configPath}: ${err}`);
158
+ }
159
+ configRaw = null;
160
+ }
161
+ if (configRaw === null) {
162
+ const organizationId = readEnv('ANTHROPIC_ORGANIZATION_ID');
163
+ const identityTokenFile = readEnv('ANTHROPIC_IDENTITY_TOKEN_FILE');
164
+ const federationRuleId = readEnv('ANTHROPIC_FEDERATION_RULE_ID');
165
+ if (federationRuleId && organizationId) {
166
+ return {
167
+ fromFile: false,
168
+ config: {
169
+ organization_id: organizationId,
170
+ // A defaulted-but-empty CI variable (`ANTHROPIC_WORKSPACE_ID=""`) is
171
+ // treated as unset — readEnv coerces empty to undefined, and the body
172
+ // builder's truthy check skips it — so `"workspace_id": ""` never goes
173
+ // on the wire.
174
+ workspace_id: readEnv('ANTHROPIC_WORKSPACE_ID'),
175
+ base_url: readEnv('ANTHROPIC_BASE_URL'),
176
+ authentication: {
177
+ type: 'oidc_federation',
178
+ federation_rule_id: federationRuleId,
179
+ service_account_id: readEnv('ANTHROPIC_SERVICE_ACCOUNT_ID'),
180
+ identity_token: identityTokenFile ? { source: 'file', path: identityTokenFile } : undefined,
181
+ scope: readEnv('ANTHROPIC_SCOPE'),
182
+ },
183
+ },
184
+ };
185
+ }
186
+ return null;
187
+ }
188
+
189
+ let config: AnthropicConfig;
190
+ try {
191
+ config = JSON.parse(configRaw);
192
+ } catch (err) {
193
+ throw new Error(`failed to parse config file ${configPath}: ${err}`);
194
+ }
195
+ if (!config.authentication) {
196
+ throw new Error(`config file ${configPath} is missing "authentication"`);
197
+ }
198
+ const authType = config.authentication.type;
199
+ if (authType !== 'oidc_federation' && authType !== 'user_oauth') {
200
+ throw new Error(`authentication.type "${authType}" is not a known authentication type`);
201
+ }
202
+
203
+ // File values are authoritative; env vars only fill fields the file left unset.
204
+ config.organization_id ??= readEnv('ANTHROPIC_ORGANIZATION_ID');
205
+ config.workspace_id ??= readEnv('ANTHROPIC_WORKSPACE_ID');
206
+ config.base_url ??= readEnv('ANTHROPIC_BASE_URL');
207
+ config.authentication.scope ??= readEnv('ANTHROPIC_SCOPE');
208
+
209
+ if (config.authentication.type === 'oidc_federation') {
210
+ if (!config.authentication.identity_token) {
211
+ const identityTokenFile = readEnv('ANTHROPIC_IDENTITY_TOKEN_FILE');
212
+ if (identityTokenFile) {
213
+ config.authentication.identity_token = {
214
+ source: 'file',
215
+ path: identityTokenFile,
216
+ };
217
+ }
218
+ }
219
+
220
+ // Unlike siblings using `??= readEnv()` (which leaves `undefined`), coerce
221
+ // to '' so the type stays `string` (always set). The downstream required
222
+ // check in credential-chain rejects empty, so semantics match but types are
223
+ // cleaner.
224
+ if (!config.authentication.federation_rule_id) {
225
+ config.authentication.federation_rule_id = readEnv('ANTHROPIC_FEDERATION_RULE_ID') ?? '';
226
+ }
227
+ config.authentication.service_account_id ??= readEnv('ANTHROPIC_SERVICE_ACCOUNT_ID');
228
+ }
229
+
230
+ return { config, fromFile: true };
231
+ };
232
+
233
+ /**
234
+ * Loads the credential material for the active profile.
235
+ *
236
+ * Returns the parsed credentials or `null` when running in a browser or
237
+ * no credentials file can be found.
238
+ *
239
+ * **Profile resolution** (first match wins):
240
+ * 1. `ANTHROPIC_PROFILE` environment variable
241
+ * 2. Contents of `<config_dir>/active_config` file
242
+ * 3. `"default"`
243
+ *
244
+ * **Credentials path resolution** (first match wins):
245
+ * 1. `authentication.credentials_path` from the active profile's config (via {@link loadConfig})
246
+ * 2. `<config_dir>/credentials/<profile>.json`
247
+ */
248
+ export const loadCredentials = async (): Promise<AnthropicCredentials | null> => {
249
+ const config = await loadConfig();
250
+ const credentialsPath = await getCredentialsPath(config);
251
+ if (!credentialsPath) {
252
+ return null;
253
+ }
254
+
255
+ const fs = await import('node:fs');
256
+ let raw: string;
257
+ try {
258
+ raw = await fs.promises.readFile(credentialsPath, 'utf-8');
259
+ } catch (err) {
260
+ if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') {
261
+ throw new Error(`failed to read credentials file ${credentialsPath}: ${err}`);
262
+ }
263
+ return null;
264
+ }
265
+
266
+ let creds: AnthropicCredentials;
267
+ try {
268
+ creds = JSON.parse(raw);
269
+ } catch (err) {
270
+ throw new Error(`failed to parse credentials file ${credentialsPath}: ${err}`);
271
+ }
272
+ if (creds.type && creds.type !== 'oauth_token') {
273
+ throw new Error(
274
+ `credentials file ${credentialsPath} has unsupported type "${creds.type}" (want "oauth_token")`,
275
+ );
276
+ }
277
+ return creds;
278
+ };
279
+
280
+ /**
281
+ * Resolves the credentials file path for the given config.
282
+ *
283
+ * Uses `authentication.credentials_path` from the config if set, otherwise
284
+ * falls back to `<config_dir>/credentials/<profile>.json`.
285
+ *
286
+ * Returns `null` when running in a browser or the path cannot be resolved.
287
+ */
288
+ export const getCredentialsPath = async (
289
+ config: AnthropicConfig | null,
290
+ profile?: string,
291
+ ): Promise<string | null> => {
292
+ if (config?.authentication.credentials_path) {
293
+ return config.authentication.credentials_path;
294
+ }
295
+
296
+ const rootConfigPath = await getRootConfigPath();
297
+ if (!rootConfigPath) {
298
+ return null;
299
+ }
300
+
301
+ const profileName = profile ?? (await getActiveProfileName());
302
+ if (!profileName) {
303
+ return null;
304
+ }
305
+ validateProfileName(profileName);
306
+
307
+ const path = await import('node:path');
308
+ return path.join(rootConfigPath, 'credentials', `${profileName}.json`);
309
+ };
310
+
311
+ const getRootConfigPath = async (): Promise<string | null> => {
312
+ if (!supportsLocalConfigFiles()) {
313
+ return null;
314
+ }
315
+
316
+ const path = await import('node:path');
317
+
318
+ // ANTHROPIC_CONFIG_DIR is treated as a trusted path: it is set by the
319
+ // process operator, not by remote input, so it is not validated.
320
+ const configDir = readEnv('ANTHROPIC_CONFIG_DIR');
321
+ if (configDir) {
322
+ return configDir;
323
+ }
324
+
325
+ const os = getPlatformHeaders()['X-Stainless-OS'];
326
+ if (os === 'Windows') {
327
+ const appData = readEnv('APPDATA');
328
+ if (appData) {
329
+ return path.join(appData, 'Anthropic');
330
+ }
331
+ const userProfile = readEnv('USERPROFILE');
332
+ if (userProfile) {
333
+ return path.join(userProfile, 'AppData', 'Roaming', 'Anthropic');
334
+ }
335
+ // No usable Windows config root — return null so callers fall through to
336
+ // "no config available" rather than silently writing under C:\.
337
+ return null;
338
+ }
339
+
340
+ const xdgConfigHome = readEnv('XDG_CONFIG_HOME');
341
+ if (xdgConfigHome) {
342
+ return path.join(xdgConfigHome, 'anthropic');
343
+ }
344
+
345
+ const home = readEnv('HOME');
346
+ if (home) {
347
+ return path.join(home, '.config', 'anthropic');
348
+ }
349
+ return null;
350
+ };
351
+
352
+ const supportsLocalConfigFiles = (): boolean => {
353
+ const runtime = getPlatformHeaders()['X-Stainless-Runtime'];
354
+ return runtime === 'node' || runtime === 'deno';
355
+ };
356
+
357
+ const getActiveProfileName = async (): Promise<string | null> => {
358
+ const rootConfigPath = await getRootConfigPath();
359
+ if (!rootConfigPath) {
360
+ return null;
361
+ }
362
+
363
+ const profileName = readEnv('ANTHROPIC_PROFILE');
364
+ if (profileName) {
365
+ return profileName;
366
+ }
367
+
368
+ const fs = await import('node:fs');
369
+ const path = await import('node:path');
370
+ const filePath = path.join(rootConfigPath, 'active_config');
371
+ try {
372
+ return (await fs.promises.readFile(filePath, 'utf-8')).trim() || 'default';
373
+ } catch (err) {
374
+ if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') {
375
+ throw new Error(`failed to read ${filePath}: ${err}`);
376
+ }
377
+ return 'default';
378
+ }
379
+ };
@@ -0,0 +1,4 @@
1
+ /** Current time as unix epoch seconds. */
2
+ export function nowAsSeconds(): number {
3
+ return Math.floor(Date.now() / 1000);
4
+ }
@@ -0,0 +1,292 @@
1
+ import type { Fetch } from '../../internal/builtin-types';
2
+ import { readEnv } from '../../internal/utils/env';
3
+ import {
4
+ CREDENTIALS_FILE_VERSION,
5
+ loadConfigWithSource,
6
+ getCredentialsPath,
7
+ type AnthropicConfig,
8
+ } from '../../core/credentials';
9
+ import type { AccessTokenProvider, CredentialResult, IdentityTokenProvider } from './types';
10
+ import {
11
+ MANDATORY_REFRESH_THRESHOLD_IN_SECONDS,
12
+ WorkloadIdentityError,
13
+ checkCredentialsFileSafety,
14
+ writeCredentialsFileAtomic,
15
+ } from './types';
16
+ import { nowAsSeconds } from '../../internal/utils/time';
17
+ import { identityTokenFromFile, identityTokenFromValue } from './identity-token';
18
+ import { oidcFederationProvider } from './oidc-federation';
19
+ import { userOAuthProvider } from './user-oauth';
20
+
21
+ /**
22
+ * Builds a {@link CredentialResult} from an explicit {@link AnthropicConfig}.
23
+ *
24
+ * Use this when constructing a client from an in-memory config object rather
25
+ * than from profile files or environment variables.
26
+ *
27
+ * For `oidc_federation`, `authentication.credentials_path` is optional —
28
+ * if omitted, every call performs a fresh exchange with no on-disk cache.
29
+ * For `user_oauth`, `authentication.credentials_path` is required (it is
30
+ * where the access/refresh tokens live).
31
+ */
32
+ export type ResolverOptions = {
33
+ baseURL: string;
34
+ fetch: Fetch;
35
+ userAgent?: string | undefined;
36
+ onCacheWriteError?: ((err: unknown) => void) | undefined;
37
+ onSafetyWarning?: ((msg: string) => void) | undefined;
38
+ };
39
+
40
+ export function resolveCredentialsFromConfig(
41
+ config: AnthropicConfig,
42
+ options: ResolverOptions,
43
+ ): CredentialResult {
44
+ const credentialsPath = config.authentication.credentials_path ?? null;
45
+ const effectiveBaseURL = (config.base_url || options.baseURL).replace(/\/+$/, '');
46
+
47
+ const provider = buildProvider(config, credentialsPath, effectiveBaseURL, options);
48
+
49
+ const extraHeaders: Record<string, string> = {};
50
+ // For federation profiles workspace_id is sent in the jwt-bearer exchange
51
+ // body, not as a request header (the minted token is already
52
+ // workspace-scoped, so the header would be ignored).
53
+ if (config.workspace_id && config.authentication.type === 'user_oauth') {
54
+ extraHeaders['anthropic-workspace-id'] = config.workspace_id;
55
+ }
56
+
57
+ // Surface the profile's own base_url (not the options.baseURL fallback) so
58
+ // the client can adopt it for outbound API requests when the caller didn't
59
+ // pin one explicitly. Echoing options.baseURL back would defeat precedence.
60
+ return { provider, extraHeaders, baseURL: config.base_url || undefined };
61
+ }
62
+
63
+ /**
64
+ * Resolves a {@link CredentialResult} from the environment. Returns `null`
65
+ * when no credentials can be resolved.
66
+ *
67
+ * Resolution order:
68
+ *
69
+ * 1. Config file for the active profile (or the explicit `profile` argument)
70
+ * → dispatch on `authentication.type` (`oidc_federation`, `user_oauth`)
71
+ * 2. Environment variables `ANTHROPIC_FEDERATION_RULE_ID` +
72
+ * `ANTHROPIC_ORGANIZATION_ID` (+ identity token) → OIDC federation
73
+ * 3. Nothing matches → `null`
74
+ *
75
+ * Passing `profile` selects `<config_dir>/configs/<profile>.json` directly,
76
+ * skipping `ANTHROPIC_PROFILE` / `active_config` resolution.
77
+ */
78
+ export async function defaultCredentials(
79
+ options: ResolverOptions,
80
+ profile?: string,
81
+ ): Promise<CredentialResult | null> {
82
+ const loaded = await loadConfigWithSource(profile);
83
+ if (!loaded) {
84
+ return null;
85
+ }
86
+ const { config, fromFile } = loaded;
87
+
88
+ // For file-loaded configs, default credentials_path to the per-profile
89
+ // location so user_oauth and federation caching work. Shallow-clone first
90
+ // so callers that retain a reference to the loaded config don't observe the
91
+ // patched-in default.
92
+ //
93
+ // Env-only credentials (no profile file on disk) skip the disk cache —
94
+ // matching the other SDKs. A disk cache keyed by profile path would
95
+ // re-serve a stale token after a change to ANTHROPIC_WORKSPACE_ID (or
96
+ // ANTHROPIC_ORGANIZATION_ID / ANTHROPIC_FEDERATION_RULE_ID) until the
97
+ // cached token expired, so the env-only chain stays in-memory only.
98
+ const withPath: AnthropicConfig =
99
+ config.authentication.credentials_path || !fromFile ?
100
+ config
101
+ : {
102
+ ...config,
103
+ authentication: {
104
+ ...config.authentication,
105
+ credentials_path: (await getCredentialsPath(config, profile)) ?? undefined,
106
+ },
107
+ };
108
+
109
+ return resolveCredentialsFromConfig(withPath, options);
110
+ }
111
+
112
+ function buildProvider(
113
+ config: AnthropicConfig,
114
+ credentialsPath: string | null,
115
+ baseURL: string,
116
+ options: ResolverOptions,
117
+ ): AccessTokenProvider {
118
+ switch (config.authentication.type) {
119
+ case 'oidc_federation': {
120
+ const auth = config.authentication;
121
+ const identityProvider = resolveIdentityTokenProvider(auth);
122
+ if (!identityProvider) {
123
+ throw new WorkloadIdentityError(
124
+ 'oidc_federation config requires an identity token (set authentication.identity_token, ' +
125
+ 'ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)',
126
+ );
127
+ }
128
+ if (!auth.federation_rule_id) {
129
+ throw new WorkloadIdentityError(
130
+ "oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).",
131
+ );
132
+ }
133
+ if (!config.organization_id) {
134
+ throw new WorkloadIdentityError(
135
+ 'oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)',
136
+ );
137
+ }
138
+
139
+ const exchange = oidcFederationProvider({
140
+ identityTokenProvider: identityProvider,
141
+ federationRuleId: auth.federation_rule_id,
142
+ organizationId: config.organization_id,
143
+ serviceAccountId: auth.service_account_id,
144
+ workspaceId: config.workspace_id,
145
+ baseURL,
146
+ fetch: options.fetch,
147
+ userAgent: options.userAgent,
148
+ });
149
+
150
+ // If there's a credentials file path, wrap the exchange with file caching
151
+ // (check file for fresh token before exchanging, write back after).
152
+ if (credentialsPath) {
153
+ return cachedExchangeProvider(
154
+ exchange,
155
+ credentialsPath,
156
+ options.onCacheWriteError,
157
+ options.onSafetyWarning,
158
+ );
159
+ }
160
+ return exchange;
161
+ }
162
+
163
+ case 'user_oauth': {
164
+ if (!credentialsPath) {
165
+ throw new WorkloadIdentityError(
166
+ 'user_oauth config requires authentication.credentials_path ' +
167
+ '(or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)',
168
+ );
169
+ }
170
+ return userOAuthProvider({
171
+ credentialsPath,
172
+ clientId: config.authentication.client_id,
173
+ baseURL,
174
+ fetch: options.fetch,
175
+ userAgent: options.userAgent,
176
+ onSafetyWarning: options.onSafetyWarning,
177
+ });
178
+ }
179
+
180
+ default: {
181
+ const t = (config.authentication as { type: string }).type;
182
+ throw new WorkloadIdentityError(`authentication.type "${t}" is not a known authentication type`);
183
+ }
184
+ }
185
+ }
186
+
187
+ /**
188
+ * Resolves the identity token provider from config fields or environment variables.
189
+ *
190
+ * Resolution order:
191
+ * 1. `identity_token.path` from the config (source: "file")
192
+ * 2. `ANTHROPIC_IDENTITY_TOKEN_FILE` env var
193
+ * 3. `ANTHROPIC_IDENTITY_TOKEN` env var (static value)
194
+ */
195
+ function resolveIdentityTokenProvider(
196
+ auth: Extract<AnthropicConfig['authentication'], { type: 'oidc_federation' }>,
197
+ ): IdentityTokenProvider | null {
198
+ if (auth.identity_token) {
199
+ // Cast needed to stringify an unknown source value for the error message:
200
+ // the on-disk JSON may contain a source this SDK version doesn't know about.
201
+ const source = (auth.identity_token as { source: string }).source;
202
+ if (source !== 'file') {
203
+ throw new WorkloadIdentityError(
204
+ `identity_token.source "${source}" is not supported by this SDK version (only "file")`,
205
+ );
206
+ }
207
+ if (!auth.identity_token.path) {
208
+ throw new WorkloadIdentityError(`identity_token.source "file" requires a non-empty path`);
209
+ }
210
+ return identityTokenFromFile(auth.identity_token.path);
211
+ }
212
+
213
+ const tokenFile = readEnv('ANTHROPIC_IDENTITY_TOKEN_FILE');
214
+ if (tokenFile) {
215
+ return identityTokenFromFile(tokenFile);
216
+ }
217
+
218
+ const tokenValue = readEnv('ANTHROPIC_IDENTITY_TOKEN');
219
+ if (tokenValue) {
220
+ return identityTokenFromValue(tokenValue);
221
+ }
222
+
223
+ return null;
224
+ }
225
+
226
+ /**
227
+ * Wraps a federation exchange provider with credential file caching.
228
+ * Checks the file for a fresh token before exchanging, and writes the
229
+ * result back after a successful exchange (best-effort, atomic replace).
230
+ *
231
+ * Note: this is not cross-process serialized — two SDK instances that
232
+ * miss the cache simultaneously will both perform a full exchange and
233
+ * the last writer wins. That is acceptable: federation exchanges are
234
+ * idempotent and the cache is an optimization, not a correctness gate.
235
+ */
236
+ function cachedExchangeProvider(
237
+ exchange: AccessTokenProvider,
238
+ credentialsPath: string,
239
+ onCacheWriteError: ((err: unknown) => void) | undefined,
240
+ onSafetyWarning: ((msg: string) => void) | undefined,
241
+ ): AccessTokenProvider {
242
+ return async (opts) => {
243
+ const fs = await import('node:fs');
244
+
245
+ await checkCredentialsFileSafety(credentialsPath, onSafetyWarning);
246
+
247
+ // Try cached credentials file
248
+ let existing: Record<string, unknown> | undefined;
249
+ try {
250
+ const raw = await fs.promises.readFile(credentialsPath, 'utf-8');
251
+ existing = JSON.parse(raw);
252
+ const token = existing?.['access_token'] as string | undefined;
253
+ if (token && !opts?.forceRefresh) {
254
+ const expiresAt = existing?.['expires_at'] as number | undefined;
255
+ if (expiresAt == null || nowAsSeconds() < expiresAt - MANDATORY_REFRESH_THRESHOLD_IN_SECONDS) {
256
+ return { token, expiresAt: expiresAt ?? null };
257
+ }
258
+ }
259
+ } catch (err) {
260
+ // ENOENT or invalid-JSON → no usable cache, exchange fresh. Other
261
+ // errors (EACCES, EISDIR, …) indicate a broken cache path; surface to
262
+ // the optional hook so they're at least debuggable, then proceed.
263
+ const code = (err as NodeJS.ErrnoException)?.code;
264
+ if (code !== 'ENOENT' && !(err instanceof SyntaxError)) {
265
+ onCacheWriteError?.(err);
266
+ }
267
+ }
268
+
269
+ // Exchange for a new token
270
+ const result = await exchange(opts);
271
+
272
+ // Write cache back (best-effort). Preserve any unknown keys from the
273
+ // existing file (notably refresh_token, in the unlikely case this path
274
+ // is shared with a user_oauth profile) so the federation cache writer
275
+ // doesn't clobber material it didn't own.
276
+ try {
277
+ await writeCredentialsFileAtomic(credentialsPath, {
278
+ ...(existing ?? {}),
279
+ version: CREDENTIALS_FILE_VERSION,
280
+ type: 'oauth_token',
281
+ access_token: result.token,
282
+ expires_at: result.expiresAt,
283
+ });
284
+ } catch (err) {
285
+ // Best-effort caching: surface to the optional hook but never fail
286
+ // the exchange itself.
287
+ onCacheWriteError?.(err);
288
+ }
289
+
290
+ return result;
291
+ };
292
+ }