@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,224 @@
1
+ import { AnthropicError } from "../../core/error.mjs";
2
+ export const GRANT_TYPE_JWT_BEARER = 'urn:ietf:params:oauth:grant-type:jwt-bearer';
3
+ export const GRANT_TYPE_REFRESH_TOKEN = 'refresh_token';
4
+ export const TOKEN_ENDPOINT = '/v1/oauth/token';
5
+ /**
6
+ * `anthropic-beta` value required on authenticated API requests using an
7
+ * OAuth bearer token, and on `refresh_token` grants against the token endpoint.
8
+ */
9
+ export const OAUTH_API_BETA_HEADER = 'oauth-2025-04-20';
10
+ /**
11
+ * `anthropic-beta` value required on jwt-bearer exchanges against the token
12
+ * endpoint. It routes the request to the federation service; it must NOT be
13
+ * sent on `refresh_token` grants, which are handled by a different backend.
14
+ */
15
+ export const FEDERATION_BETA_HEADER = 'oidc-federation-2026-04-01';
16
+ export const ADVISORY_REFRESH_THRESHOLD_IN_SECONDS = 120;
17
+ export const MANDATORY_REFRESH_THRESHOLD_IN_SECONDS = 30;
18
+ export const ADVISORY_REFRESH_BACKOFF_IN_SECONDS = 5;
19
+ const MAX_TOKEN_RESPONSE_BYTES = 1 << 20;
20
+ /**
21
+ * Rejects base URLs that would cause a JWT assertion or refresh token to be
22
+ * sent over cleartext HTTP. Loopback hosts are allowed for local development.
23
+ */
24
+ export function requireSecureTokenEndpoint(baseURL) {
25
+ if (!baseURL)
26
+ return;
27
+ let u;
28
+ try {
29
+ u = new URL(baseURL);
30
+ }
31
+ catch (err) {
32
+ throw new WorkloadIdentityError(`Invalid token endpoint base URL "${baseURL}": ${err}`);
33
+ }
34
+ if (u.protocol === 'https:')
35
+ return;
36
+ // WHATWG URL.hostname returns bracketed IPv6 ("[::1]"); Go's net/url strips them.
37
+ const host = u.hostname.toLowerCase().replace(/^\[|\]$/g, '');
38
+ if (u.protocol === 'http:' && (host === 'localhost' || host === '127.0.0.1' || host === '::1')) {
39
+ return;
40
+ }
41
+ throw new WorkloadIdentityError(`Refusing to send credential over non-https token endpoint "${baseURL}"`);
42
+ }
43
+ /**
44
+ * Reads the response body as text, parses it as a token-endpoint JSON
45
+ * response, validates `access_token` is present, and rejects a non-Bearer
46
+ * `token_type` when one is provided. Reads at most
47
+ * {@link MAX_TOKEN_RESPONSE_BYTES} from the body stream.
48
+ */
49
+ export async function parseTokenResponse(resp, requestId) {
50
+ const text = await readLimitedText(resp);
51
+ let data;
52
+ try {
53
+ data = JSON.parse(text);
54
+ }
55
+ catch {
56
+ throw new WorkloadIdentityError(`Token endpoint returned non-JSON response (status ${resp.status})`, resp.status, redactSensitive(text), requestId);
57
+ }
58
+ if (!data.access_token) {
59
+ throw new WorkloadIdentityError(`Token endpoint response missing access_token: ${JSON.stringify(redactSensitive(data))}`, resp.status, redactSensitive(data), requestId);
60
+ }
61
+ if (data.token_type && data.token_type.toLowerCase() !== 'bearer') {
62
+ throw new WorkloadIdentityError(`Token endpoint response: unsupported token_type "${data.token_type}" (want Bearer)`, resp.status, redactSensitive(data), requestId);
63
+ }
64
+ return data;
65
+ }
66
+ const MAX_ERROR_BODY_CHARS = 2000;
67
+ // RFC 6749 §5.2 standard error-response fields. Anything else in a token
68
+ // endpoint error body is potentially echoed input (assertion, refresh_token,
69
+ // access_token, …) and is dropped rather than allowlisted-with-exceptions.
70
+ const SAFE_ERROR_KEYS = new Set(['error', 'error_description', 'error_uri']);
71
+ /**
72
+ * Returns a redacted copy of a token-endpoint error body for safe inclusion
73
+ * in an exception. Strings are truncated; objects keep only the RFC 6749
74
+ * §5.2 error fields.
75
+ */
76
+ export function redactSensitive(body) {
77
+ if (body == null)
78
+ return body;
79
+ if (typeof body === 'string') {
80
+ let parsed;
81
+ try {
82
+ parsed = JSON.parse(body);
83
+ }
84
+ catch {
85
+ if (body.length <= MAX_ERROR_BODY_CHARS)
86
+ return body;
87
+ return body.slice(0, MAX_ERROR_BODY_CHARS) + `... <${body.length - MAX_ERROR_BODY_CHARS} more chars>`;
88
+ }
89
+ return JSON.stringify(redactSensitive(parsed));
90
+ }
91
+ if (typeof body === 'object' && !Array.isArray(body)) {
92
+ const out = {};
93
+ for (const [k, v] of Object.entries(body)) {
94
+ if (SAFE_ERROR_KEYS.has(k))
95
+ out[k] = v;
96
+ }
97
+ return out;
98
+ }
99
+ return null;
100
+ }
101
+ /**
102
+ * Best-effort safety check on a credentials file before reading it.
103
+ *
104
+ * On POSIX: resolves symlinks (so containerized deployments that mount the
105
+ * credential as a symlink to a tmpfs-backed file keep working), then rejects
106
+ * the resolved target if it is group- or world- readable or writable. A uid
107
+ * mismatch on the resolved target is surfaced via `onWarn` since
108
+ * root-written/app-read is common in init-container setups. No-op on Windows.
109
+ */
110
+ export async function checkCredentialsFileSafety(path, onWarn = (m) => console.warn(`anthropic-sdk: ${m}`)) {
111
+ if (typeof process === 'undefined' || process.platform === 'win32')
112
+ return;
113
+ const fs = await import('node:fs');
114
+ let resolved = path;
115
+ let st;
116
+ try {
117
+ resolved = await fs.promises.realpath(path);
118
+ st = await fs.promises.stat(resolved);
119
+ }
120
+ catch {
121
+ return; // ENOENT etc — let the subsequent read surface a precise error
122
+ }
123
+ const mode = st.mode & 0o777;
124
+ // 0o022 = group/world write; 0o044 = group/world read.
125
+ if (mode & 0o022) {
126
+ throw new WorkloadIdentityError(`Credentials file at ${resolved} is group/world-writable (mode 0o${mode.toString(8)}); ` +
127
+ `this allows other local users to plant tokens. Run \`chmod 600 ${resolved}\`.`);
128
+ }
129
+ if (mode & 0o044) {
130
+ throw new WorkloadIdentityError(`Credentials file at ${resolved} is group/world-readable (mode 0o${mode.toString(8)}); ` +
131
+ `run \`chmod 600 ${resolved}\` before retrying.`);
132
+ }
133
+ if (typeof process.getuid === 'function' && st.uid !== process.getuid()) {
134
+ onWarn(`credentials file at ${resolved} is owned by uid ${st.uid} (current process uid ${process.getuid()}); ` + `verify this is intentional.`);
135
+ }
136
+ }
137
+ /**
138
+ * Atomically writes JSON to `targetPath` via a `.tmp` sibling + rename,
139
+ * with fsync on the file and (best-effort) on the parent directory.
140
+ * Creates the parent directory with mode 0700 and the file with mode 0600.
141
+ */
142
+ export async function writeCredentialsFileAtomic(targetPath, data) {
143
+ const fs = await import('node:fs');
144
+ const path = await import('node:path');
145
+ const dir = path.dirname(targetPath);
146
+ await fs.promises.mkdir(dir, { recursive: true, mode: 0o700 });
147
+ // Unique temp name avoids two concurrent writers (different processes or
148
+ // SDK instances) racing on the same '.tmp' sibling and corrupting each
149
+ // other's bytes mid-write before the rename.
150
+ const tmpPath = `${targetPath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
151
+ try {
152
+ const fh = await fs.promises.open(tmpPath, 'w', 0o600);
153
+ try {
154
+ await fh.writeFile(JSON.stringify(data, null, 2));
155
+ await fh.sync();
156
+ }
157
+ finally {
158
+ await fh.close();
159
+ }
160
+ await fs.promises.rename(tmpPath, targetPath);
161
+ }
162
+ catch (err) {
163
+ // Don't leak the temp file if anything between create and rename failed.
164
+ await fs.promises.unlink(tmpPath).catch(() => { });
165
+ throw err;
166
+ }
167
+ // fsync the parent directory so the rename survives a crash.
168
+ try {
169
+ const dirFh = await fs.promises.open(dir, 'r');
170
+ try {
171
+ await dirFh.sync();
172
+ }
173
+ finally {
174
+ await dirFh.close();
175
+ }
176
+ }
177
+ catch {
178
+ // Directory fsync is best-effort (unsupported on some platforms, e.g. Windows).
179
+ }
180
+ }
181
+ async function readLimitedText(resp) {
182
+ if (!resp.body) {
183
+ return '';
184
+ }
185
+ const reader = resp.body.getReader();
186
+ const chunks = [];
187
+ let received = 0;
188
+ for (;;) {
189
+ const { done, value } = await reader.read();
190
+ if (done)
191
+ break;
192
+ if (received + value.length > MAX_TOKEN_RESPONSE_BYTES) {
193
+ const remaining = MAX_TOKEN_RESPONSE_BYTES - received;
194
+ if (remaining > 0)
195
+ chunks.push(value.subarray(0, remaining));
196
+ await reader.cancel();
197
+ break;
198
+ }
199
+ chunks.push(value);
200
+ received += value.length;
201
+ }
202
+ let merged;
203
+ if (chunks.length === 1) {
204
+ merged = chunks[0];
205
+ }
206
+ else {
207
+ merged = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
208
+ let offset = 0;
209
+ for (const c of chunks) {
210
+ merged.set(c, offset);
211
+ offset += c.length;
212
+ }
213
+ }
214
+ return new TextDecoder('utf-8').decode(merged);
215
+ }
216
+ export class WorkloadIdentityError extends AnthropicError {
217
+ constructor(message, statusCode = null, body = null, requestId = null) {
218
+ super(message);
219
+ this.statusCode = statusCode;
220
+ this.body = body;
221
+ this.requestId = requestId;
222
+ }
223
+ }
224
+ //# sourceMappingURL=types.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.mjs","sourceRoot":"","sources":["../../src/lib/credentials/types.ts"],"names":[],"mappings":"OAAO,EAAE,cAAc,EAAE;AAwCzB,MAAM,CAAC,MAAM,qBAAqB,GAAG,6CAA6C,CAAC;AACnF,MAAM,CAAC,MAAM,wBAAwB,GAAG,eAAe,CAAC;AACxD,MAAM,CAAC,MAAM,cAAc,GAAG,iBAAiB,CAAC;AAEhD;;;GAGG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,kBAAkB,CAAC;AAExD;;;;GAIG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,4BAA4B,CAAC;AAEnE,MAAM,CAAC,MAAM,qCAAqC,GAAG,GAAG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AAQ,cAAc;IAKvD,YACE,OAAe,EACf,aAA4B,IAAI,EAChC,OAAgB,IAAI,EACpB,YAA2B,IAAI;QAE/B,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;CACF"}
@@ -0,0 +1,21 @@
1
+ import type { Fetch } from "../../internal/builtin-types.mjs";
2
+ import type { AccessTokenProvider } from "./types.mjs";
3
+ export type UserOAuthConfig = {
4
+ credentialsPath: string;
5
+ clientId?: string | undefined;
6
+ baseURL: string;
7
+ fetch: Fetch;
8
+ userAgent?: string | undefined;
9
+ onSafetyWarning?: ((msg: string) => void) | undefined;
10
+ };
11
+ /**
12
+ * Reads a user-oauth credential file. Returns the cached access token while
13
+ * fresh; on expiry performs a `refresh_token` grant and writes the new
14
+ * tokens back to the credentials file (atomic replace, fsync'd).
15
+ *
16
+ * If `clientId` is empty, the access token is treated as static — the
17
+ * credentials file is read on every call but no refresh is attempted, and
18
+ * an expired token without a `refresh_token` raises.
19
+ */
20
+ export declare function userOAuthProvider(config: UserOAuthConfig): AccessTokenProvider;
21
+ //# sourceMappingURL=user-oauth.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"user-oauth.d.mts","sourceRoot":"","sources":["../../src/lib/credentials/user-oauth.ts"],"names":[],"mappings":"OAAO,KAAK,EAAE,KAAK,EAAE;OAEd,KAAK,EAAE,mBAAmB,EAAE;AAgBnC,MAAM,MAAM,eAAe,GAAG;IAC5B,eAAe,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,KAAK,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC/B,eAAe,CAAC,EAAE,CAAC,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;CACvD,CAAC;AAEF;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,eAAe,GAAG,mBAAmB,CA2G9E"}
@@ -0,0 +1,21 @@
1
+ import type { Fetch } from "../../internal/builtin-types.js";
2
+ import type { AccessTokenProvider } from "./types.js";
3
+ export type UserOAuthConfig = {
4
+ credentialsPath: string;
5
+ clientId?: string | undefined;
6
+ baseURL: string;
7
+ fetch: Fetch;
8
+ userAgent?: string | undefined;
9
+ onSafetyWarning?: ((msg: string) => void) | undefined;
10
+ };
11
+ /**
12
+ * Reads a user-oauth credential file. Returns the cached access token while
13
+ * fresh; on expiry performs a `refresh_token` grant and writes the new
14
+ * tokens back to the credentials file (atomic replace, fsync'd).
15
+ *
16
+ * If `clientId` is empty, the access token is treated as static — the
17
+ * credentials file is read on every call but no refresh is attempted, and
18
+ * an expired token without a `refresh_token` raises.
19
+ */
20
+ export declare function userOAuthProvider(config: UserOAuthConfig): AccessTokenProvider;
21
+ //# sourceMappingURL=user-oauth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"user-oauth.d.ts","sourceRoot":"","sources":["../../src/lib/credentials/user-oauth.ts"],"names":[],"mappings":"OAAO,KAAK,EAAE,KAAK,EAAE;OAEd,KAAK,EAAE,mBAAmB,EAAE;AAgBnC,MAAM,MAAM,eAAe,GAAG;IAC5B,eAAe,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,KAAK,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC/B,eAAe,CAAC,EAAE,CAAC,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;CACvD,CAAC;AAEF;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,eAAe,GAAG,mBAAmB,CA2G9E"}
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.userOAuthProvider = userOAuthProvider;
37
+ const credentials_1 = require("../../core/credentials.js");
38
+ const types_1 = require("./types.js");
39
+ const time_1 = require("../../internal/utils/time.js");
40
+ const version_1 = require("../../version.js");
41
+ /**
42
+ * Reads a user-oauth credential file. Returns the cached access token while
43
+ * fresh; on expiry performs a `refresh_token` grant and writes the new
44
+ * tokens back to the credentials file (atomic replace, fsync'd).
45
+ *
46
+ * If `clientId` is empty, the access token is treated as static — the
47
+ * credentials file is read on every call but no refresh is attempted, and
48
+ * an expired token without a `refresh_token` raises.
49
+ */
50
+ function userOAuthProvider(config) {
51
+ return async (opts) => {
52
+ const fs = await Promise.resolve().then(() => __importStar(require('node:fs')));
53
+ await (0, types_1.checkCredentialsFileSafety)(config.credentialsPath, config.onSafetyWarning);
54
+ let raw;
55
+ try {
56
+ raw = await fs.promises.readFile(config.credentialsPath, 'utf-8');
57
+ }
58
+ catch (err) {
59
+ throw new types_1.WorkloadIdentityError(`Credentials file not found at ${config.credentialsPath}: ${err}`);
60
+ }
61
+ let creds;
62
+ try {
63
+ creds = JSON.parse(raw);
64
+ }
65
+ catch (err) {
66
+ throw new types_1.WorkloadIdentityError(`Credentials file at ${config.credentialsPath} is not valid JSON: ${err}`);
67
+ }
68
+ const accessToken = creds.access_token;
69
+ if (!accessToken) {
70
+ throw new types_1.WorkloadIdentityError(`Credentials file at ${config.credentialsPath} must include 'access_token'`);
71
+ }
72
+ // Return cached token if still fresh (or no expiry info), unless the
73
+ // caller is forcing a refresh after a 401 — then go straight to refresh
74
+ // even if the file's expires_at still looks valid.
75
+ const expiresAt = creds.expires_at;
76
+ if (!opts?.forceRefresh &&
77
+ (expiresAt == null || (0, time_1.nowAsSeconds)() < expiresAt - types_1.MANDATORY_REFRESH_THRESHOLD_IN_SECONDS)) {
78
+ return { token: accessToken, expiresAt: expiresAt ?? null };
79
+ }
80
+ const refreshToken = creds.refresh_token;
81
+ if (!config.clientId || !refreshToken) {
82
+ throw new types_1.WorkloadIdentityError(`Access token at ${config.credentialsPath} has expired and no refresh is available ` +
83
+ `(client_id ${config.clientId ? 'set' : 'empty'}, refresh_token ${refreshToken ? 'set' : 'empty'})`);
84
+ }
85
+ (0, types_1.requireSecureTokenEndpoint)(config.baseURL);
86
+ const body = {
87
+ grant_type: types_1.GRANT_TYPE_REFRESH_TOKEN,
88
+ refresh_token: refreshToken,
89
+ client_id: config.clientId,
90
+ };
91
+ const url = `${config.baseURL}${types_1.TOKEN_ENDPOINT}`;
92
+ let resp;
93
+ try {
94
+ resp = await config.fetch(url, {
95
+ method: 'POST',
96
+ headers: {
97
+ 'Content-Type': 'application/json',
98
+ 'anthropic-beta': types_1.OAUTH_API_BETA_HEADER,
99
+ 'User-Agent': config.userAgent || `anthropic-sdk-typescript/${version_1.VERSION} userOAuthProvider`,
100
+ },
101
+ body: JSON.stringify(body),
102
+ });
103
+ }
104
+ catch (err) {
105
+ throw new types_1.WorkloadIdentityError(`User OAuth refresh failed to reach token endpoint: ${err}`);
106
+ }
107
+ const requestId = resp.headers.get('Request-Id');
108
+ if (!resp.ok) {
109
+ const text = await resp.text().catch(() => '');
110
+ throw new types_1.WorkloadIdentityError(`User OAuth refresh failed (HTTP ${resp.status}): ${(0, types_1.redactSensitive)(text)}`, resp.status, (0, types_1.redactSensitive)(text), requestId);
111
+ }
112
+ const data = await (0, types_1.parseTokenResponse)(resp, requestId);
113
+ const expiresIn = Number(data.expires_in);
114
+ if (!Number.isFinite(expiresIn)) {
115
+ throw new types_1.WorkloadIdentityError(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify((0, types_1.redactSensitive)(data))}`, resp.status, (0, types_1.redactSensitive)(data), requestId);
116
+ }
117
+ const newExpiresAt = (0, time_1.nowAsSeconds)() + expiresIn;
118
+ const newRefreshToken = data.refresh_token || refreshToken;
119
+ await (0, types_1.writeCredentialsFileAtomic)(config.credentialsPath, {
120
+ ...creds,
121
+ version: credentials_1.CREDENTIALS_FILE_VERSION,
122
+ type: 'oauth_token',
123
+ access_token: data.access_token,
124
+ expires_at: newExpiresAt,
125
+ refresh_token: newRefreshToken,
126
+ });
127
+ return { token: data.access_token, expiresAt: newExpiresAt };
128
+ };
129
+ }
130
+ //# sourceMappingURL=user-oauth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"user-oauth.js","sourceRoot":"","sources":["../../src/lib/credentials/user-oauth.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,8CA2GC;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CAAC;IAC/D,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,94 @@
1
+ import { CREDENTIALS_FILE_VERSION } from "../../core/credentials.mjs";
2
+ import { GRANT_TYPE_REFRESH_TOKEN, MANDATORY_REFRESH_THRESHOLD_IN_SECONDS, OAUTH_API_BETA_HEADER, TOKEN_ENDPOINT, WorkloadIdentityError, checkCredentialsFileSafety, parseTokenResponse, redactSensitive, requireSecureTokenEndpoint, writeCredentialsFileAtomic, } from "./types.mjs";
3
+ import { nowAsSeconds } from "../../internal/utils/time.mjs";
4
+ import { VERSION } from "../../version.mjs";
5
+ /**
6
+ * Reads a user-oauth credential file. Returns the cached access token while
7
+ * fresh; on expiry performs a `refresh_token` grant and writes the new
8
+ * tokens back to the credentials file (atomic replace, fsync'd).
9
+ *
10
+ * If `clientId` is empty, the access token is treated as static — the
11
+ * credentials file is read on every call but no refresh is attempted, and
12
+ * an expired token without a `refresh_token` raises.
13
+ */
14
+ export function userOAuthProvider(config) {
15
+ return async (opts) => {
16
+ const fs = await import('node:fs');
17
+ await checkCredentialsFileSafety(config.credentialsPath, config.onSafetyWarning);
18
+ let raw;
19
+ try {
20
+ raw = await fs.promises.readFile(config.credentialsPath, 'utf-8');
21
+ }
22
+ catch (err) {
23
+ throw new WorkloadIdentityError(`Credentials file not found at ${config.credentialsPath}: ${err}`);
24
+ }
25
+ let creds;
26
+ try {
27
+ creds = JSON.parse(raw);
28
+ }
29
+ catch (err) {
30
+ throw new WorkloadIdentityError(`Credentials file at ${config.credentialsPath} is not valid JSON: ${err}`);
31
+ }
32
+ const accessToken = creds.access_token;
33
+ if (!accessToken) {
34
+ throw new WorkloadIdentityError(`Credentials file at ${config.credentialsPath} must include 'access_token'`);
35
+ }
36
+ // Return cached token if still fresh (or no expiry info), unless the
37
+ // caller is forcing a refresh after a 401 — then go straight to refresh
38
+ // even if the file's expires_at still looks valid.
39
+ const expiresAt = creds.expires_at;
40
+ if (!opts?.forceRefresh &&
41
+ (expiresAt == null || nowAsSeconds() < expiresAt - MANDATORY_REFRESH_THRESHOLD_IN_SECONDS)) {
42
+ return { token: accessToken, expiresAt: expiresAt ?? null };
43
+ }
44
+ const refreshToken = creds.refresh_token;
45
+ if (!config.clientId || !refreshToken) {
46
+ throw new WorkloadIdentityError(`Access token at ${config.credentialsPath} has expired and no refresh is available ` +
47
+ `(client_id ${config.clientId ? 'set' : 'empty'}, refresh_token ${refreshToken ? 'set' : 'empty'})`);
48
+ }
49
+ requireSecureTokenEndpoint(config.baseURL);
50
+ const body = {
51
+ grant_type: GRANT_TYPE_REFRESH_TOKEN,
52
+ refresh_token: refreshToken,
53
+ client_id: config.clientId,
54
+ };
55
+ const url = `${config.baseURL}${TOKEN_ENDPOINT}`;
56
+ let resp;
57
+ try {
58
+ resp = await config.fetch(url, {
59
+ method: 'POST',
60
+ headers: {
61
+ 'Content-Type': 'application/json',
62
+ 'anthropic-beta': OAUTH_API_BETA_HEADER,
63
+ 'User-Agent': config.userAgent || `anthropic-sdk-typescript/${VERSION} userOAuthProvider`,
64
+ },
65
+ body: JSON.stringify(body),
66
+ });
67
+ }
68
+ catch (err) {
69
+ throw new WorkloadIdentityError(`User OAuth refresh failed to reach token endpoint: ${err}`);
70
+ }
71
+ const requestId = resp.headers.get('Request-Id');
72
+ if (!resp.ok) {
73
+ const text = await resp.text().catch(() => '');
74
+ throw new WorkloadIdentityError(`User OAuth refresh failed (HTTP ${resp.status}): ${redactSensitive(text)}`, resp.status, redactSensitive(text), requestId);
75
+ }
76
+ const data = await parseTokenResponse(resp, requestId);
77
+ const expiresIn = Number(data.expires_in);
78
+ if (!Number.isFinite(expiresIn)) {
79
+ throw new WorkloadIdentityError(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(redactSensitive(data))}`, resp.status, redactSensitive(data), requestId);
80
+ }
81
+ const newExpiresAt = nowAsSeconds() + expiresIn;
82
+ const newRefreshToken = data.refresh_token || refreshToken;
83
+ await writeCredentialsFileAtomic(config.credentialsPath, {
84
+ ...creds,
85
+ version: CREDENTIALS_FILE_VERSION,
86
+ type: 'oauth_token',
87
+ access_token: data.access_token,
88
+ expires_at: newExpiresAt,
89
+ refresh_token: newRefreshToken,
90
+ });
91
+ return { token: data.access_token, expiresAt: newExpiresAt };
92
+ };
93
+ }
94
+ //# sourceMappingURL=user-oauth.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"user-oauth.mjs","sourceRoot":"","sources":["../../src/lib/credentials/user-oauth.ts"],"names":[],"mappings":"OACO,EAAE,wBAAwB,EAA6B;OAEvD,EACL,wBAAwB,EACxB,sCAAsC,EACtC,qBAAqB,EACrB,cAAc,EACd,qBAAqB,EACrB,0BAA0B,EAC1B,kBAAkB,EAClB,eAAe,EACf,0BAA0B,EAC1B,0BAA0B,GAC3B;OACM,EAAE,YAAY,EAAE;OAChB,EAAE,OAAO,EAAE;AAWlB;;;;;;;;GAQG;AACH,MAAM,UAAU,iBAAiB,CAAC,MAAuB;IACvD,OAAO,KAAK,EAAE,IAAI,EAAE,EAAE;QACpB,MAAM,EAAE,GAAG,MAAM,MAAM,CAAC,SAAS,CAAC,CAAC;QAEnC,MAAM,0BAA0B,CAAC,MAAM,CAAC,eAAe,EAAE,MAAM,CAAC,eAAe,CAAC,CAAC;QAEjF,IAAI,GAAW,CAAC;QAChB,IAAI,CAAC;YACH,GAAG,GAAG,MAAM,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,eAAe,EAAE,OAAO,CAAC,CAAC;QACpE,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,IAAI,qBAAqB,CAAC,iCAAiC,MAAM,CAAC,eAAe,KAAK,GAAG,EAAE,CAAC,CAAC;QACrG,CAAC;QACD,IAAI,KAA2B,CAAC;QAChC,IAAI,CAAC;YACH,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAC1B,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,IAAI,qBAAqB,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QACD,MAAM,YAAY,GAAG,YAAY,EAAE,GAAG,SAAS,CAAC;QAChD,MAAM,eAAe,GAAG,IAAI,CAAC,aAAa,IAAI,YAAY,CAAC;QAE3D,MAAM,0BAA0B,CAAC,MAAM,CAAC,eAAe,EAAE;YACvD,GAAG,KAAK;YACR,OAAO,EAAE,wBAAwB;YACjC,IAAI,EAAE,aAAa;YACnB,YAAY,EAAE,IAAI,CAAC,YAAY;YAC/B,UAAU,EAAE,YAAY;YACxB,aAAa,EAAE,eAAe;SAC/B,CAAC,CAAC;QAEH,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,YAAY,EAAE,SAAS,EAAE,YAAY,EAAE,CAAC;IAC/D,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,4 @@
1
+ export { type AccessToken, type AccessTokenProvider } from "./credentials/types.mjs";
2
+ export { type AnthropicConfig, type AuthenticationInfo, loadConfig } from "../core/credentials.mjs";
3
+ export { resolveCredentialsFromConfig } from "./credentials/credential-chain.mjs";
4
+ //# sourceMappingURL=credentials.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credentials.d.mts","sourceRoot":"","sources":["../src/lib/credentials.ts"],"names":[],"mappings":"OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,mBAAmB,EAAE;OAC9C,EAAE,KAAK,eAAe,EAAE,KAAK,kBAAkB,EAAE,UAAU,EAAE;OAC7D,EAAE,4BAA4B,EAAE"}
@@ -0,0 +1,4 @@
1
+ export { type AccessToken, type AccessTokenProvider } from "./credentials/types.js";
2
+ export { type AnthropicConfig, type AuthenticationInfo, loadConfig } from "../core/credentials.js";
3
+ export { resolveCredentialsFromConfig } from "./credentials/credential-chain.js";
4
+ //# sourceMappingURL=credentials.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credentials.d.ts","sourceRoot":"","sources":["../src/lib/credentials.ts"],"names":[],"mappings":"OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,mBAAmB,EAAE;OAC9C,EAAE,KAAK,eAAe,EAAE,KAAK,kBAAkB,EAAE,UAAU,EAAE;OAC7D,EAAE,4BAA4B,EAAE"}
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveCredentialsFromConfig = exports.loadConfig = void 0;
4
+ var credentials_1 = require("../core/credentials.js");
5
+ Object.defineProperty(exports, "loadConfig", { enumerable: true, get: function () { return credentials_1.loadConfig; } });
6
+ var credential_chain_1 = require("./credentials/credential-chain.js");
7
+ Object.defineProperty(exports, "resolveCredentialsFromConfig", { enumerable: true, get: function () { return credential_chain_1.resolveCredentialsFromConfig; } });
8
+ //# sourceMappingURL=credentials.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credentials.js","sourceRoot":"","sources":["../src/lib/credentials.ts"],"names":[],"mappings":";;;AACA,sDAAgG;AAAxC,yGAAA,UAAU,OAAA;AAClE,sEAA8E;AAArE,gIAAA,4BAA4B,OAAA"}
@@ -0,0 +1,3 @@
1
+ export { loadConfig } from "../core/credentials.mjs";
2
+ export { resolveCredentialsFromConfig } from "./credentials/credential-chain.mjs";
3
+ //# sourceMappingURL=credentials.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credentials.mjs","sourceRoot":"","sources":["../src/lib/credentials.ts"],"names":[],"mappings":"OACO,EAAiD,UAAU,EAAE;OAC7D,EAAE,4BAA4B,EAAE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anthropic-ai/sdk",
3
- "version": "0.92.0",
3
+ "version": "0.94.0",
4
4
  "description": "The official TypeScript library for the Anthropic API",
5
5
  "author": "Anthropic <support@anthropic.com>",
6
6
  "types": "./index.d.ts",