@anthropic-ai/sdk 0.92.0 → 0.93.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.
- package/CHANGELOG.md +8 -0
- package/client.d.mts +73 -0
- package/client.d.mts.map +1 -1
- package/client.d.ts +73 -0
- package/client.d.ts.map +1 -1
- package/client.js +258 -9
- package/client.js.map +1 -1
- package/client.mjs +258 -9
- package/client.mjs.map +1 -1
- package/core/credentials.d.mts +111 -0
- package/core/credentials.d.mts.map +1 -0
- package/core/credentials.d.ts +111 -0
- package/core/credentials.d.ts.map +1 -0
- package/core/credentials.js +298 -0
- package/core/credentials.js.map +1 -0
- package/core/credentials.mjs +259 -0
- package/core/credentials.mjs.map +1 -0
- package/internal/utils/time.d.mts +3 -0
- package/internal/utils/time.d.mts.map +1 -0
- package/internal/utils/time.d.ts +3 -0
- package/internal/utils/time.d.ts.map +1 -0
- package/internal/utils/time.js +8 -0
- package/internal/utils/time.js.map +1 -0
- package/internal/utils/time.mjs +5 -0
- package/internal/utils/time.mjs.map +1 -0
- package/lib/credentials/credential-chain.d.mts +39 -0
- package/lib/credentials/credential-chain.d.mts.map +1 -0
- package/lib/credentials/credential-chain.d.ts +39 -0
- package/lib/credentials/credential-chain.d.ts.map +1 -0
- package/lib/credentials/credential-chain.js +237 -0
- package/lib/credentials/credential-chain.js.map +1 -0
- package/lib/credentials/credential-chain.mjs +200 -0
- package/lib/credentials/credential-chain.mjs.map +1 -0
- package/lib/credentials/identity-token.d.mts +11 -0
- package/lib/credentials/identity-token.d.mts.map +1 -0
- package/lib/credentials/identity-token.d.ts +11 -0
- package/lib/credentials/identity-token.d.ts.map +1 -0
- package/lib/credentials/identity-token.js +72 -0
- package/lib/credentials/identity-token.js.map +1 -0
- package/lib/credentials/identity-token.mjs +35 -0
- package/lib/credentials/identity-token.mjs.map +1 -0
- package/lib/credentials/oidc-federation.d.mts +28 -0
- package/lib/credentials/oidc-federation.d.mts.map +1 -0
- package/lib/credentials/oidc-federation.d.ts +28 -0
- package/lib/credentials/oidc-federation.d.ts.map +1 -0
- package/lib/credentials/oidc-federation.js +69 -0
- package/lib/credentials/oidc-federation.js.map +1 -0
- package/lib/credentials/oidc-federation.mjs +66 -0
- package/lib/credentials/oidc-federation.mjs.map +1 -0
- package/lib/credentials/token-cache.d.mts +54 -0
- package/lib/credentials/token-cache.d.mts.map +1 -0
- package/lib/credentials/token-cache.d.ts +54 -0
- package/lib/credentials/token-cache.d.ts.map +1 -0
- package/lib/credentials/token-cache.js +112 -0
- package/lib/credentials/token-cache.js.map +1 -0
- package/lib/credentials/token-cache.mjs +108 -0
- package/lib/credentials/token-cache.mjs.map +1 -0
- package/lib/credentials/types.d.mts +96 -0
- package/lib/credentials/types.d.mts.map +1 -0
- package/lib/credentials/types.d.ts +96 -0
- package/lib/credentials/types.d.ts.map +1 -0
- package/lib/credentials/types.js +266 -0
- package/lib/credentials/types.js.map +1 -0
- package/lib/credentials/types.mjs +224 -0
- package/lib/credentials/types.mjs.map +1 -0
- package/lib/credentials/user-oauth.d.mts +21 -0
- package/lib/credentials/user-oauth.d.mts.map +1 -0
- package/lib/credentials/user-oauth.d.ts +21 -0
- package/lib/credentials/user-oauth.d.ts.map +1 -0
- package/lib/credentials/user-oauth.js +130 -0
- package/lib/credentials/user-oauth.js.map +1 -0
- package/lib/credentials/user-oauth.mjs +94 -0
- package/lib/credentials/user-oauth.mjs.map +1 -0
- package/lib/credentials.d.mts +4 -0
- package/lib/credentials.d.mts.map +1 -0
- package/lib/credentials.d.ts +4 -0
- package/lib/credentials.d.ts.map +1 -0
- package/lib/credentials.js +8 -0
- package/lib/credentials.js.map +1 -0
- package/lib/credentials.mjs +3 -0
- package/lib/credentials.mjs.map +1 -0
- package/package.json +1 -1
- package/src/client.ts +342 -14
- package/src/core/credentials.ts +349 -0
- package/src/internal/utils/time.ts +4 -0
- package/src/lib/credentials/credential-chain.ts +284 -0
- package/src/lib/credentials/identity-token.ts +37 -0
- package/src/lib/credentials/oidc-federation.ts +112 -0
- package/src/lib/credentials/token-cache.ts +130 -0
- package/src/lib/credentials/types.ts +295 -0
- package/src/lib/credentials/user-oauth.ts +144 -0
- package/src/lib/credentials.ts +3 -0
- package/src/version.ts +1 -1
- package/version.d.mts +1 -1
- package/version.d.ts +1 -1
- package/version.js +1 -1
- package/version.mjs +1 -1
|
@@ -0,0 +1,349 @@
|
|
|
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_SCOPE` → `authentication.scope`
|
|
109
|
+
* - `ANTHROPIC_FEDERATION_RULE_ID` → `authentication.federation_rule_id` (oidc_federation)
|
|
110
|
+
* - `ANTHROPIC_IDENTITY_TOKEN_FILE` → `authentication.identity_token` (oidc_federation)
|
|
111
|
+
* - `ANTHROPIC_SERVICE_ACCOUNT_ID` → `authentication.service_account_id` (oidc_federation)
|
|
112
|
+
* - If no config file exists, an `oidc_federation` config is synthesized
|
|
113
|
+
* entirely from environment variables when both `ANTHROPIC_FEDERATION_RULE_ID`
|
|
114
|
+
* and `ANTHROPIC_ORGANIZATION_ID` are set.
|
|
115
|
+
*/
|
|
116
|
+
export const loadConfig = async (profile?: string): Promise<AnthropicConfig | null> => {
|
|
117
|
+
const rootConfigPath = await getRootConfigPath();
|
|
118
|
+
if (rootConfigPath === null) {
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const profileName = profile ?? (await getActiveProfileName());
|
|
123
|
+
if (profileName === null) {
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
validateProfileName(profileName);
|
|
127
|
+
|
|
128
|
+
const fs = await import('node:fs');
|
|
129
|
+
const path = await import('node:path');
|
|
130
|
+
const configPath = path.join(rootConfigPath, 'configs', `${profileName}.json`);
|
|
131
|
+
let configRaw: string | null;
|
|
132
|
+
try {
|
|
133
|
+
configRaw = await fs.promises.readFile(configPath, 'utf-8');
|
|
134
|
+
} catch (err) {
|
|
135
|
+
if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') {
|
|
136
|
+
throw new Error(`failed to read config file ${configPath}: ${err}`);
|
|
137
|
+
}
|
|
138
|
+
configRaw = null;
|
|
139
|
+
}
|
|
140
|
+
if (configRaw === null) {
|
|
141
|
+
const organizationId = readEnv('ANTHROPIC_ORGANIZATION_ID');
|
|
142
|
+
const identityTokenFile = readEnv('ANTHROPIC_IDENTITY_TOKEN_FILE');
|
|
143
|
+
const federationRuleId = readEnv('ANTHROPIC_FEDERATION_RULE_ID');
|
|
144
|
+
if (federationRuleId && organizationId) {
|
|
145
|
+
return {
|
|
146
|
+
organization_id: organizationId,
|
|
147
|
+
base_url: readEnv('ANTHROPIC_BASE_URL'),
|
|
148
|
+
authentication: {
|
|
149
|
+
type: 'oidc_federation',
|
|
150
|
+
federation_rule_id: federationRuleId,
|
|
151
|
+
service_account_id: readEnv('ANTHROPIC_SERVICE_ACCOUNT_ID'),
|
|
152
|
+
identity_token: identityTokenFile ? { source: 'file', path: identityTokenFile } : undefined,
|
|
153
|
+
scope: readEnv('ANTHROPIC_SCOPE'),
|
|
154
|
+
},
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
let config: AnthropicConfig;
|
|
161
|
+
try {
|
|
162
|
+
config = JSON.parse(configRaw);
|
|
163
|
+
} catch (err) {
|
|
164
|
+
throw new Error(`failed to parse config file ${configPath}: ${err}`);
|
|
165
|
+
}
|
|
166
|
+
if (!config.authentication) {
|
|
167
|
+
throw new Error(`config file ${configPath} is missing "authentication"`);
|
|
168
|
+
}
|
|
169
|
+
const authType = config.authentication.type;
|
|
170
|
+
if (authType !== 'oidc_federation' && authType !== 'user_oauth') {
|
|
171
|
+
throw new Error(`authentication.type "${authType}" is not a known authentication type`);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// File values are authoritative; env vars only fill fields the file left unset.
|
|
175
|
+
config.organization_id ??= readEnv('ANTHROPIC_ORGANIZATION_ID');
|
|
176
|
+
config.base_url ??= readEnv('ANTHROPIC_BASE_URL');
|
|
177
|
+
config.authentication.scope ??= readEnv('ANTHROPIC_SCOPE');
|
|
178
|
+
|
|
179
|
+
if (config.authentication.type === 'oidc_federation') {
|
|
180
|
+
if (!config.authentication.identity_token) {
|
|
181
|
+
const identityTokenFile = readEnv('ANTHROPIC_IDENTITY_TOKEN_FILE');
|
|
182
|
+
if (identityTokenFile) {
|
|
183
|
+
config.authentication.identity_token = {
|
|
184
|
+
source: 'file',
|
|
185
|
+
path: identityTokenFile,
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// Unlike siblings using `??= readEnv()` (which leaves `undefined`), coerce
|
|
191
|
+
// to '' so the type stays `string` (always set). The downstream required
|
|
192
|
+
// check in credential-chain rejects empty, so semantics match but types are
|
|
193
|
+
// cleaner.
|
|
194
|
+
if (!config.authentication.federation_rule_id) {
|
|
195
|
+
config.authentication.federation_rule_id = readEnv('ANTHROPIC_FEDERATION_RULE_ID') ?? '';
|
|
196
|
+
}
|
|
197
|
+
config.authentication.service_account_id ??= readEnv('ANTHROPIC_SERVICE_ACCOUNT_ID');
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
return config;
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Loads the credential material for the active profile.
|
|
205
|
+
*
|
|
206
|
+
* Returns the parsed credentials or `null` when running in a browser or
|
|
207
|
+
* no credentials file can be found.
|
|
208
|
+
*
|
|
209
|
+
* **Profile resolution** (first match wins):
|
|
210
|
+
* 1. `ANTHROPIC_PROFILE` environment variable
|
|
211
|
+
* 2. Contents of `<config_dir>/active_config` file
|
|
212
|
+
* 3. `"default"`
|
|
213
|
+
*
|
|
214
|
+
* **Credentials path resolution** (first match wins):
|
|
215
|
+
* 1. `authentication.credentials_path` from the active profile's config (via {@link loadConfig})
|
|
216
|
+
* 2. `<config_dir>/credentials/<profile>.json`
|
|
217
|
+
*/
|
|
218
|
+
export const loadCredentials = async (): Promise<AnthropicCredentials | null> => {
|
|
219
|
+
const config = await loadConfig();
|
|
220
|
+
const credentialsPath = await getCredentialsPath(config);
|
|
221
|
+
if (!credentialsPath) {
|
|
222
|
+
return null;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const fs = await import('node:fs');
|
|
226
|
+
let raw: string;
|
|
227
|
+
try {
|
|
228
|
+
raw = await fs.promises.readFile(credentialsPath, 'utf-8');
|
|
229
|
+
} catch (err) {
|
|
230
|
+
if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') {
|
|
231
|
+
throw new Error(`failed to read credentials file ${credentialsPath}: ${err}`);
|
|
232
|
+
}
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
let creds: AnthropicCredentials;
|
|
237
|
+
try {
|
|
238
|
+
creds = JSON.parse(raw);
|
|
239
|
+
} catch (err) {
|
|
240
|
+
throw new Error(`failed to parse credentials file ${credentialsPath}: ${err}`);
|
|
241
|
+
}
|
|
242
|
+
if (creds.type && creds.type !== 'oauth_token') {
|
|
243
|
+
throw new Error(
|
|
244
|
+
`credentials file ${credentialsPath} has unsupported type "${creds.type}" (want "oauth_token")`,
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
return creds;
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Resolves the credentials file path for the given config.
|
|
252
|
+
*
|
|
253
|
+
* Uses `authentication.credentials_path` from the config if set, otherwise
|
|
254
|
+
* falls back to `<config_dir>/credentials/<profile>.json`.
|
|
255
|
+
*
|
|
256
|
+
* Returns `null` when running in a browser or the path cannot be resolved.
|
|
257
|
+
*/
|
|
258
|
+
export const getCredentialsPath = async (
|
|
259
|
+
config: AnthropicConfig | null,
|
|
260
|
+
profile?: string,
|
|
261
|
+
): Promise<string | null> => {
|
|
262
|
+
if (config?.authentication.credentials_path) {
|
|
263
|
+
return config.authentication.credentials_path;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const rootConfigPath = await getRootConfigPath();
|
|
267
|
+
if (!rootConfigPath) {
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const profileName = profile ?? (await getActiveProfileName());
|
|
272
|
+
if (!profileName) {
|
|
273
|
+
return null;
|
|
274
|
+
}
|
|
275
|
+
validateProfileName(profileName);
|
|
276
|
+
|
|
277
|
+
const path = await import('node:path');
|
|
278
|
+
return path.join(rootConfigPath, 'credentials', `${profileName}.json`);
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
const getRootConfigPath = async (): Promise<string | null> => {
|
|
282
|
+
if (!supportsLocalConfigFiles()) {
|
|
283
|
+
return null;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const path = await import('node:path');
|
|
287
|
+
|
|
288
|
+
// ANTHROPIC_CONFIG_DIR is treated as a trusted path: it is set by the
|
|
289
|
+
// process operator, not by remote input, so it is not validated.
|
|
290
|
+
const configDir = readEnv('ANTHROPIC_CONFIG_DIR');
|
|
291
|
+
if (configDir) {
|
|
292
|
+
return configDir;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
const os = getPlatformHeaders()['X-Stainless-OS'];
|
|
296
|
+
if (os === 'Windows') {
|
|
297
|
+
const appData = readEnv('APPDATA');
|
|
298
|
+
if (appData) {
|
|
299
|
+
return path.join(appData, 'Anthropic');
|
|
300
|
+
}
|
|
301
|
+
const userProfile = readEnv('USERPROFILE');
|
|
302
|
+
if (userProfile) {
|
|
303
|
+
return path.join(userProfile, 'AppData', 'Roaming', 'Anthropic');
|
|
304
|
+
}
|
|
305
|
+
// No usable Windows config root — return null so callers fall through to
|
|
306
|
+
// "no config available" rather than silently writing under C:\.
|
|
307
|
+
return null;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const xdgConfigHome = readEnv('XDG_CONFIG_HOME');
|
|
311
|
+
if (xdgConfigHome) {
|
|
312
|
+
return path.join(xdgConfigHome, 'anthropic');
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const home = readEnv('HOME');
|
|
316
|
+
if (home) {
|
|
317
|
+
return path.join(home, '.config', 'anthropic');
|
|
318
|
+
}
|
|
319
|
+
return null;
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
const supportsLocalConfigFiles = (): boolean => {
|
|
323
|
+
const runtime = getPlatformHeaders()['X-Stainless-Runtime'];
|
|
324
|
+
return runtime === 'node' || runtime === 'deno';
|
|
325
|
+
};
|
|
326
|
+
|
|
327
|
+
const getActiveProfileName = async (): Promise<string | null> => {
|
|
328
|
+
const rootConfigPath = await getRootConfigPath();
|
|
329
|
+
if (!rootConfigPath) {
|
|
330
|
+
return null;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
const profileName = readEnv('ANTHROPIC_PROFILE');
|
|
334
|
+
if (profileName) {
|
|
335
|
+
return profileName;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const fs = await import('node:fs');
|
|
339
|
+
const path = await import('node:path');
|
|
340
|
+
const filePath = path.join(rootConfigPath, 'active_config');
|
|
341
|
+
try {
|
|
342
|
+
return (await fs.promises.readFile(filePath, 'utf-8')).trim() || 'default';
|
|
343
|
+
} catch (err) {
|
|
344
|
+
if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') {
|
|
345
|
+
throw new Error(`failed to read ${filePath}: ${err}`);
|
|
346
|
+
}
|
|
347
|
+
return 'default';
|
|
348
|
+
}
|
|
349
|
+
};
|
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import type { Fetch } from '../../internal/builtin-types';
|
|
2
|
+
import { readEnv } from '../../internal/utils/env';
|
|
3
|
+
import {
|
|
4
|
+
CREDENTIALS_FILE_VERSION,
|
|
5
|
+
loadConfig,
|
|
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
|
+
// Workspace scoping for oidc_federation is server-side (the federation rule
|
|
51
|
+
// encodes the workspace and the minted token is workspace-scoped), so the
|
|
52
|
+
// header is only meaningful for user_oauth.
|
|
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 config = await loadConfig(profile);
|
|
83
|
+
if (!config) {
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// For env/file-loaded configs, default credentials_path to the
|
|
88
|
+
// per-profile location so user_oauth and federation caching work.
|
|
89
|
+
// Shallow-clone first so callers that retain a reference to the loaded
|
|
90
|
+
// config don't observe the patched-in default.
|
|
91
|
+
const withPath: AnthropicConfig =
|
|
92
|
+
config.authentication.credentials_path ?
|
|
93
|
+
config
|
|
94
|
+
: {
|
|
95
|
+
...config,
|
|
96
|
+
authentication: {
|
|
97
|
+
...config.authentication,
|
|
98
|
+
credentials_path: (await getCredentialsPath(config, profile)) ?? undefined,
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
return resolveCredentialsFromConfig(withPath, options);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function buildProvider(
|
|
106
|
+
config: AnthropicConfig,
|
|
107
|
+
credentialsPath: string | null,
|
|
108
|
+
baseURL: string,
|
|
109
|
+
options: ResolverOptions,
|
|
110
|
+
): AccessTokenProvider {
|
|
111
|
+
switch (config.authentication.type) {
|
|
112
|
+
case 'oidc_federation': {
|
|
113
|
+
const auth = config.authentication;
|
|
114
|
+
const identityProvider = resolveIdentityTokenProvider(auth);
|
|
115
|
+
if (!identityProvider) {
|
|
116
|
+
throw new WorkloadIdentityError(
|
|
117
|
+
'oidc_federation config requires an identity token (set authentication.identity_token, ' +
|
|
118
|
+
'ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)',
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
if (!auth.federation_rule_id) {
|
|
122
|
+
throw new WorkloadIdentityError(
|
|
123
|
+
"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).",
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
if (!config.organization_id) {
|
|
127
|
+
throw new WorkloadIdentityError(
|
|
128
|
+
'oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)',
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const exchange = oidcFederationProvider({
|
|
133
|
+
identityTokenProvider: identityProvider,
|
|
134
|
+
federationRuleId: auth.federation_rule_id,
|
|
135
|
+
organizationId: config.organization_id,
|
|
136
|
+
serviceAccountId: auth.service_account_id,
|
|
137
|
+
baseURL,
|
|
138
|
+
fetch: options.fetch,
|
|
139
|
+
userAgent: options.userAgent,
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
// If there's a credentials file path, wrap the exchange with file caching
|
|
143
|
+
// (check file for fresh token before exchanging, write back after).
|
|
144
|
+
if (credentialsPath) {
|
|
145
|
+
return cachedExchangeProvider(
|
|
146
|
+
exchange,
|
|
147
|
+
credentialsPath,
|
|
148
|
+
options.onCacheWriteError,
|
|
149
|
+
options.onSafetyWarning,
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
return exchange;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
case 'user_oauth': {
|
|
156
|
+
if (!credentialsPath) {
|
|
157
|
+
throw new WorkloadIdentityError(
|
|
158
|
+
'user_oauth config requires authentication.credentials_path ' +
|
|
159
|
+
'(or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)',
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
return userOAuthProvider({
|
|
163
|
+
credentialsPath,
|
|
164
|
+
clientId: config.authentication.client_id,
|
|
165
|
+
baseURL,
|
|
166
|
+
fetch: options.fetch,
|
|
167
|
+
userAgent: options.userAgent,
|
|
168
|
+
onSafetyWarning: options.onSafetyWarning,
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
default: {
|
|
173
|
+
const t = (config.authentication as { type: string }).type;
|
|
174
|
+
throw new WorkloadIdentityError(`authentication.type "${t}" is not a known authentication type`);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Resolves the identity token provider from config fields or environment variables.
|
|
181
|
+
*
|
|
182
|
+
* Resolution order:
|
|
183
|
+
* 1. `identity_token.path` from the config (source: "file")
|
|
184
|
+
* 2. `ANTHROPIC_IDENTITY_TOKEN_FILE` env var
|
|
185
|
+
* 3. `ANTHROPIC_IDENTITY_TOKEN` env var (static value)
|
|
186
|
+
*/
|
|
187
|
+
function resolveIdentityTokenProvider(
|
|
188
|
+
auth: Extract<AnthropicConfig['authentication'], { type: 'oidc_federation' }>,
|
|
189
|
+
): IdentityTokenProvider | null {
|
|
190
|
+
if (auth.identity_token) {
|
|
191
|
+
// Cast needed to stringify an unknown source value for the error message:
|
|
192
|
+
// the on-disk JSON may contain a source this SDK version doesn't know about.
|
|
193
|
+
const source = (auth.identity_token as { source: string }).source;
|
|
194
|
+
if (source !== 'file') {
|
|
195
|
+
throw new WorkloadIdentityError(
|
|
196
|
+
`identity_token.source "${source}" is not supported by this SDK version (only "file")`,
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
if (!auth.identity_token.path) {
|
|
200
|
+
throw new WorkloadIdentityError(`identity_token.source "file" requires a non-empty path`);
|
|
201
|
+
}
|
|
202
|
+
return identityTokenFromFile(auth.identity_token.path);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const tokenFile = readEnv('ANTHROPIC_IDENTITY_TOKEN_FILE');
|
|
206
|
+
if (tokenFile) {
|
|
207
|
+
return identityTokenFromFile(tokenFile);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const tokenValue = readEnv('ANTHROPIC_IDENTITY_TOKEN');
|
|
211
|
+
if (tokenValue) {
|
|
212
|
+
return identityTokenFromValue(tokenValue);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
return null;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Wraps a federation exchange provider with credential file caching.
|
|
220
|
+
* Checks the file for a fresh token before exchanging, and writes the
|
|
221
|
+
* result back after a successful exchange (best-effort, atomic replace).
|
|
222
|
+
*
|
|
223
|
+
* Note: this is not cross-process serialized — two SDK instances that
|
|
224
|
+
* miss the cache simultaneously will both perform a full exchange and
|
|
225
|
+
* the last writer wins. That is acceptable: federation exchanges are
|
|
226
|
+
* idempotent and the cache is an optimization, not a correctness gate.
|
|
227
|
+
*/
|
|
228
|
+
function cachedExchangeProvider(
|
|
229
|
+
exchange: AccessTokenProvider,
|
|
230
|
+
credentialsPath: string,
|
|
231
|
+
onCacheWriteError: ((err: unknown) => void) | undefined,
|
|
232
|
+
onSafetyWarning: ((msg: string) => void) | undefined,
|
|
233
|
+
): AccessTokenProvider {
|
|
234
|
+
return async (opts) => {
|
|
235
|
+
const fs = await import('node:fs');
|
|
236
|
+
|
|
237
|
+
await checkCredentialsFileSafety(credentialsPath, onSafetyWarning);
|
|
238
|
+
|
|
239
|
+
// Try cached credentials file
|
|
240
|
+
let existing: Record<string, unknown> | undefined;
|
|
241
|
+
try {
|
|
242
|
+
const raw = await fs.promises.readFile(credentialsPath, 'utf-8');
|
|
243
|
+
existing = JSON.parse(raw);
|
|
244
|
+
const token = existing?.['access_token'] as string | undefined;
|
|
245
|
+
if (token && !opts?.forceRefresh) {
|
|
246
|
+
const expiresAt = existing?.['expires_at'] as number | undefined;
|
|
247
|
+
if (expiresAt == null || nowAsSeconds() < expiresAt - MANDATORY_REFRESH_THRESHOLD_IN_SECONDS) {
|
|
248
|
+
return { token, expiresAt: expiresAt ?? null };
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
} catch (err) {
|
|
252
|
+
// ENOENT or invalid-JSON → no usable cache, exchange fresh. Other
|
|
253
|
+
// errors (EACCES, EISDIR, …) indicate a broken cache path; surface to
|
|
254
|
+
// the optional hook so they're at least debuggable, then proceed.
|
|
255
|
+
const code = (err as NodeJS.ErrnoException)?.code;
|
|
256
|
+
if (code !== 'ENOENT' && !(err instanceof SyntaxError)) {
|
|
257
|
+
onCacheWriteError?.(err);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// Exchange for a new token
|
|
262
|
+
const result = await exchange(opts);
|
|
263
|
+
|
|
264
|
+
// Write cache back (best-effort). Preserve any unknown keys from the
|
|
265
|
+
// existing file (notably refresh_token, in the unlikely case this path
|
|
266
|
+
// is shared with a user_oauth profile) so the federation cache writer
|
|
267
|
+
// doesn't clobber material it didn't own.
|
|
268
|
+
try {
|
|
269
|
+
await writeCredentialsFileAtomic(credentialsPath, {
|
|
270
|
+
...(existing ?? {}),
|
|
271
|
+
version: CREDENTIALS_FILE_VERSION,
|
|
272
|
+
type: 'oauth_token',
|
|
273
|
+
access_token: result.token,
|
|
274
|
+
expires_at: result.expiresAt,
|
|
275
|
+
});
|
|
276
|
+
} catch (err) {
|
|
277
|
+
// Best-effort caching: surface to the optional hook but never fail
|
|
278
|
+
// the exchange itself.
|
|
279
|
+
onCacheWriteError?.(err);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
return result;
|
|
283
|
+
};
|
|
284
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { AnthropicError } from '../../core/error';
|
|
2
|
+
import type { IdentityTokenProvider } from './types';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Reads a JWT from a file on every call. Supports automatic rotation
|
|
6
|
+
* (e.g. Kubernetes projected service-account tokens).
|
|
7
|
+
*/
|
|
8
|
+
export function identityTokenFromFile(path: string): IdentityTokenProvider {
|
|
9
|
+
if (!path) {
|
|
10
|
+
throw new AnthropicError('Identity token file path is empty');
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
return async () => {
|
|
14
|
+
const fs = await import('node:fs');
|
|
15
|
+
let content: string;
|
|
16
|
+
try {
|
|
17
|
+
content = await fs.promises.readFile(path, 'utf-8');
|
|
18
|
+
} catch (err) {
|
|
19
|
+
throw new AnthropicError(`Failed to read identity token file at ${path}: ${err}`);
|
|
20
|
+
}
|
|
21
|
+
const token = content.trim();
|
|
22
|
+
if (!token) {
|
|
23
|
+
throw new AnthropicError(`Identity token file at ${path} is empty`);
|
|
24
|
+
}
|
|
25
|
+
return token;
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Wraps a static JWT string as an {@link IdentityTokenProvider}.
|
|
31
|
+
*/
|
|
32
|
+
export function identityTokenFromValue(token: string): IdentityTokenProvider {
|
|
33
|
+
if (!token) {
|
|
34
|
+
throw new AnthropicError('Identity token value is empty');
|
|
35
|
+
}
|
|
36
|
+
return () => token;
|
|
37
|
+
}
|