first commit
SAP-ERP Portal CI/CD / build (push) Failing after 5m20s

This commit is contained in:
John
2026-09-23 17:31:02 +05:30
commit 69b4e68baf
51657 changed files with 3864077 additions and 0 deletions
@@ -0,0 +1,39 @@
import type { Fetch } from "../../internal/builtin-types.mjs";
import { type AnthropicConfig } from "../../core/credentials.mjs";
import type { CredentialResult } from "./types.mjs";
/**
* Builds a {@link CredentialResult} from an explicit {@link AnthropicConfig}.
*
* Use this when constructing a client from an in-memory config object rather
* than from profile files or environment variables.
*
* For `oidc_federation`, `authentication.credentials_path` is optional —
* if omitted, every call performs a fresh exchange with no on-disk cache.
* For `user_oauth`, `authentication.credentials_path` is required (it is
* where the access/refresh tokens live).
*/
export type ResolverOptions = {
baseURL: string;
fetch: Fetch;
userAgent?: string | undefined;
onCacheWriteError?: ((err: unknown) => void) | undefined;
onSafetyWarning?: ((msg: string) => void) | undefined;
};
export declare function resolveCredentialsFromConfig(config: AnthropicConfig, options: ResolverOptions): CredentialResult;
/**
* Resolves a {@link CredentialResult} from the environment. Returns `null`
* when no credentials can be resolved.
*
* Resolution order:
*
* 1. Config file for the active profile (or the explicit `profile` argument)
* → dispatch on `authentication.type` (`oidc_federation`, `user_oauth`)
* 2. Environment variables `ANTHROPIC_FEDERATION_RULE_ID` +
* `ANTHROPIC_ORGANIZATION_ID` (+ identity token) → OIDC federation
* 3. Nothing matches → `null`
*
* Passing `profile` selects `<config_dir>/configs/<profile>.json` directly,
* skipping `ANTHROPIC_PROFILE` / `active_config` resolution.
*/
export declare function defaultCredentials(options: ResolverOptions, profile?: string): Promise<CredentialResult | null>;
//# sourceMappingURL=credential-chain.d.mts.map
@@ -0,0 +1 @@
{"version":3,"file":"credential-chain.d.mts","sourceRoot":"","sources":["../../src/lib/credentials/credential-chain.ts"],"names":[],"mappings":"OAAO,KAAK,EAAE,KAAK,EAAE;OAEd,EAIL,KAAK,eAAe,EACrB;OACM,KAAK,EAAuB,gBAAgB,EAAyB;AAY5E;;;;;;;;;;GAUG;AACH,MAAM,MAAM,eAAe,GAAG;IAC5B,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,KAAK,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC/B,iBAAiB,CAAC,EAAE,CAAC,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;IACzD,eAAe,CAAC,EAAE,CAAC,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;CACvD,CAAC;AAEF,wBAAgB,4BAA4B,CAC1C,MAAM,EAAE,eAAe,EACvB,OAAO,EAAE,eAAe,GACvB,gBAAgB,CAkBlB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,kBAAkB,CACtC,OAAO,EAAE,eAAe,EACxB,OAAO,CAAC,EAAE,MAAM,GACf,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC,CA6BlC"}
@@ -0,0 +1,39 @@
import type { Fetch } from "../../internal/builtin-types.js";
import { type AnthropicConfig } from "../../core/credentials.js";
import type { CredentialResult } from "./types.js";
/**
* Builds a {@link CredentialResult} from an explicit {@link AnthropicConfig}.
*
* Use this when constructing a client from an in-memory config object rather
* than from profile files or environment variables.
*
* For `oidc_federation`, `authentication.credentials_path` is optional —
* if omitted, every call performs a fresh exchange with no on-disk cache.
* For `user_oauth`, `authentication.credentials_path` is required (it is
* where the access/refresh tokens live).
*/
export type ResolverOptions = {
baseURL: string;
fetch: Fetch;
userAgent?: string | undefined;
onCacheWriteError?: ((err: unknown) => void) | undefined;
onSafetyWarning?: ((msg: string) => void) | undefined;
};
export declare function resolveCredentialsFromConfig(config: AnthropicConfig, options: ResolverOptions): CredentialResult;
/**
* Resolves a {@link CredentialResult} from the environment. Returns `null`
* when no credentials can be resolved.
*
* Resolution order:
*
* 1. Config file for the active profile (or the explicit `profile` argument)
* → dispatch on `authentication.type` (`oidc_federation`, `user_oauth`)
* 2. Environment variables `ANTHROPIC_FEDERATION_RULE_ID` +
* `ANTHROPIC_ORGANIZATION_ID` (+ identity token) → OIDC federation
* 3. Nothing matches → `null`
*
* Passing `profile` selects `<config_dir>/configs/<profile>.json` directly,
* skipping `ANTHROPIC_PROFILE` / `active_config` resolution.
*/
export declare function defaultCredentials(options: ResolverOptions, profile?: string): Promise<CredentialResult | null>;
//# sourceMappingURL=credential-chain.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"credential-chain.d.ts","sourceRoot":"","sources":["../../src/lib/credentials/credential-chain.ts"],"names":[],"mappings":"OAAO,KAAK,EAAE,KAAK,EAAE;OAEd,EAIL,KAAK,eAAe,EACrB;OACM,KAAK,EAAuB,gBAAgB,EAAyB;AAY5E;;;;;;;;;;GAUG;AACH,MAAM,MAAM,eAAe,GAAG;IAC5B,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,KAAK,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC/B,iBAAiB,CAAC,EAAE,CAAC,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;IACzD,eAAe,CAAC,EAAE,CAAC,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;CACvD,CAAC;AAEF,wBAAgB,4BAA4B,CAC1C,MAAM,EAAE,eAAe,EACvB,OAAO,EAAE,eAAe,GACvB,gBAAgB,CAkBlB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,kBAAkB,CACtC,OAAO,EAAE,eAAe,EACxB,OAAO,CAAC,EAAE,MAAM,GACf,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC,CA6BlC"}
@@ -0,0 +1,245 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveCredentialsFromConfig = resolveCredentialsFromConfig;
exports.defaultCredentials = defaultCredentials;
const env_1 = require("../../internal/utils/env.js");
const credentials_1 = require("../../core/credentials.js");
const types_1 = require("./types.js");
const time_1 = require("../../internal/utils/time.js");
const identity_token_1 = require("./identity-token.js");
const oidc_federation_1 = require("./oidc-federation.js");
const user_oauth_1 = require("./user-oauth.js");
function resolveCredentialsFromConfig(config, options) {
const credentialsPath = config.authentication.credentials_path ?? null;
const effectiveBaseURL = (config.base_url || options.baseURL).replace(/\/+$/, '');
const provider = buildProvider(config, credentialsPath, effectiveBaseURL, options);
const extraHeaders = {};
// For federation profiles workspace_id is sent in the jwt-bearer exchange
// body, not as a request header (the minted token is already
// workspace-scoped, so the header would be ignored).
if (config.workspace_id && config.authentication.type === 'user_oauth') {
extraHeaders['anthropic-workspace-id'] = config.workspace_id;
}
// Surface the profile's own base_url (not the options.baseURL fallback) so
// the client can adopt it for outbound API requests when the caller didn't
// pin one explicitly. Echoing options.baseURL back would defeat precedence.
return { provider, extraHeaders, baseURL: config.base_url || undefined };
}
/**
* Resolves a {@link CredentialResult} from the environment. Returns `null`
* when no credentials can be resolved.
*
* Resolution order:
*
* 1. Config file for the active profile (or the explicit `profile` argument)
* → dispatch on `authentication.type` (`oidc_federation`, `user_oauth`)
* 2. Environment variables `ANTHROPIC_FEDERATION_RULE_ID` +
* `ANTHROPIC_ORGANIZATION_ID` (+ identity token) → OIDC federation
* 3. Nothing matches → `null`
*
* Passing `profile` selects `<config_dir>/configs/<profile>.json` directly,
* skipping `ANTHROPIC_PROFILE` / `active_config` resolution.
*/
async function defaultCredentials(options, profile) {
const loaded = await (0, credentials_1.loadConfigWithSource)(profile);
if (!loaded) {
return null;
}
const { config, fromFile } = loaded;
// For file-loaded configs, default credentials_path to the per-profile
// location so user_oauth and federation caching work. Shallow-clone first
// so callers that retain a reference to the loaded config don't observe the
// patched-in default.
//
// Env-only credentials (no profile file on disk) skip the disk cache —
// matching the other SDKs. A disk cache keyed by profile path would
// re-serve a stale token after a change to ANTHROPIC_WORKSPACE_ID (or
// ANTHROPIC_ORGANIZATION_ID / ANTHROPIC_FEDERATION_RULE_ID) until the
// cached token expired, so the env-only chain stays in-memory only.
const withPath = config.authentication.credentials_path || !fromFile ?
config
: {
...config,
authentication: {
...config.authentication,
credentials_path: (await (0, credentials_1.getCredentialsPath)(config, profile)) ?? undefined,
},
};
return resolveCredentialsFromConfig(withPath, options);
}
function buildProvider(config, credentialsPath, baseURL, options) {
switch (config.authentication.type) {
case 'oidc_federation': {
const auth = config.authentication;
const identityProvider = resolveIdentityTokenProvider(auth);
if (!identityProvider) {
throw new types_1.WorkloadIdentityError('oidc_federation config requires an identity token (set authentication.identity_token, ' +
'ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)');
}
if (!auth.federation_rule_id) {
throw new types_1.WorkloadIdentityError("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).");
}
if (!config.organization_id) {
throw new types_1.WorkloadIdentityError('oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)');
}
const exchange = (0, oidc_federation_1.oidcFederationProvider)({
identityTokenProvider: identityProvider,
federationRuleId: auth.federation_rule_id,
organizationId: config.organization_id,
serviceAccountId: auth.service_account_id,
workspaceId: config.workspace_id,
baseURL,
fetch: options.fetch,
userAgent: options.userAgent,
});
// If there's a credentials file path, wrap the exchange with file caching
// (check file for fresh token before exchanging, write back after).
if (credentialsPath) {
return cachedExchangeProvider(exchange, credentialsPath, options.onCacheWriteError, options.onSafetyWarning);
}
return exchange;
}
case 'user_oauth': {
if (!credentialsPath) {
throw new types_1.WorkloadIdentityError('user_oauth config requires authentication.credentials_path ' +
'(or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)');
}
return (0, user_oauth_1.userOAuthProvider)({
credentialsPath,
clientId: config.authentication.client_id,
baseURL,
fetch: options.fetch,
userAgent: options.userAgent,
onSafetyWarning: options.onSafetyWarning,
});
}
default: {
const t = config.authentication.type;
throw new types_1.WorkloadIdentityError(`authentication.type "${t}" is not a known authentication type`);
}
}
}
/**
* Resolves the identity token provider from config fields or environment variables.
*
* Resolution order:
* 1. `identity_token.path` from the config (source: "file")
* 2. `ANTHROPIC_IDENTITY_TOKEN_FILE` env var
* 3. `ANTHROPIC_IDENTITY_TOKEN` env var (static value)
*/
function resolveIdentityTokenProvider(auth) {
if (auth.identity_token) {
// Cast needed to stringify an unknown source value for the error message:
// the on-disk JSON may contain a source this SDK version doesn't know about.
const source = auth.identity_token.source;
if (source !== 'file') {
throw new types_1.WorkloadIdentityError(`identity_token.source "${source}" is not supported by this SDK version (only "file")`);
}
if (!auth.identity_token.path) {
throw new types_1.WorkloadIdentityError(`identity_token.source "file" requires a non-empty path`);
}
return (0, identity_token_1.identityTokenFromFile)(auth.identity_token.path);
}
const tokenFile = (0, env_1.readEnv)('ANTHROPIC_IDENTITY_TOKEN_FILE');
if (tokenFile) {
return (0, identity_token_1.identityTokenFromFile)(tokenFile);
}
const tokenValue = (0, env_1.readEnv)('ANTHROPIC_IDENTITY_TOKEN');
if (tokenValue) {
return (0, identity_token_1.identityTokenFromValue)(tokenValue);
}
return null;
}
/**
* Wraps a federation exchange provider with credential file caching.
* Checks the file for a fresh token before exchanging, and writes the
* result back after a successful exchange (best-effort, atomic replace).
*
* Note: this is not cross-process serialized — two SDK instances that
* miss the cache simultaneously will both perform a full exchange and
* the last writer wins. That is acceptable: federation exchanges are
* idempotent and the cache is an optimization, not a correctness gate.
*/
function cachedExchangeProvider(exchange, credentialsPath, onCacheWriteError, onSafetyWarning) {
return async (opts) => {
const fs = await Promise.resolve().then(() => __importStar(require('node:fs')));
await (0, types_1.checkCredentialsFileSafety)(credentialsPath, onSafetyWarning);
// Try cached credentials file
let existing;
try {
const raw = await fs.promises.readFile(credentialsPath, 'utf-8');
existing = JSON.parse(raw);
const token = existing?.['access_token'];
if (token && !opts?.forceRefresh) {
const expiresAt = existing?.['expires_at'];
if (expiresAt == null || (0, time_1.nowAsSeconds)() < expiresAt - types_1.MANDATORY_REFRESH_THRESHOLD_IN_SECONDS) {
return { token, expiresAt: expiresAt ?? null };
}
}
}
catch (err) {
// ENOENT or invalid-JSON → no usable cache, exchange fresh. Other
// errors (EACCES, EISDIR, …) indicate a broken cache path; surface to
// the optional hook so they're at least debuggable, then proceed.
const code = err?.code;
if (code !== 'ENOENT' && !(err instanceof SyntaxError)) {
onCacheWriteError?.(err);
}
}
// Exchange for a new token
const result = await exchange(opts);
// Write cache back (best-effort). Preserve any unknown keys from the
// existing file (notably refresh_token, in the unlikely case this path
// is shared with a user_oauth profile) so the federation cache writer
// doesn't clobber material it didn't own.
try {
await (0, types_1.writeCredentialsFileAtomic)(credentialsPath, {
...(existing ?? {}),
version: credentials_1.CREDENTIALS_FILE_VERSION,
type: 'oauth_token',
access_token: result.token,
expires_at: result.expiresAt,
});
}
catch (err) {
// Best-effort caching: surface to the optional hook but never fail
// the exchange itself.
onCacheWriteError?.(err);
}
return result;
};
}
//# sourceMappingURL=credential-chain.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,208 @@
import { readEnv } from "../../internal/utils/env.mjs";
import { CREDENTIALS_FILE_VERSION, loadConfigWithSource, getCredentialsPath, } from "../../core/credentials.mjs";
import { MANDATORY_REFRESH_THRESHOLD_IN_SECONDS, WorkloadIdentityError, checkCredentialsFileSafety, writeCredentialsFileAtomic, } from "./types.mjs";
import { nowAsSeconds } from "../../internal/utils/time.mjs";
import { identityTokenFromFile, identityTokenFromValue } from "./identity-token.mjs";
import { oidcFederationProvider } from "./oidc-federation.mjs";
import { userOAuthProvider } from "./user-oauth.mjs";
export function resolveCredentialsFromConfig(config, options) {
const credentialsPath = config.authentication.credentials_path ?? null;
const effectiveBaseURL = (config.base_url || options.baseURL).replace(/\/+$/, '');
const provider = buildProvider(config, credentialsPath, effectiveBaseURL, options);
const extraHeaders = {};
// For federation profiles workspace_id is sent in the jwt-bearer exchange
// body, not as a request header (the minted token is already
// workspace-scoped, so the header would be ignored).
if (config.workspace_id && config.authentication.type === 'user_oauth') {
extraHeaders['anthropic-workspace-id'] = config.workspace_id;
}
// Surface the profile's own base_url (not the options.baseURL fallback) so
// the client can adopt it for outbound API requests when the caller didn't
// pin one explicitly. Echoing options.baseURL back would defeat precedence.
return { provider, extraHeaders, baseURL: config.base_url || undefined };
}
/**
* Resolves a {@link CredentialResult} from the environment. Returns `null`
* when no credentials can be resolved.
*
* Resolution order:
*
* 1. Config file for the active profile (or the explicit `profile` argument)
* → dispatch on `authentication.type` (`oidc_federation`, `user_oauth`)
* 2. Environment variables `ANTHROPIC_FEDERATION_RULE_ID` +
* `ANTHROPIC_ORGANIZATION_ID` (+ identity token) → OIDC federation
* 3. Nothing matches → `null`
*
* Passing `profile` selects `<config_dir>/configs/<profile>.json` directly,
* skipping `ANTHROPIC_PROFILE` / `active_config` resolution.
*/
export async function defaultCredentials(options, profile) {
const loaded = await loadConfigWithSource(profile);
if (!loaded) {
return null;
}
const { config, fromFile } = loaded;
// For file-loaded configs, default credentials_path to the per-profile
// location so user_oauth and federation caching work. Shallow-clone first
// so callers that retain a reference to the loaded config don't observe the
// patched-in default.
//
// Env-only credentials (no profile file on disk) skip the disk cache —
// matching the other SDKs. A disk cache keyed by profile path would
// re-serve a stale token after a change to ANTHROPIC_WORKSPACE_ID (or
// ANTHROPIC_ORGANIZATION_ID / ANTHROPIC_FEDERATION_RULE_ID) until the
// cached token expired, so the env-only chain stays in-memory only.
const withPath = config.authentication.credentials_path || !fromFile ?
config
: {
...config,
authentication: {
...config.authentication,
credentials_path: (await getCredentialsPath(config, profile)) ?? undefined,
},
};
return resolveCredentialsFromConfig(withPath, options);
}
function buildProvider(config, credentialsPath, baseURL, options) {
switch (config.authentication.type) {
case 'oidc_federation': {
const auth = config.authentication;
const identityProvider = resolveIdentityTokenProvider(auth);
if (!identityProvider) {
throw new WorkloadIdentityError('oidc_federation config requires an identity token (set authentication.identity_token, ' +
'ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)');
}
if (!auth.federation_rule_id) {
throw new WorkloadIdentityError("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).");
}
if (!config.organization_id) {
throw new WorkloadIdentityError('oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)');
}
const exchange = oidcFederationProvider({
identityTokenProvider: identityProvider,
federationRuleId: auth.federation_rule_id,
organizationId: config.organization_id,
serviceAccountId: auth.service_account_id,
workspaceId: config.workspace_id,
baseURL,
fetch: options.fetch,
userAgent: options.userAgent,
});
// If there's a credentials file path, wrap the exchange with file caching
// (check file for fresh token before exchanging, write back after).
if (credentialsPath) {
return cachedExchangeProvider(exchange, credentialsPath, options.onCacheWriteError, options.onSafetyWarning);
}
return exchange;
}
case 'user_oauth': {
if (!credentialsPath) {
throw new WorkloadIdentityError('user_oauth config requires authentication.credentials_path ' +
'(or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)');
}
return userOAuthProvider({
credentialsPath,
clientId: config.authentication.client_id,
baseURL,
fetch: options.fetch,
userAgent: options.userAgent,
onSafetyWarning: options.onSafetyWarning,
});
}
default: {
const t = config.authentication.type;
throw new WorkloadIdentityError(`authentication.type "${t}" is not a known authentication type`);
}
}
}
/**
* Resolves the identity token provider from config fields or environment variables.
*
* Resolution order:
* 1. `identity_token.path` from the config (source: "file")
* 2. `ANTHROPIC_IDENTITY_TOKEN_FILE` env var
* 3. `ANTHROPIC_IDENTITY_TOKEN` env var (static value)
*/
function resolveIdentityTokenProvider(auth) {
if (auth.identity_token) {
// Cast needed to stringify an unknown source value for the error message:
// the on-disk JSON may contain a source this SDK version doesn't know about.
const source = auth.identity_token.source;
if (source !== 'file') {
throw new WorkloadIdentityError(`identity_token.source "${source}" is not supported by this SDK version (only "file")`);
}
if (!auth.identity_token.path) {
throw new WorkloadIdentityError(`identity_token.source "file" requires a non-empty path`);
}
return identityTokenFromFile(auth.identity_token.path);
}
const tokenFile = readEnv('ANTHROPIC_IDENTITY_TOKEN_FILE');
if (tokenFile) {
return identityTokenFromFile(tokenFile);
}
const tokenValue = readEnv('ANTHROPIC_IDENTITY_TOKEN');
if (tokenValue) {
return identityTokenFromValue(tokenValue);
}
return null;
}
/**
* Wraps a federation exchange provider with credential file caching.
* Checks the file for a fresh token before exchanging, and writes the
* result back after a successful exchange (best-effort, atomic replace).
*
* Note: this is not cross-process serialized — two SDK instances that
* miss the cache simultaneously will both perform a full exchange and
* the last writer wins. That is acceptable: federation exchanges are
* idempotent and the cache is an optimization, not a correctness gate.
*/
function cachedExchangeProvider(exchange, credentialsPath, onCacheWriteError, onSafetyWarning) {
return async (opts) => {
const fs = await import('node:fs');
await checkCredentialsFileSafety(credentialsPath, onSafetyWarning);
// Try cached credentials file
let existing;
try {
const raw = await fs.promises.readFile(credentialsPath, 'utf-8');
existing = JSON.parse(raw);
const token = existing?.['access_token'];
if (token && !opts?.forceRefresh) {
const expiresAt = existing?.['expires_at'];
if (expiresAt == null || nowAsSeconds() < expiresAt - MANDATORY_REFRESH_THRESHOLD_IN_SECONDS) {
return { token, expiresAt: expiresAt ?? null };
}
}
}
catch (err) {
// ENOENT or invalid-JSON → no usable cache, exchange fresh. Other
// errors (EACCES, EISDIR, …) indicate a broken cache path; surface to
// the optional hook so they're at least debuggable, then proceed.
const code = err?.code;
if (code !== 'ENOENT' && !(err instanceof SyntaxError)) {
onCacheWriteError?.(err);
}
}
// Exchange for a new token
const result = await exchange(opts);
// Write cache back (best-effort). Preserve any unknown keys from the
// existing file (notably refresh_token, in the unlikely case this path
// is shared with a user_oauth profile) so the federation cache writer
// doesn't clobber material it didn't own.
try {
await writeCredentialsFileAtomic(credentialsPath, {
...(existing ?? {}),
version: CREDENTIALS_FILE_VERSION,
type: 'oauth_token',
access_token: result.token,
expires_at: result.expiresAt,
});
}
catch (err) {
// Best-effort caching: surface to the optional hook but never fail
// the exchange itself.
onCacheWriteError?.(err);
}
return result;
};
}
//# sourceMappingURL=credential-chain.mjs.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,11 @@
import type { IdentityTokenProvider } from "./types.mjs";
/**
* Reads a JWT from a file on every call. Supports automatic rotation
* (e.g. Kubernetes projected service-account tokens).
*/
export declare function identityTokenFromFile(path: string): IdentityTokenProvider;
/**
* Wraps a static JWT string as an {@link IdentityTokenProvider}.
*/
export declare function identityTokenFromValue(token: string): IdentityTokenProvider;
//# sourceMappingURL=identity-token.d.mts.map
@@ -0,0 +1 @@
{"version":3,"file":"identity-token.d.mts","sourceRoot":"","sources":["../../src/lib/credentials/identity-token.ts"],"names":[],"mappings":"OACO,KAAK,EAAE,qBAAqB,EAAE;AAErC;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,GAAG,qBAAqB,CAmBzE;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,qBAAqB,CAK3E"}
@@ -0,0 +1,11 @@
import type { IdentityTokenProvider } from "./types.js";
/**
* Reads a JWT from a file on every call. Supports automatic rotation
* (e.g. Kubernetes projected service-account tokens).
*/
export declare function identityTokenFromFile(path: string): IdentityTokenProvider;
/**
* Wraps a static JWT string as an {@link IdentityTokenProvider}.
*/
export declare function identityTokenFromValue(token: string): IdentityTokenProvider;
//# sourceMappingURL=identity-token.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"identity-token.d.ts","sourceRoot":"","sources":["../../src/lib/credentials/identity-token.ts"],"names":[],"mappings":"OACO,KAAK,EAAE,qBAAqB,EAAE;AAErC;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,GAAG,qBAAqB,CAmBzE;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,qBAAqB,CAK3E"}
@@ -0,0 +1,72 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.identityTokenFromFile = identityTokenFromFile;
exports.identityTokenFromValue = identityTokenFromValue;
const error_1 = require("../../core/error.js");
/**
* Reads a JWT from a file on every call. Supports automatic rotation
* (e.g. Kubernetes projected service-account tokens).
*/
function identityTokenFromFile(path) {
if (!path) {
throw new error_1.AnthropicError('Identity token file path is empty');
}
return async () => {
const fs = await Promise.resolve().then(() => __importStar(require('node:fs')));
let content;
try {
content = await fs.promises.readFile(path, 'utf-8');
}
catch (err) {
throw new error_1.AnthropicError(`Failed to read identity token file at ${path}: ${err}`);
}
const token = content.trim();
if (!token) {
throw new error_1.AnthropicError(`Identity token file at ${path} is empty`);
}
return token;
};
}
/**
* Wraps a static JWT string as an {@link IdentityTokenProvider}.
*/
function identityTokenFromValue(token) {
if (!token) {
throw new error_1.AnthropicError('Identity token value is empty');
}
return () => token;
}
//# sourceMappingURL=identity-token.js.map
@@ -0,0 +1 @@
{"version":3,"file":"identity-token.js","sourceRoot":"","sources":["../../src/lib/credentials/identity-token.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,sDAmBC;AAKD,wDAKC;AApCD,+CAAkD;AAGlD;;;GAGG;AACH,SAAgB,qBAAqB,CAAC,IAAY;IAChD,IAAI,CAAC,IAAI,EAAE,CAAC;QACV,MAAM,IAAI,sBAAc,CAAC,mCAAmC,CAAC,CAAC;IAChE,CAAC;IAED,OAAO,KAAK,IAAI,EAAE;QAChB,MAAM,EAAE,GAAG,wDAAa,SAAS,GAAC,CAAC;QACnC,IAAI,OAAe,CAAC;QACpB,IAAI,CAAC;YACH,OAAO,GAAG,MAAM,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QACtD,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,IAAI,sBAAc,CAAC,yCAAyC,IAAI,KAAK,GAAG,EAAE,CAAC,CAAC;QACpF,CAAC;QACD,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;QAC7B,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,MAAM,IAAI,sBAAc,CAAC,0BAA0B,IAAI,WAAW,CAAC,CAAC;QACtE,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,SAAgB,sBAAsB,CAAC,KAAa;IAClD,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,MAAM,IAAI,sBAAc,CAAC,+BAA+B,CAAC,CAAC;IAC5D,CAAC;IACD,OAAO,GAAG,EAAE,CAAC,KAAK,CAAC;AACrB,CAAC"}
@@ -0,0 +1,35 @@
import { AnthropicError } from "../../core/error.mjs";
/**
* Reads a JWT from a file on every call. Supports automatic rotation
* (e.g. Kubernetes projected service-account tokens).
*/
export function identityTokenFromFile(path) {
if (!path) {
throw new AnthropicError('Identity token file path is empty');
}
return async () => {
const fs = await import('node:fs');
let content;
try {
content = await fs.promises.readFile(path, 'utf-8');
}
catch (err) {
throw new AnthropicError(`Failed to read identity token file at ${path}: ${err}`);
}
const token = content.trim();
if (!token) {
throw new AnthropicError(`Identity token file at ${path} is empty`);
}
return token;
};
}
/**
* Wraps a static JWT string as an {@link IdentityTokenProvider}.
*/
export function identityTokenFromValue(token) {
if (!token) {
throw new AnthropicError('Identity token value is empty');
}
return () => token;
}
//# sourceMappingURL=identity-token.mjs.map
@@ -0,0 +1 @@
{"version":3,"file":"identity-token.mjs","sourceRoot":"","sources":["../../src/lib/credentials/identity-token.ts"],"names":[],"mappings":"OAAO,EAAE,cAAc,EAAE;AAGzB;;;GAGG;AACH,MAAM,UAAU,qBAAqB,CAAC,IAAY;IAChD,IAAI,CAAC,IAAI,EAAE,CAAC;QACV,MAAM,IAAI,cAAc,CAAC,mCAAmC,CAAC,CAAC;IAChE,CAAC;IAED,OAAO,KAAK,IAAI,EAAE;QAChB,MAAM,EAAE,GAAG,MAAM,MAAM,CAAC,SAAS,CAAC,CAAC;QACnC,IAAI,OAAe,CAAC;QACpB,IAAI,CAAC;YACH,OAAO,GAAG,MAAM,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QACtD,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,IAAI,cAAc,CAAC,yCAAyC,IAAI,KAAK,GAAG,EAAE,CAAC,CAAC;QACpF,CAAC;QACD,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;QAC7B,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,MAAM,IAAI,cAAc,CAAC,0BAA0B,IAAI,WAAW,CAAC,CAAC;QACtE,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,sBAAsB,CAAC,KAAa;IAClD,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,MAAM,IAAI,cAAc,CAAC,+BAA+B,CAAC,CAAC;IAC5D,CAAC;IACD,OAAO,GAAG,EAAE,CAAC,KAAK,CAAC;AACrB,CAAC"}
@@ -0,0 +1,40 @@
import type { Fetch } from "../../internal/builtin-types.mjs";
import type { AccessTokenProvider, IdentityTokenProvider } from "./types.mjs";
export type OIDCFederationConfig = {
identityTokenProvider: IdentityTokenProvider;
federationRuleId: string;
organizationId: string;
serviceAccountId?: string | undefined;
/**
* Optional `wrkspc_*` tagged ID, or the literal `"default"` to scope the
* token to the organization's default workspace. When omitted the server
* picks the rule's sole enabled workspace, else the org default if the rule
* covers it. Required when the rule enables more than one non-default
* workspace, or to target a specific workspace other than the one the
* server would pick. The minted token is workspace-scoped: per-request
* workspace selection (the `anthropic-workspace-id` header) is not supported
* for federation tokens — switching workspaces requires a new token exchange
* with a different `workspaceId`.
*/
workspaceId?: string | undefined;
baseURL: string;
fetch: Fetch;
/**
* Overrides the outgoing User-Agent header on the token exchange. When
* empty, sends an SDK-identified UA so the token endpoint's access logs
* identify the caller.
*/
userAgent?: string | undefined;
};
/**
* Exchanges an external OIDC JWT for an Anthropic access token via the
* RFC 7523 jwt-bearer grant.
*
* Each invocation performs a fresh token exchange. Wrap in a
* {@link TokenCache} to avoid exchanging on every request.
*
* Federation grants do not return a refresh token — callers re-exchange
* their assertion on expiry.
*/
export declare function oidcFederationProvider(config: OIDCFederationConfig): AccessTokenProvider;
//# sourceMappingURL=oidc-federation.d.mts.map
@@ -0,0 +1 @@
{"version":3,"file":"oidc-federation.d.mts","sourceRoot":"","sources":["../../src/lib/credentials/oidc-federation.ts"],"names":[],"mappings":"OAAO,KAAK,EAAE,KAAK,EAAE;OACd,KAAK,EAAE,mBAAmB,EAAE,qBAAqB,EAAE;AAc1D,MAAM,MAAM,oBAAoB,GAAG;IACjC,qBAAqB,EAAE,qBAAqB,CAAC;IAC7C,gBAAgB,EAAE,MAAM,CAAC;IACzB,cAAc,EAAE,MAAM,CAAC;IACvB,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC;;;;;;;;;;OAUG;IACH,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,KAAK,CAAC;IACb;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAChC,CAAC;AAEF;;;;;;;;;GASG;AACH,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,oBAAoB,GAAG,mBAAmB,CAuFxF"}
@@ -0,0 +1,40 @@
import type { Fetch } from "../../internal/builtin-types.js";
import type { AccessTokenProvider, IdentityTokenProvider } from "./types.js";
export type OIDCFederationConfig = {
identityTokenProvider: IdentityTokenProvider;
federationRuleId: string;
organizationId: string;
serviceAccountId?: string | undefined;
/**
* Optional `wrkspc_*` tagged ID, or the literal `"default"` to scope the
* token to the organization's default workspace. When omitted the server
* picks the rule's sole enabled workspace, else the org default if the rule
* covers it. Required when the rule enables more than one non-default
* workspace, or to target a specific workspace other than the one the
* server would pick. The minted token is workspace-scoped: per-request
* workspace selection (the `anthropic-workspace-id` header) is not supported
* for federation tokens — switching workspaces requires a new token exchange
* with a different `workspaceId`.
*/
workspaceId?: string | undefined;
baseURL: string;
fetch: Fetch;
/**
* Overrides the outgoing User-Agent header on the token exchange. When
* empty, sends an SDK-identified UA so the token endpoint's access logs
* identify the caller.
*/
userAgent?: string | undefined;
};
/**
* Exchanges an external OIDC JWT for an Anthropic access token via the
* RFC 7523 jwt-bearer grant.
*
* Each invocation performs a fresh token exchange. Wrap in a
* {@link TokenCache} to avoid exchanging on every request.
*
* Federation grants do not return a refresh token — callers re-exchange
* their assertion on expiry.
*/
export declare function oidcFederationProvider(config: OIDCFederationConfig): AccessTokenProvider;
//# sourceMappingURL=oidc-federation.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"oidc-federation.d.ts","sourceRoot":"","sources":["../../src/lib/credentials/oidc-federation.ts"],"names":[],"mappings":"OAAO,KAAK,EAAE,KAAK,EAAE;OACd,KAAK,EAAE,mBAAmB,EAAE,qBAAqB,EAAE;AAc1D,MAAM,MAAM,oBAAoB,GAAG;IACjC,qBAAqB,EAAE,qBAAqB,CAAC;IAC7C,gBAAgB,EAAE,MAAM,CAAC;IACzB,cAAc,EAAE,MAAM,CAAC;IACvB,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC;;;;;;;;;;OAUG;IACH,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,KAAK,CAAC;IACb;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAChC,CAAC;AAEF;;;;;;;;;GASG;AACH,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,oBAAoB,GAAG,mBAAmB,CAuFxF"}
@@ -0,0 +1,82 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.oidcFederationProvider = oidcFederationProvider;
const types_1 = require("./types.js");
const time_1 = require("../../internal/utils/time.js");
const version_1 = require("../../version.js");
/**
* Exchanges an external OIDC JWT for an Anthropic access token via the
* RFC 7523 jwt-bearer grant.
*
* Each invocation performs a fresh token exchange. Wrap in a
* {@link TokenCache} to avoid exchanging on every request.
*
* Federation grants do not return a refresh token — callers re-exchange
* their assertion on expiry.
*/
function oidcFederationProvider(config) {
return async () => {
(0, types_1.requireSecureTokenEndpoint)(config.baseURL);
const jwt = await config.identityTokenProvider();
// The token endpoint enforces a 16 KiB assertion limit; surface a clear
// client-side error so misconfigured projected-token sources are
// diagnosable without a server round-trip.
if (jwt.length > 16 * 1024) {
throw new types_1.WorkloadIdentityError(`Identity token is ${Math.ceil(jwt.length / 1024)} KiB, exceeds the 16 KiB assertion limit`);
}
const body = {
grant_type: types_1.GRANT_TYPE_JWT_BEARER,
assertion: jwt,
federation_rule_id: config.federationRuleId,
organization_id: config.organizationId,
};
if (config.serviceAccountId) {
body['service_account_id'] = config.serviceAccountId;
}
if (config.workspaceId) {
body['workspace_id'] = config.workspaceId;
}
const url = `${config.baseURL}${types_1.TOKEN_ENDPOINT}`;
let resp;
try {
resp = await config.fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'anthropic-beta': `${types_1.OAUTH_API_BETA_HEADER},${types_1.FEDERATION_BETA_HEADER}`,
'User-Agent': config.userAgent || `anthropic-sdk-typescript/${version_1.VERSION} oidcFederationProvider`,
},
body: JSON.stringify(body),
});
}
catch (err) {
throw new types_1.WorkloadIdentityError(`Failed to reach token endpoint ${url}: ${err}`);
}
const requestId = resp.headers.get('Request-Id');
if (!resp.ok) {
const text = await resp.text().catch(() => '');
const redacted = (0, types_1.redactSensitive)(text);
// A 401 is hard to debug from the status code alone, so surface
// guidance: check the federation rule, optionally set a workspace ID
// (the most common fix when no workspaceId is configured), and point at
// the Workload identity page in Claude Console for the server-side
// authentication event log. Other statuses (5xx, 400, ...) get no hint.
let hint = '';
if (resp.status === 401) {
const hintMiddle = config.workspaceId ? '' : ("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. ");
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.`;
}
throw new types_1.WorkloadIdentityError(`Token exchange failed with status ${resp.status}${requestId ? ` (request-id ${requestId})` : ''}: ${redacted}${hint}`, resp.status, redacted, requestId);
}
const data = await (0, types_1.parseTokenResponse)(resp, requestId);
const expiresIn = Number(data.expires_in);
if (!Number.isFinite(expiresIn)) {
throw new types_1.WorkloadIdentityError(`Token endpoint response missing required fields: ${JSON.stringify((0, types_1.redactSensitive)(data))}`, resp.status, (0, types_1.redactSensitive)(data), requestId);
}
return {
token: data.access_token,
expiresAt: (0, time_1.nowAsSeconds)() + expiresIn,
};
};
}
//# sourceMappingURL=oidc-federation.js.map
@@ -0,0 +1 @@
{"version":3,"file":"oidc-federation.js","sourceRoot":"","sources":["../../src/lib/credentials/oidc-federation.ts"],"names":[],"mappings":";;AAoDA,wDAuFC;AAzID,sCASiB;AACjB,uDAAyD;AACzD,8CAAwC;AA6BxC;;;;;;;;;GASG;AACH,SAAgB,sBAAsB,CAAC,MAA4B;IACjE,OAAO,KAAK,IAAI,EAAE;QAChB,IAAA,kCAA0B,EAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAE3C,MAAM,GAAG,GAAG,MAAM,MAAM,CAAC,qBAAqB,EAAE,CAAC;QACjD,wEAAwE;QACxE,iEAAiE;QACjE,2CAA2C;QAC3C,IAAI,GAAG,CAAC,MAAM,GAAG,EAAE,GAAG,IAAI,EAAE,CAAC;YAC3B,MAAM,IAAI,6BAAqB,CAC7B,qBAAqB,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,GAAG,IAAI,CAAC,0CAA0C,CAC5F,CAAC;QACJ,CAAC;QAED,MAAM,IAAI,GAA2B;YACnC,UAAU,EAAE,6BAAqB;YACjC,SAAS,EAAE,GAAG;YACd,kBAAkB,EAAE,MAAM,CAAC,gBAAgB;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;YACxE,IAAI,IAAI,GAAG,EAAE,CAAC;YACd,IAAI,IAAI,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;gBACxB,MAAM,UAAU,GACd,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CACxB,6KAA6K,CAC9K,CAAC;gBACJ,IAAI,GAAG,6DAA6D,UAAU,mGAAmG,CAAC;YACpL,CAAC;YACD,MAAM,IAAI,6BAAqB,CAC7B,qCAAqC,IAAI,CAAC,MAAM,GAC9C,SAAS,CAAC,CAAC,CAAC,gBAAgB,SAAS,GAAG,CAAC,CAAC,CAAC,EAC7C,KAAK,QAAQ,GAAG,IAAI,EAAE,EACtB,IAAI,CAAC,MAAM,EACX,QAAQ,EACR,SAAS,CACV,CAAC;QACJ,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,IAAA,0BAAkB,EAAC,IAAI,EAAE,SAAS,CAAC,CAAC;QACvD,MAAM,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QAC1C,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC;YAChC,MAAM,IAAI,6BAAqB,CAC7B,oDAAoD,IAAI,CAAC,SAAS,CAAC,IAAA,uBAAe,EAAC,IAAI,CAAC,CAAC,EAAE,EAC3F,IAAI,CAAC,MAAM,EACX,IAAA,uBAAe,EAAC,IAAI,CAAC,EACrB,SAAS,CACV,CAAC;QACJ,CAAC;QAED,OAAO;YACL,KAAK,EAAE,IAAI,CAAC,YAAY;YACxB,SAAS,EAAE,IAAA,mBAAY,GAAE,GAAG,SAAS;SACtC,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,79 @@
import { FEDERATION_BETA_HEADER, GRANT_TYPE_JWT_BEARER, OAUTH_API_BETA_HEADER, TOKEN_ENDPOINT, WorkloadIdentityError, parseTokenResponse, redactSensitive, requireSecureTokenEndpoint, } from "./types.mjs";
import { nowAsSeconds } from "../../internal/utils/time.mjs";
import { VERSION } from "../../version.mjs";
/**
* Exchanges an external OIDC JWT for an Anthropic access token via the
* RFC 7523 jwt-bearer grant.
*
* Each invocation performs a fresh token exchange. Wrap in a
* {@link TokenCache} to avoid exchanging on every request.
*
* Federation grants do not return a refresh token — callers re-exchange
* their assertion on expiry.
*/
export function oidcFederationProvider(config) {
return async () => {
requireSecureTokenEndpoint(config.baseURL);
const jwt = await config.identityTokenProvider();
// The token endpoint enforces a 16 KiB assertion limit; surface a clear
// client-side error so misconfigured projected-token sources are
// diagnosable without a server round-trip.
if (jwt.length > 16 * 1024) {
throw new WorkloadIdentityError(`Identity token is ${Math.ceil(jwt.length / 1024)} KiB, exceeds the 16 KiB assertion limit`);
}
const body = {
grant_type: GRANT_TYPE_JWT_BEARER,
assertion: jwt,
federation_rule_id: config.federationRuleId,
organization_id: config.organizationId,
};
if (config.serviceAccountId) {
body['service_account_id'] = config.serviceAccountId;
}
if (config.workspaceId) {
body['workspace_id'] = config.workspaceId;
}
const url = `${config.baseURL}${TOKEN_ENDPOINT}`;
let resp;
try {
resp = await config.fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'anthropic-beta': `${OAUTH_API_BETA_HEADER},${FEDERATION_BETA_HEADER}`,
'User-Agent': config.userAgent || `anthropic-sdk-typescript/${VERSION} oidcFederationProvider`,
},
body: JSON.stringify(body),
});
}
catch (err) {
throw new WorkloadIdentityError(`Failed to reach token endpoint ${url}: ${err}`);
}
const requestId = resp.headers.get('Request-Id');
if (!resp.ok) {
const text = await resp.text().catch(() => '');
const redacted = redactSensitive(text);
// A 401 is hard to debug from the status code alone, so surface
// guidance: check the federation rule, optionally set a workspace ID
// (the most common fix when no workspaceId is configured), and point at
// the Workload identity page in Claude Console for the server-side
// authentication event log. Other statuses (5xx, 400, ...) get no hint.
let hint = '';
if (resp.status === 401) {
const hintMiddle = config.workspaceId ? '' : ("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. ");
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.`;
}
throw new WorkloadIdentityError(`Token exchange failed with status ${resp.status}${requestId ? ` (request-id ${requestId})` : ''}: ${redacted}${hint}`, resp.status, redacted, requestId);
}
const data = await parseTokenResponse(resp, requestId);
const expiresIn = Number(data.expires_in);
if (!Number.isFinite(expiresIn)) {
throw new WorkloadIdentityError(`Token endpoint response missing required fields: ${JSON.stringify(redactSensitive(data))}`, resp.status, redactSensitive(data), requestId);
}
return {
token: data.access_token,
expiresAt: nowAsSeconds() + expiresIn,
};
};
}
//# sourceMappingURL=oidc-federation.mjs.map
@@ -0,0 +1 @@
{"version":3,"file":"oidc-federation.mjs","sourceRoot":"","sources":["../../src/lib/credentials/oidc-federation.ts"],"names":[],"mappings":"OAEO,EACL,sBAAsB,EACtB,qBAAqB,EACrB,qBAAqB,EACrB,cAAc,EACd,qBAAqB,EACrB,kBAAkB,EAClB,eAAe,EACf,0BAA0B,GAC3B;OACM,EAAE,YAAY,EAAE;OAChB,EAAE,OAAO,EAAE;AA6BlB;;;;;;;;;GASG;AACH,MAAM,UAAU,sBAAsB,CAAC,MAA4B;IACjE,OAAO,KAAK,IAAI,EAAE;QAChB,0BAA0B,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAE3C,MAAM,GAAG,GAAG,MAAM,MAAM,CAAC,qBAAqB,EAAE,CAAC;QACjD,wEAAwE;QACxE,iEAAiE;QACjE,2CAA2C;QAC3C,IAAI,GAAG,CAAC,MAAM,GAAG,EAAE,GAAG,IAAI,EAAE,CAAC;YAC3B,MAAM,IAAI,qBAAqB,CAC7B,qBAAqB,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,GAAG,IAAI,CAAC,0CAA0C,CAC5F,CAAC;QACJ,CAAC;QAED,MAAM,IAAI,GAA2B;YACnC,UAAU,EAAE,qBAAqB;YACjC,SAAS,EAAE,GA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AAwE;YACxE,mEAAmE;YACnE,wEAAwE;YACxE,IAAI,IAAI,GAAG,EAAE,CAAC;YACd,IAAI,IAAI,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;gBACxB,MAAM,UAAU,GACd,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CACxB,6KAA6K,CAC9K,CAAC;gBACJ,IAAI,GAAG,6DAA6D,UAAU,mGAAmG,CAAC;YACpL,CAAC;YACD,MAAM,IAAI,qBAAqB,CAC7B,qCAAqC,IAAI,CAAC,MAAM,GAC9C,SAAS,CAAC,CAAC,CAAC,gBAAgB,SAAS,GAAG,CAAC,CAAC,CAAC,EAC7C,KAAK,QAAQ,GAAG,IAAI,EAAE,EACtB,IAAI,CAAC,MAAM,EACX,QAAQ,EACR,SAAS,CACV,CAAC;QACJ,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,kBAAkB,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;QACvD,MAAM,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QAC1C,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC;YAChC,MAAM,IAAI,qBAAqB,CAC7B,oDAAoD,IAAI,CAAC,SAAS,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,EAAE,EAC3F,IAAI,CAAC,MAAM,EACX,eAAe,CAAC,IAAI,CAAC,EACrB,SAAS,CACV,CAAC;QACJ,CAAC;QAED,OAAO;YACL,KAAK,EAAE,IAAI,CAAC,YAAY;YACxB,SAAS,EAAE,YAAY,EAAE,GAAG,SAAS;SACtC,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,54 @@
import type { AccessTokenProvider } from "./types.mjs";
/**
* Wraps an {@link AccessTokenProvider} with two-tier proactive refresh
* and concurrent deduplication.
*
* Refresh policy on each {@link getToken} call:
*
* - No cached token → call provider (blocking), cache, return.
* - Cached with `expiresAt == null` → return cached forever.
* - More than 120s remaining → return cached.
* - 30–120s remaining (advisory window) → return stale token immediately,
* kick off background refresh. On failure, log and keep stale.
* - Less than 30s remaining or expired (mandatory) → block and refresh.
* On failure, throw.
*
* Concurrent mandatory callers coalesce into a single provider call.
*/
export declare class TokenCache {
private provider;
private cached;
private pendingRefresh;
private nextForce;
private lastAdvisoryError;
private onAdvisoryRefreshError;
constructor(provider: AccessTokenProvider, onAdvisoryRefreshError?: (err: unknown) => void);
getToken(): Promise<string>;
/**
* Clears the cached token and marks the next {@link getToken} as a forced
* refresh, so the underlying provider bypasses any on-disk freshness check.
* Called after a 401 — the server has just told us the token is bad even
* if its `expires_at` still looks fresh.
*/
invalidate(): void;
/**
* Mandatory refresh. Joins any in-flight refresh unless forced — a forced
* refresh must not coalesce into a non-forced one that may re-serve the
* same stale disk token.
*/
private refresh;
/**
* Advisory background refresh. Shares the same in-flight promise as
* mandatory refreshes for deduplication, but swallows errors so the
* stale cached token keeps being served. Backs off for
* {@link ADVISORY_REFRESH_BACKOFF_IN_SECONDS} after a failure so an
* outage during the advisory window doesn't hammer the token endpoint.
*/
private backgroundRefresh;
/**
* Core refresh. Sets {@link pendingRefresh} so concurrent callers
* (both advisory and mandatory) coalesce into a single provider call.
*/
private doRefresh;
}
//# sourceMappingURL=token-cache.d.mts.map
@@ -0,0 +1 @@
{"version":3,"file":"token-cache.d.mts","sourceRoot":"","sources":["../../src/lib/credentials/token-cache.ts"],"names":[],"mappings":"OAAO,KAAK,EAAe,mBAAmB,EAAE;AAQhD;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,UAAU;IACrB,OAAO,CAAC,QAAQ,CAAsB;IACtC,OAAO,CAAC,MAAM,CAA4B;IAC1C,OAAO,CAAC,cAAc,CAAqC;IAC3D,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,iBAAiB,CAAK;IAC9B,OAAO,CAAC,sBAAsB,CAAuC;gBAEzD,QAAQ,EAAE,mBAAmB,EAAE,sBAAsB,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI;IAKpF,QAAQ,IAAI,OAAO,CAAC,MAAM,CAAC;IA6BjC;;;;;OAKG;IACH,UAAU,IAAI,IAAI;IAKlB;;;;OAIG;IACH,OAAO,CAAC,OAAO;IAOf;;;;;;OAMG;IACH,OAAO,CAAC,iBAAiB;IAezB;;;OAGG;IACH,OAAO,CAAC,SAAS;CAclB"}
@@ -0,0 +1,54 @@
import type { AccessTokenProvider } from "./types.js";
/**
* Wraps an {@link AccessTokenProvider} with two-tier proactive refresh
* and concurrent deduplication.
*
* Refresh policy on each {@link getToken} call:
*
* - No cached token → call provider (blocking), cache, return.
* - Cached with `expiresAt == null` → return cached forever.
* - More than 120s remaining → return cached.
* - 30–120s remaining (advisory window) → return stale token immediately,
* kick off background refresh. On failure, log and keep stale.
* - Less than 30s remaining or expired (mandatory) → block and refresh.
* On failure, throw.
*
* Concurrent mandatory callers coalesce into a single provider call.
*/
export declare class TokenCache {
private provider;
private cached;
private pendingRefresh;
private nextForce;
private lastAdvisoryError;
private onAdvisoryRefreshError;
constructor(provider: AccessTokenProvider, onAdvisoryRefreshError?: (err: unknown) => void);
getToken(): Promise<string>;
/**
* Clears the cached token and marks the next {@link getToken} as a forced
* refresh, so the underlying provider bypasses any on-disk freshness check.
* Called after a 401 — the server has just told us the token is bad even
* if its `expires_at` still looks fresh.
*/
invalidate(): void;
/**
* Mandatory refresh. Joins any in-flight refresh unless forced — a forced
* refresh must not coalesce into a non-forced one that may re-serve the
* same stale disk token.
*/
private refresh;
/**
* Advisory background refresh. Shares the same in-flight promise as
* mandatory refreshes for deduplication, but swallows errors so the
* stale cached token keeps being served. Backs off for
* {@link ADVISORY_REFRESH_BACKOFF_IN_SECONDS} after a failure so an
* outage during the advisory window doesn't hammer the token endpoint.
*/
private backgroundRefresh;
/**
* Core refresh. Sets {@link pendingRefresh} so concurrent callers
* (both advisory and mandatory) coalesce into a single provider call.
*/
private doRefresh;
}
//# sourceMappingURL=token-cache.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"token-cache.d.ts","sourceRoot":"","sources":["../../src/lib/credentials/token-cache.ts"],"names":[],"mappings":"OAAO,KAAK,EAAe,mBAAmB,EAAE;AAQhD;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,UAAU;IACrB,OAAO,CAAC,QAAQ,CAAsB;IACtC,OAAO,CAAC,MAAM,CAA4B;IAC1C,OAAO,CAAC,cAAc,CAAqC;IAC3D,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,iBAAiB,CAAK;IAC9B,OAAO,CAAC,sBAAsB,CAAuC;gBAEzD,QAAQ,EAAE,mBAAmB,EAAE,sBAAsB,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI;IAKpF,QAAQ,IAAI,OAAO,CAAC,MAAM,CAAC;IA6BjC;;;;;OAKG;IACH,UAAU,IAAI,IAAI;IAKlB;;;;OAIG;IACH,OAAO,CAAC,OAAO;IAOf;;;;;;OAMG;IACH,OAAO,CAAC,iBAAiB;IAezB;;;OAGG;IACH,OAAO,CAAC,SAAS;CAclB"}
+112
View File
@@ -0,0 +1,112 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TokenCache = void 0;
const types_1 = require("./types.js");
const time_1 = require("../../internal/utils/time.js");
/**
* Wraps an {@link AccessTokenProvider} with two-tier proactive refresh
* and concurrent deduplication.
*
* Refresh policy on each {@link getToken} call:
*
* - No cached token → call provider (blocking), cache, return.
* - Cached with `expiresAt == null` → return cached forever.
* - More than 120s remaining → return cached.
* - 30–120s remaining (advisory window) → return stale token immediately,
* kick off background refresh. On failure, log and keep stale.
* - Less than 30s remaining or expired (mandatory) → block and refresh.
* On failure, throw.
*
* Concurrent mandatory callers coalesce into a single provider call.
*/
class TokenCache {
constructor(provider, onAdvisoryRefreshError) {
this.cached = null;
this.pendingRefresh = null;
this.nextForce = false;
this.lastAdvisoryError = 0;
this.provider = provider;
this.onAdvisoryRefreshError = onAdvisoryRefreshError;
}
async getToken() {
const force = this.nextForce;
this.nextForce = false;
const cached = this.cached;
if (force || cached == null) {
const token = await this.refresh(force);
return token.token;
}
if (cached.expiresAt == null) {
return cached.token;
}
const remaining = cached.expiresAt - (0, time_1.nowAsSeconds)();
if (remaining > types_1.ADVISORY_REFRESH_THRESHOLD_IN_SECONDS) {
return cached.token;
}
if (remaining > types_1.MANDATORY_REFRESH_THRESHOLD_IN_SECONDS) {
this.backgroundRefresh();
return cached.token;
}
const token = await this.refresh();
return token.token;
}
/**
* Clears the cached token and marks the next {@link getToken} as a forced
* refresh, so the underlying provider bypasses any on-disk freshness check.
* Called after a 401 — the server has just told us the token is bad even
* if its `expires_at` still looks fresh.
*/
invalidate() {
this.cached = null;
this.nextForce = true;
}
/**
* Mandatory refresh. Joins any in-flight refresh unless forced — a forced
* refresh must not coalesce into a non-forced one that may re-serve the
* same stale disk token.
*/
refresh(force = false) {
if (this.pendingRefresh && !force) {
return this.pendingRefresh;
}
return this.doRefresh(force);
}
/**
* Advisory background refresh. Shares the same in-flight promise as
* mandatory refreshes for deduplication, but swallows errors so the
* stale cached token keeps being served. Backs off for
* {@link ADVISORY_REFRESH_BACKOFF_IN_SECONDS} after a failure so an
* outage during the advisory window doesn't hammer the token endpoint.
*/
backgroundRefresh() {
if (this.pendingRefresh) {
return;
}
if ((0, time_1.nowAsSeconds)() - this.lastAdvisoryError < types_1.ADVISORY_REFRESH_BACKOFF_IN_SECONDS) {
return;
}
this.doRefresh().catch((err) => {
this.lastAdvisoryError = (0, time_1.nowAsSeconds)();
// Advisory failure: keep serving the stale cached token, but surface
// the error to the caller-provided hook so it can be logged.
this.onAdvisoryRefreshError?.(err);
});
}
/**
* Core refresh. Sets {@link pendingRefresh} so concurrent callers
* (both advisory and mandatory) coalesce into a single provider call.
*/
doRefresh(force = false) {
this.pendingRefresh = this.provider(force ? { forceRefresh: true } : undefined).then((token) => {
this.cached = token;
this.pendingRefresh = null;
return token;
}, (err) => {
this.pendingRefresh = null;
throw err;
});
return this.pendingRefresh;
}
}
exports.TokenCache = TokenCache;
//# sourceMappingURL=token-cache.js.map
@@ -0,0 +1 @@
{"version":3,"file":"token-cache.js","sourceRoot":"","sources":["../../src/lib/credentials/token-cache.ts"],"names":[],"mappings":";;;AACA,sCAIiB;AACjB,uDAAyD;AAEzD;;;;;;;;;;;;;;;GAeG;AACH,MAAa,UAAU;IAQrB,YAAY,QAA6B,EAAE,sBAA+C;QANlF,WAAM,GAAuB,IAAI,CAAC;QAClC,mBAAc,GAAgC,IAAI,CAAC;QACnD,cAAS,GAAG,KAAK,CAAC;QAClB,sBAAiB,GAAG,CAAC,CAAC;QAI5B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,sBAAsB,GAAG,sBAAsB,CAAC;IACvD,CAAC;IAED,KAAK,CAAC,QAAQ;QACZ,MAAM,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC;QAC7B,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;QACvB,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAE3B,IAAI,KAAK,IAAI,MAAM,IAAI,IAAI,EAAE,CAAC;YAC5B,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YACxC,OAAO,KAAK,CAAC,KAAK,CAAC;QACrB,CAAC;QAED,IAAI,MAAM,CAAC,SAAS,IAAI,IAAI,EAAE,CAAC;YAC7B,OAAO,MAAM,CAAC,KAAK,CAAC;QACtB,CAAC;QAED,MAAM,SAAS,GAAG,MAAM,CAAC,SAAS,GAAG,IAAA,mBAAY,GAAE,CAAC;QAEpD,IAAI,SAAS,GAAG,6CAAqC,EAAE,CAAC;YACtD,OAAO,MAAM,CAAC,KAAK,CAAC;QACtB,CAAC;QAED,IAAI,SAAS,GAAG,8CAAsC,EAAE,CAAC;YACvD,IAAI,CAAC,iBAAiB,EAAE,CAAC;YACzB,OAAO,MAAM,CAAC,KAA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AI,CAAC;YAC3B,OAAO,KAAK,CAAC;QACf,CAAC,EACD,CAAC,GAAG,EAAE,EAAE;YACN,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;YAC3B,MAAM,GAAG,CAAC;QACZ,CAAC,CACF,CAAC;QACF,OAAO,IAAI,CAAC,cAAc,CAAC;IAC7B,CAAC;CACF;AAzGD,gCAyGC"}
+108
View File
@@ -0,0 +1,108 @@
import { ADVISORY_REFRESH_BACKOFF_IN_SECONDS, ADVISORY_REFRESH_THRESHOLD_IN_SECONDS, MANDATORY_REFRESH_THRESHOLD_IN_SECONDS, } from "./types.mjs";
import { nowAsSeconds } from "../../internal/utils/time.mjs";
/**
* Wraps an {@link AccessTokenProvider} with two-tier proactive refresh
* and concurrent deduplication.
*
* Refresh policy on each {@link getToken} call:
*
* - No cached token → call provider (blocking), cache, return.
* - Cached with `expiresAt == null` → return cached forever.
* - More than 120s remaining → return cached.
* - 30–120s remaining (advisory window) → return stale token immediately,
* kick off background refresh. On failure, log and keep stale.
* - Less than 30s remaining or expired (mandatory) → block and refresh.
* On failure, throw.
*
* Concurrent mandatory callers coalesce into a single provider call.
*/
export class TokenCache {
constructor(provider, onAdvisoryRefreshError) {
this.cached = null;
this.pendingRefresh = null;
this.nextForce = false;
this.lastAdvisoryError = 0;
this.provider = provider;
this.onAdvisoryRefreshError = onAdvisoryRefreshError;
}
async getToken() {
const force = this.nextForce;
this.nextForce = false;
const cached = this.cached;
if (force || cached == null) {
const token = await this.refresh(force);
return token.token;
}
if (cached.expiresAt == null) {
return cached.token;
}
const remaining = cached.expiresAt - nowAsSeconds();
if (remaining > ADVISORY_REFRESH_THRESHOLD_IN_SECONDS) {
return cached.token;
}
if (remaining > MANDATORY_REFRESH_THRESHOLD_IN_SECONDS) {
this.backgroundRefresh();
return cached.token;
}
const token = await this.refresh();
return token.token;
}
/**
* Clears the cached token and marks the next {@link getToken} as a forced
* refresh, so the underlying provider bypasses any on-disk freshness check.
* Called after a 401 — the server has just told us the token is bad even
* if its `expires_at` still looks fresh.
*/
invalidate() {
this.cached = null;
this.nextForce = true;
}
/**
* Mandatory refresh. Joins any in-flight refresh unless forced — a forced
* refresh must not coalesce into a non-forced one that may re-serve the
* same stale disk token.
*/
refresh(force = false) {
if (this.pendingRefresh && !force) {
return this.pendingRefresh;
}
return this.doRefresh(force);
}
/**
* Advisory background refresh. Shares the same in-flight promise as
* mandatory refreshes for deduplication, but swallows errors so the
* stale cached token keeps being served. Backs off for
* {@link ADVISORY_REFRESH_BACKOFF_IN_SECONDS} after a failure so an
* outage during the advisory window doesn't hammer the token endpoint.
*/
backgroundRefresh() {
if (this.pendingRefresh) {
return;
}
if (nowAsSeconds() - this.lastAdvisoryError < ADVISORY_REFRESH_BACKOFF_IN_SECONDS) {
return;
}
this.doRefresh().catch((err) => {
this.lastAdvisoryError = nowAsSeconds();
// Advisory failure: keep serving the stale cached token, but surface
// the error to the caller-provided hook so it can be logged.
this.onAdvisoryRefreshError?.(err);
});
}
/**
* Core refresh. Sets {@link pendingRefresh} so concurrent callers
* (both advisory and mandatory) coalesce into a single provider call.
*/
doRefresh(force = false) {
this.pendingRefresh = this.provider(force ? { forceRefresh: true } : undefined).then((token) => {
this.cached = token;
this.pendingRefresh = null;
return token;
}, (err) => {
this.pendingRefresh = null;
throw err;
});
return this.pendingRefresh;
}
}
//# sourceMappingURL=token-cache.mjs.map
@@ -0,0 +1 @@
{"version":3,"file":"token-cache.mjs","sourceRoot":"","sources":["../../src/lib/credentials/token-cache.ts"],"names":[],"mappings":"OACO,EACL,mCAAmC,EACnC,qCAAqC,EACrC,sCAAsC,GACvC;OACM,EAAE,YAAY,EAAE;AAEvB;;;;;;;;;;;;;;;GAeG;AACH,MAAM,OAAO,UAAU;IAQrB,YAAY,QAA6B,EAAE,sBAA+C;QANlF,WAAM,GAAuB,IAAI,CAAC;QAClC,mBAAc,GAAgC,IAAI,CAAC;QACnD,cAAS,GAAG,KAAK,CAAC;QAClB,sBAAiB,GAAG,CAAC,CAAC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AAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IAC/B,CAAC;IAED;;;;;;OAMG;IACK,iBAAiB;QACvB,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;YACxB,OAAO;QACT,CAAC;QACD,IAAI,YAAY,EAAE,GAAG,IAAI,CAAC,iBAAiB,GAAG,mCAAmC,EAAE,CAAC;YAClF,OAAO;QACT,CAAC;QACD,IAAI,CAAC,SAAS,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;YAC7B,IAAI,CAAC,iBAAiB,GAAG,YAAY,EAAE,CAAC;YACxC,qEAAqE;YACrE,6DAA6D;YAC7D,IAAI,CAAC,sBAAsB,EAAE,CAAC,GAAG,CAAC,CAAC;QACrC,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;;OAGG;IACK,SAAS,CAAC,KAAK,GAAG,KAAK;QAC7B,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,IAAI,CAClF,CAAC,KAAK,EAAE,EAAE;YACR,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;YACpB,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;YAC3B,OAAO,KAAK,CAAC;QACf,CAAC,EACD,CAAC,GAAG,EAAE,EAAE;YACN,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;YAC3B,MAAM,GAAG,CAAC;QACZ,CAAC,CACF,CAAC;QACF,OAAO,IAAI,CAAC,cAAc,CAAC;IAC7B,CAAC;CACF"}
+96
View File
@@ -0,0 +1,96 @@
import { AnthropicError } from "../../core/error.mjs";
export type AccessToken = {
token: string;
/** Unix epoch seconds. `null` means no expiry (cache forever). */
expiresAt: number | null;
};
/**
* Mints or returns a cached access token.
*
* The optional `opts.forceRefresh` flag, set by {@link TokenCache.invalidate}
* after a 401, tells providers with on-disk caches (user_oauth, cachedExchange)
* to bypass their freshness short-circuit and always fetch fresh. Providers
* without a cache can ignore it.
*/
export type AccessTokenProvider = (opts?: {
forceRefresh?: boolean;
}) => Promise<AccessToken>;
export type IdentityTokenProvider = () => string | Promise<string>;
export type CredentialResult = {
provider: AccessTokenProvider;
extraHeaders: Record<string, string>;
/**
* The `base_url` from the resolved config/profile, if any. The client
* applies this to outbound API requests when no explicit `baseURL` (constructor
* option or `ANTHROPIC_BASE_URL` env) was given, so a profile pointing at a
* non-default API host both mints its token against that host AND sends
* subsequent API requests there.
*/
baseURL?: string | undefined;
};
/** Response body from `POST /v1/oauth/token`. */
export type TokenEndpointResponse = {
access_token?: string;
expires_in?: number;
refresh_token?: string;
};
export declare const GRANT_TYPE_JWT_BEARER = "urn:ietf:params:oauth:grant-type:jwt-bearer";
export declare const GRANT_TYPE_REFRESH_TOKEN = "refresh_token";
export declare const TOKEN_ENDPOINT = "/v1/oauth/token";
/**
* `anthropic-beta` value required on authenticated API requests using an
* OAuth bearer token, and on `refresh_token` grants against the token endpoint.
*/
export declare const OAUTH_API_BETA_HEADER = "oauth-2025-04-20";
/**
* `anthropic-beta` value required on jwt-bearer exchanges against the token
* endpoint. It routes the request to the federation service; it must NOT be
* sent on `refresh_token` grants, which are handled by a different backend.
*/
export declare const FEDERATION_BETA_HEADER = "oidc-federation-2026-04-01";
export declare const ADVISORY_REFRESH_THRESHOLD_IN_SECONDS = 120;
export declare const MANDATORY_REFRESH_THRESHOLD_IN_SECONDS = 30;
export declare const ADVISORY_REFRESH_BACKOFF_IN_SECONDS = 5;
/**
* Rejects base URLs that would cause a JWT assertion or refresh token to be
* sent over cleartext HTTP. Loopback hosts are allowed for local development.
*/
export declare function requireSecureTokenEndpoint(baseURL: string): void;
/**
* Reads the response body as text, parses it as a token-endpoint JSON
* response, validates `access_token` is present, and rejects a non-Bearer
* `token_type` when one is provided. Reads at most
* {@link MAX_TOKEN_RESPONSE_BYTES} from the body stream.
*/
export declare function parseTokenResponse(resp: Response, requestId: string | null): Promise<TokenEndpointResponse & {
access_token: string;
}>;
/**
* Returns a redacted copy of a token-endpoint error body for safe inclusion
* in an exception. Strings are truncated; objects keep only the RFC 6749
* §5.2 error fields.
*/
export declare function redactSensitive(body: unknown): unknown;
/**
* Best-effort safety check on a credentials file before reading it.
*
* On POSIX: resolves symlinks (so containerized deployments that mount the
* credential as a symlink to a tmpfs-backed file keep working), then rejects
* the resolved target if it is group- or world- readable or writable. A uid
* mismatch on the resolved target is surfaced via `onWarn` since
* root-written/app-read is common in init-container setups. No-op on Windows.
*/
export declare function checkCredentialsFileSafety(path: string, onWarn?: (msg: string) => void): Promise<void>;
/**
* Atomically writes JSON to `targetPath` via a `.tmp` sibling + rename,
* with fsync on the file and (best-effort) on the parent directory.
* Creates the parent directory with mode 0700 and the file with mode 0600.
*/
export declare function writeCredentialsFileAtomic(targetPath: string, data: unknown): Promise<void>;
export declare class WorkloadIdentityError extends AnthropicError {
readonly statusCode: number | null;
readonly body: unknown;
readonly requestId: string | null;
constructor(message: string, statusCode?: number | null, body?: unknown, requestId?: string | null);
}
//# sourceMappingURL=types.d.mts.map
@@ -0,0 +1 @@
{"version":3,"file":"types.d.mts","sourceRoot":"","sources":["../../src/lib/credentials/types.ts"],"names":[],"mappings":"OAAO,EAAE,cAAc,EAAE;AAEzB,MAAM,MAAM,WAAW,GAAG;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,kEAAkE;IAClE,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1B,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,MAAM,mBAAmB,GAAG,CAAC,IAAI,CAAC,EAAE;IAAE,YAAY,CAAC,EAAE,OAAO,CAAA;CAAE,KAAK,OAAO,CAAC,WAAW,CAAC,CAAC;AAE9F,MAAM,MAAM,qBAAqB,GAAG,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;AAEnE,MAAM,MAAM,gBAAgB,GAAG;IAC7B,QAAQ,EAAE,mBAAmB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EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAkCjG;AAmCD,qBAAa,qBAAsB,SAAQ,cAAc;IACvD,QAAQ,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IACnC,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;IACvB,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;gBAGhC,OAAO,EAAE,MAAM,EACf,UAAU,GAAE,MAAM,GAAG,IAAW,EAChC,IAAI,GAAE,OAAc,EACpB,SAAS,GAAE,MAAM,GAAG,IAAW;CAOlC"}
+96
View File
@@ -0,0 +1,96 @@
import { AnthropicError } from "../../core/error.js";
export type AccessToken = {
token: string;
/** Unix epoch seconds. `null` means no expiry (cache forever). */
expiresAt: number | null;
};
/**
* Mints or returns a cached access token.
*
* The optional `opts.forceRefresh` flag, set by {@link TokenCache.invalidate}
* after a 401, tells providers with on-disk caches (user_oauth, cachedExchange)
* to bypass their freshness short-circuit and always fetch fresh. Providers
* without a cache can ignore it.
*/
export type AccessTokenProvider = (opts?: {
forceRefresh?: boolean;
}) => Promise<AccessToken>;
export type IdentityTokenProvider = () => string | Promise<string>;
export type CredentialResult = {
provider: AccessTokenProvider;
extraHeaders: Record<string, string>;
/**
* The `base_url` from the resolved config/profile, if any. The client
* applies this to outbound API requests when no explicit `baseURL` (constructor
* option or `ANTHROPIC_BASE_URL` env) was given, so a profile pointing at a
* non-default API host both mints its token against that host AND sends
* subsequent API requests there.
*/
baseURL?: string | undefined;
};
/** Response body from `POST /v1/oauth/token`. */
export type TokenEndpointResponse = {
access_token?: string;
expires_in?: number;
refresh_token?: string;
};
export declare const GRANT_TYPE_JWT_BEARER = "urn:ietf:params:oauth:grant-type:jwt-bearer";
export declare const GRANT_TYPE_REFRESH_TOKEN = "refresh_token";
export declare const TOKEN_ENDPOINT = "/v1/oauth/token";
/**
* `anthropic-beta` value required on authenticated API requests using an
* OAuth bearer token, and on `refresh_token` grants against the token endpoint.
*/
export declare const OAUTH_API_BETA_HEADER = "oauth-2025-04-20";
/**
* `anthropic-beta` value required on jwt-bearer exchanges against the token
* endpoint. It routes the request to the federation service; it must NOT be
* sent on `refresh_token` grants, which are handled by a different backend.
*/
export declare const FEDERATION_BETA_HEADER = "oidc-federation-2026-04-01";
export declare const ADVISORY_REFRESH_THRESHOLD_IN_SECONDS = 120;
export declare const MANDATORY_REFRESH_THRESHOLD_IN_SECONDS = 30;
export declare const ADVISORY_REFRESH_BACKOFF_IN_SECONDS = 5;
/**
* Rejects base URLs that would cause a JWT assertion or refresh token to be
* sent over cleartext HTTP. Loopback hosts are allowed for local development.
*/
export declare function requireSecureTokenEndpoint(baseURL: string): void;
/**
* Reads the response body as text, parses it as a token-endpoint JSON
* response, validates `access_token` is present, and rejects a non-Bearer
* `token_type` when one is provided. Reads at most
* {@link MAX_TOKEN_RESPONSE_BYTES} from the body stream.
*/
export declare function parseTokenResponse(resp: Response, requestId: string | null): Promise<TokenEndpointResponse & {
access_token: string;
}>;
/**
* Returns a redacted copy of a token-endpoint error body for safe inclusion
* in an exception. Strings are truncated; objects keep only the RFC 6749
* §5.2 error fields.
*/
export declare function redactSensitive(body: unknown): unknown;
/**
* Best-effort safety check on a credentials file before reading it.
*
* On POSIX: resolves symlinks (so containerized deployments that mount the
* credential as a symlink to a tmpfs-backed file keep working), then rejects
* the resolved target if it is group- or world- readable or writable. A uid
* mismatch on the resolved target is surfaced via `onWarn` since
* root-written/app-read is common in init-container setups. No-op on Windows.
*/
export declare function checkCredentialsFileSafety(path: string, onWarn?: (msg: string) => void): Promise<void>;
/**
* Atomically writes JSON to `targetPath` via a `.tmp` sibling + rename,
* with fsync on the file and (best-effort) on the parent directory.
* Creates the parent directory with mode 0700 and the file with mode 0600.
*/
export declare function writeCredentialsFileAtomic(targetPath: string, data: unknown): Promise<void>;
export declare class WorkloadIdentityError extends AnthropicError {
readonly statusCode: number | null;
readonly body: unknown;
readonly requestId: string | null;
constructor(message: string, statusCode?: number | null, body?: unknown, requestId?: string | null);
}
//# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/lib/credentials/types.ts"],"names":[],"mappings":"OAAO,EAAE,cAAc,EAAE;AAEzB,MAAM,MAAM,WAAW,GAAG;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,kEAAkE;IAClE,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1B,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,MAAM,mBAAmB,GAAG,CAAC,IAAI,CAAC,EAAE;IAAE,YAAY,CAAC,EAAE,OAAO,CAAA;CAAE,KAAK,OAAO,CAAC,WAAW,CAAC,CAAC;AAE9F,MAAM,MAAM,qBAAqB,GAAG,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;AAEnE,MAAM,MAAM,gBAAgB,GAAG;IAC7B,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACrC;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAC9B,CAAC;AAEF,iDAAiD;AACjD,MAAM,MAAM,qBAAqB,GAAG;IAClC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB,CAAC;AAEF,eAAO,MAAM,qBAAqB,gDAAgD,CAAC;AACnF,eAAO,MAAM,wBAAwB,kBAAkB,CAAC;AACxD,eAAO,MAAM,cAAc,oBAAoB,CAAC;AAEhD;;;GAGG;AACH,eAAO,MAAM,qBAAqB,qBAAqB,CAAC;AAExD;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,+BAA+B,CAAC;AAEnE,eAAO,MAAM,qCAAqC,MAAM,CAAC;AACzD,eAAO,MAAM,sCAAsC,KAAK,CAAC;AACzD,eAAO,MAAM,mCAAmC,IAAI,CAAC;AAIrD;;;GAGG;AACH,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAehE;AAED;;;;;GAKG;AACH,wBAAsB,kBAAkB,CACtC,IAAI,EAAE,QAAQ,EACd,SAAS,EAAE,MAAM,GAAG,IAAI,GACvB,OAAO,CAAC,qBAAqB,GAAG;IAAE,YAAY,EAAE,MAAM,CAAA;CAAE,CAAC,CA8B3D;AAQD;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO,CAoBtD;AAED;;;;;;;;GAQG;AACH,wBAAsB,0BAA0B,CAC9C,IAAI,EAAE,MAAM,EACZ,MAAM,GAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAiD,GACzE,OAAO,CAAC,IAAI,CAAC,CAgCf;AAED;;;;GAIG;AACH,wBAAsB,0BAA0B,CAAC,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAkCjG;AAmCD,qBAAa,qBAAsB,SAAQ,cAAc;IACvD,QAAQ,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IACnC,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;IACvB,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;gBAGhC,OAAO,EAAE,MAAM,EACf,UAAU,GAAE,MAAM,GAAG,IAAW,EAChC,IAAI,GAAE,OAAc,EACpB,SAAS,GAAE,MAAM,GAAG,IAAW;CAOlC"}
+266
View File
@@ -0,0 +1,266 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.WorkloadIdentityError = exports.ADVISORY_REFRESH_BACKOFF_IN_SECONDS = exports.MANDATORY_REFRESH_THRESHOLD_IN_SECONDS = exports.ADVISORY_REFRESH_THRESHOLD_IN_SECONDS = exports.FEDERATION_BETA_HEADER = exports.OAUTH_API_BETA_HEADER = exports.TOKEN_ENDPOINT = exports.GRANT_TYPE_REFRESH_TOKEN = exports.GRANT_TYPE_JWT_BEARER = void 0;
exports.requireSecureTokenEndpoint = requireSecureTokenEndpoint;
exports.parseTokenResponse = parseTokenResponse;
exports.redactSensitive = redactSensitive;
exports.checkCredentialsFileSafety = checkCredentialsFileSafety;
exports.writeCredentialsFileAtomic = writeCredentialsFileAtomic;
const error_1 = require("../../core/error.js");
exports.GRANT_TYPE_JWT_BEARER = 'urn:ietf:params:oauth:grant-type:jwt-bearer';
exports.GRANT_TYPE_REFRESH_TOKEN = 'refresh_token';
exports.TOKEN_ENDPOINT = '/v1/oauth/token';
/**
* `anthropic-beta` value required on authenticated API requests using an
* OAuth bearer token, and on `refresh_token` grants against the token endpoint.
*/
exports.OAUTH_API_BETA_HEADER = 'oauth-2025-04-20';
/**
* `anthropic-beta` value required on jwt-bearer exchanges against the token
* endpoint. It routes the request to the federation service; it must NOT be
* sent on `refresh_token` grants, which are handled by a different backend.
*/
exports.FEDERATION_BETA_HEADER = 'oidc-federation-2026-04-01';
exports.ADVISORY_REFRESH_THRESHOLD_IN_SECONDS = 120;
exports.MANDATORY_REFRESH_THRESHOLD_IN_SECONDS = 30;
exports.ADVISORY_REFRESH_BACKOFF_IN_SECONDS = 5;
const MAX_TOKEN_RESPONSE_BYTES = 1 << 20;
/**
* Rejects base URLs that would cause a JWT assertion or refresh token to be
* sent over cleartext HTTP. Loopback hosts are allowed for local development.
*/
function requireSecureTokenEndpoint(baseURL) {
if (!baseURL)
return;
let u;
try {
u = new URL(baseURL);
}
catch (err) {
throw new WorkloadIdentityError(`Invalid token endpoint base URL "${baseURL}": ${err}`);
}
if (u.protocol === 'https:')
return;
// WHATWG URL.hostname returns bracketed IPv6 ("[::1]"); Go's net/url strips them.
const host = u.hostname.toLowerCase().replace(/^\[|\]$/g, '');
if (u.protocol === 'http:' && (host === 'localhost' || host === '127.0.0.1' || host === '::1')) {
return;
}
throw new WorkloadIdentityError(`Refusing to send credential over non-https token endpoint "${baseURL}"`);
}
/**
* Reads the response body as text, parses it as a token-endpoint JSON
* response, validates `access_token` is present, and rejects a non-Bearer
* `token_type` when one is provided. Reads at most
* {@link MAX_TOKEN_RESPONSE_BYTES} from the body stream.
*/
async function parseTokenResponse(resp, requestId) {
const text = await readLimitedText(resp);
let data;
try {
data = JSON.parse(text);
}
catch {
throw new WorkloadIdentityError(`Token endpoint returned non-JSON response (status ${resp.status})`, resp.status, redactSensitive(text), requestId);
}
if (!data.access_token) {
throw new WorkloadIdentityError(`Token endpoint response missing access_token: ${JSON.stringify(redactSensitive(data))}`, resp.status, redactSensitive(data), requestId);
}
if (data.token_type && data.token_type.toLowerCase() !== 'bearer') {
throw new WorkloadIdentityError(`Token endpoint response: unsupported token_type "${data.token_type}" (want Bearer)`, resp.status, redactSensitive(data), requestId);
}
return data;
}
const MAX_ERROR_BODY_CHARS = 2000;
// RFC 6749 §5.2 standard error-response fields. Anything else in a token
// endpoint error body is potentially echoed input (assertion, refresh_token,
// access_token, …) and is dropped rather than allowlisted-with-exceptions.
const SAFE_ERROR_KEYS = new Set(['error', 'error_description', 'error_uri']);
/**
* Returns a redacted copy of a token-endpoint error body for safe inclusion
* in an exception. Strings are truncated; objects keep only the RFC 6749
* §5.2 error fields.
*/
function redactSensitive(body) {
if (body == null)
return body;
if (typeof body === 'string') {
let parsed;
try {
parsed = JSON.parse(body);
}
catch {
if (body.length <= MAX_ERROR_BODY_CHARS)
return body;
return body.slice(0, MAX_ERROR_BODY_CHARS) + `... <${body.length - MAX_ERROR_BODY_CHARS} more chars>`;
}
return JSON.stringify(redactSensitive(parsed));
}
if (typeof body === 'object' && !Array.isArray(body)) {
const out = {};
for (const [k, v] of Object.entries(body)) {
if (SAFE_ERROR_KEYS.has(k))
out[k] = v;
}
return out;
}
return null;
}
/**
* Best-effort safety check on a credentials file before reading it.
*
* On POSIX: resolves symlinks (so containerized deployments that mount the
* credential as a symlink to a tmpfs-backed file keep working), then rejects
* the resolved target if it is group- or world- readable or writable. A uid
* mismatch on the resolved target is surfaced via `onWarn` since
* root-written/app-read is common in init-container setups. No-op on Windows.
*/
async function checkCredentialsFileSafety(path, onWarn = (m) => console.warn(`anthropic-sdk: ${m}`)) {
if (typeof process === 'undefined' || process.platform === 'win32')
return;
const fs = await Promise.resolve().then(() => __importStar(require('node:fs')));
let resolved = path;
let st;
try {
resolved = await fs.promises.realpath(path);
st = await fs.promises.stat(resolved);
}
catch {
return; // ENOENT etc — let the subsequent read surface a precise error
}
const mode = st.mode & 0o777;
// 0o022 = group/world write; 0o044 = group/world read.
if (mode & 0o022) {
throw new WorkloadIdentityError(`Credentials file at ${resolved} is group/world-writable (mode 0o${mode.toString(8)}); ` +
`this allows other local users to plant tokens. Run \`chmod 600 ${resolved}\`.`);
}
if (mode & 0o044) {
throw new WorkloadIdentityError(`Credentials file at ${resolved} is group/world-readable (mode 0o${mode.toString(8)}); ` +
`run \`chmod 600 ${resolved}\` before retrying.`);
}
if (typeof process.getuid === 'function' && st.uid !== process.getuid()) {
onWarn(`credentials file at ${resolved} is owned by uid ${st.uid} (current process uid ${process.getuid()}); ` + `verify this is intentional.`);
}
}
/**
* Atomically writes JSON to `targetPath` via a `.tmp` sibling + rename,
* with fsync on the file and (best-effort) on the parent directory.
* Creates the parent directory with mode 0700 and the file with mode 0600.
*/
async function writeCredentialsFileAtomic(targetPath, data) {
const fs = await Promise.resolve().then(() => __importStar(require('node:fs')));
const path = await Promise.resolve().then(() => __importStar(require('node:path')));
const dir = path.dirname(targetPath);
await fs.promises.mkdir(dir, { recursive: true, mode: 0o700 });
// Unique temp name avoids two concurrent writers (different processes or
// SDK instances) racing on the same '.tmp' sibling and corrupting each
// other's bytes mid-write before the rename.
const tmpPath = `${targetPath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
try {
const fh = await fs.promises.open(tmpPath, 'w', 0o600);
try {
await fh.writeFile(JSON.stringify(data, null, 2));
await fh.sync();
}
finally {
await fh.close();
}
await fs.promises.rename(tmpPath, targetPath);
}
catch (err) {
// Don't leak the temp file if anything between create and rename failed.
await fs.promises.unlink(tmpPath).catch(() => { });
throw err;
}
// fsync the parent directory so the rename survives a crash.
try {
const dirFh = await fs.promises.open(dir, 'r');
try {
await dirFh.sync();
}
finally {
await dirFh.close();
}
}
catch {
// Directory fsync is best-effort (unsupported on some platforms, e.g. Windows).
}
}
async function readLimitedText(resp) {
if (!resp.body) {
return '';
}
const reader = resp.body.getReader();
const chunks = [];
let received = 0;
for (;;) {
const { done, value } = await reader.read();
if (done)
break;
if (received + value.length > MAX_TOKEN_RESPONSE_BYTES) {
const remaining = MAX_TOKEN_RESPONSE_BYTES - received;
if (remaining > 0)
chunks.push(value.subarray(0, remaining));
await reader.cancel();
break;
}
chunks.push(value);
received += value.length;
}
let merged;
if (chunks.length === 1) {
merged = chunks[0];
}
else {
merged = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
let offset = 0;
for (const c of chunks) {
merged.set(c, offset);
offset += c.length;
}
}
return new TextDecoder('utf-8').decode(merged);
}
class WorkloadIdentityError extends error_1.AnthropicError {
constructor(message, statusCode = null, body = null, requestId = null) {
super(message);
this.statusCode = statusCode;
this.body = body;
this.requestId = requestId;
}
}
exports.WorkloadIdentityError = WorkloadIdentityError;
//# sourceMappingURL=types.js.map
File diff suppressed because one or more lines are too long
+224
View File
@@ -0,0 +1,224 @@
import { AnthropicError } from "../../core/error.mjs";
export const GRANT_TYPE_JWT_BEARER = 'urn:ietf:params:oauth:grant-type:jwt-bearer';
export const GRANT_TYPE_REFRESH_TOKEN = 'refresh_token';
export const TOKEN_ENDPOINT = '/v1/oauth/token';
/**
* `anthropic-beta` value required on authenticated API requests using an
* OAuth bearer token, and on `refresh_token` grants against the token endpoint.
*/
export const OAUTH_API_BETA_HEADER = 'oauth-2025-04-20';
/**
* `anthropic-beta` value required on jwt-bearer exchanges against the token
* endpoint. It routes the request to the federation service; it must NOT be
* sent on `refresh_token` grants, which are handled by a different backend.
*/
export const FEDERATION_BETA_HEADER = 'oidc-federation-2026-04-01';
export const ADVISORY_REFRESH_THRESHOLD_IN_SECONDS = 120;
export const MANDATORY_REFRESH_THRESHOLD_IN_SECONDS = 30;
export const ADVISORY_REFRESH_BACKOFF_IN_SECONDS = 5;
const MAX_TOKEN_RESPONSE_BYTES = 1 << 20;
/**
* Rejects base URLs that would cause a JWT assertion or refresh token to be
* sent over cleartext HTTP. Loopback hosts are allowed for local development.
*/
export function requireSecureTokenEndpoint(baseURL) {
if (!baseURL)
return;
let u;
try {
u = new URL(baseURL);
}
catch (err) {
throw new WorkloadIdentityError(`Invalid token endpoint base URL "${baseURL}": ${err}`);
}
if (u.protocol === 'https:')
return;
// WHATWG URL.hostname returns bracketed IPv6 ("[::1]"); Go's net/url strips them.
const host = u.hostname.toLowerCase().replace(/^\[|\]$/g, '');
if (u.protocol === 'http:' && (host === 'localhost' || host === '127.0.0.1' || host === '::1')) {
return;
}
throw new WorkloadIdentityError(`Refusing to send credential over non-https token endpoint "${baseURL}"`);
}
/**
* Reads the response body as text, parses it as a token-endpoint JSON
* response, validates `access_token` is present, and rejects a non-Bearer
* `token_type` when one is provided. Reads at most
* {@link MAX_TOKEN_RESPONSE_BYTES} from the body stream.
*/
export async function parseTokenResponse(resp, requestId) {
const text = await readLimitedText(resp);
let data;
try {
data = JSON.parse(text);
}
catch {
throw new WorkloadIdentityError(`Token endpoint returned non-JSON response (status ${resp.status})`, resp.status, redactSensitive(text), requestId);
}
if (!data.access_token) {
throw new WorkloadIdentityError(`Token endpoint response missing access_token: ${JSON.stringify(redactSensitive(data))}`, resp.status, redactSensitive(data), requestId);
}
if (data.token_type && data.token_type.toLowerCase() !== 'bearer') {
throw new WorkloadIdentityError(`Token endpoint response: unsupported token_type "${data.token_type}" (want Bearer)`, resp.status, redactSensitive(data), requestId);
}
return data;
}
const MAX_ERROR_BODY_CHARS = 2000;
// RFC 6749 §5.2 standard error-response fields. Anything else in a token
// endpoint error body is potentially echoed input (assertion, refresh_token,
// access_token, …) and is dropped rather than allowlisted-with-exceptions.
const SAFE_ERROR_KEYS = new Set(['error', 'error_description', 'error_uri']);
/**
* Returns a redacted copy of a token-endpoint error body for safe inclusion
* in an exception. Strings are truncated; objects keep only the RFC 6749
* §5.2 error fields.
*/
export function redactSensitive(body) {
if (body == null)
return body;
if (typeof body === 'string') {
let parsed;
try {
parsed = JSON.parse(body);
}
catch {
if (body.length <= MAX_ERROR_BODY_CHARS)
return body;
return body.slice(0, MAX_ERROR_BODY_CHARS) + `... <${body.length - MAX_ERROR_BODY_CHARS} more chars>`;
}
return JSON.stringify(redactSensitive(parsed));
}
if (typeof body === 'object' && !Array.isArray(body)) {
const out = {};
for (const [k, v] of Object.entries(body)) {
if (SAFE_ERROR_KEYS.has(k))
out[k] = v;
}
return out;
}
return null;
}
/**
* Best-effort safety check on a credentials file before reading it.
*
* On POSIX: resolves symlinks (so containerized deployments that mount the
* credential as a symlink to a tmpfs-backed file keep working), then rejects
* the resolved target if it is group- or world- readable or writable. A uid
* mismatch on the resolved target is surfaced via `onWarn` since
* root-written/app-read is common in init-container setups. No-op on Windows.
*/
export async function checkCredentialsFileSafety(path, onWarn = (m) => console.warn(`anthropic-sdk: ${m}`)) {
if (typeof process === 'undefined' || process.platform === 'win32')
return;
const fs = await import('node:fs');
let resolved = path;
let st;
try {
resolved = await fs.promises.realpath(path);
st = await fs.promises.stat(resolved);
}
catch {
return; // ENOENT etc — let the subsequent read surface a precise error
}
const mode = st.mode & 0o777;
// 0o022 = group/world write; 0o044 = group/world read.
if (mode & 0o022) {
throw new WorkloadIdentityError(`Credentials file at ${resolved} is group/world-writable (mode 0o${mode.toString(8)}); ` +
`this allows other local users to plant tokens. Run \`chmod 600 ${resolved}\`.`);
}
if (mode & 0o044) {
throw new WorkloadIdentityError(`Credentials file at ${resolved} is group/world-readable (mode 0o${mode.toString(8)}); ` +
`run \`chmod 600 ${resolved}\` before retrying.`);
}
if (typeof process.getuid === 'function' && st.uid !== process.getuid()) {
onWarn(`credentials file at ${resolved} is owned by uid ${st.uid} (current process uid ${process.getuid()}); ` + `verify this is intentional.`);
}
}
/**
* Atomically writes JSON to `targetPath` via a `.tmp` sibling + rename,
* with fsync on the file and (best-effort) on the parent directory.
* Creates the parent directory with mode 0700 and the file with mode 0600.
*/
export async function writeCredentialsFileAtomic(targetPath, data) {
const fs = await import('node:fs');
const path = await import('node:path');
const dir = path.dirname(targetPath);
await fs.promises.mkdir(dir, { recursive: true, mode: 0o700 });
// Unique temp name avoids two concurrent writers (different processes or
// SDK instances) racing on the same '.tmp' sibling and corrupting each
// other's bytes mid-write before the rename.
const tmpPath = `${targetPath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
try {
const fh = await fs.promises.open(tmpPath, 'w', 0o600);
try {
await fh.writeFile(JSON.stringify(data, null, 2));
await fh.sync();
}
finally {
await fh.close();
}
await fs.promises.rename(tmpPath, targetPath);
}
catch (err) {
// Don't leak the temp file if anything between create and rename failed.
await fs.promises.unlink(tmpPath).catch(() => { });
throw err;
}
// fsync the parent directory so the rename survives a crash.
try {
const dirFh = await fs.promises.open(dir, 'r');
try {
await dirFh.sync();
}
finally {
await dirFh.close();
}
}
catch {
// Directory fsync is best-effort (unsupported on some platforms, e.g. Windows).
}
}
async function readLimitedText(resp) {
if (!resp.body) {
return '';
}
const reader = resp.body.getReader();
const chunks = [];
let received = 0;
for (;;) {
const { done, value } = await reader.read();
if (done)
break;
if (received + value.length > MAX_TOKEN_RESPONSE_BYTES) {
const remaining = MAX_TOKEN_RESPONSE_BYTES - received;
if (remaining > 0)
chunks.push(value.subarray(0, remaining));
await reader.cancel();
break;
}
chunks.push(value);
received += value.length;
}
let merged;
if (chunks.length === 1) {
merged = chunks[0];
}
else {
merged = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
let offset = 0;
for (const c of chunks) {
merged.set(c, offset);
offset += c.length;
}
}
return new TextDecoder('utf-8').decode(merged);
}
export class WorkloadIdentityError extends AnthropicError {
constructor(message, statusCode = null, body = null, requestId = null) {
super(message);
this.statusCode = statusCode;
this.body = body;
this.requestId = requestId;
}
}
//# sourceMappingURL=types.mjs.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,21 @@
import type { Fetch } from "../../internal/builtin-types.mjs";
import type { AccessTokenProvider } from "./types.mjs";
export type UserOAuthConfig = {
credentialsPath: string;
clientId?: string | undefined;
baseURL: string;
fetch: Fetch;
userAgent?: string | undefined;
onSafetyWarning?: ((msg: string) => void) | undefined;
};
/**
* Reads a user-oauth credential file. Returns the cached access token while
* fresh; on expiry performs a `refresh_token` grant and writes the new
* tokens back to the credentials file (atomic replace, fsync'd).
*
* If `clientId` is empty, the access token is treated as static — the
* credentials file is read on every call but no refresh is attempted, and
* an expired token without a `refresh_token` raises.
*/
export declare function userOAuthProvider(config: UserOAuthConfig): AccessTokenProvider;
//# sourceMappingURL=user-oauth.d.mts.map
@@ -0,0 +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 @@
import type { Fetch } from "../../internal/builtin-types.js";
import type { AccessTokenProvider } from "./types.js";
export type UserOAuthConfig = {
credentialsPath: string;
clientId?: string | undefined;
baseURL: string;
fetch: Fetch;
userAgent?: string | undefined;
onSafetyWarning?: ((msg: string) => void) | undefined;
};
/**
* Reads a user-oauth credential file. Returns the cached access token while
* fresh; on expiry performs a `refresh_token` grant and writes the new
* tokens back to the credentials file (atomic replace, fsync'd).
*
* If `clientId` is empty, the access token is treated as static — the
* credentials file is read on every call but no refresh is attempted, and
* an expired token without a `refresh_token` raises.
*/
export declare function userOAuthProvider(config: UserOAuthConfig): AccessTokenProvider;
//# sourceMappingURL=user-oauth.d.ts.map
@@ -0,0 +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"}
+130
View File
@@ -0,0 +1,130 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.userOAuthProvider = userOAuthProvider;
const credentials_1 = require("../../core/credentials.js");
const types_1 = require("./types.js");
const time_1 = require("../../internal/utils/time.js");
const version_1 = require("../../version.js");
/**
* Reads a user-oauth credential file. Returns the cached access token while
* fresh; on expiry performs a `refresh_token` grant and writes the new
* tokens back to the credentials file (atomic replace, fsync'd).
*
* If `clientId` is empty, the access token is treated as static — the
* credentials file is read on every call but no refresh is attempted, and
* an expired token without a `refresh_token` raises.
*/
function userOAuthProvider(config) {
return async (opts) => {
const fs = await Promise.resolve().then(() => __importStar(require('node:fs')));
await (0, types_1.checkCredentialsFileSafety)(config.credentialsPath, config.onSafetyWarning);
let raw;
try {
raw = await fs.promises.readFile(config.credentialsPath, 'utf-8');
}
catch (err) {
throw new types_1.WorkloadIdentityError(`Credentials file not found at ${config.credentialsPath}: ${err}`);
}
let creds;
try {
creds = JSON.parse(raw);
}
catch (err) {
throw new types_1.WorkloadIdentityError(`Credentials file at ${config.credentialsPath} is not valid JSON: ${err}`);
}
const accessToken = creds.access_token;
if (!accessToken) {
throw new types_1.WorkloadIdentityError(`Credentials file at ${config.credentialsPath} must include 'access_token'`);
}
// Return cached token if still fresh (or no expiry info), unless the
// caller is forcing a refresh after a 401 — then go straight to refresh
// even if the file's expires_at still looks valid.
const expiresAt = creds.expires_at;
if (!opts?.forceRefresh &&
(expiresAt == null || (0, time_1.nowAsSeconds)() < expiresAt - types_1.MANDATORY_REFRESH_THRESHOLD_IN_SECONDS)) {
return { token: accessToken, expiresAt: expiresAt ?? null };
}
const refreshToken = creds.refresh_token;
if (!config.clientId || !refreshToken) {
throw new types_1.WorkloadIdentityError(`Access token at ${config.credentialsPath} has expired and no refresh is available ` +
`(client_id ${config.clientId ? 'set' : 'empty'}, refresh_token ${refreshToken ? 'set' : 'empty'})`);
}
(0, types_1.requireSecureTokenEndpoint)(config.baseURL);
const body = {
grant_type: types_1.GRANT_TYPE_REFRESH_TOKEN,
refresh_token: refreshToken,
client_id: config.clientId,
};
const url = `${config.baseURL}${types_1.TOKEN_ENDPOINT}`;
let resp;
try {
resp = await config.fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'anthropic-beta': types_1.OAUTH_API_BETA_HEADER,
'User-Agent': config.userAgent || `anthropic-sdk-typescript/${version_1.VERSION} userOAuthProvider`,
},
body: JSON.stringify(body),
});
}
catch (err) {
throw new types_1.WorkloadIdentityError(`User OAuth refresh failed to reach token endpoint: ${err}`);
}
const requestId = resp.headers.get('Request-Id');
if (!resp.ok) {
const text = await resp.text().catch(() => '');
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);
}
const data = await (0, types_1.parseTokenResponse)(resp, requestId);
const expiresIn = Number(data.expires_in);
if (!Number.isFinite(expiresIn)) {
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);
}
const newExpiresAt = (0, time_1.nowAsSeconds)() + expiresIn;
const newRefreshToken = data.refresh_token || refreshToken;
await (0, types_1.writeCredentialsFileAtomic)(config.credentialsPath, {
...creds,
version: credentials_1.CREDENTIALS_FILE_VERSION,
type: 'oauth_token',
access_token: data.access_token,
expires_at: newExpiresAt,
refresh_token: newRefreshToken,
});
return { token: data.access_token, expiresAt: newExpiresAt };
};
}
//# sourceMappingURL=user-oauth.js.map
@@ -0,0 +1 @@
{"version":3,"file":"user-oauth.js","sourceRoot":"","sources":["../../src/lib/credentials/user-oauth.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,8CA2GC;AA9ID,2DAA6F;AAE7F,sCAWiB;AACjB,uDAAyD;AACzD,8CAAwC;AAWxC;;;;;;;;GAQG;AACH,SAAgB,iBAAiB,CAAC,MAAuB;IACvD,OAAO,KAAK,EAAE,IAAI,EAAE,EAAE;QACpB,MAAM,EAAE,GAAG,wDAAa,SAAS,GAAC,CAAC;QAEnC,MAAM,IAAA,kCAA0B,EAAC,MAAM,CAAC,eAAe,EAAE,MAAM,CAAC,eAAe,CAAC,CAAC;QAEjF,IAAI,GAAW,CAAC;QAChB,IAAI,CAAC;YACH,GAAG,GAAG,MAAM,EAAE,CAAC,QAAQ,CAA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;QAED,MAAM,IAAI,GAAG,MAAM,IAAA,0BAAkB,EAAC,IAAI,EAAE,SAAS,CAAC,CAAC;QACvD,MAAM,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QAC1C,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC;YAChC,MAAM,IAAI,6BAAqB,CAC7B,8DAA8D,IAAI,CAAC,SAAS,CAAC,IAAA,uBAAe,EAAC,IAAI,CAAC,CAAC,EAAE,EACrG,IAAI,CAAC,MAAM,EACX,IAAA,uBAAe,EAAC,IAAI,CAAC,EACrB,SAAS,CACV,CAAC;QACJ,CAAC;QACD,MAAM,YAAY,GAAG,IAAA,mBAAY,GAAE,GAAG,SAAS,CAAC;QAChD,MAAM,eAAe,GAAG,IAAI,CAAC,aAAa,IAAI,YAAY,CAAC;QAE3D,MAAM,IAAA,kCAA0B,EAAC,MAAM,CAAC,eAAe,EAAE;YACvD,GAAG,KAAK;YACR,OAAO,EAAE,sCAAwB;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"}
+94
View File
@@ -0,0 +1,94 @@
import { CREDENTIALS_FILE_VERSION } from "../../core/credentials.mjs";
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";
import { nowAsSeconds } from "../../internal/utils/time.mjs";
import { VERSION } from "../../version.mjs";
/**
* Reads a user-oauth credential file. Returns the cached access token while
* fresh; on expiry performs a `refresh_token` grant and writes the new
* tokens back to the credentials file (atomic replace, fsync'd).
*
* If `clientId` is empty, the access token is treated as static — the
* credentials file is read on every call but no refresh is attempted, and
* an expired token without a `refresh_token` raises.
*/
export function userOAuthProvider(config) {
return async (opts) => {
const fs = await import('node:fs');
await checkCredentialsFileSafety(config.credentialsPath, config.onSafetyWarning);
let raw;
try {
raw = await fs.promises.readFile(config.credentialsPath, 'utf-8');
}
catch (err) {
throw new WorkloadIdentityError(`Credentials file not found at ${config.credentialsPath}: ${err}`);
}
let creds;
try {
creds = JSON.parse(raw);
}
catch (err) {
throw new WorkloadIdentityError(`Credentials file at ${config.credentialsPath} is not valid JSON: ${err}`);
}
const accessToken = creds.access_token;
if (!accessToken) {
throw new WorkloadIdentityError(`Credentials file at ${config.credentialsPath} must include 'access_token'`);
}
// Return cached token if still fresh (or no expiry info), unless the
// caller is forcing a refresh after a 401 — then go straight to refresh
// even if the file's expires_at still looks valid.
const expiresAt = creds.expires_at;
if (!opts?.forceRefresh &&
(expiresAt == null || nowAsSeconds() < expiresAt - MANDATORY_REFRESH_THRESHOLD_IN_SECONDS)) {
return { token: accessToken, expiresAt: expiresAt ?? null };
}
const refreshToken = creds.refresh_token;
if (!config.clientId || !refreshToken) {
throw new WorkloadIdentityError(`Access token at ${config.credentialsPath} has expired and no refresh is available ` +
`(client_id ${config.clientId ? 'set' : 'empty'}, refresh_token ${refreshToken ? 'set' : 'empty'})`);
}
requireSecureTokenEndpoint(config.baseURL);
const body = {
grant_type: GRANT_TYPE_REFRESH_TOKEN,
refresh_token: refreshToken,
client_id: config.clientId,
};
const url = `${config.baseURL}${TOKEN_ENDPOINT}`;
let resp;
try {
resp = await config.fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'anthropic-beta': OAUTH_API_BETA_HEADER,
'User-Agent': config.userAgent || `anthropic-sdk-typescript/${VERSION} userOAuthProvider`,
},
body: JSON.stringify(body),
});
}
catch (err) {
throw new WorkloadIdentityError(`User OAuth refresh failed to reach token endpoint: ${err}`);
}
const requestId = resp.headers.get('Request-Id');
if (!resp.ok) {
const text = await resp.text().catch(() => '');
throw new WorkloadIdentityError(`User OAuth refresh failed (HTTP ${resp.status}): ${redactSensitive(text)}`, resp.status, redactSensitive(text), requestId);
}
const data = await parseTokenResponse(resp, requestId);
const expiresIn = Number(data.expires_in);
if (!Number.isFinite(expiresIn)) {
throw new WorkloadIdentityError(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(redactSensitive(data))}`, resp.status, redactSensitive(data), requestId);
}
const newExpiresAt = nowAsSeconds() + expiresIn;
const newRefreshToken = data.refresh_token || refreshToken;
await writeCredentialsFileAtomic(config.credentialsPath, {
...creds,
version: CREDENTIALS_FILE_VERSION,
type: 'oauth_token',
access_token: data.access_token,
expires_at: newExpiresAt,
refresh_token: newRefreshToken,
});
return { token: data.access_token, expiresAt: newExpiresAt };
};
}
//# sourceMappingURL=user-oauth.mjs.map
@@ -0,0 +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,MAA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