@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.
- package/CHANGELOG.md +16 -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 +131 -0
- package/core/credentials.d.mts.map +1 -0
- package/core/credentials.d.ts +131 -0
- package/core/credentials.d.ts.map +1 -0
- package/core/credentials.js +317 -0
- package/core/credentials.js.map +1 -0
- package/core/credentials.mjs +277 -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 +245 -0
- package/lib/credentials/credential-chain.js.map +1 -0
- package/lib/credentials/credential-chain.mjs +208 -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 +40 -0
- package/lib/credentials/oidc-federation.d.mts.map +1 -0
- package/lib/credentials/oidc-federation.d.ts +40 -0
- package/lib/credentials/oidc-federation.d.ts.map +1 -0
- package/lib/credentials/oidc-federation.js +82 -0
- package/lib/credentials/oidc-federation.js.map +1 -0
- package/lib/credentials/oidc-federation.mjs +79 -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 +379 -0
- package/src/internal/utils/time.ts +4 -0
- package/src/lib/credentials/credential-chain.ts +292 -0
- package/src/lib/credentials/identity-token.ts +37 -0
- package/src/lib/credentials/oidc-federation.ts +140 -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,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
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import type { Fetch } from '../../internal/builtin-types';
|
|
2
|
+
import type { AccessTokenProvider, IdentityTokenProvider } from './types';
|
|
3
|
+
import {
|
|
4
|
+
FEDERATION_BETA_HEADER,
|
|
5
|
+
GRANT_TYPE_JWT_BEARER,
|
|
6
|
+
OAUTH_API_BETA_HEADER,
|
|
7
|
+
TOKEN_ENDPOINT,
|
|
8
|
+
WorkloadIdentityError,
|
|
9
|
+
parseTokenResponse,
|
|
10
|
+
redactSensitive,
|
|
11
|
+
requireSecureTokenEndpoint,
|
|
12
|
+
} from './types';
|
|
13
|
+
import { nowAsSeconds } from '../../internal/utils/time';
|
|
14
|
+
import { VERSION } from '../../version';
|
|
15
|
+
|
|
16
|
+
export type OIDCFederationConfig = {
|
|
17
|
+
identityTokenProvider: IdentityTokenProvider;
|
|
18
|
+
federationRuleId: string;
|
|
19
|
+
organizationId: string;
|
|
20
|
+
serviceAccountId?: string | undefined;
|
|
21
|
+
/**
|
|
22
|
+
* Optional `wrkspc_*` tagged ID, or the literal `"default"` to scope the
|
|
23
|
+
* token to the organization's default workspace. When omitted the server
|
|
24
|
+
* picks the rule's sole enabled workspace, else the org default if the rule
|
|
25
|
+
* covers it. Required when the rule enables more than one non-default
|
|
26
|
+
* workspace, or to target a specific workspace other than the one the
|
|
27
|
+
* server would pick. The minted token is workspace-scoped: per-request
|
|
28
|
+
* workspace selection (the `anthropic-workspace-id` header) is not supported
|
|
29
|
+
* for federation tokens — switching workspaces requires a new token exchange
|
|
30
|
+
* with a different `workspaceId`.
|
|
31
|
+
*/
|
|
32
|
+
workspaceId?: string | undefined;
|
|
33
|
+
baseURL: string;
|
|
34
|
+
fetch: Fetch;
|
|
35
|
+
/**
|
|
36
|
+
* Overrides the outgoing User-Agent header on the token exchange. When
|
|
37
|
+
* empty, sends an SDK-identified UA so the token endpoint's access logs
|
|
38
|
+
* identify the caller.
|
|
39
|
+
*/
|
|
40
|
+
userAgent?: string | undefined;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Exchanges an external OIDC JWT for an Anthropic access token via the
|
|
45
|
+
* RFC 7523 jwt-bearer grant.
|
|
46
|
+
*
|
|
47
|
+
* Each invocation performs a fresh token exchange. Wrap in a
|
|
48
|
+
* {@link TokenCache} to avoid exchanging on every request.
|
|
49
|
+
*
|
|
50
|
+
* Federation grants do not return a refresh token — callers re-exchange
|
|
51
|
+
* their assertion on expiry.
|
|
52
|
+
*/
|
|
53
|
+
export function oidcFederationProvider(config: OIDCFederationConfig): AccessTokenProvider {
|
|
54
|
+
return async () => {
|
|
55
|
+
requireSecureTokenEndpoint(config.baseURL);
|
|
56
|
+
|
|
57
|
+
const jwt = await config.identityTokenProvider();
|
|
58
|
+
// The token endpoint enforces a 16 KiB assertion limit; surface a clear
|
|
59
|
+
// client-side error so misconfigured projected-token sources are
|
|
60
|
+
// diagnosable without a server round-trip.
|
|
61
|
+
if (jwt.length > 16 * 1024) {
|
|
62
|
+
throw new WorkloadIdentityError(
|
|
63
|
+
`Identity token is ${Math.ceil(jwt.length / 1024)} KiB, exceeds the 16 KiB assertion limit`,
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const body: Record<string, string> = {
|
|
68
|
+
grant_type: GRANT_TYPE_JWT_BEARER,
|
|
69
|
+
assertion: jwt,
|
|
70
|
+
federation_rule_id: config.federationRuleId,
|
|
71
|
+
organization_id: config.organizationId,
|
|
72
|
+
};
|
|
73
|
+
if (config.serviceAccountId) {
|
|
74
|
+
body['service_account_id'] = config.serviceAccountId;
|
|
75
|
+
}
|
|
76
|
+
if (config.workspaceId) {
|
|
77
|
+
body['workspace_id'] = config.workspaceId;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const url = `${config.baseURL}${TOKEN_ENDPOINT}`;
|
|
81
|
+
let resp: Response;
|
|
82
|
+
try {
|
|
83
|
+
resp = await config.fetch(url, {
|
|
84
|
+
method: 'POST',
|
|
85
|
+
headers: {
|
|
86
|
+
'Content-Type': 'application/json',
|
|
87
|
+
'anthropic-beta': `${OAUTH_API_BETA_HEADER},${FEDERATION_BETA_HEADER}`,
|
|
88
|
+
'User-Agent': config.userAgent || `anthropic-sdk-typescript/${VERSION} oidcFederationProvider`,
|
|
89
|
+
},
|
|
90
|
+
body: JSON.stringify(body),
|
|
91
|
+
});
|
|
92
|
+
} catch (err) {
|
|
93
|
+
throw new WorkloadIdentityError(`Failed to reach token endpoint ${url}: ${err}`);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const requestId = resp.headers.get('Request-Id');
|
|
97
|
+
|
|
98
|
+
if (!resp.ok) {
|
|
99
|
+
const text = await resp.text().catch(() => '');
|
|
100
|
+
const redacted = redactSensitive(text);
|
|
101
|
+
// A 401 is hard to debug from the status code alone, so surface
|
|
102
|
+
// guidance: check the federation rule, optionally set a workspace ID
|
|
103
|
+
// (the most common fix when no workspaceId is configured), and point at
|
|
104
|
+
// the Workload identity page in Claude Console for the server-side
|
|
105
|
+
// authentication event log. Other statuses (5xx, 400, ...) get no hint.
|
|
106
|
+
let hint = '';
|
|
107
|
+
if (resp.status === 401) {
|
|
108
|
+
const hintMiddle =
|
|
109
|
+
config.workspaceId ? '' : (
|
|
110
|
+
"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "
|
|
111
|
+
);
|
|
112
|
+
hint = ` Ensure your federation rule matches your identity token. ${hintMiddle}View your authentication events in the Workload identity page of Claude Console for more details.`;
|
|
113
|
+
}
|
|
114
|
+
throw new WorkloadIdentityError(
|
|
115
|
+
`Token exchange failed with status ${resp.status}${
|
|
116
|
+
requestId ? ` (request-id ${requestId})` : ''
|
|
117
|
+
}: ${redacted}${hint}`,
|
|
118
|
+
resp.status,
|
|
119
|
+
redacted,
|
|
120
|
+
requestId,
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const data = await parseTokenResponse(resp, requestId);
|
|
125
|
+
const expiresIn = Number(data.expires_in);
|
|
126
|
+
if (!Number.isFinite(expiresIn)) {
|
|
127
|
+
throw new WorkloadIdentityError(
|
|
128
|
+
`Token endpoint response missing required fields: ${JSON.stringify(redactSensitive(data))}`,
|
|
129
|
+
resp.status,
|
|
130
|
+
redactSensitive(data),
|
|
131
|
+
requestId,
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return {
|
|
136
|
+
token: data.access_token,
|
|
137
|
+
expiresAt: nowAsSeconds() + expiresIn,
|
|
138
|
+
};
|
|
139
|
+
};
|
|
140
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import type { AccessToken, AccessTokenProvider } from './types';
|
|
2
|
+
import {
|
|
3
|
+
ADVISORY_REFRESH_BACKOFF_IN_SECONDS,
|
|
4
|
+
ADVISORY_REFRESH_THRESHOLD_IN_SECONDS,
|
|
5
|
+
MANDATORY_REFRESH_THRESHOLD_IN_SECONDS,
|
|
6
|
+
} from './types';
|
|
7
|
+
import { nowAsSeconds } from '../../internal/utils/time';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Wraps an {@link AccessTokenProvider} with two-tier proactive refresh
|
|
11
|
+
* and concurrent deduplication.
|
|
12
|
+
*
|
|
13
|
+
* Refresh policy on each {@link getToken} call:
|
|
14
|
+
*
|
|
15
|
+
* - No cached token → call provider (blocking), cache, return.
|
|
16
|
+
* - Cached with `expiresAt == null` → return cached forever.
|
|
17
|
+
* - More than 120s remaining → return cached.
|
|
18
|
+
* - 30–120s remaining (advisory window) → return stale token immediately,
|
|
19
|
+
* kick off background refresh. On failure, log and keep stale.
|
|
20
|
+
* - Less than 30s remaining or expired (mandatory) → block and refresh.
|
|
21
|
+
* On failure, throw.
|
|
22
|
+
*
|
|
23
|
+
* Concurrent mandatory callers coalesce into a single provider call.
|
|
24
|
+
*/
|
|
25
|
+
export class TokenCache {
|
|
26
|
+
private provider: AccessTokenProvider;
|
|
27
|
+
private cached: AccessToken | null = null;
|
|
28
|
+
private pendingRefresh: Promise<AccessToken> | null = null;
|
|
29
|
+
private nextForce = false;
|
|
30
|
+
private lastAdvisoryError = 0;
|
|
31
|
+
private onAdvisoryRefreshError: ((err: unknown) => void) | undefined;
|
|
32
|
+
|
|
33
|
+
constructor(provider: AccessTokenProvider, onAdvisoryRefreshError?: (err: unknown) => void) {
|
|
34
|
+
this.provider = provider;
|
|
35
|
+
this.onAdvisoryRefreshError = onAdvisoryRefreshError;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async getToken(): Promise<string> {
|
|
39
|
+
const force = this.nextForce;
|
|
40
|
+
this.nextForce = false;
|
|
41
|
+
const cached = this.cached;
|
|
42
|
+
|
|
43
|
+
if (force || cached == null) {
|
|
44
|
+
const token = await this.refresh(force);
|
|
45
|
+
return token.token;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
if (cached.expiresAt == null) {
|
|
49
|
+
return cached.token;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const remaining = cached.expiresAt - nowAsSeconds();
|
|
53
|
+
|
|
54
|
+
if (remaining > ADVISORY_REFRESH_THRESHOLD_IN_SECONDS) {
|
|
55
|
+
return cached.token;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (remaining > MANDATORY_REFRESH_THRESHOLD_IN_SECONDS) {
|
|
59
|
+
this.backgroundRefresh();
|
|
60
|
+
return cached.token;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const token = await this.refresh();
|
|
64
|
+
return token.token;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Clears the cached token and marks the next {@link getToken} as a forced
|
|
69
|
+
* refresh, so the underlying provider bypasses any on-disk freshness check.
|
|
70
|
+
* Called after a 401 — the server has just told us the token is bad even
|
|
71
|
+
* if its `expires_at` still looks fresh.
|
|
72
|
+
*/
|
|
73
|
+
invalidate(): void {
|
|
74
|
+
this.cached = null;
|
|
75
|
+
this.nextForce = true;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Mandatory refresh. Joins any in-flight refresh unless forced — a forced
|
|
80
|
+
* refresh must not coalesce into a non-forced one that may re-serve the
|
|
81
|
+
* same stale disk token.
|
|
82
|
+
*/
|
|
83
|
+
private refresh(force = false): Promise<AccessToken> {
|
|
84
|
+
if (this.pendingRefresh && !force) {
|
|
85
|
+
return this.pendingRefresh;
|
|
86
|
+
}
|
|
87
|
+
return this.doRefresh(force);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Advisory background refresh. Shares the same in-flight promise as
|
|
92
|
+
* mandatory refreshes for deduplication, but swallows errors so the
|
|
93
|
+
* stale cached token keeps being served. Backs off for
|
|
94
|
+
* {@link ADVISORY_REFRESH_BACKOFF_IN_SECONDS} after a failure so an
|
|
95
|
+
* outage during the advisory window doesn't hammer the token endpoint.
|
|
96
|
+
*/
|
|
97
|
+
private backgroundRefresh(): void {
|
|
98
|
+
if (this.pendingRefresh) {
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
if (nowAsSeconds() - this.lastAdvisoryError < ADVISORY_REFRESH_BACKOFF_IN_SECONDS) {
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
this.doRefresh().catch((err) => {
|
|
105
|
+
this.lastAdvisoryError = nowAsSeconds();
|
|
106
|
+
// Advisory failure: keep serving the stale cached token, but surface
|
|
107
|
+
// the error to the caller-provided hook so it can be logged.
|
|
108
|
+
this.onAdvisoryRefreshError?.(err);
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Core refresh. Sets {@link pendingRefresh} so concurrent callers
|
|
114
|
+
* (both advisory and mandatory) coalesce into a single provider call.
|
|
115
|
+
*/
|
|
116
|
+
private doRefresh(force = false): Promise<AccessToken> {
|
|
117
|
+
this.pendingRefresh = this.provider(force ? { forceRefresh: true } : undefined).then(
|
|
118
|
+
(token) => {
|
|
119
|
+
this.cached = token;
|
|
120
|
+
this.pendingRefresh = null;
|
|
121
|
+
return token;
|
|
122
|
+
},
|
|
123
|
+
(err) => {
|
|
124
|
+
this.pendingRefresh = null;
|
|
125
|
+
throw err;
|
|
126
|
+
},
|
|
127
|
+
);
|
|
128
|
+
return this.pendingRefresh;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
import { AnthropicError } from '../../core/error';
|
|
2
|
+
|
|
3
|
+
export type AccessToken = {
|
|
4
|
+
token: string;
|
|
5
|
+
/** Unix epoch seconds. `null` means no expiry (cache forever). */
|
|
6
|
+
expiresAt: number | null;
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Mints or returns a cached access token.
|
|
11
|
+
*
|
|
12
|
+
* The optional `opts.forceRefresh` flag, set by {@link TokenCache.invalidate}
|
|
13
|
+
* after a 401, tells providers with on-disk caches (user_oauth, cachedExchange)
|
|
14
|
+
* to bypass their freshness short-circuit and always fetch fresh. Providers
|
|
15
|
+
* without a cache can ignore it.
|
|
16
|
+
*/
|
|
17
|
+
export type AccessTokenProvider = (opts?: { forceRefresh?: boolean }) => Promise<AccessToken>;
|
|
18
|
+
|
|
19
|
+
export type IdentityTokenProvider = () => string | Promise<string>;
|
|
20
|
+
|
|
21
|
+
export type CredentialResult = {
|
|
22
|
+
provider: AccessTokenProvider;
|
|
23
|
+
extraHeaders: Record<string, string>;
|
|
24
|
+
/**
|
|
25
|
+
* The `base_url` from the resolved config/profile, if any. The client
|
|
26
|
+
* applies this to outbound API requests when no explicit `baseURL` (constructor
|
|
27
|
+
* option or `ANTHROPIC_BASE_URL` env) was given, so a profile pointing at a
|
|
28
|
+
* non-default API host both mints its token against that host AND sends
|
|
29
|
+
* subsequent API requests there.
|
|
30
|
+
*/
|
|
31
|
+
baseURL?: string | undefined;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/** Response body from `POST /v1/oauth/token`. */
|
|
35
|
+
export type TokenEndpointResponse = {
|
|
36
|
+
access_token?: string;
|
|
37
|
+
expires_in?: number;
|
|
38
|
+
refresh_token?: string;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export const GRANT_TYPE_JWT_BEARER = 'urn:ietf:params:oauth:grant-type:jwt-bearer';
|
|
42
|
+
export const GRANT_TYPE_REFRESH_TOKEN = 'refresh_token';
|
|
43
|
+
export const TOKEN_ENDPOINT = '/v1/oauth/token';
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* `anthropic-beta` value required on authenticated API requests using an
|
|
47
|
+
* OAuth bearer token, and on `refresh_token` grants against the token endpoint.
|
|
48
|
+
*/
|
|
49
|
+
export const OAUTH_API_BETA_HEADER = 'oauth-2025-04-20';
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* `anthropic-beta` value required on jwt-bearer exchanges against the token
|
|
53
|
+
* endpoint. It routes the request to the federation service; it must NOT be
|
|
54
|
+
* sent on `refresh_token` grants, which are handled by a different backend.
|
|
55
|
+
*/
|
|
56
|
+
export const FEDERATION_BETA_HEADER = 'oidc-federation-2026-04-01';
|
|
57
|
+
|
|
58
|
+
export const ADVISORY_REFRESH_THRESHOLD_IN_SECONDS = 120;
|
|
59
|
+
export const MANDATORY_REFRESH_THRESHOLD_IN_SECONDS = 30;
|
|
60
|
+
export const ADVISORY_REFRESH_BACKOFF_IN_SECONDS = 5;
|
|
61
|
+
|
|
62
|
+
const MAX_TOKEN_RESPONSE_BYTES = 1 << 20;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Rejects base URLs that would cause a JWT assertion or refresh token to be
|
|
66
|
+
* sent over cleartext HTTP. Loopback hosts are allowed for local development.
|
|
67
|
+
*/
|
|
68
|
+
export function requireSecureTokenEndpoint(baseURL: string): void {
|
|
69
|
+
if (!baseURL) return;
|
|
70
|
+
let u: URL;
|
|
71
|
+
try {
|
|
72
|
+
u = new URL(baseURL);
|
|
73
|
+
} catch (err) {
|
|
74
|
+
throw new WorkloadIdentityError(`Invalid token endpoint base URL "${baseURL}": ${err}`);
|
|
75
|
+
}
|
|
76
|
+
if (u.protocol === 'https:') return;
|
|
77
|
+
// WHATWG URL.hostname returns bracketed IPv6 ("[::1]"); Go's net/url strips them.
|
|
78
|
+
const host = u.hostname.toLowerCase().replace(/^\[|\]$/g, '');
|
|
79
|
+
if (u.protocol === 'http:' && (host === 'localhost' || host === '127.0.0.1' || host === '::1')) {
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
throw new WorkloadIdentityError(`Refusing to send credential over non-https token endpoint "${baseURL}"`);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Reads the response body as text, parses it as a token-endpoint JSON
|
|
87
|
+
* response, validates `access_token` is present, and rejects a non-Bearer
|
|
88
|
+
* `token_type` when one is provided. Reads at most
|
|
89
|
+
* {@link MAX_TOKEN_RESPONSE_BYTES} from the body stream.
|
|
90
|
+
*/
|
|
91
|
+
export async function parseTokenResponse(
|
|
92
|
+
resp: Response,
|
|
93
|
+
requestId: string | null,
|
|
94
|
+
): Promise<TokenEndpointResponse & { access_token: string }> {
|
|
95
|
+
const text = await readLimitedText(resp);
|
|
96
|
+
let data: TokenEndpointResponse & { token_type?: string };
|
|
97
|
+
try {
|
|
98
|
+
data = JSON.parse(text);
|
|
99
|
+
} catch {
|
|
100
|
+
throw new WorkloadIdentityError(
|
|
101
|
+
`Token endpoint returned non-JSON response (status ${resp.status})`,
|
|
102
|
+
resp.status,
|
|
103
|
+
redactSensitive(text),
|
|
104
|
+
requestId,
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
if (!data.access_token) {
|
|
108
|
+
throw new WorkloadIdentityError(
|
|
109
|
+
`Token endpoint response missing access_token: ${JSON.stringify(redactSensitive(data))}`,
|
|
110
|
+
resp.status,
|
|
111
|
+
redactSensitive(data),
|
|
112
|
+
requestId,
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
if (data.token_type && data.token_type.toLowerCase() !== 'bearer') {
|
|
116
|
+
throw new WorkloadIdentityError(
|
|
117
|
+
`Token endpoint response: unsupported token_type "${data.token_type}" (want Bearer)`,
|
|
118
|
+
resp.status,
|
|
119
|
+
redactSensitive(data),
|
|
120
|
+
requestId,
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
return data as TokenEndpointResponse & { access_token: string };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const MAX_ERROR_BODY_CHARS = 2000;
|
|
127
|
+
// RFC 6749 §5.2 standard error-response fields. Anything else in a token
|
|
128
|
+
// endpoint error body is potentially echoed input (assertion, refresh_token,
|
|
129
|
+
// access_token, …) and is dropped rather than allowlisted-with-exceptions.
|
|
130
|
+
const SAFE_ERROR_KEYS = new Set(['error', 'error_description', 'error_uri']);
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Returns a redacted copy of a token-endpoint error body for safe inclusion
|
|
134
|
+
* in an exception. Strings are truncated; objects keep only the RFC 6749
|
|
135
|
+
* §5.2 error fields.
|
|
136
|
+
*/
|
|
137
|
+
export function redactSensitive(body: unknown): unknown {
|
|
138
|
+
if (body == null) return body;
|
|
139
|
+
if (typeof body === 'string') {
|
|
140
|
+
let parsed: unknown;
|
|
141
|
+
try {
|
|
142
|
+
parsed = JSON.parse(body);
|
|
143
|
+
} catch {
|
|
144
|
+
if (body.length <= MAX_ERROR_BODY_CHARS) return body;
|
|
145
|
+
return body.slice(0, MAX_ERROR_BODY_CHARS) + `... <${body.length - MAX_ERROR_BODY_CHARS} more chars>`;
|
|
146
|
+
}
|
|
147
|
+
return JSON.stringify(redactSensitive(parsed));
|
|
148
|
+
}
|
|
149
|
+
if (typeof body === 'object' && !Array.isArray(body)) {
|
|
150
|
+
const out: Record<string, unknown> = {};
|
|
151
|
+
for (const [k, v] of Object.entries(body)) {
|
|
152
|
+
if (SAFE_ERROR_KEYS.has(k)) out[k] = v;
|
|
153
|
+
}
|
|
154
|
+
return out;
|
|
155
|
+
}
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Best-effort safety check on a credentials file before reading it.
|
|
161
|
+
*
|
|
162
|
+
* On POSIX: resolves symlinks (so containerized deployments that mount the
|
|
163
|
+
* credential as a symlink to a tmpfs-backed file keep working), then rejects
|
|
164
|
+
* the resolved target if it is group- or world- readable or writable. A uid
|
|
165
|
+
* mismatch on the resolved target is surfaced via `onWarn` since
|
|
166
|
+
* root-written/app-read is common in init-container setups. No-op on Windows.
|
|
167
|
+
*/
|
|
168
|
+
export async function checkCredentialsFileSafety(
|
|
169
|
+
path: string,
|
|
170
|
+
onWarn: (msg: string) => void = (m) => console.warn(`anthropic-sdk: ${m}`),
|
|
171
|
+
): Promise<void> {
|
|
172
|
+
if (typeof process === 'undefined' || process.platform === 'win32') return;
|
|
173
|
+
const fs = await import('node:fs');
|
|
174
|
+
let resolved = path;
|
|
175
|
+
let st;
|
|
176
|
+
try {
|
|
177
|
+
resolved = await fs.promises.realpath(path);
|
|
178
|
+
st = await fs.promises.stat(resolved);
|
|
179
|
+
} catch {
|
|
180
|
+
return; // ENOENT etc — let the subsequent read surface a precise error
|
|
181
|
+
}
|
|
182
|
+
const mode = st.mode & 0o777;
|
|
183
|
+
// 0o022 = group/world write; 0o044 = group/world read.
|
|
184
|
+
if (mode & 0o022) {
|
|
185
|
+
throw new WorkloadIdentityError(
|
|
186
|
+
`Credentials file at ${resolved} is group/world-writable (mode 0o${mode.toString(8)}); ` +
|
|
187
|
+
`this allows other local users to plant tokens. Run \`chmod 600 ${resolved}\`.`,
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
if (mode & 0o044) {
|
|
191
|
+
throw new WorkloadIdentityError(
|
|
192
|
+
`Credentials file at ${resolved} is group/world-readable (mode 0o${mode.toString(8)}); ` +
|
|
193
|
+
`run \`chmod 600 ${resolved}\` before retrying.`,
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
if (typeof process.getuid === 'function' && st.uid !== process.getuid()) {
|
|
197
|
+
onWarn(
|
|
198
|
+
`credentials file at ${resolved} is owned by uid ${
|
|
199
|
+
st.uid
|
|
200
|
+
} (current process uid ${process.getuid()}); ` + `verify this is intentional.`,
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Atomically writes JSON to `targetPath` via a `.tmp` sibling + rename,
|
|
207
|
+
* with fsync on the file and (best-effort) on the parent directory.
|
|
208
|
+
* Creates the parent directory with mode 0700 and the file with mode 0600.
|
|
209
|
+
*/
|
|
210
|
+
export async function writeCredentialsFileAtomic(targetPath: string, data: unknown): Promise<void> {
|
|
211
|
+
const fs = await import('node:fs');
|
|
212
|
+
const path = await import('node:path');
|
|
213
|
+
const dir = path.dirname(targetPath);
|
|
214
|
+
await fs.promises.mkdir(dir, { recursive: true, mode: 0o700 });
|
|
215
|
+
// Unique temp name avoids two concurrent writers (different processes or
|
|
216
|
+
// SDK instances) racing on the same '.tmp' sibling and corrupting each
|
|
217
|
+
// other's bytes mid-write before the rename.
|
|
218
|
+
const tmpPath = `${targetPath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
219
|
+
try {
|
|
220
|
+
const fh = await fs.promises.open(tmpPath, 'w', 0o600);
|
|
221
|
+
try {
|
|
222
|
+
await fh.writeFile(JSON.stringify(data, null, 2));
|
|
223
|
+
await fh.sync();
|
|
224
|
+
} finally {
|
|
225
|
+
await fh.close();
|
|
226
|
+
}
|
|
227
|
+
await fs.promises.rename(tmpPath, targetPath);
|
|
228
|
+
} catch (err) {
|
|
229
|
+
// Don't leak the temp file if anything between create and rename failed.
|
|
230
|
+
await fs.promises.unlink(tmpPath).catch(() => {});
|
|
231
|
+
throw err;
|
|
232
|
+
}
|
|
233
|
+
// fsync the parent directory so the rename survives a crash.
|
|
234
|
+
try {
|
|
235
|
+
const dirFh = await fs.promises.open(dir, 'r');
|
|
236
|
+
try {
|
|
237
|
+
await dirFh.sync();
|
|
238
|
+
} finally {
|
|
239
|
+
await dirFh.close();
|
|
240
|
+
}
|
|
241
|
+
} catch {
|
|
242
|
+
// Directory fsync is best-effort (unsupported on some platforms, e.g. Windows).
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async function readLimitedText(resp: Response): Promise<string> {
|
|
247
|
+
if (!resp.body) {
|
|
248
|
+
return '';
|
|
249
|
+
}
|
|
250
|
+
const reader = resp.body.getReader();
|
|
251
|
+
const chunks: Uint8Array[] = [];
|
|
252
|
+
let received = 0;
|
|
253
|
+
for (;;) {
|
|
254
|
+
const { done, value } = await reader.read();
|
|
255
|
+
if (done) break;
|
|
256
|
+
if (received + value.length > MAX_TOKEN_RESPONSE_BYTES) {
|
|
257
|
+
const remaining = MAX_TOKEN_RESPONSE_BYTES - received;
|
|
258
|
+
if (remaining > 0) chunks.push(value.subarray(0, remaining));
|
|
259
|
+
await reader.cancel();
|
|
260
|
+
break;
|
|
261
|
+
}
|
|
262
|
+
chunks.push(value);
|
|
263
|
+
received += value.length;
|
|
264
|
+
}
|
|
265
|
+
let merged: Uint8Array;
|
|
266
|
+
if (chunks.length === 1) {
|
|
267
|
+
merged = chunks[0]!;
|
|
268
|
+
} else {
|
|
269
|
+
merged = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
|
|
270
|
+
let offset = 0;
|
|
271
|
+
for (const c of chunks) {
|
|
272
|
+
merged.set(c, offset);
|
|
273
|
+
offset += c.length;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return new TextDecoder('utf-8').decode(merged);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
export class WorkloadIdentityError extends AnthropicError {
|
|
280
|
+
readonly statusCode: number | null;
|
|
281
|
+
readonly body: unknown;
|
|
282
|
+
readonly requestId: string | null;
|
|
283
|
+
|
|
284
|
+
constructor(
|
|
285
|
+
message: string,
|
|
286
|
+
statusCode: number | null = null,
|
|
287
|
+
body: unknown = null,
|
|
288
|
+
requestId: string | null = null,
|
|
289
|
+
) {
|
|
290
|
+
super(message);
|
|
291
|
+
this.statusCode = statusCode;
|
|
292
|
+
this.body = body;
|
|
293
|
+
this.requestId = requestId;
|
|
294
|
+
}
|
|
295
|
+
}
|