@lumoauth/agent 1.4.2 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/agent.ts","../src/client-assertion.ts","../src/keys.ts","../src/signing.ts","../src/verify.ts","../src/errors.ts","../src/client.ts","../src/dpop.ts","../src/attest.ts","../src/access-token.ts"],"sourcesContent":["// ─── @lumoauth/agent — the agent SDK ─────────────────────────────────\n//\n// Two layers:\n// - `LumoAgent` — high-level client (client-credentials auth, ask/\n// isAllowed, jit/delegation/approvals/mcp namespaces). Python parity\n// with `lumoauth.LumoAuthAgent`.\n// - `AAuthClient` + signing/verify primitives — the AAuth protocol\n// (cryptographic agent identity, RFC 9421 HTTP message signing).\n// Uses `node:crypto`, therefore Node-only (>= 18).\n\nexport { LumoAgent, type LumoAgentOptions } from './agent';\n\nexport {\n AAuthClient,\n type AAuthClientOptions,\n type AAuthTokenResponse,\n type AAuthAuthorizationRequired,\n type AAuthIssuerMetadata,\n type AAuthAgentMetadata,\n type AAuthResourceMetadata,\n} from './client';\n\nexport {\n generateKeypair,\n jwkThumbprint,\n publicJwkFromPrivateKey,\n type AAuthJwk,\n type AAuthKeypair,\n} from './keys';\n\nexport {\n signRequest,\n buildSignatureBase,\n signatureParams,\n signSignatureBase,\n verifySignatureBase,\n contentDigestSha256,\n generateNonce,\n AAUTH_COVERED_COMPONENTS,\n type SignRequestOptions,\n} from './signing';\n\nexport {\n verifyAuthToken,\n decodeJwt,\n type AAuthTokenClaims,\n type VerifyAuthTokenOptions,\n} from './verify';\n\n// ─── private_key_jwt client assertions (RFC 7523) ─────────────────────\nexport {\n ClientAssertionSigner,\n CLIENT_ASSERTION_TYPE,\n CLIENT_ASSERTION_TYP,\n MAX_ASSERTION_LIFETIME_SECONDS,\n issuerFor,\n type ClientAssertionAlgorithm,\n type ClientAssertionJwk,\n type ClientAssertionSignerOptions,\n} from './client-assertion';\n\n// ─── DPoP (RFC 9449) ──────────────────────────────────────────────────\nexport {\n DpopProofSigner,\n dpopAth,\n type DpopAlgorithm,\n type DpopJwk,\n type DpopProofSignerOptions,\n} from './dpop';\nexport {\n fetchWithDpop,\n buildDpopHeaders,\n dpopHtu,\n DPOP_SCHEME,\n DPOP_NONCE_HEADER,\n USE_DPOP_NONCE,\n type DpopProofProvider,\n type DpopProofRequest,\n type DpopHeadersInput,\n type FetchWithDpopOptions,\n} from '@lumoauth/shared';\n\n// ─── Workload attestation ─────────────────────────────────────────────\nexport { attestWorkload, type AttestWorkloadOptions, type AttestWorkloadResult } from './attest';\n\n// ─── Core access token (at+jwt) verification, resource-server side ────\nexport {\n verifyAccessToken,\n createAccessTokenVerifier,\n verifyDpopProof,\n parseAuthorizationHeader,\n accessTokenScopes,\n AccessTokenError,\n JwksCache,\n InMemoryDpopReplayCache,\n type AccessTokenClaims,\n type ActorClaim,\n type AccessTokenVerifier,\n type AccessTokenVerifierOptions,\n type VerifyAccessTokenOptions,\n type IncomingDpopProof,\n type IncomingRequest,\n type DpopReplayCache,\n type VerifyDpopProofOptions,\n type VerifiedDpopProof,\n} from './access-token';\n\nexport { AAuthError } from './errors';\n\n// The shared error taxonomy, so agent code can catch these without a direct\n// dependency on @lumoauth/shared.\nexport {\n LumoAuthError,\n LumoAuthApiError,\n LumoAuthAuthenticationError,\n LumoAuthPermissionDeniedError,\n LumoAuthNotFoundError,\n LumoAuthRateLimitError,\n LumoAuthValidationError,\n LumoAuthConfigError,\n LumoAuthNetworkError,\n LumoAuthApprovalDeniedError,\n LumoAuthApprovalTimeoutError,\n LumoAuthApprovalNotDeliveredError,\n LumoAuthBudgetExceededError,\n type ApprovalNotDeliveredReason,\n type ApprovalResult,\n type ApprovalRequestResult,\n type CreateApprovalRequest,\n type RequireApprovalRequest,\n type AgentMcpToolDecision,\n type AgentBudget,\n type UsageReport,\n type UsageReportResult,\n type McpAuthorizeToolOptions,\n type McpSubject,\n type McpSubjectType,\n type McpToolDecision,\n type McpToolResource,\n} from '@lumoauth/shared';\n","import {\n HttpClient,\n AgentsModule,\n ApprovalsModule,\n DelegationModule,\n JitModule,\n McpModule,\n LumoAuthApiError,\n LumoAuthConfigError,\n LumoAuthNetworkError,\n ROUTES,\n buildPath,\n fetchWithDpop,\n type DpopProofProvider,\n type AgentAskResult,\n type AgentIdentity,\n type AgentBudget,\n type AgentMcpToolDecision,\n type UsageReport,\n type UsageReportResult,\n} from '@lumoauth/shared';\nimport { CLIENT_ASSERTION_TYPE, ClientAssertionSigner, issuerFor } from './client-assertion';\n\n// ─── Types ────────────────────────────────────────────────────────────\n\nexport interface LumoAgentOptions {\n /**\n * LumoAuth instance URL. Defaults to `process.env.LUMOAUTH_URL` or\n * `https://app.lumoauth.dev`.\n */\n baseUrl?: string;\n /** Organization slug. Defaults to `process.env.LUMOAUTH_ORG_ID`. */\n orgId?: string;\n /** OAuth client ID. Defaults to `process.env.AGENT_CLIENT_ID`. */\n clientId?: string;\n /** OAuth client secret. Defaults to `process.env.AGENT_CLIENT_SECRET`. */\n clientSecret?: string;\n /**\n * For an agent registered with the **Private key JWT** identity type: a\n * `ClientAssertionSigner`, or the PEM private key. The agent then signs a\n * client assertion (RFC 7523) for every token request and needs no\n * `clientSecret`. Defaults to `process.env.AGENT_PRIVATE_KEY` (PEM).\n */\n privateKey?: ClientAssertionSigner | string;\n /** `kid` of the registered public key, used with a PEM `privateKey`. Defaults to `process.env.AGENT_KEY_ID`. */\n keyId?: string;\n /**\n * The organization's issuer identifier, the assertion's `aud`. Defaults to\n * `{baseUrl}/orgs/{orgId}/api/v1`; set it on a custom domain.\n */\n issuer?: string;\n /** Scopes to request. When omitted the server grants the agent's defaults. */\n scopes?: string[];\n /** OAuth callback URL for the delegation consent flow. */\n redirectUri?: string;\n /** Custom fetch implementation. */\n fetch?: typeof globalThis.fetch;\n /** Request timeout in milliseconds. Default: 30 000 ms. */\n timeout?: number;\n /**\n * DPoP proof signer (RFC 9449), e.g. `DpopProofSigner.generate()`. When\n * set, the client-credentials token and every exchanged token (MCP,\n * delegation) are sender-constrained to its key, and every request\n * carries `Authorization: DPoP <token>` plus a proof. Needed for MCP\n * servers registered with \"Require DPoP\".\n */\n dpop?: DpopProofProvider;\n}\n\ninterface TokenState {\n accessToken: string;\n /** `DPoP` or `Bearer`, as the token endpoint reported it. */\n tokenType: string;\n /** Epoch ms after which we refresh (real expiry minus the safety buffer). */\n refreshAt: number;\n scopes: string[];\n}\n\nfunction envVar(name: string): string | undefined {\n return typeof process !== 'undefined' && process.env ? process.env[name] : undefined;\n}\n\n/** Safety margin (ms) subtracted from `expires_in` so we refresh early. */\nconst TOKEN_REFRESH_BUFFER_MS = 60_000;\n\n// ─── LumoAgent ────────────────────────────────────────────────────────\n\n/**\n * High-level agent client — the Node.js counterpart of the Python SDK's\n * `LumoAuthAgent`.\n *\n * Handles the full agent lifecycle:\n * - OAuth 2.0 client-credentials authentication with transparent refresh\n * (60 s safety buffer)\n * - Preflight capability checks (`ask` / `isAllowed`)\n * - Self-inspection (`getCurrentAgent`, `capabilities`, `budget`)\n * - `jit`, `delegation`, `approvals`, and `mcp` namespaces\n *\n * For the AAuth protocol (cryptographic agent identity, RFC 9421 message\n * signing) use {@link AAuthClient} from this same package.\n *\n * @example\n * ```ts\n * import { LumoAgent } from '@lumoauth/agent';\n *\n * const agent = new LumoAgent(); // reads env vars by default\n * if (await agent.isAllowed('document.read', { id: 'doc_99' })) {\n * // ... do the thing\n * }\n *\n * const approval = await agent.approvals.require({\n * taskId: 'wire-001',\n * reason: 'Wire $4,500 to vendor INV-7741',\n * impact: 'high',\n * onBehalfOf: 'ada@acme.com',\n * });\n * ```\n */\nexport class LumoAgent {\n readonly baseUrl: string;\n readonly orgId: string;\n readonly clientId: string;\n\n /** Agent identity — ask/isAllowed, self-inspection, registration. */\n readonly agents: AgentsModule;\n /** Just-in-Time permissions — ephemeral tasks and scoped tokens. */\n readonly jit: JitModule;\n /** Chain of Agency — RFC 8693 delegation and nested agent chains. */\n readonly delegation: DelegationModule;\n /** Push-approval-for-agent-actions. */\n readonly approvals: ApprovalsModule;\n /** MCP servers: token exchange and per-tool checks (`authorizeTool`). */\n readonly mcp: McpModule;\n\n private readonly clientSecret: string;\n private readonly assertionSigner: ClientAssertionSigner | undefined;\n private readonly issuer: string | undefined;\n private readonly scopes: string[] | undefined;\n private readonly fetchFn: typeof globalThis.fetch;\n private readonly dpop: DpopProofProvider | undefined;\n private token: TokenState | null = null;\n private refreshPromise: Promise<string> | null = null;\n\n constructor(options: LumoAgentOptions = {}) {\n this.baseUrl = (options.baseUrl ?? envVar('LUMOAUTH_URL') ?? 'https://app.lumoauth.dev').replace(/\\/+$/, '');\n this.orgId = options.orgId ?? envVar('LUMOAUTH_ORG_ID') ?? '';\n this.clientId = options.clientId ?? envVar('AGENT_CLIENT_ID') ?? '';\n const privateKey = options.privateKey ?? envVar('AGENT_PRIVATE_KEY');\n const keyId = options.keyId ?? envVar('AGENT_KEY_ID');\n this.assertionSigner =\n privateKey === undefined || privateKey === ''\n ? undefined\n : privateKey instanceof ClientAssertionSigner\n ? privateKey\n : ClientAssertionSigner.fromPem(privateKey, { keyId });\n // A private key JWT agent has no secret; an AGENT_CLIENT_SECRET left\n // in the environment must not become a second method.\n this.clientSecret = options.clientSecret ?? (this.assertionSigner ? '' : envVar('AGENT_CLIENT_SECRET') ?? '');\n this.issuer = options.issuer;\n this.scopes = options.scopes;\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.dpop = options.dpop;\n\n if (!this.clientId || (!this.clientSecret && !this.assertionSigner)) {\n throw new LumoAuthConfigError(\n 'Agent credentials required. Set AGENT_CLIENT_ID and AGENT_CLIENT_SECRET ' +\n '(or AGENT_PRIVATE_KEY for a private key JWT agent), or pass clientId with ' +\n 'clientSecret or privateKey to the constructor.',\n );\n }\n if (this.clientSecret && this.assertionSigner) {\n throw new LumoAuthConfigError(\n 'Pass clientSecret or privateKey, not both: an agent authenticates with one method.',\n );\n }\n\n const tokenProvider = () => this.getAccessToken();\n const http = new HttpClient({\n baseUrl: this.baseUrl,\n token: tokenProvider,\n timeout: options.timeout,\n fetch: options.fetch,\n dpop: this.dpop,\n });\n\n this.agents = new AgentsModule(http, this.orgId);\n this.jit = new JitModule(http, this.orgId);\n this.approvals = new ApprovalsModule(http, this.orgId);\n this.mcp = new McpModule({\n baseUrl: this.baseUrl,\n orgId: this.orgId,\n token: tokenProvider,\n fetch: options.fetch,\n http,\n dpop: this.dpop,\n });\n this.delegation = new DelegationModule({\n baseUrl: this.baseUrl,\n orgId: this.orgId,\n clientId: this.clientId,\n clientSecret: this.clientSecret,\n redirectUri: options.redirectUri,\n agentToken: tokenProvider,\n fetch: options.fetch,\n dpop: this.dpop,\n });\n }\n\n // ── Authentication ────────────────────────────────────────────────\n\n /**\n * Authenticate with the client-credentials flow. Called automatically\n * by every API method — invoke it directly only to fail fast at\n * startup or to request non-default scopes.\n */\n async authenticate(scopes?: string[]): Promise<string> {\n const form: Record<string, string> = {\n grant_type: 'client_credentials',\n client_id: this.clientId,\n };\n if (this.assertionSigner) {\n form.client_assertion_type = CLIENT_ASSERTION_TYPE;\n form.client_assertion = this.createClientAssertion();\n } else {\n form.client_secret = this.clientSecret;\n }\n const requested = scopes ?? this.scopes;\n if (requested?.length) form.scope = requested.join(' ');\n\n const url = `${this.baseUrl}${buildPath(ROUTES['oauth.token'].path, { orgId: this.requireOrgId() })}`;\n const init: RequestInit = {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams(form),\n };\n let res: Response;\n try {\n // With a DPoP signer the proof binds the new token to our key; a\n // `use_dpop_nonce` answer is retried once with the server's nonce.\n res = this.dpop\n ? await fetchWithDpop(this.fetchFn, url, init, this.dpop)\n : await this.fetchFn(url, init);\n } catch (error) {\n throw new LumoAuthNetworkError(\n `Agent authentication failed: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n\n const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n if (!res.ok || typeof body.access_token !== 'string') {\n throw new LumoAuthApiError(\n typeof body.error_description === 'string'\n ? body.error_description\n : `Agent authentication failed (HTTP ${res.status})`,\n typeof body.error === 'string' ? body.error : 'AUTHENTICATION_ERROR',\n res.status,\n body,\n );\n }\n\n const expiresIn = typeof body.expires_in === 'number' ? body.expires_in : 3600;\n this.token = {\n accessToken: body.access_token,\n tokenType: typeof body.token_type === 'string' ? body.token_type : 'Bearer',\n refreshAt: Date.now() + expiresIn * 1000 - TOKEN_REFRESH_BUFFER_MS,\n scopes: typeof body.scope === 'string' ? body.scope.split(' ').filter(Boolean) : [],\n };\n return this.token.accessToken;\n }\n\n /**\n * `token_type` of the last successful authentication: `DPoP` when the\n * token is sender-constrained, otherwise `Bearer`; `null` before the\n * first sign-in. Present the token with that `Authorization` scheme.\n */\n get tokenType(): string | null {\n return this.token?.tokenType ?? null;\n }\n\n /**\n * A new `private_key_jwt` client assertion for this agent (single-use),\n * addressed to `issuer` or `{baseUrl}/orgs/{orgId}/api/v1`.\n */\n createClientAssertion(): string {\n if (!this.assertionSigner) {\n throw new LumoAuthConfigError('This agent signs no client assertions: create it with privateKey.');\n }\n const audience = this.issuer ?? issuerFor(this.baseUrl, this.requireOrgId());\n return this.assertionSigner.create(this.clientId, audience);\n }\n\n /** The client assertion signer this agent was configured with, if any. */\n get clientAssertionSigner(): ClientAssertionSigner | undefined {\n return this.assertionSigner;\n }\n\n /** The DPoP proof signer this agent was configured with, if any. */\n get dpopSigner(): DpopProofProvider | undefined {\n return this.dpop;\n }\n\n /**\n * The current access token, re-authenticating transparently when it is\n * missing or within 60 s of expiry. Concurrent callers share one\n * in-flight token request.\n */\n async getAccessToken(): Promise<string> {\n if (this.token && Date.now() < this.token.refreshAt) {\n return this.token.accessToken;\n }\n this.refreshPromise ??= this.authenticate(\n this.token?.scopes.length ? this.token.scopes : undefined,\n ).finally(() => {\n this.refreshPromise = null;\n });\n return this.refreshPromise;\n }\n\n /** Scopes granted by the last successful authentication. */\n get tokenScopes(): string[] {\n return this.token ? [...this.token.scopes] : [];\n }\n\n // ── Ask API & self-inspection (delegates to `agents`) ─────────────\n\n /** Preflight check: is the agent authorised to perform `action`? */\n async ask(action: string, context?: Record<string, unknown>): Promise<AgentAskResult> {\n return this.agents.ask(action, context);\n }\n\n /** Convenience wrapper: `true` when `action` is allowed. */\n async isAllowed(action: string, context?: Record<string, unknown>): Promise<boolean> {\n return this.agents.isAllowed(action, context);\n }\n\n /**\n * May this agent run `tool` on the registered MCP server `serverId`?\n * A deny returns `{ allowed: false }` and does not throw.\n */\n async authorizeMcpTool(serverId: string, tool: string): Promise<AgentMcpToolDecision> {\n return this.agents.authorizeMcpTool(serverId, tool);\n }\n\n /** The agent's own identity, capabilities, and workspace. */\n async getCurrentAgent(): Promise<AgentIdentity> {\n return this.agents.me();\n }\n\n /** The agent's declared capability slugs. */\n async capabilities(): Promise<string[]> {\n return this.agents.capabilities();\n }\n\n /** The agent's budget policy (empty object when no policy is set). */\n async budget(): Promise<AgentBudget> {\n return this.agents.budget();\n }\n\n /**\n * Report the model tokens and cost that the agent just used, for example\n * the `usage` that the model provider returned. LumoAuth does not see\n * model calls, so token and cost limits count only reported usage. The\n * result's `budget.exhausted` says whether the next metered call (Ask,\n * token or JIT request) will get 429.\n *\n * ```ts\n * const resp = await llm.chat(...);\n * const { budget } = await agent.reportUsage({ tokens: resp.usage.total_tokens, costUsd: 0.0042 });\n * if (budget.exhausted) throw new Error('budget spent');\n * ```\n */\n async reportUsage(report: UsageReport): Promise<UsageReportResult> {\n return this.agents.reportUsage(report);\n }\n\n // ── Internal ──────────────────────────────────────────────────────\n\n private requireOrgId(): string {\n if (!this.orgId) {\n throw new LumoAuthConfigError(\n 'orgId is required — pass it to the LumoAgent constructor or set LUMOAUTH_ORG_ID.',\n );\n }\n return this.orgId;\n }\n}\n","import {\n createPrivateKey,\n createPublicKey,\n generateKeyPairSync,\n randomBytes,\n sign as cryptoSign,\n constants as cryptoConstants,\n type KeyObject,\n} from 'node:crypto';\n\n/**\n * `private_key_jwt` client assertions (RFC 7523 §2.2, OpenID Connect Core §9).\n *\n * A LumoAuth agent registered with the **Private key JWT** identity type has\n * no client secret. Whenever it needs a token, it signs a short-lived JWT with\n * its private key and sends that instead:\n *\n * ```ts\n * const agent = new LumoAgent({\n * clientId: 'agt_0123456789abcdef',\n * privateKey: ClientAssertionSigner.fromPem(process.env.AGENT_PRIVATE_KEY!, { keyId: 'agent-2026-11' }),\n * });\n * ```\n *\n * Register `signer.jwks` (the public key only) on the agent.\n *\n * What the server checks, and what `create()` produces:\n * - header `alg` (ES256, ES384, ES512, EdDSA, RS256–RS512 or PS256–PS512),\n * `kid` and `typ: client-authentication+jwt`;\n * - `iss` = `sub` = the agent ID, `aud` = the organization's issuer\n * identifier alone (not the token endpoint URL);\n * - `iat` now, `exp` at most 10 minutes later (60 s by default) and a random\n * `jti`: every assertion is single-use, so sign a new one per request.\n */\n\n/** `client_assertion_type` for a JWT client assertion. */\nexport const CLIENT_ASSERTION_TYPE = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';\n/** The `typ` header of a client-authentication JWT. */\nexport const CLIENT_ASSERTION_TYP = 'client-authentication+jwt';\n/** The longest validity LumoAuth accepts for an assertion, in seconds. */\nexport const MAX_ASSERTION_LIFETIME_SECONDS = 600;\n\nexport type ClientAssertionAlgorithm =\n | 'ES256'\n | 'ES384'\n | 'ES512'\n | 'EdDSA'\n | 'RS256'\n | 'RS384'\n | 'RS512'\n | 'PS256'\n | 'PS384'\n | 'PS512';\n\nconst RSA_ALGORITHMS: readonly ClientAssertionAlgorithm[] = ['RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512'];\nconst EC_ALGORITHM_BY_CURVE: Record<string, ClientAssertionAlgorithm> = {\n prime256v1: 'ES256',\n 'P-256': 'ES256',\n secp384r1: 'ES384',\n 'P-384': 'ES384',\n secp521r1: 'ES512',\n 'P-521': 'ES512',\n};\n\nexport interface ClientAssertionSignerOptions {\n /** PEM private key (PKCS#8, SEC 1 or PKCS#1): EC P-256/P-384/P-521, Ed25519 or RSA ≥ 2048 bits. */\n privateKeyPem?: string;\n /** A Node `KeyObject` private key, as an alternative to `privateKeyPem`. */\n privateKey?: KeyObject;\n /** `kid` of the registered public key. Required by the server when the agent has several keys. */\n keyId?: string;\n /** JWS algorithm. Defaults to the key's natural one (ES256/ES384/ES512, EdDSA, RS256); RSA keys may also use RS384/RS512/PS256/PS384/PS512. */\n algorithm?: ClientAssertionAlgorithm;\n /** Seconds until `exp`, 1–600. Default 60. */\n lifetimeSeconds?: number;\n /** Clock override in epoch seconds (tests only). */\n now?: () => number;\n}\n\n/** A public JWK as registered on the agent. */\nexport interface ClientAssertionJwk {\n kty: string;\n kid?: string;\n alg: ClientAssertionAlgorithm;\n use: 'sig';\n crv?: string;\n x?: string;\n y?: string;\n n?: string;\n e?: string;\n}\n\nexport class ClientAssertionSigner {\n /** The JWS algorithm the assertions are signed with. */\n readonly algorithm: ClientAssertionAlgorithm;\n /** `kid` put in every assertion header, if set. */\n readonly keyId: string | undefined;\n /** Seconds until `exp`. */\n readonly lifetimeSeconds: number;\n\n private readonly key: KeyObject;\n private readonly now: () => number;\n\n /** Generate a new key: ES256 (default), ES384, ES512, EdDSA, or an RSA algorithm (2048-bit key). */\n static generate(algorithm: ClientAssertionAlgorithm = 'ES256', keyId?: string): ClientAssertionSigner {\n let privateKey: KeyObject;\n if (algorithm === 'ES256' || algorithm === 'ES384' || algorithm === 'ES512') {\n const namedCurve = { ES256: 'P-256', ES384: 'P-384', ES512: 'P-521' }[algorithm];\n privateKey = generateKeyPairSync('ec', { namedCurve }).privateKey;\n } else if (algorithm === 'EdDSA') {\n privateKey = generateKeyPairSync('ed25519').privateKey;\n } else if (RSA_ALGORITHMS.includes(algorithm)) {\n privateKey = generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey;\n } else {\n throw new Error(`Unsupported client assertion algorithm: ${String(algorithm)}`);\n }\n return new ClientAssertionSigner({ privateKey, keyId, algorithm });\n }\n\n /** Load a PEM private key. */\n static fromPem(pem: string, options: Omit<ClientAssertionSignerOptions, 'privateKeyPem' | 'privateKey'> = {}): ClientAssertionSigner {\n return new ClientAssertionSigner({ ...options, privateKeyPem: pem });\n }\n\n constructor(options: ClientAssertionSignerOptions) {\n if (options.privateKey) {\n this.key = options.privateKey;\n } else if (options.privateKeyPem) {\n this.key = createPrivateKey(options.privateKeyPem);\n } else {\n throw new Error('ClientAssertionSigner needs privateKeyPem or privateKey');\n }\n if (this.key.type !== 'private') {\n throw new Error('ClientAssertionSigner needs a private key');\n }\n const natural = naturalAlgorithm(this.key);\n const chosen = options.algorithm ?? natural;\n if (this.key.asymmetricKeyType === 'rsa') {\n if (!RSA_ALGORITHMS.includes(chosen)) {\n throw new Error(`${chosen} does not fit an RSA key; use one of ${RSA_ALGORITHMS.join(', ')}`);\n }\n const bits = this.key.asymmetricKeyDetails?.modulusLength ?? 0;\n if (bits < 2048) throw new Error('RSA keys must be at least 2048 bits');\n } else if (chosen !== natural) {\n throw new Error(`${chosen} does not fit this key; it signs with ${natural}`);\n }\n const lifetime = options.lifetimeSeconds ?? 60;\n if (!Number.isInteger(lifetime) || lifetime < 1 || lifetime > MAX_ASSERTION_LIFETIME_SECONDS) {\n throw new Error(`lifetimeSeconds must be an integer from 1 to ${MAX_ASSERTION_LIFETIME_SECONDS}`);\n }\n this.algorithm = chosen;\n this.keyId = options.keyId;\n this.lifetimeSeconds = lifetime;\n this.now = options.now ?? (() => Math.floor(Date.now() / 1000));\n }\n\n /** Sign one assertion for `clientId` (the agent ID) and `audience` (the organization's issuer). */\n create(clientId: string, audience: string): string {\n if (!clientId || !audience) {\n throw new Error('clientId and audience are required for a client assertion');\n }\n const iat = this.now();\n const header: Record<string, unknown> = { alg: this.algorithm, typ: CLIENT_ASSERTION_TYP };\n if (this.keyId) header.kid = this.keyId;\n const claims = {\n iss: clientId,\n sub: clientId,\n aud: audience,\n iat,\n exp: iat + this.lifetimeSeconds,\n jti: randomBytes(24).toString('base64url'),\n };\n const signingInput = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(claims))}`;\n return `${signingInput}.${signAssertion(this.algorithm, Buffer.from(signingInput, 'utf8'), this.key).toString('base64url')}`;\n }\n\n /** The public key as a JWK with `kid` (when set), `alg` and `use: \"sig\"`. */\n get jwk(): ClientAssertionJwk {\n const pub = createPublicKey(this.key).export({ format: 'jwk' }) as Record<string, unknown>;\n const out: Record<string, unknown> = { kty: pub.kty };\n for (const member of ['crv', 'x', 'y', 'n', 'e'] as const) {\n if (typeof pub[member] === 'string') out[member] = pub[member];\n }\n if (this.keyId) out.kid = this.keyId;\n out.alg = this.algorithm;\n out.use = 'sig';\n return out as unknown as ClientAssertionJwk;\n }\n\n /** `{ keys: [jwk] }`: what to register on the agent. */\n get jwks(): { keys: ClientAssertionJwk[] } {\n return { keys: [this.jwk] };\n }\n\n /** The private key as PKCS#8 PEM, for your secret store. */\n get privateKeyPem(): string {\n return this.key.export({ type: 'pkcs8', format: 'pem' }).toString();\n }\n}\n\n/**\n * The issuer identifier of an organization on `baseUrl`: the `issuer` of\n * `/orgs/{orgId}/api/v1/.well-known/openid-configuration`, and the `aud` a\n * client assertion must carry. On a custom domain the issuer differs; pass it\n * explicitly there.\n */\nexport function issuerFor(baseUrl: string, orgId: string): string {\n return `${baseUrl.replace(/\\/+$/, '')}/orgs/${orgId}/api/v1`;\n}\n\nfunction naturalAlgorithm(key: KeyObject): ClientAssertionAlgorithm {\n switch (key.asymmetricKeyType) {\n case 'ec': {\n const curve = String(key.asymmetricKeyDetails?.namedCurve ?? '');\n const alg = EC_ALGORITHM_BY_CURVE[curve];\n if (!alg) throw new Error(`EC keys must use P-256, P-384 or P-521 (got ${curve})`);\n return alg;\n }\n case 'ed25519':\n return 'EdDSA';\n case 'rsa':\n return 'RS256';\n default:\n throw new Error(`Unsupported key type: ${String(key.asymmetricKeyType)}`);\n }\n}\n\nfunction signAssertion(alg: ClientAssertionAlgorithm, data: Buffer, key: KeyObject): Buffer {\n const hash = `sha${alg.slice(2)}`;\n switch (alg) {\n case 'ES256':\n case 'ES384':\n case 'ES512':\n return cryptoSign(hash, data, { key, dsaEncoding: 'ieee-p1363' });\n case 'EdDSA':\n return cryptoSign(null, data, key);\n case 'PS256':\n case 'PS384':\n case 'PS512':\n return cryptoSign(hash, data, {\n key,\n padding: cryptoConstants.RSA_PKCS1_PSS_PADDING,\n saltLength: cryptoConstants.RSA_PSS_SALTLEN_DIGEST,\n });\n default:\n return cryptoSign(hash, data, key);\n }\n}\n\nfunction b64url(text: string): string {\n return Buffer.from(text, 'utf8').toString('base64url');\n}\n","import { createHash, createPublicKey, createPrivateKey, generateKeyPairSync, type KeyObject } from 'node:crypto';\n\n// ─── Types ────────────────────────────────────────────────────────────\n\n/** A public JSON Web Key as published in a JWKS. */\nexport interface AAuthJwk {\n kty: string;\n crv?: string;\n x?: string;\n y?: string;\n n?: string;\n e?: string;\n use?: string;\n kid?: string;\n alg?: string;\n [key: string]: unknown;\n}\n\nexport interface AAuthKeypair {\n /** PKCS#8 PEM-encoded Ed25519 private key. Store in your secret manager. */\n privateKeyPem: string;\n /** SPKI PEM-encoded public key. */\n publicKeyPem: string;\n /** The public key as a JWK (with `use: \"sig\"` and the given `kid`). */\n jwk: AAuthJwk;\n /** A JWKS document ready to publish at `/.well-known/jwks.json`. */\n jwks: { keys: AAuthJwk[] };\n}\n\n// ─── Helpers ──────────────────────────────────────────────────────────\n\nexport function base64UrlEncode(data: Buffer | Uint8Array | string): string {\n return Buffer.from(data).toString('base64url');\n}\n\nexport function base64UrlDecode(data: string): Buffer {\n return Buffer.from(data, 'base64url');\n}\n\n// ─── Key generation ───────────────────────────────────────────────────\n\n/**\n * Generate an Ed25519 key pair suitable for AAuth.\n *\n * Mirrors the Python SDK's `AAuthClient.generate_keypair()`: returns the\n * PKCS#8 private key PEM plus a JWKS document ready to be published at\n * `/.well-known/jwks.json` (or registered inline with LumoAuth).\n *\n * @example\n * ```ts\n * import { generateKeypair } from '@lumoauth/agent';\n *\n * const { privateKeyPem, jwks } = generateKeypair();\n * console.log(JSON.stringify(jwks, null, 2));\n * ```\n */\nexport function generateKeypair(kid = 'key-1'): AAuthKeypair {\n const { privateKey, publicKey } = generateKeyPairSync('ed25519');\n\n const privateKeyPem = privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();\n const publicKeyPem = publicKey.export({ type: 'spki', format: 'pem' }).toString();\n\n const rawJwk = publicKey.export({ format: 'jwk' }) as { kty: string; crv: string; x: string };\n const jwk: AAuthJwk = {\n kty: rawJwk.kty,\n crv: rawJwk.crv,\n x: rawJwk.x,\n use: 'sig',\n kid,\n };\n\n return { privateKeyPem, publicKeyPem, jwk, jwks: { keys: [jwk] } };\n}\n\n/**\n * Compute the RFC 7638 JWK thumbprint (base64url-encoded SHA-256) of a\n * public JWK. This is the `jkt` value AAuth uses to bind tokens to keys.\n */\nexport function jwkThumbprint(jwk: AAuthJwk): string {\n let canonical: string;\n switch (jwk.kty) {\n case 'OKP':\n canonical = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x });\n break;\n case 'EC':\n canonical = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y });\n break;\n case 'RSA':\n canonical = JSON.stringify({ e: jwk.e, kty: jwk.kty, n: jwk.n });\n break;\n default:\n throw new Error(`Unsupported key type for thumbprint: ${jwk.kty}`);\n }\n return createHash('sha256').update(canonical, 'utf8').digest('base64url');\n}\n\n/**\n * Load a PEM private key (Ed25519 or RSA) into a Node.js KeyObject and\n * classify it for the RFC 9421 signing dispatch.\n */\nexport function loadPrivateKey(pem: string): { key: KeyObject; type: 'ed25519' | 'rsa' } {\n const key = createPrivateKey(pem);\n if (key.asymmetricKeyType === 'ed25519') {\n return { key, type: 'ed25519' };\n }\n if (key.asymmetricKeyType === 'rsa' || key.asymmetricKeyType === 'rsa-pss') {\n return { key, type: 'rsa' };\n }\n throw new Error(\n `AAuth requires an Ed25519 or RSA private key (got ${String(key.asymmetricKeyType)}).`\n );\n}\n\n/** Derive the public JWK for a loaded private key. */\nexport function publicJwkFromPrivateKey(pem: string, kid?: string): AAuthJwk {\n const priv = createPrivateKey(pem);\n const pub = createPublicKey(priv);\n const jwk = pub.export({ format: 'jwk' }) as AAuthJwk;\n if (kid) jwk.kid = kid;\n return jwk;\n}\n","import {\n constants,\n createHash,\n randomBytes,\n sign as cryptoSign,\n verify as cryptoVerify,\n type KeyObject,\n} from 'node:crypto';\nimport { loadPrivateKey } from './keys';\n\n/**\n * RFC 9421 HTTP Message Signing, profiled for AAuth.\n *\n * The LumoAuth agent token endpoint enforces a strict profile (AAuth 1.0 §4):\n *\n * - Covered components: `@method @authority @path signature-key\n * content-digest content-type authorization` (plus `@query` if and only if\n * the target URI has a query string).\n * - `Signature-Input` parameters: exactly `created` (within ±60 s) and a\n * fresh `nonce` (≥ 12 bytes / 96 bits of entropy, base64url).\n * - `Content-Digest` per RFC 9530 with **standard** base64 (`sha-256=:…:`).\n * - The `Signature` value is **base64url** encoded (`label=:…:`).\n * - Algorithms: Ed25519 or RSA-PSS-SHA512 (MGF1-SHA512, 64-byte salt),\n * dispatched by key type — do NOT declare an `alg` parameter.\n */\n\n// ─── Constants ────────────────────────────────────────────────────────\n\n/** Covered components required by the AAuth agent token endpoint, in order. */\nexport const AAUTH_COVERED_COMPONENTS = [\n '@method',\n '@authority',\n '@path',\n 'signature-key',\n 'content-digest',\n 'content-type',\n 'authorization',\n] as const;\n\nconst SIGNATURE_LABEL = 'sig1';\n\n// ─── Primitives ───────────────────────────────────────────────────────\n\n/**\n * Compute an RFC 9530 `Content-Digest` header value over the exact body\n * bytes. Uses sha-256 with STANDARD base64 (the server base64-decodes it).\n */\nexport function contentDigestSha256(body: Buffer | Uint8Array | string): string {\n const digest = createHash('sha256').update(body).digest('base64');\n return `sha-256=:${digest}:`;\n}\n\n/** Generate a fresh signature nonce: base64url of 16 random bytes (128 bits). */\nexport function generateNonce(): string {\n return randomBytes(16).toString('base64url');\n}\n\n/**\n * Build the RFC 9421 signature base: one `\"<component>\": <value>` line per\n * covered component in declared order, then the `\"@signature-params\"` line\n * carrying ONLY `created` and `nonce`.\n */\nexport function buildSignatureBase(\n components: readonly string[],\n values: Record<string, string>,\n created: number,\n nonce: string\n): string {\n const lines = components.map((c) => `\"${c}\": ${values[c] ?? ''}`);\n lines.push(`\"@signature-params\": ${signatureParams(components, created, nonce)}`);\n return lines.join('\\n');\n}\n\n/** The `(…);created=…;nonce=\"…\"` parameter string shared by the base and header. */\nexport function signatureParams(\n components: readonly string[],\n created: number,\n nonce: string\n): string {\n const coveredList = components.map((c) => `\"${c}\"`).join(' ');\n return `(${coveredList});created=${created};nonce=\"${nonce}\"`;\n}\n\n/**\n * Sign a signature base with the agent's private key.\n * Ed25519 keys produce `ed25519` signatures; RSA keys produce\n * `rsa-pss-sha512` signatures (MGF1-SHA512, salt length = digest length).\n * Returns the base64url-encoded signature (RFC 9421 profile).\n */\nexport function signSignatureBase(signatureBase: string, privateKey: KeyObject): string {\n const data = Buffer.from(signatureBase, 'utf8');\n let signature: Buffer;\n if (privateKey.asymmetricKeyType === 'ed25519') {\n signature = cryptoSign(null, data, privateKey);\n } else {\n signature = cryptoSign('sha512', data, {\n key: privateKey,\n padding: constants.RSA_PKCS1_PSS_PADDING,\n saltLength: constants.RSA_PSS_SALTLEN_DIGEST, // 64 bytes for SHA-512\n });\n }\n return signature.toString('base64url');\n}\n\n/**\n * Verify a base64url signature over a signature base (resource-server side).\n * Dispatches on key type like the LumoAuth server does.\n */\nexport function verifySignatureBase(\n signatureBase: string,\n signatureB64url: string,\n publicKey: KeyObject\n): boolean {\n const data = Buffer.from(signatureBase, 'utf8');\n const sig = Buffer.from(signatureB64url, 'base64url');\n if (publicKey.asymmetricKeyType === 'ed25519') {\n return cryptoVerify(null, data, publicKey, sig);\n }\n return cryptoVerify('sha512', data, {\n key: publicKey,\n padding: constants.RSA_PKCS1_PSS_PADDING,\n saltLength: constants.RSA_PSS_SALTLEN_DIGEST,\n }, sig);\n}\n\n// ─── Request signing ──────────────────────────────────────────────────\n\nexport interface SignRequestOptions {\n /** Raw request body. Defaults to the empty body. */\n body?: Buffer | Uint8Array | string;\n /** Media type of the body. Default: `application/json`. */\n contentType?: string;\n /** The `agent+jwt` to present in the `Agent-Auth` header. */\n agentToken?: string;\n /** Value of a covered `Authorization` header, if any (e.g. `Bearer …`). */\n authorization?: string;\n /** Value of a covered `Signature-Key` header, if any. */\n signatureKey?: string;\n /**\n * Override the `created` timestamp (seconds). Testing only — the server\n * rejects timestamps more than 60 s from its clock.\n */\n created?: number;\n /** Override the nonce. Testing only — nonces are single-use server-side. */\n nonce?: string;\n}\n\n/**\n * Create RFC 9421 signature headers for a request to the AAuth agent token\n * endpoint (or any endpoint enforcing the AAuth profile).\n *\n * Byte-compatible with the Python SDK's `AAuthClient.sign_request()`.\n */\nexport function signRequest(\n privateKeyPem: string,\n method: string,\n url: string,\n options: SignRequestOptions = {}\n): Record<string, string> {\n const { key } = loadPrivateKey(privateKeyPem);\n const parsed = new URL(url);\n const authority = parsed.host; // host[:port], lowercased by the URL parser\n const path = parsed.pathname || '/';\n const query = parsed.search; // '' or '?…'\n\n const body = options.body ?? Buffer.alloc(0);\n const contentType = options.contentType ?? 'application/json';\n const contentDigest = contentDigestSha256(body);\n\n const created = options.created ?? Math.floor(Date.now() / 1000);\n const nonce = options.nonce ?? generateNonce();\n\n // @query MUST be covered if and only if the target has a query string.\n const components: string[] = ['@method', '@authority', '@path'];\n if (query !== '') components.push('@query');\n components.push('signature-key', 'content-digest', 'content-type', 'authorization');\n\n const values: Record<string, string> = {\n '@method': method.toUpperCase(),\n '@authority': authority,\n '@path': path,\n 'signature-key': options.signatureKey ?? '',\n 'content-digest': contentDigest,\n 'content-type': contentType,\n authorization: options.authorization ?? '',\n };\n if (query !== '') values['@query'] = query;\n\n const signatureBase = buildSignatureBase(components, values, created, nonce);\n const signature = signSignatureBase(signatureBase, key);\n\n const headers: Record<string, string> = {\n 'Content-Digest': contentDigest,\n 'Content-Type': contentType,\n 'Signature-Input': `${SIGNATURE_LABEL}=${signatureParams(components, created, nonce)}`,\n Signature: `${SIGNATURE_LABEL}=:${signature}:`,\n };\n if (options.agentToken) {\n headers['Agent-Auth'] = `agent_token=${options.agentToken}`;\n }\n if (options.signatureKey) {\n headers['Signature-Key'] = options.signatureKey;\n }\n return headers;\n}\n","import { constants, createPublicKey, verify as cryptoVerify, type KeyObject } from 'node:crypto';\nimport type { AAuthJwk } from './keys';\nimport { AAuthError } from './errors';\n\n/**\n * Auth-token (`auth+jwt`) verification for resource servers.\n *\n * Verifies the JWS signature against the organization's AAuth issuer JWKS\n * (`{issuer}/aauth/jwks.json`), plus `typ`, `iss`, `aud`, and `exp` — the\n * same checks LumoAuth's own `validateAuthToken()` performs (revocation\n * excepted: use `POST {issuer}/aauth/auth/token/verify` for live\n * revocation-aware introspection).\n *\n * NOTE: AAuth auth tokens are proof-of-possession tokens. After verifying\n * the JWT, the resource MUST also verify the request's RFC 9421 signature\n * against the key in `cnf.jwk` (see `verifySignatureBase` and\n * `jwkThumbprint`).\n */\n\n// ─── Types ────────────────────────────────────────────────────────────\n\nexport interface AAuthTokenClaims {\n iss: string;\n aud: string;\n exp: number;\n iat: number;\n jti: string;\n cnf: { jwk: AAuthJwk };\n agent?: string;\n agent_delegate?: string;\n scope?: string;\n sub?: string;\n act?: Record<string, unknown>;\n [claim: string]: unknown;\n}\n\nexport interface VerifyAuthTokenOptions {\n /** The trusted issuer URL, e.g. `https://app.lumoauth.dev/orgs/acme-corp/api/v1`. */\n issuer: string;\n /** Your resource identifier — must equal the token's `aud`. */\n resource: string;\n /** Pre-fetched issuer JWKS (skips the network fetch). */\n jwks?: { keys: AAuthJwk[] };\n /** Custom fetch implementation. */\n fetch?: typeof globalThis.fetch;\n /** Allowed clock skew in seconds for `exp`. Default 0 (like the server). */\n clockSkew?: number;\n}\n\n// Only asymmetric JWS algorithms; HS* and none are always rejected.\nconst JWS_VERIFIERS: Record<string, (data: Buffer, key: KeyObject, sig: Buffer) => boolean> = {\n RS256: (d, k, s) => cryptoVerify('sha256', d, k, s),\n RS384: (d, k, s) => cryptoVerify('sha384', d, k, s),\n RS512: (d, k, s) => cryptoVerify('sha512', d, k, s),\n PS256: (d, k, s) => cryptoVerify('sha256', d, pss(k), s),\n PS384: (d, k, s) => cryptoVerify('sha384', d, pss(k), s),\n PS512: (d, k, s) => cryptoVerify('sha512', d, pss(k), s),\n ES256: (d, k, s) => cryptoVerify('sha256', d, p1363(k), s),\n ES384: (d, k, s) => cryptoVerify('sha384', d, p1363(k), s),\n ES512: (d, k, s) => cryptoVerify('sha512', d, p1363(k), s),\n EdDSA: (d, k, s) => cryptoVerify(null, d, k, s),\n};\n\nfunction pss(key: KeyObject) {\n return { key, padding: constants.RSA_PKCS1_PSS_PADDING, saltLength: constants.RSA_PSS_SALTLEN_DIGEST };\n}\n\nfunction p1363(key: KeyObject) {\n return { key, dsaEncoding: 'ieee-p1363' as const };\n}\n\nfunction decodeSegment(segment: string): unknown {\n return JSON.parse(Buffer.from(segment, 'base64url').toString('utf8'));\n}\n\n/** Decode a JWT without verifying it. Useful for reading `aud`/`cnf` first. */\nexport function decodeJwt(token: string): { header: Record<string, unknown>; claims: Record<string, unknown> } {\n const parts = token.split('.');\n if (parts.length !== 3) {\n throw new AAuthError('Invalid JWT format', 'invalid_token');\n }\n return {\n header: decodeSegment(parts[0]) as Record<string, unknown>,\n claims: decodeSegment(parts[1]) as Record<string, unknown>,\n };\n}\n\n/**\n * Verify an AAuth auth token (`auth+jwt`) against the issuing\n * organization's JWKS. Returns the verified claims or throws `AAuthError`.\n *\n * @example\n * ```ts\n * import { verifyAuthToken } from '@lumoauth/agent';\n *\n * const claims = await verifyAuthToken(bearer, {\n * issuer: 'https://app.lumoauth.dev/orgs/acme-corp/api/v1',\n * resource: 'https://api.example.com',\n * });\n * // Then enforce PoP: verify the request signature against claims.cnf.jwk.\n * ```\n */\nexport async function verifyAuthToken(\n token: string,\n options: VerifyAuthTokenOptions\n): Promise<AAuthTokenClaims> {\n const parts = token.split('.');\n if (parts.length !== 3) {\n throw new AAuthError('Invalid JWT format', 'invalid_token');\n }\n const header = decodeSegment(parts[0]) as Record<string, unknown>;\n const claims = decodeSegment(parts[1]) as Record<string, unknown>;\n\n if (header.typ !== 'auth+jwt') {\n throw new AAuthError(`Unexpected token type: ${String(header.typ)}`, 'invalid_token');\n }\n const alg = typeof header.alg === 'string' ? header.alg : '';\n const kid = typeof header.kid === 'string' ? header.kid : '';\n if (!alg || !kid) {\n throw new AAuthError('Missing kid or alg in JOSE header', 'invalid_token');\n }\n const verifier = JWS_VERIFIERS[alg];\n if (!verifier) {\n throw new AAuthError(`Disallowed JWS algorithm: ${alg}`, 'invalid_token');\n }\n\n if (claims.iss !== options.issuer) {\n throw new AAuthError('Untrusted issuer', 'invalid_token');\n }\n\n // Resolve the signing key from the issuer JWKS\n const jwks = options.jwks ?? (await fetchIssuerJwks(options.issuer, options.fetch));\n const jwk = jwks.keys.find((k) => k.kid === kid);\n if (!jwk) {\n throw new AAuthError(`Key not found: kid=${kid}`, 'invalid_token');\n }\n assertAlgMatchesKey(alg, jwk);\n\n const publicKey = createPublicKey({ key: jwk as unknown as Record<string, unknown>, format: 'jwk' });\n const data = Buffer.from(`${parts[0]}.${parts[1]}`, 'utf8');\n const signature = Buffer.from(parts[2], 'base64url');\n if (!verifier(data, publicKey, signature)) {\n throw new AAuthError('Signature verification failed', 'invalid_token');\n }\n\n // Temporal + audience checks (post-signature, like the server)\n const now = Math.floor(Date.now() / 1000);\n const skew = options.clockSkew ?? 0;\n if (typeof claims.exp !== 'number' || claims.exp < now - skew) {\n throw new AAuthError('Auth token expired', 'invalid_token');\n }\n if (claims.aud !== options.resource) {\n throw new AAuthError('Invalid audience', 'invalid_token');\n }\n const cnf = claims.cnf as { jwk?: AAuthJwk } | undefined;\n if (!cnf || !cnf.jwk) {\n throw new AAuthError('Missing cnf.jwk claim', 'invalid_token');\n }\n\n return claims as unknown as AAuthTokenClaims;\n}\n\nfunction assertAlgMatchesKey(alg: string, jwk: AAuthJwk): void {\n const compatible =\n (jwk.kty === 'RSA' && (alg.startsWith('RS') || alg.startsWith('PS'))) ||\n (jwk.kty === 'EC' && alg.startsWith('ES')) ||\n (jwk.kty === 'OKP' && alg === 'EdDSA');\n if (!compatible) {\n throw new AAuthError(`Algorithm ${alg} incompatible with key type ${jwk.kty}`, 'invalid_token');\n }\n if (jwk.alg && jwk.alg !== alg) {\n throw new AAuthError(`Algorithm ${alg} does not match key alg ${jwk.alg}`, 'invalid_token');\n }\n}\n\nasync function fetchIssuerJwks(\n issuer: string,\n fetchFn?: typeof globalThis.fetch\n): Promise<{ keys: AAuthJwk[] }> {\n const doFetch = fetchFn ?? globalThis.fetch;\n const url = `${issuer.replace(/\\/+$/, '')}/aauth/jwks.json`;\n const response = await doFetch(url, { headers: { Accept: 'application/json' } });\n if (!response.ok) {\n throw new AAuthError(`Failed to fetch issuer JWKS (HTTP ${response.status})`, 'jwks_fetch_failed', response.status);\n }\n const jwks = (await response.json()) as { keys?: AAuthJwk[] };\n if (!Array.isArray(jwks.keys)) {\n throw new AAuthError('Issuer JWKS is malformed', 'jwks_fetch_failed');\n }\n return { keys: jwks.keys };\n}\n","import { LumoAuthError } from '@lumoauth/shared';\n\n/**\n * Thrown for AAuth protocol failures — OAuth-style `{error,\n * error_description}` bodies from the agent token endpoint, signature\n * problems, and token-verification failures.\n */\nexport class AAuthError extends LumoAuthError {\n constructor(\n message: string,\n /** OAuth-style error code, e.g. `invalid_grant`, `authentication_required`. */\n code: string,\n statusCode?: number,\n /** The parsed response body, when the error came from the server. */\n public readonly body?: unknown\n ) {\n super(message, code, statusCode);\n this.name = 'AAuthError';\n }\n}\n","import { generateKeypair, jwkThumbprint, publicJwkFromPrivateKey, type AAuthJwk, type AAuthKeypair } from './keys';\nimport { signRequest, type SignRequestOptions } from './signing';\nimport { verifyAuthToken, type AAuthTokenClaims, type VerifyAuthTokenOptions } from './verify';\nimport { AAuthError } from './errors';\nimport { LumoAuthConfigError, LumoAuthNetworkError, ROUTES, buildPath } from '@lumoauth/shared';\n\n// ─── Types ────────────────────────────────────────────────────────────\n\nexport interface AAuthClientOptions {\n /** HTTPS URL uniquely identifying the agent (e.g. `https://my-agent.example.com`). */\n agentIdentifier: string;\n /** PEM-encoded Ed25519 (PKCS#8) or RSA private key. */\n privateKeyPem: string;\n /**\n * LumoAuth instance URL. Defaults to `process.env.LUMOAUTH_URL` or\n * `https://app.lumoauth.dev`.\n */\n baseUrl?: string;\n /** Organization ID (slug). Defaults to `process.env.LUMOAUTH_ORG_ID`. */\n orgId?: string;\n /** Key ID matching the JWKS entry registered with LumoAuth. Default `key-1`. */\n kid?: string;\n /** Custom fetch implementation (defaults to the global `fetch`). */\n fetch?: typeof globalThis.fetch;\n /** Request timeout in milliseconds. Default: 30 000 ms. */\n timeout?: number;\n}\n\n/** Successful response from the agent token endpoint. */\nexport interface AAuthTokenResponse {\n requestType: 'auth' | 'code' | 'exchange' | 'refresh';\n /** The `auth+jwt` access token to present to the resource. */\n authToken: string;\n expiresIn: number;\n tokenType: string; // \"auth+jwt\"\n refreshToken?: string;\n}\n\n/** Returned by `requestAuthToken()` when the user must consent first. */\nexport interface AAuthAuthorizationRequired {\n authorizationRequired: true;\n /** Opaque token identifying the pending request (600 s TTL). */\n requestToken: string;\n /** Consent page URL — redirect the user here. */\n authorizationUri: string;\n expiresIn?: number;\n}\n\nexport interface AAuthIssuerMetadata {\n issuer: string;\n aauth_version: string;\n jwks_uri: string;\n agent_token_endpoint: string;\n agent_auth_endpoint: string;\n agent_signing_algs_supported: string[];\n token_signing_algs_supported: string[];\n request_types_supported: string[];\n scopes_supported: string[];\n [key: string]: unknown;\n}\n\nexport interface AAuthAgentMetadata {\n agent: string;\n jwks_uri: string;\n redirect_uris?: string[];\n name?: string;\n [key: string]: unknown;\n}\n\nexport interface AAuthResourceMetadata {\n resource: string;\n jwks_uri: string;\n resource_token_endpoint?: string;\n supported_scopes?: string[];\n [key: string]: unknown;\n}\n\ninterface RawTokenResponse {\n request_type?: string;\n auth_token?: string;\n expires_in?: number;\n token_type?: string;\n refresh_token?: string;\n request_token?: string;\n authorization_uri?: string;\n auth_url?: string;\n error?: string;\n error_description?: string;\n}\n\nfunction envVar(name: string): string | undefined {\n return typeof process !== 'undefined' && process.env ? process.env[name] : undefined;\n}\n\n// ─── Client ───────────────────────────────────────────────────────────\n\n/**\n * Client for the AAuth (Agent Auth) protocol — the Node.js counterpart of\n * the Python SDK's `lumoauth.AAuthClient`.\n *\n * AAuth extends OAuth 2.1 with cryptographic agent identity,\n * proof-of-possession tokens, and RFC 9421 HTTP message signing.\n *\n * @example\n * ```ts\n * import { AAuthClient } from '@lumoauth/agent';\n *\n * const client = new AAuthClient({\n * agentIdentifier: 'https://my-agent.example.com',\n * privateKeyPem: process.env.AGENT_PRIVATE_KEY!,\n * baseUrl: 'https://app.lumoauth.dev',\n * orgId: 'acme-corp',\n * });\n *\n * const result = await client.requestAuthToken({\n * resourceToken,\n * scope: 'read write',\n * agentToken,\n * });\n * if ('authorizationRequired' in result) {\n * // redirect the user to result.authorizationUri, then exchangeCode()\n * } else {\n * const resp = await client.signedRequest('GET', 'https://api.example.com/v1/data', {\n * authToken: result.authToken,\n * });\n * }\n * ```\n */\nexport class AAuthClient {\n /** Generate an Ed25519 key pair suitable for AAuth (parity with Python). */\n static generateKeypair = generateKeypair;\n\n readonly agentIdentifier: string;\n readonly baseUrl: string;\n readonly orgId: string;\n readonly kid: string;\n\n private readonly privateKeyPem: string;\n private readonly fetchFn: typeof globalThis.fetch;\n private readonly timeout: number;\n\n constructor(options: AAuthClientOptions) {\n if (!options.agentIdentifier) {\n throw new LumoAuthConfigError('agentIdentifier is required');\n }\n if (!options.privateKeyPem) {\n throw new LumoAuthConfigError('privateKeyPem is required');\n }\n this.agentIdentifier = options.agentIdentifier;\n this.privateKeyPem = options.privateKeyPem;\n this.baseUrl = (options.baseUrl ?? envVar('LUMOAUTH_URL') ?? 'https://app.lumoauth.dev').replace(/\\/+$/, '');\n this.orgId = options.orgId ?? envVar('LUMOAUTH_ORG_ID') ?? '';\n this.kid = options.kid ?? 'key-1';\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.timeout = options.timeout ?? 30_000;\n }\n\n /** The organization's AAuth issuer URL: `{baseUrl}/orgs/{orgId}/api/v1`. */\n get issuer(): string {\n return `${this.baseUrl}/orgs/${this.orgId}/api/v1`;\n }\n\n /** The agent's public JWK derived from its private key. */\n get publicJwk(): AAuthJwk {\n return publicJwkFromPrivateKey(this.privateKeyPem, this.kid);\n }\n\n /** RFC 7638 thumbprint of the agent's public key (the `jkt` binding value). */\n get publicJwkThumbprint(): string {\n return jwkThumbprint(this.publicJwk);\n }\n\n // ─── HTTP Message Signing ─────────────────────────────────────────\n\n /**\n * Create RFC 9421 signature headers for a request per the AAuth profile.\n * See `signRequest()` in `signing.ts` for the exact contract.\n */\n signRequest(method: string, url: string, options: SignRequestOptions = {}): Record<string, string> {\n return signRequest(this.privateKeyPem, method, url, options);\n }\n\n // ─── Token flows ──────────────────────────────────────────────────\n\n /**\n * Request an auth token (`request_type=auth` — direct authorization).\n *\n * Presents the resource token in the body and the agent token in the\n * `Agent-Auth` header, signed with the agent's key. If the server\n * requires user consent it returns `{ authorizationRequired: true,\n * requestToken, authorizationUri }` — redirect the user, then call\n * `exchangeCode()` with the code delivered to your `redirectUri`.\n */\n async requestAuthToken(params: {\n /** Resource token (`resource+jwt`) obtained from the target resource. */\n resourceToken: string;\n /** Space-separated scopes (informational; scopes bind via the resource token). */\n scope?: string;\n /** The `agent+jwt` presented in `Agent-Auth`. */\n agentToken: string;\n /** Redirect URI for user-consent flows (must be registered). */\n redirectUri?: string;\n }): Promise<AAuthTokenResponse | AAuthAuthorizationRequired> {\n this.requireAgentToken(params.agentToken);\n const body: Record<string, unknown> = {\n request_type: 'auth',\n resource_token: params.resourceToken,\n };\n if (params.scope) body.scope = params.scope;\n if (params.redirectUri) body.redirect_uri = params.redirectUri;\n\n const data = await this.tokenRequest(body, params.agentToken);\n\n if (!data.auth_token && (data.request_token || data.authorization_uri || data.auth_url)) {\n return {\n authorizationRequired: true,\n requestToken: data.request_token ?? '',\n authorizationUri: data.authorization_uri ?? data.auth_url ?? '',\n expiresIn: data.expires_in,\n };\n }\n return this.mapTokenResponse(data);\n }\n\n /**\n * Build the user-consent URL for a pending request token\n * (`GET {issuer}/aauth/agent/auth?request_token=…`). Prefer the\n * `authorizationUri` returned by `requestAuthToken()` when present.\n */\n buildConsentUrl(requestToken: string): string {\n return `${this.routeUrl('aauth.agentAuth')}?request_token=${encodeURIComponent(requestToken)}`;\n }\n\n /**\n * Exchange an authorization code for tokens (`request_type=code`) after\n * user consent. `redirectUri` must be the exact URI the code was\n * delivered to.\n */\n async exchangeCode(params: {\n code: string;\n redirectUri: string;\n agentToken: string;\n }): Promise<AAuthTokenResponse> {\n this.requireAgentToken(params.agentToken);\n const data = await this.tokenRequest(\n { request_type: 'code', code: params.code, redirect_uri: params.redirectUri },\n params.agentToken\n );\n return this.mapTokenResponse(data);\n }\n\n /**\n * Multi-hop token exchange (`request_type=exchange`): trade an upstream\n * auth token plus a downstream resource token for a new auth token with\n * an `act` actor chain. Requires token exchange to be enabled for the\n * agent.\n */\n async exchangeToken(params: {\n /** The upstream `auth+jwt` addressed to this agent. */\n authToken: string;\n /** Resource token issued by the downstream resource to this agent. */\n resourceToken: string;\n agentToken: string;\n }): Promise<AAuthTokenResponse> {\n this.requireAgentToken(params.agentToken);\n const data = await this.tokenRequest(\n {\n request_type: 'exchange',\n auth_token: params.authToken,\n resource_token: params.resourceToken,\n },\n params.agentToken\n );\n return this.mapTokenResponse(data);\n }\n\n /**\n * Refresh an auth token (`request_type=refresh`). A fresh resource token\n * for the target resource is required; scopes requested via the resource\n * token must be a subset of the original grant. Refresh tokens are not\n * rotated.\n */\n async refresh(params: {\n refreshToken: string;\n /** Fresh resource token for the target resource. */\n resourceToken: string;\n /** Optional scope narrowing. */\n scope?: string;\n agentToken: string;\n }): Promise<AAuthTokenResponse> {\n this.requireAgentToken(params.agentToken);\n const body: Record<string, unknown> = {\n request_type: 'refresh',\n refresh_token: params.refreshToken,\n resource_token: params.resourceToken,\n };\n if (params.scope) body.scope = params.scope;\n const data = await this.tokenRequest(body, params.agentToken);\n return this.mapTokenResponse(data);\n }\n\n /**\n * Revoke an auth token (by its `jti`) or a refresh token (by value).\n * Always resolves `{ revoked: true }` — the server does not reveal\n * whether the token existed.\n */\n async revoke(params: {\n /** A refresh-token value, or an auth token's `jti`. */\n token: string;\n tokenType?: 'auth_token' | 'refresh_token';\n agentToken: string;\n }): Promise<{ revoked: boolean }> {\n this.requireAgentToken(params.agentToken);\n const url = this.routeUrl('aauth.tokenRevoke');\n const data = await this.signedPost(url, {\n token: params.token,\n token_type: params.tokenType ?? 'auth_token',\n }, params.agentToken);\n return { revoked: Boolean((data as { revoked?: boolean }).revoked ?? true) };\n }\n\n // ─── Signed requests to protected resources ───────────────────────\n\n /**\n * Make a signed, authenticated request to a protected resource.\n *\n * Carries the auth token as `Authorization: Bearer …` **and** an RFC\n * 9421 signature proving possession of the key bound in the token's\n * `cnf.jwk`. The signature covers the `authorization` component, so the\n * resource can verify both together.\n *\n * Returns the raw `fetch` Response.\n */\n async signedRequest(\n method: string,\n url: string,\n options: {\n /** The AAuth `auth+jwt` access token. */\n authToken: string;\n /** JSON body (for POST/PUT). */\n data?: unknown;\n /** Extra headers (not covered by the signature). */\n headers?: Record<string, string>;\n }\n ): Promise<Response> {\n const bodyStr = options.data != null ? JSON.stringify(options.data) : '';\n const authorization = `Bearer ${options.authToken}`;\n const sigHeaders = this.signRequest(method, url, { body: bodyStr, authorization });\n\n return this.doFetch(url, {\n method: method.toUpperCase(),\n headers: { Authorization: authorization, ...sigHeaders, ...(options.headers ?? {}) },\n body: bodyStr !== '' ? bodyStr : undefined,\n });\n }\n\n // ─── Verification (resource-server side) ──────────────────────────\n\n /**\n * Verify an `auth+jwt` against this organization's issuer JWKS.\n * See `verifyAuthToken()` for details (PoP still required!).\n */\n async verifyAuthToken(\n token: string,\n options: Omit<VerifyAuthTokenOptions, 'issuer' | 'fetch'> & { issuer?: string }\n ): Promise<AAuthTokenClaims> {\n return verifyAuthToken(token, {\n issuer: options.issuer ?? this.issuer,\n fetch: this.fetchFn,\n ...options,\n });\n }\n\n // ─── Discovery ────────────────────────────────────────────────────\n\n /** Fetch `{issuer}/.well-known/aauth-issuer`. */\n async discoverIssuer(): Promise<AAuthIssuerMetadata> {\n return this.getJson<AAuthIssuerMetadata>(this.routeUrl('aauth.issuerMetadata'));\n }\n\n /** Fetch `{issuer}/.well-known/aauth-agent` — metadata for all active agents. */\n async discoverAgents(): Promise<AAuthAgentMetadata[]> {\n return this.getJson<AAuthAgentMetadata[]>(this.routeUrl('aauth.agentMetadata'));\n }\n\n /** Fetch `{resourceUrl}/.well-known/aauth-resource` from a resource server. */\n async discoverResource(resourceUrl: string): Promise<AAuthResourceMetadata | AAuthResourceMetadata[]> {\n const base = resourceUrl.replace(/\\/+$/, '');\n return this.getJson<AAuthResourceMetadata | AAuthResourceMetadata[]>(`${base}/.well-known/aauth-resource`);\n }\n\n // ─── Internals ────────────────────────────────────────────────────\n\n private requireAgentToken(agentToken: string): void {\n if (!agentToken) {\n throw new AAuthError(\n 'agentToken is required — the /agent/token endpoint authenticates the agent via the Agent-Auth header.',\n 'invalid_request'\n );\n }\n }\n\n private tokenUrl(): string {\n return this.routeUrl('aauth.agentToken');\n }\n\n /** Absolute URL for an org-scoped route from the shared registry. */\n private routeUrl(name: keyof typeof ROUTES): string {\n return `${this.baseUrl}${buildPath(ROUTES[name].path, { orgId: this.orgId })}`;\n }\n\n private async tokenRequest(body: Record<string, unknown>, agentToken: string): Promise<RawTokenResponse> {\n return (await this.signedPost(this.tokenUrl(), body, agentToken)) as RawTokenResponse;\n }\n\n private async signedPost(url: string, body: Record<string, unknown>, agentToken: string): Promise<unknown> {\n if (!this.orgId) {\n throw new LumoAuthConfigError('orgId is required for AAuth token operations');\n }\n const bodyStr = JSON.stringify(body);\n const headers = this.signRequest('POST', url, { body: bodyStr, agentToken });\n\n const response = await this.doFetch(url, { method: 'POST', headers, body: bodyStr });\n const text = await response.text();\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = undefined;\n }\n\n if (!response.ok) {\n const err = (parsed ?? {}) as { error?: string; error_description?: string };\n throw new AAuthError(\n err.error_description ?? err.error ?? `AAuth request failed: HTTP ${response.status}`,\n err.error ?? 'aauth_error',\n response.status,\n parsed ?? text\n );\n }\n return parsed ?? {};\n }\n\n private mapTokenResponse(data: RawTokenResponse): AAuthTokenResponse {\n if (!data.auth_token) {\n throw new AAuthError('Token response missing auth_token', 'invalid_response', undefined, data);\n }\n const result: AAuthTokenResponse = {\n requestType: (data.request_type ?? 'auth') as AAuthTokenResponse['requestType'],\n authToken: data.auth_token,\n expiresIn: data.expires_in ?? 0,\n tokenType: data.token_type ?? 'auth+jwt',\n };\n if (data.refresh_token) result.refreshToken = data.refresh_token;\n return result;\n }\n\n private async getJson<T>(url: string): Promise<T> {\n const response = await this.doFetch(url, { headers: { Accept: 'application/json' } });\n if (!response.ok) {\n throw new AAuthError(`Discovery request failed: HTTP ${response.status}`, 'discovery_failed', response.status);\n }\n return (await response.json()) as T;\n }\n\n private async doFetch(url: string, init: RequestInit): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n try {\n return await this.fetchFn(url, { ...init, signal: controller.signal });\n } catch (error) {\n if (error instanceof DOMException && error.name === 'AbortError') {\n throw new LumoAuthNetworkError(`Request to ${url} timed out after ${this.timeout}ms`, error);\n }\n throw new LumoAuthNetworkError(\n `Network request to ${url} failed: ${error instanceof Error ? error.message : String(error)}`,\n error\n );\n } finally {\n clearTimeout(timeoutId);\n }\n }\n}\n\nexport type { AAuthKeypair };\n","import {\n createHash,\n createPrivateKey,\n createPublicKey,\n generateKeyPairSync,\n randomBytes,\n sign as cryptoSign,\n type KeyObject,\n} from 'node:crypto';\nimport { dpopHtu, type DpopProofProvider, type DpopProofRequest } from '@lumoauth/shared';\nimport { jwkThumbprint, type AAuthJwk } from './keys';\n\n/**\n * RFC 9449 DPoP proof signing.\n *\n * A `DpopProofSigner` holds the agent's DPoP key and mints proof JWTs for\n * the token endpoint, the attestation endpoint and resource requests. The\n * LumoAuth server (`DPoPService`) accepts ES256/ES384/ES512, RS256/RS384/\n * RS512, PS256/PS384/PS512 and EdDSA; this signer produces ES256 (P-256,\n * the default), EdDSA (Ed25519, so the AAuth key can double as the DPoP\n * key) and RS256.\n *\n * Proof contents, as the server checks them:\n * - header `typ: \"dpop+jwt\"`, `alg`, `jwk` (public members only);\n * - `jti` 32 random characters, `htm` upper-case method, `htu` the URL\n * without query or fragment, `iat` now (the server allows 60 s ahead and\n * 300 s behind);\n * - `ath` = base64url(SHA-256(access token)) on resource requests;\n * - `nonce` when the server handed one out (`DPoP-Nonce`). The signer\n * remembers the latest nonce per origin, so `fetchWithDpop` only has to\n * retry once after a `use_dpop_nonce` answer.\n */\n\nexport type DpopAlgorithm = 'ES256' | 'EdDSA' | 'RS256';\n\nexport interface DpopProofSignerOptions {\n /** PEM (PKCS#8) private key: EC P-256, Ed25519 or RSA. */\n privateKeyPem?: string;\n /** A Node `KeyObject` private key, as an alternative to `privateKeyPem`. */\n privateKey?: KeyObject;\n /** Clock override in epoch seconds (tests only). */\n now?: () => number;\n}\n\n/** The public JWK carried in a DPoP proof header. */\nexport type DpopJwk = AAuthJwk;\n\nexport class DpopProofSigner implements DpopProofProvider {\n /** The JWS algorithm the proofs are signed with. */\n readonly algorithm: DpopAlgorithm;\n /** The public key as a JWK, with public members only. */\n readonly jwk: DpopJwk;\n /** RFC 7638 thumbprint of `jwk`: the `cnf.jkt` value of bound tokens. */\n readonly thumbprint: string;\n\n private readonly key: KeyObject;\n private readonly now: () => number;\n private readonly nonces = new Map<string, string>();\n\n /**\n * Generate a fresh key. ES256 (P-256) by default; pass `'EdDSA'` for an\n * Ed25519 key or `'RS256'` for a 2048-bit RSA key.\n */\n static generate(algorithm: DpopAlgorithm = 'ES256'): DpopProofSigner {\n let privateKey: KeyObject;\n switch (algorithm) {\n case 'ES256':\n privateKey = generateKeyPairSync('ec', { namedCurve: 'P-256' }).privateKey;\n break;\n case 'EdDSA':\n privateKey = generateKeyPairSync('ed25519').privateKey;\n break;\n case 'RS256':\n privateKey = generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey;\n break;\n default:\n throw new Error(`Unsupported DPoP algorithm: ${String(algorithm)}`);\n }\n return new DpopProofSigner({ privateKey });\n }\n\n constructor(options: DpopProofSignerOptions) {\n if (options.privateKey) {\n this.key = options.privateKey;\n } else if (options.privateKeyPem) {\n this.key = createPrivateKey(options.privateKeyPem);\n } else {\n throw new Error('DpopProofSigner needs privateKeyPem or privateKey');\n }\n if (this.key.type !== 'private') {\n throw new Error('DpopProofSigner needs a private key');\n }\n this.algorithm = algorithmFor(this.key);\n this.now = options.now ?? (() => Math.floor(Date.now() / 1000));\n\n const pub = createPublicKey(this.key).export({ format: 'jwk' }) as Record<string, unknown>;\n this.jwk = publicMembers(pub);\n this.thumbprint = jwkThumbprint(this.jwk);\n }\n\n /** The private key as PKCS#8 PEM, for your secret store. */\n get privateKeyPem(): string {\n return this.key.export({ type: 'pkcs8', format: 'pem' }).toString();\n }\n\n /** Create one proof JWT. See the file comment for the claims. */\n createProof(input: DpopProofRequest): string {\n const method = input.method.toUpperCase();\n const htu = dpopHtu(input.url);\n const nonce = input.nonce ?? this.getNonce(input.url);\n\n const header: Record<string, unknown> = { typ: 'dpop+jwt', alg: this.algorithm, jwk: this.jwk };\n const claims: Record<string, unknown> = {\n jti: randomBytes(24).toString('base64url'),\n htm: method,\n htu,\n iat: this.now(),\n };\n if (input.accessToken) claims.ath = dpopAth(input.accessToken);\n if (nonce) claims.nonce = nonce;\n\n const signingInput = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(claims))}`;\n const signature = signJws(this.algorithm, Buffer.from(signingInput, 'utf8'), this.key);\n return `${signingInput}.${signature.toString('base64url')}`;\n }\n\n /** Remember the latest server nonce for the origin of `url`. */\n setNonce(url: string, nonce: string): void {\n this.nonces.set(originOf(url), nonce);\n }\n\n /** The remembered nonce for the origin of `url`, if any. */\n getNonce(url: string): string | undefined {\n return this.nonces.get(originOf(url));\n }\n\n /** Forget every remembered nonce. */\n clearNonces(): void {\n this.nonces.clear();\n }\n}\n\n/** `ath` for an access token: base64url(SHA-256(token)). */\nexport function dpopAth(accessToken: string): string {\n return createHash('sha256').update(accessToken, 'ascii').digest('base64url');\n}\n\n/** Sign a JWS signing input with the algorithm's node:crypto settings. */\nexport function signJws(alg: DpopAlgorithm, data: Buffer, key: KeyObject): Buffer {\n switch (alg) {\n case 'ES256':\n return cryptoSign('sha256', data, { key, dsaEncoding: 'ieee-p1363' });\n case 'EdDSA':\n return cryptoSign(null, data, key);\n case 'RS256':\n return cryptoSign('sha256', data, key);\n default:\n throw new Error(`Unsupported DPoP algorithm: ${String(alg)}`);\n }\n}\n\nfunction algorithmFor(key: KeyObject): DpopAlgorithm {\n switch (key.asymmetricKeyType) {\n case 'ec': {\n const curve = key.asymmetricKeyDetails?.namedCurve;\n if (curve !== 'prime256v1' && curve !== 'P-256') {\n throw new Error(`DPoP EC keys must use P-256 (got ${String(curve)})`);\n }\n return 'ES256';\n }\n case 'ed25519':\n return 'EdDSA';\n case 'rsa':\n return 'RS256';\n default:\n throw new Error(`Unsupported DPoP key type: ${String(key.asymmetricKeyType)}`);\n }\n}\n\nfunction publicMembers(jwk: Record<string, unknown>): DpopJwk {\n const out: Record<string, unknown> = { kty: jwk.kty };\n for (const member of ['crv', 'x', 'y', 'n', 'e'] as const) {\n if (typeof jwk[member] === 'string') out[member] = jwk[member];\n }\n return out as DpopJwk;\n}\n\nfunction originOf(url: string): string {\n return new URL(url).origin;\n}\n\nfunction b64url(text: string): string {\n return Buffer.from(text, 'utf8').toString('base64url');\n}\n","import {\n LumoAuthApiError,\n LumoAuthConfigError,\n LumoAuthNetworkError,\n fetchWithDpop,\n type DpopProofProvider,\n} from '@lumoauth/shared';\n\n/**\n * Workload attestation: `POST {issuer}/agents/{agentId}/attest`.\n *\n * The agent's runtime presents a cloud-issued OIDC token (GitHub Actions,\n * GCP, AWS, Kubernetes, Azure, SPIFFE, …) and gets a short-lived LumoAuth\n * access token for the agent, with no client secret in the environment.\n * With a `dpop` signer the request carries an RFC 9449 proof and the token\n * comes back sender-constrained (`tokenType: \"DPoP\"`).\n *\n * NOTE: this endpoint is not yet in sdk-contract/routes.json, so the path\n * is built here rather than taken from the shared route registry.\n */\n\nexport interface AttestWorkloadOptions {\n /** LumoAuth instance URL. Defaults to `LUMOAUTH_URL` or `https://app.lumoauth.dev`. */\n baseUrl?: string;\n /** Organization slug. Defaults to `LUMOAUTH_ORG_ID`. */\n orgId?: string;\n /** The agent id (`agt_…`). */\n agentId: string;\n /** The workload's OIDC token. */\n attestationToken: string;\n /** DPoP proof signer; the returned token is bound to its key. */\n dpop?: DpopProofProvider;\n /** Custom fetch implementation. */\n fetch?: typeof globalThis.fetch;\n}\n\nexport interface AttestWorkloadResult {\n accessToken: string;\n /** `DPoP` when bound to the signer's key, otherwise `Bearer`. */\n tokenType: string;\n expiresIn: number | null;\n /** Space-separated agent capabilities. */\n scope: string | null;\n /** The verified workload identity (`provider`, `subject`, `issuer`, …). */\n identity: Record<string, unknown>;\n}\n\nfunction envVar(name: string): string | undefined {\n return typeof process !== 'undefined' && process.env ? process.env[name] : undefined;\n}\n\nexport async function attestWorkload(options: AttestWorkloadOptions): Promise<AttestWorkloadResult> {\n const baseUrl = (options.baseUrl ?? envVar('LUMOAUTH_URL') ?? 'https://app.lumoauth.dev').replace(/\\/+$/, '');\n const orgId = options.orgId ?? envVar('LUMOAUTH_ORG_ID') ?? '';\n if (!orgId) {\n throw new LumoAuthConfigError('attestWorkload requires orgId (or LUMOAUTH_ORG_ID).');\n }\n if (!options.agentId || !options.attestationToken) {\n throw new LumoAuthConfigError('attestWorkload requires agentId and attestationToken.');\n }\n const url = `${baseUrl}/orgs/${encodeURIComponent(orgId)}/api/v1/agents/${encodeURIComponent(options.agentId)}/attest`;\n const fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n const init: RequestInit = {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Accept: 'application/json' },\n body: JSON.stringify({ attestation_token: options.attestationToken }),\n };\n\n let res: Response;\n try {\n res = options.dpop ? await fetchWithDpop(fetchFn, url, init, options.dpop) : await fetchFn(url, init);\n } catch (error) {\n throw new LumoAuthNetworkError(\n `Agent attestation failed: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n\n const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n if (!res.ok || typeof body.access_token !== 'string') {\n throw new LumoAuthApiError(\n typeof body.error_description === 'string'\n ? body.error_description\n : `Agent attestation failed (HTTP ${res.status})`,\n typeof body.error === 'string' ? body.error : 'ATTESTATION_ERROR',\n res.status,\n body,\n );\n }\n return {\n accessToken: body.access_token,\n tokenType: typeof body.token_type === 'string' ? body.token_type : 'Bearer',\n expiresIn: typeof body.expires_in === 'number' ? body.expires_in : null,\n scope: typeof body.scope === 'string' ? body.scope : null,\n identity: typeof body.identity === 'object' && body.identity !== null ? (body.identity as Record<string, unknown>) : {},\n };\n}\n","import { constants, createHash, createPublicKey, verify as cryptoVerify, type KeyObject } from 'node:crypto';\nimport { DPOP_SCHEME, LumoAuthError, dpopHtu } from '@lumoauth/shared';\nimport { jwkThumbprint, type AAuthJwk } from './keys';\n\n/**\n * Local verification of LumoAuth core access tokens (`at+jwt`, RFC 9068).\n *\n * This is the token an MCP server or any other resource server receives\n * from an agent or a delegated user: a token-exchange result with `aud` set\n * to the resource URI, or an agent's client-credentials token. (AAuth\n * `auth+jwt` tokens are a different format; see `verifyAuthToken`.)\n *\n * Checks, in order: compact JWS shape; `typ` is `at+jwt` or\n * `application/at+jwt`; `alg` is an asymmetric JWS algorithm (`none` and\n * HMAC are refused); `kid` resolves in the issuer's JWKS, which is read from\n * `{issuer}/.well-known/openid-configuration` → `jwks_uri` and cached, with\n * one refetch on an unknown `kid`; signature; `iss`; `aud` contains the\n * resource; `exp` / `nbf` with a clock skew (default 60 s); `token_use` is\n * not `test`; and, when the token carries `cnf.jkt`, the RFC 9449 proof\n * binding of the incoming request.\n */\n\n// ─── Types ────────────────────────────────────────────────────────────\n\n/** OAuth Actor Profile actor object (`act` claim), nested for chains. */\nexport interface ActorClaim {\n /** `agent_agt_…` for an agent, a user id for a user. */\n sub: string;\n iss?: string;\n /** Entity classification, e.g. `ai_agent` or `user`. */\n sub_profile?: string;\n name?: string;\n act?: ActorClaim;\n [claim: string]: unknown;\n}\n\nexport interface AccessTokenClaims {\n iss: string;\n /** `agent_agt_…` for an agent, the user id for a delegated token. */\n sub: string;\n aud: string | string[];\n exp: number;\n iat: number;\n nbf?: number;\n jti: string;\n /** Space-separated scopes. */\n scope?: string;\n is_agent?: boolean;\n capabilities?: string[];\n act?: ActorClaim;\n cnf?: { jkt?: string; [member: string]: unknown };\n token_use?: string;\n client_id?: string;\n name?: string;\n [claim: string]: unknown;\n}\n\n/** Pluggable replay cache for DPoP `jti` values. */\nexport interface DpopReplayCache {\n /**\n * Record `key` for `ttlSeconds`. Return `true` when it was not seen\n * before, `false` when it was (a replay).\n */\n add(key: string, ttlSeconds: number): boolean | Promise<boolean>;\n}\n\n/** The DPoP proof of an incoming request, for the binding check. */\nexport interface IncomingDpopProof {\n /** HTTP method of the incoming request. */\n method: string;\n /** Full URL of the incoming request (the public one, behind any proxy). */\n url: string;\n /** The `DPoP` request header. */\n proof?: string | null;\n /**\n * The scheme of the `Authorization` header (`DPoP` or `Bearer`). A\n * DPoP-bound token must arrive with the `DPoP` scheme.\n */\n authorizationScheme?: string | null;\n /** The nonce this resource server expects in the proof, if it issues any. */\n nonce?: string;\n}\n\nexport interface VerifyAccessTokenOptions {\n /** The trusted issuer, e.g. `https://app.lumoauth.dev/orgs/acme-corp/api/v1`. */\n issuer: string;\n /** This resource server's URI. The token's `aud` must contain it. */\n resource: string;\n /** Pre-fetched issuer JWKS (no network). */\n jwks?: { keys: AAuthJwk[] };\n /** Custom fetch implementation. */\n fetch?: typeof globalThis.fetch;\n /** Allowed clock skew in seconds for `exp` and `nbf`. Default 60. */\n clockSkew?: number;\n /** Refuse tokens that are not DPoP-bound (no `cnf.jkt`). Default false. */\n requireDpop?: boolean;\n /** The incoming request's proof. Required when the token has `cnf.jkt`. */\n dpop?: IncomingDpopProof;\n /** Replay cache for proof `jti`s. Default: in-memory, 300 s. */\n replayCache?: DpopReplayCache;\n /** JWKS cache. Default: one shared per process, keyed by issuer. */\n jwksCache?: JwksCache;\n}\n\n/** Thrown when an access token or its DPoP binding is refused. */\nexport class AccessTokenError extends LumoAuthError {\n constructor(\n message: string,\n /** `invalid_token`, `invalid_dpop_proof` or `jwks_fetch_failed`. */\n code: 'invalid_token' | 'invalid_dpop_proof' | 'jwks_fetch_failed',\n statusCode = 401,\n ) {\n super(message, code, statusCode);\n this.name = 'AccessTokenError';\n }\n}\n\n// ─── Constants ────────────────────────────────────────────────────────\n\nconst AT_JWT_TYPES = new Set(['at+jwt', 'application/at+jwt']);\nconst DPOP_PROOF_TYP = 'dpop+jwt';\n/** Server window for a proof's `iat`: 60 s ahead, 300 s behind. */\nconst DPOP_IAT_FUTURE_SECONDS = 60;\nconst DPOP_IAT_PAST_SECONDS = 300;\nconst DPOP_JTI_TTL_SECONDS = 300;\nconst DPOP_JTI_MIN_LENGTH = 16;\n/** Do not hammer the JWKS endpoint on a stream of unknown kids. */\nconst JWKS_REFETCH_INTERVAL_MS = 30_000;\n\nconst JWS_VERIFIERS: Record<string, (data: Buffer, key: KeyObject, sig: Buffer) => boolean> = {\n RS256: (d, k, s) => cryptoVerify('sha256', d, k, s),\n RS384: (d, k, s) => cryptoVerify('sha384', d, k, s),\n RS512: (d, k, s) => cryptoVerify('sha512', d, k, s),\n PS256: (d, k, s) => cryptoVerify('sha256', d, pss(k), s),\n PS384: (d, k, s) => cryptoVerify('sha384', d, pss(k), s),\n PS512: (d, k, s) => cryptoVerify('sha512', d, pss(k), s),\n ES256: (d, k, s) => cryptoVerify('sha256', d, p1363(k), s),\n ES384: (d, k, s) => cryptoVerify('sha384', d, p1363(k), s),\n ES512: (d, k, s) => cryptoVerify('sha512', d, p1363(k), s),\n EdDSA: (d, k, s) => cryptoVerify(null, d, k, s),\n};\n\n/** Key type (and curve) each DPoP proof algorithm must be paired with. */\nconst DPOP_ALG_KEYS: Record<string, { kty: string; crv?: string }> = {\n ES256: { kty: 'EC', crv: 'P-256' },\n ES384: { kty: 'EC', crv: 'P-384' },\n ES512: { kty: 'EC', crv: 'P-521' },\n RS256: { kty: 'RSA' },\n RS384: { kty: 'RSA' },\n RS512: { kty: 'RSA' },\n PS256: { kty: 'RSA' },\n PS384: { kty: 'RSA' },\n PS512: { kty: 'RSA' },\n EdDSA: { kty: 'OKP', crv: 'Ed25519' },\n};\n\nfunction pss(key: KeyObject) {\n return { key, padding: constants.RSA_PKCS1_PSS_PADDING, saltLength: constants.RSA_PSS_SALTLEN_DIGEST };\n}\n\nfunction p1363(key: KeyObject) {\n return { key, dsaEncoding: 'ieee-p1363' as const };\n}\n\n// ─── JWKS cache ───────────────────────────────────────────────────────\n\n/** Per-issuer JWKS cache with discovery and a throttled refetch on unknown `kid`. */\nexport class JwksCache {\n private readonly entries = new Map<string, { keys: AAuthJwk[]; missRefetchAt: number }>();\n\n constructor(private readonly fetchFn?: typeof globalThis.fetch) {}\n\n /**\n * Find `kid` in the issuer's JWKS. An unknown `kid` triggers one refetch\n * (a key rotation); repeated misses refetch at most every 30 s, so a\n * stream of bogus tokens cannot hammer the JWKS endpoint.\n */\n async find(issuer: string, kid: string, fetchFn?: typeof globalThis.fetch): Promise<AAuthJwk | undefined> {\n const doFetch = fetchFn ?? this.fetchFn ?? globalThis.fetch;\n let entry = this.entries.get(issuer);\n if (!entry) {\n entry = { keys: await fetchJwks(issuer, doFetch), missRefetchAt: 0 };\n this.entries.set(issuer, entry);\n }\n let jwk = entry.keys.find((k) => k.kid === kid);\n if (!jwk && Date.now() - entry.missRefetchAt >= JWKS_REFETCH_INTERVAL_MS) {\n entry = { keys: await fetchJwks(issuer, doFetch), missRefetchAt: Date.now() };\n this.entries.set(issuer, entry);\n jwk = entry.keys.find((k) => k.kid === kid);\n }\n return jwk;\n }\n\n /** Drop the cached keys of one issuer, or of all when omitted. */\n clear(issuer?: string): void {\n if (issuer) this.entries.delete(issuer);\n else this.entries.clear();\n }\n}\n\nasync function fetchJwks(issuer: string, doFetch: typeof globalThis.fetch): Promise<AAuthJwk[]> {\n const base = issuer.replace(/\\/+$/, '');\n const discovery = await doFetch(`${base}/.well-known/openid-configuration`, {\n headers: { Accept: 'application/json' },\n });\n if (!discovery.ok) {\n throw new AccessTokenError(`Failed to fetch issuer discovery (HTTP ${discovery.status})`, 'jwks_fetch_failed', 503);\n }\n const metadata = (await discovery.json()) as { jwks_uri?: unknown };\n const jwksUri = typeof metadata.jwks_uri === 'string' ? metadata.jwks_uri : `${base}/.well-known/jwks.json`;\n\n const response = await doFetch(jwksUri, { headers: { Accept: 'application/json' } });\n if (!response.ok) {\n throw new AccessTokenError(`Failed to fetch issuer JWKS (HTTP ${response.status})`, 'jwks_fetch_failed', 503);\n }\n const jwks = (await response.json()) as { keys?: unknown };\n if (!Array.isArray(jwks.keys)) {\n throw new AccessTokenError('Issuer JWKS is malformed', 'jwks_fetch_failed', 503);\n }\n return jwks.keys as AAuthJwk[];\n}\n\nconst sharedJwksCache = new JwksCache();\n\n// ─── Replay cache ─────────────────────────────────────────────────────\n\n/** In-memory `jti` replay cache. One process only; use a shared store across replicas. */\nexport class InMemoryDpopReplayCache implements DpopReplayCache {\n private readonly seen = new Map<string, number>();\n\n constructor(private readonly now: () => number = () => Date.now()) {}\n\n add(key: string, ttlSeconds: number): boolean {\n const now = this.now();\n if (this.seen.size > 0 && this.seen.size % 256 === 0) this.prune(now);\n const expiresAt = this.seen.get(key);\n if (expiresAt !== undefined && expiresAt > now) return false;\n this.seen.set(key, now + ttlSeconds * 1000);\n return true;\n }\n\n private prune(now: number): void {\n for (const [key, expiresAt] of this.seen) {\n if (expiresAt <= now) this.seen.delete(key);\n }\n }\n}\n\nconst sharedReplayCache = new InMemoryDpopReplayCache();\n\n// ─── Helpers ──────────────────────────────────────────────────────────\n\nfunction decodeSegment(segment: string): unknown {\n try {\n return JSON.parse(Buffer.from(segment, 'base64url').toString('utf8'));\n } catch {\n throw new AccessTokenError('Invalid JWT encoding', 'invalid_token');\n }\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Split an `Authorization` header into scheme and credential. */\nexport function parseAuthorizationHeader(\n header: string | null | undefined,\n): { scheme: string; token: string } | null {\n if (!header) return null;\n const match = /^\\s*([A-Za-z][A-Za-z0-9+.-]*)\\s+(\\S+)\\s*$/.exec(header);\n return match ? { scheme: match[1], token: match[2] } : null;\n}\n\n/** The scopes of a verified token, as an array. */\nexport function accessTokenScopes(claims: AccessTokenClaims): string[] {\n return typeof claims.scope === 'string' ? claims.scope.split(' ').filter(Boolean) : [];\n}\n\n// ─── Access token verification ────────────────────────────────────────\n\n/**\n * Verify a LumoAuth `at+jwt` access token. Returns the claims or throws\n * `AccessTokenError`.\n *\n * @example\n * ```ts\n * const claims = await verifyAccessToken(token, {\n * issuer: 'https://app.lumoauth.dev/orgs/acme-corp/api/v1',\n * resource: 'https://mcp.example.com/mcp',\n * dpop: { method: req.method, url, proof: req.headers.dpop, authorizationScheme: 'DPoP' },\n * });\n * ```\n */\nexport async function verifyAccessToken(\n token: string,\n options: VerifyAccessTokenOptions,\n): Promise<AccessTokenClaims> {\n if (typeof token !== 'string' || token === '') {\n throw new AccessTokenError('Missing access token', 'invalid_token');\n }\n const parts = token.split('.');\n if (parts.length !== 3) {\n throw new AccessTokenError('Invalid JWT format', 'invalid_token');\n }\n const header = decodeSegment(parts[0]);\n const claims = decodeSegment(parts[1]);\n if (!isObject(header) || !isObject(claims)) {\n throw new AccessTokenError('Invalid JWT format', 'invalid_token');\n }\n\n if (typeof header.typ !== 'string' || !AT_JWT_TYPES.has(header.typ)) {\n throw new AccessTokenError(`Unexpected token type: ${String(header.typ)}`, 'invalid_token');\n }\n const alg = typeof header.alg === 'string' ? header.alg : '';\n const kid = typeof header.kid === 'string' ? header.kid : '';\n if (!alg || !kid) {\n throw new AccessTokenError('Missing kid or alg in JOSE header', 'invalid_token');\n }\n const verifier = JWS_VERIFIERS[alg];\n if (!verifier) {\n throw new AccessTokenError(`Disallowed JWS algorithm: ${alg}`, 'invalid_token');\n }\n\n if (claims.iss !== options.issuer) {\n throw new AccessTokenError('Untrusted issuer', 'invalid_token');\n }\n\n // Resolve the signing key.\n let jwk: AAuthJwk | undefined;\n if (options.jwks) {\n jwk = options.jwks.keys.find((k) => k.kid === kid);\n } else {\n const cache = options.jwksCache ?? sharedJwksCache;\n jwk = await cache.find(options.issuer, kid, options.fetch);\n }\n if (!jwk) {\n throw new AccessTokenError(`Key not found: kid=${kid}`, 'invalid_token');\n }\n assertAlgMatchesKey(alg, jwk);\n\n const publicKey = createPublicKey({ key: jwk as unknown as Record<string, unknown>, format: 'jwk' });\n const data = Buffer.from(`${parts[0]}.${parts[1]}`, 'utf8');\n const signature = Buffer.from(parts[2], 'base64url');\n if (!verifier(data, publicKey, signature)) {\n throw new AccessTokenError('Signature verification failed', 'invalid_token');\n }\n\n // Temporal and audience checks.\n const now = Math.floor(Date.now() / 1000);\n const skew = options.clockSkew ?? 60;\n if (typeof claims.exp !== 'number' || claims.exp < now - skew) {\n throw new AccessTokenError('Access token expired', 'invalid_token');\n }\n if (claims.nbf !== undefined && (typeof claims.nbf !== 'number' || claims.nbf > now + skew)) {\n throw new AccessTokenError('Access token not yet valid', 'invalid_token');\n }\n const aud = claims.aud;\n const audiences = typeof aud === 'string' ? [aud] : Array.isArray(aud) ? aud : [];\n if (!audiences.includes(options.resource)) {\n throw new AccessTokenError('Invalid audience', 'invalid_token');\n }\n if (typeof claims.sub !== 'string' || claims.sub === '') {\n throw new AccessTokenError('Missing sub claim', 'invalid_token');\n }\n if (claims.token_use === 'test') {\n throw new AccessTokenError('Test tokens are not accepted by resource servers', 'invalid_token');\n }\n\n // DPoP binding (RFC 9449 §7.1).\n const cnf = isObject(claims.cnf) ? claims.cnf : undefined;\n const jkt = typeof cnf?.jkt === 'string' ? cnf.jkt : undefined;\n if (jkt) {\n await verifyDpopBinding(token, jkt, options);\n } else if (options.requireDpop) {\n throw new AccessTokenError('Access token is not DPoP-bound', 'invalid_token');\n } else if (options.dpop?.authorizationScheme && options.dpop.authorizationScheme.toLowerCase() === DPOP_SCHEME.toLowerCase()) {\n throw new AccessTokenError('Access token is not DPoP-bound but was presented with the DPoP scheme', 'invalid_token');\n }\n\n return claims as unknown as AccessTokenClaims;\n}\n\nasync function verifyDpopBinding(token: string, jkt: string, options: VerifyAccessTokenOptions): Promise<void> {\n const incoming = options.dpop;\n if (!incoming) {\n throw new AccessTokenError(\n 'Access token is DPoP-bound: pass the incoming request (method, url, proof, authorizationScheme) in `dpop`',\n 'invalid_dpop_proof',\n );\n }\n if ((incoming.authorizationScheme ?? '').toLowerCase() !== DPOP_SCHEME.toLowerCase()) {\n throw new AccessTokenError('DPoP-bound access token must be presented with the DPoP scheme', 'invalid_token');\n }\n if (!incoming.proof) {\n throw new AccessTokenError('DPoP proof required for sender-constrained token', 'invalid_dpop_proof');\n }\n const proof = await verifyDpopProof(incoming.proof, {\n method: incoming.method,\n url: incoming.url,\n accessToken: token,\n nonce: incoming.nonce,\n replayCache: options.replayCache,\n });\n if (proof.thumbprint !== jkt) {\n throw new AccessTokenError('DPoP key does not match token binding', 'invalid_dpop_proof');\n }\n}\n\nfunction assertAlgMatchesKey(alg: string, jwk: AAuthJwk): void {\n const compatible =\n (jwk.kty === 'RSA' && (alg.startsWith('RS') || alg.startsWith('PS'))) ||\n (jwk.kty === 'EC' && alg.startsWith('ES')) ||\n (jwk.kty === 'OKP' && alg === 'EdDSA');\n if (!compatible) {\n throw new AccessTokenError(`Algorithm ${alg} incompatible with key type ${jwk.kty}`, 'invalid_token');\n }\n if (jwk.alg && jwk.alg !== alg) {\n throw new AccessTokenError(`Algorithm ${alg} does not match key alg ${jwk.alg}`, 'invalid_token');\n }\n}\n\n// ─── DPoP proof verification (resource side) ──────────────────────────\n\nexport interface VerifyDpopProofOptions {\n /** Method of the incoming request. */\n method: string;\n /** Full URL of the incoming request. */\n url: string;\n /** The presented access token, when the proof must carry `ath`. */\n accessToken?: string;\n /** Expected `nonce`, when this server issues nonces. */\n nonce?: string;\n /** Replay cache for `jti`. Default: in-memory, 300 s. */\n replayCache?: DpopReplayCache;\n /** Clock override in epoch seconds (tests only). */\n now?: () => number;\n}\n\nexport interface VerifiedDpopProof {\n /** The proof's public key. */\n jwk: AAuthJwk;\n /** RFC 7638 thumbprint of `jwk`. Compare with the token's `cnf.jkt`. */\n thumbprint: string;\n claims: { jti: string; htm: string; htu: string; iat: number; ath?: string; nonce?: string; [claim: string]: unknown };\n}\n\n/**\n * Verify a DPoP proof JWT against the incoming request, the same way the\n * LumoAuth server does: header (`typ`, allow-listed `alg`, public `jwk`\n * matching the algorithm), signature, `htm`, `htu` (scheme, host, port,\n * path; query and fragment ignored), `iat` window, `jti` replay, `ath` when\n * an access token is given, `nonce` when one is expected.\n */\nexport async function verifyDpopProof(proof: string, options: VerifyDpopProofOptions): Promise<VerifiedDpopProof> {\n const parts = proof.split('.');\n if (parts.length !== 3) {\n throw new AccessTokenError('Invalid DPoP proof format', 'invalid_dpop_proof');\n }\n let header: unknown;\n let claims: unknown;\n try {\n header = decodeSegment(parts[0]);\n claims = decodeSegment(parts[1]);\n } catch {\n throw new AccessTokenError('Invalid DPoP proof encoding', 'invalid_dpop_proof');\n }\n if (!isObject(header) || !isObject(claims)) {\n throw new AccessTokenError('Invalid DPoP proof format', 'invalid_dpop_proof');\n }\n if (header.typ !== DPOP_PROOF_TYP) {\n throw new AccessTokenError('DPoP proof typ must be dpop+jwt', 'invalid_dpop_proof');\n }\n const alg = typeof header.alg === 'string' ? header.alg : '';\n const expectedKey = DPOP_ALG_KEYS[alg];\n if (!expectedKey) {\n throw new AccessTokenError(`Disallowed DPoP proof algorithm: ${alg || '(none)'}`, 'invalid_dpop_proof');\n }\n const jwk = header.jwk;\n if (!isObject(jwk) || typeof jwk.kty !== 'string') {\n throw new AccessTokenError('DPoP proof is missing its jwk', 'invalid_dpop_proof');\n }\n if ('d' in jwk) {\n throw new AccessTokenError('DPoP proof jwk must not carry private members', 'invalid_dpop_proof');\n }\n if (jwk.kty !== expectedKey.kty || (expectedKey.crv && jwk.crv !== expectedKey.crv)) {\n throw new AccessTokenError(`DPoP proof jwk does not match ${alg}`, 'invalid_dpop_proof');\n }\n if (typeof jwk.alg === 'string' && jwk.alg !== alg) {\n throw new AccessTokenError('DPoP proof jwk alg does not match the header', 'invalid_dpop_proof');\n }\n\n let publicKey: KeyObject;\n try {\n publicKey = createPublicKey({ key: jwk as Record<string, unknown>, format: 'jwk' });\n } catch {\n throw new AccessTokenError('DPoP proof jwk is not a valid public key', 'invalid_dpop_proof');\n }\n const data = Buffer.from(`${parts[0]}.${parts[1]}`, 'utf8');\n const signature = Buffer.from(parts[2], 'base64url');\n let valid = false;\n try {\n valid = JWS_VERIFIERS[alg](data, publicKey, signature);\n } catch {\n valid = false;\n }\n if (!valid) {\n throw new AccessTokenError('DPoP proof signature verification failed', 'invalid_dpop_proof');\n }\n\n if (typeof claims.htm !== 'string' || claims.htm.toUpperCase() !== options.method.toUpperCase()) {\n throw new AccessTokenError('DPoP proof htm does not match the request method', 'invalid_dpop_proof');\n }\n if (typeof claims.htu !== 'string' || !htuMatches(claims.htu, options.url)) {\n throw new AccessTokenError('DPoP proof htu does not match the request URL', 'invalid_dpop_proof');\n }\n const now = options.now ? options.now() : Math.floor(Date.now() / 1000);\n if (typeof claims.iat !== 'number' || claims.iat > now + DPOP_IAT_FUTURE_SECONDS || claims.iat < now - DPOP_IAT_PAST_SECONDS) {\n throw new AccessTokenError('DPoP proof iat is outside the accepted window', 'invalid_dpop_proof');\n }\n if (typeof claims.jti !== 'string' || claims.jti.length < DPOP_JTI_MIN_LENGTH) {\n throw new AccessTokenError('DPoP proof jti is missing or too short', 'invalid_dpop_proof');\n }\n if (options.nonce !== undefined && claims.nonce !== options.nonce) {\n throw new AccessTokenError('DPoP proof nonce does not match', 'invalid_dpop_proof');\n }\n if (options.accessToken !== undefined) {\n const expectedAth = createHash('sha256').update(options.accessToken, 'ascii').digest('base64url');\n if (claims.ath !== expectedAth) {\n throw new AccessTokenError('DPoP proof ath does not match the access token', 'invalid_dpop_proof');\n }\n }\n\n const thumbprint = jwkThumbprint(jwk as AAuthJwk);\n const cache = options.replayCache ?? sharedReplayCache;\n if (!(await cache.add(`${thumbprint}:${claims.jti}`, DPOP_JTI_TTL_SECONDS))) {\n throw new AccessTokenError('DPoP proof jti was already used', 'invalid_dpop_proof');\n }\n\n return { jwk: jwk as AAuthJwk, thumbprint, claims: claims as VerifiedDpopProof['claims'] };\n}\n\nfunction htuMatches(htu: string, requestUrl: string): boolean {\n try {\n return dpopHtu(htu) === dpopHtu(requestUrl);\n } catch {\n return false;\n }\n}\n\n// ─── Verifier factory ─────────────────────────────────────────────────\n\nexport interface AccessTokenVerifierOptions extends Omit<VerifyAccessTokenOptions, 'dpop' | 'jwksCache' | 'replayCache'> {\n /** Replay cache for proof `jti`s. Default: one in-memory cache per verifier. */\n replayCache?: DpopReplayCache;\n}\n\n/** A request as a resource server sees it, for `verifyRequest`. */\nexport interface IncomingRequest {\n method: string;\n /** The full public URL of the request. */\n url: string;\n /** `Authorization` and `DPoP` headers, any case; or a `Headers` object. */\n headers: Headers | Record<string, string | string[] | undefined>;\n /** Expected nonce, when this server issues nonces. */\n nonce?: string;\n}\n\nexport interface AccessTokenVerifier {\n /** Verify a token; `dpop` is the incoming request when the token may be bound. */\n verify(token: string, dpop?: IncomingDpopProof): Promise<AccessTokenClaims>;\n /** Read `Authorization` (+ `DPoP`) from a request and verify. */\n verifyRequest(request: IncomingRequest): Promise<AccessTokenClaims>;\n /** Drop the cached JWKS. */\n clearCache(): void;\n}\n\n/**\n * A verifier with its own JWKS and replay caches, for a long-running\n * resource server.\n *\n * @example\n * ```ts\n * const verifier = createAccessTokenVerifier({\n * issuer: 'https://app.lumoauth.dev/orgs/acme-corp/api/v1',\n * resource: 'https://mcp.example.com/mcp',\n * });\n * const claims = await verifier.verifyRequest({ method: req.method, url, headers: req.headers });\n * ```\n */\nexport function createAccessTokenVerifier(options: AccessTokenVerifierOptions): AccessTokenVerifier {\n const jwksCache = new JwksCache(options.fetch);\n const replayCache = options.replayCache ?? new InMemoryDpopReplayCache();\n const base: VerifyAccessTokenOptions = { ...options, jwksCache, replayCache };\n\n return {\n verify: (token, dpop) => verifyAccessToken(token, dpop ? { ...base, dpop } : base),\n verifyRequest: async (request) => {\n const authorization = parseAuthorizationHeader(headerValue(request.headers, 'authorization'));\n if (!authorization) {\n throw new AccessTokenError('Missing or malformed Authorization header', 'invalid_token');\n }\n if (!['bearer', 'dpop'].includes(authorization.scheme.toLowerCase())) {\n throw new AccessTokenError(`Unsupported authorization scheme: ${authorization.scheme}`, 'invalid_token');\n }\n return verifyAccessToken(authorization.token, {\n ...base,\n dpop: {\n method: request.method,\n url: request.url,\n proof: headerValue(request.headers, 'dpop'),\n authorizationScheme: authorization.scheme,\n nonce: request.nonce,\n },\n });\n },\n clearCache: () => jwksCache.clear(),\n };\n}\n\nfunction headerValue(headers: IncomingRequest['headers'], name: string): string | null {\n if (typeof Headers !== 'undefined' && headers instanceof Headers) {\n return headers.get(name);\n }\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === name) {\n if (Array.isArray(value)) return value[0] ?? null;\n return value ?? null;\n }\n }\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;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AM,MAAM;AAC5B,UAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,CAAC,KAAK;AAC7C,aAAO,SAAS;AAAA,IACpB;AAAA,EACJ;AACA,SAAO;AACX;;;AVvgBA,IAAAM,iBA4BO;","names":["cryptoSign","cryptoConstants","import_node_crypto","import_node_crypto","cryptoSign","cryptoVerify","import_node_crypto","import_shared","cryptoVerify","import_shared","envVar","import_node_crypto","import_shared","b64url","cryptoSign","import_shared","import_shared","envVar","import_node_crypto","import_shared","JWS_VERIFIERS","cryptoVerify","pss","p1363","decodeSegment","assertAlgMatchesKey","import_shared"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/agent.ts","../src/client-assertion.ts","../src/keys.ts","../src/signing.ts","../src/verify.ts","../src/errors.ts","../src/client.ts","../src/dpop.ts","../src/attest.ts","../src/access-token.ts"],"sourcesContent":["// ─── @lumoauth/agent — the agent SDK ─────────────────────────────────\n//\n// Two layers:\n// - `LumoAgent` — high-level client (client-credentials auth, ask/\n// isAllowed, jit/delegation/approvals/mcp namespaces). Python parity\n// with `lumoauth.LumoAuthAgent`.\n// - `AAuthClient` + signing/verify primitives — the AAuth protocol\n// (cryptographic agent identity, RFC 9421 HTTP message signing).\n// Uses `node:crypto`, therefore Node-only (>= 18).\n\nexport { LumoAgent, type LumoAgentOptions } from './agent';\n\nexport {\n AAuthClient,\n type AAuthClientOptions,\n type AAuthTokenResponse,\n type AAuthAuthorizationRequired,\n type AAuthIssuerMetadata,\n type AAuthAgentMetadata,\n type AAuthResourceMetadata,\n} from './client';\n\nexport {\n generateKeypair,\n jwkThumbprint,\n publicJwkFromPrivateKey,\n type AAuthJwk,\n type AAuthKeypair,\n} from './keys';\n\nexport {\n signRequest,\n buildSignatureBase,\n signatureParams,\n signSignatureBase,\n verifySignatureBase,\n contentDigestSha256,\n generateNonce,\n AAUTH_COVERED_COMPONENTS,\n type SignRequestOptions,\n} from './signing';\n\nexport {\n verifyAuthToken,\n decodeJwt,\n type AAuthTokenClaims,\n type VerifyAuthTokenOptions,\n} from './verify';\n\n// ─── private_key_jwt client assertions (RFC 7523) ─────────────────────\nexport {\n ClientAssertionSigner,\n CLIENT_ASSERTION_TYPE,\n CLIENT_ASSERTION_TYP,\n MAX_ASSERTION_LIFETIME_SECONDS,\n issuerFor,\n type ClientAssertionAlgorithm,\n type ClientAssertionJwk,\n type ClientAssertionSignerOptions,\n} from './client-assertion';\n\n// ─── DPoP (RFC 9449) ──────────────────────────────────────────────────\nexport {\n DpopProofSigner,\n dpopAth,\n type DpopAlgorithm,\n type DpopJwk,\n type DpopProofSignerOptions,\n} from './dpop';\nexport {\n fetchWithDpop,\n buildDpopHeaders,\n dpopHtu,\n DPOP_SCHEME,\n DPOP_NONCE_HEADER,\n USE_DPOP_NONCE,\n type DpopProofProvider,\n type DpopProofRequest,\n type DpopHeadersInput,\n type FetchWithDpopOptions,\n} from '@lumoauth/shared';\n\n// ─── Workload attestation ─────────────────────────────────────────────\nexport { attestWorkload, type AttestWorkloadOptions, type AttestWorkloadResult } from './attest';\n\n// ─── Core access token (at+jwt) verification, resource-server side ────\nexport {\n verifyAccessToken,\n createAccessTokenVerifier,\n verifyDpopProof,\n parseAuthorizationHeader,\n accessTokenScopes,\n AccessTokenError,\n JwksCache,\n InMemoryDpopReplayCache,\n type AccessTokenClaims,\n type ActorClaim,\n type AccessTokenVerifier,\n type AccessTokenVerifierOptions,\n type VerifyAccessTokenOptions,\n type IncomingDpopProof,\n type IncomingRequest,\n type DpopReplayCache,\n type VerifyDpopProofOptions,\n type VerifiedDpopProof,\n} from './access-token';\n\nexport { AAuthError } from './errors';\n\n// The shared error taxonomy, so agent code can catch these without a direct\n// dependency on @lumoauth/shared.\nexport {\n LumoAuthError,\n LumoAuthApiError,\n LumoAuthAuthenticationError,\n LumoAuthPermissionDeniedError,\n LumoAuthNotFoundError,\n LumoAuthRateLimitError,\n LumoAuthValidationError,\n LumoAuthConfigError,\n LumoAuthNetworkError,\n LumoAuthApprovalDeniedError,\n LumoAuthApprovalTimeoutError,\n LumoAuthApprovalNotDeliveredError,\n LumoAuthBudgetExceededError,\n type ApprovalNotDeliveredReason,\n type ApprovalResult,\n type ApprovalRequestResult,\n type CreateApprovalRequest,\n type RequireApprovalRequest,\n type AgentMcpToolDecision,\n type AgentBudget,\n type UsageReport,\n type UsageReportResult,\n type McpAuthorizeToolOptions,\n type McpSubject,\n type McpSubjectType,\n type McpToolDecision,\n type McpToolResource,\n} from '@lumoauth/shared';\n","import {\n HttpClient,\n AgentsModule,\n ApprovalsModule,\n DelegationModule,\n JitModule,\n McpModule,\n LumoAuthApiError,\n LumoAuthConfigError,\n LumoAuthNetworkError,\n ROUTES,\n buildPath,\n fetchWithDpop,\n type DpopProofProvider,\n type AgentAskResult,\n type AgentIdentity,\n type AgentBudget,\n type AgentMcpToolDecision,\n type UsageReport,\n type UsageReportResult,\n} from '@lumoauth/shared';\nimport { CLIENT_ASSERTION_TYPE, ClientAssertionSigner, issuerFor } from './client-assertion';\n\n// ─── Types ────────────────────────────────────────────────────────────\n\nexport interface LumoAgentOptions {\n /**\n * LumoAuth instance URL. Defaults to `process.env.LUMOAUTH_URL` or\n * `https://app.lumoauth.dev`.\n */\n baseUrl?: string;\n /** Organization slug. Defaults to `process.env.LUMOAUTH_ORG_ID`. */\n orgId?: string;\n /** OAuth client ID. Defaults to `process.env.AGENT_CLIENT_ID`. */\n clientId?: string;\n /** OAuth client secret. Defaults to `process.env.AGENT_CLIENT_SECRET`. */\n clientSecret?: string;\n /**\n * For an agent registered with the **Private key JWT** identity type: a\n * `ClientAssertionSigner`, or the PEM private key. The agent then signs a\n * client assertion (RFC 7523) for every token request and needs no\n * `clientSecret`. Defaults to `process.env.AGENT_PRIVATE_KEY` (PEM).\n */\n privateKey?: ClientAssertionSigner | string;\n /** `kid` of the registered public key, used with a PEM `privateKey`. Defaults to `process.env.AGENT_KEY_ID`. */\n keyId?: string;\n /**\n * The organization's issuer identifier, the assertion's `aud`. Defaults to\n * `{baseUrl}/orgs/{orgId}/api/v1`; set it on a custom domain.\n */\n issuer?: string;\n /** Scopes to request. When omitted the server grants the agent's defaults. */\n scopes?: string[];\n /** OAuth callback URL for the delegation consent flow. */\n redirectUri?: string;\n /** Custom fetch implementation. */\n fetch?: typeof globalThis.fetch;\n /** Request timeout in milliseconds. Default: 30 000 ms. */\n timeout?: number;\n /**\n * DPoP proof signer (RFC 9449), e.g. `DpopProofSigner.generate()`. When\n * set, the client-credentials token and every exchanged token (MCP,\n * delegation) are sender-constrained to its key, and every request\n * carries `Authorization: DPoP <token>` plus a proof. Needed for MCP\n * servers registered with \"Require DPoP\".\n */\n dpop?: DpopProofProvider;\n}\n\ninterface TokenState {\n accessToken: string;\n /** `DPoP` or `Bearer`, as the token endpoint reported it. */\n tokenType: string;\n /** Epoch ms after which we refresh (real expiry minus the safety buffer). */\n refreshAt: number;\n scopes: string[];\n}\n\nfunction envVar(name: string): string | undefined {\n return typeof process !== 'undefined' && process.env ? process.env[name] : undefined;\n}\n\n/** Safety margin (ms) subtracted from `expires_in` so we refresh early. */\nconst TOKEN_REFRESH_BUFFER_MS = 60_000;\n\n// ─── LumoAgent ────────────────────────────────────────────────────────\n\n/**\n * High-level agent client — the Node.js counterpart of the Python SDK's\n * `LumoAuthAgent`.\n *\n * Handles the full agent lifecycle:\n * - OAuth 2.0 client-credentials authentication with transparent refresh\n * (60 s safety buffer)\n * - Preflight capability checks (`ask` / `isAllowed`)\n * - Self-inspection (`getCurrentAgent`, `capabilities`, `budget`)\n * - `jit`, `delegation`, `approvals`, and `mcp` namespaces\n *\n * For the AAuth protocol (cryptographic agent identity, RFC 9421 message\n * signing) use {@link AAuthClient} from this same package.\n *\n * @example\n * ```ts\n * import { LumoAgent } from '@lumoauth/agent';\n *\n * const agent = new LumoAgent(); // reads env vars by default\n * if (await agent.isAllowed('document:read', { id: 'doc_99' })) {\n * // ... do the thing\n * }\n *\n * const approval = await agent.approvals.require({\n * taskId: 'wire-001',\n * reason: 'Wire $4,500 to vendor INV-7741',\n * impact: 'high',\n * onBehalfOf: 'ada@acme.com',\n * });\n * ```\n */\nexport class LumoAgent {\n readonly baseUrl: string;\n readonly orgId: string;\n readonly clientId: string;\n\n /** Agent identity — ask/isAllowed, self-inspection, registration. */\n readonly agents: AgentsModule;\n /** Just-in-Time permissions — ephemeral tasks and scoped tokens. */\n readonly jit: JitModule;\n /** Chain of Agency — RFC 8693 delegation and nested agent chains. */\n readonly delegation: DelegationModule;\n /** Push-approval-for-agent-actions. */\n readonly approvals: ApprovalsModule;\n /** MCP servers: token exchange and per-tool checks (`authorizeTool`). */\n readonly mcp: McpModule;\n\n private readonly clientSecret: string;\n private readonly assertionSigner: ClientAssertionSigner | undefined;\n private readonly issuer: string | undefined;\n private readonly scopes: string[] | undefined;\n private readonly fetchFn: typeof globalThis.fetch;\n private readonly dpop: DpopProofProvider | undefined;\n private token: TokenState | null = null;\n private refreshPromise: Promise<string> | null = null;\n\n constructor(options: LumoAgentOptions = {}) {\n this.baseUrl = (options.baseUrl ?? envVar('LUMOAUTH_URL') ?? 'https://app.lumoauth.dev').replace(/\\/+$/, '');\n this.orgId = options.orgId ?? envVar('LUMOAUTH_ORG_ID') ?? '';\n this.clientId = options.clientId ?? envVar('AGENT_CLIENT_ID') ?? '';\n const privateKey = options.privateKey ?? envVar('AGENT_PRIVATE_KEY');\n const keyId = options.keyId ?? envVar('AGENT_KEY_ID');\n this.assertionSigner =\n privateKey === undefined || privateKey === ''\n ? undefined\n : privateKey instanceof ClientAssertionSigner\n ? privateKey\n : ClientAssertionSigner.fromPem(privateKey, { keyId });\n // A private key JWT agent has no secret; an AGENT_CLIENT_SECRET left\n // in the environment must not become a second method.\n this.clientSecret = options.clientSecret ?? (this.assertionSigner ? '' : envVar('AGENT_CLIENT_SECRET') ?? '');\n this.issuer = options.issuer;\n this.scopes = options.scopes;\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.dpop = options.dpop;\n\n if (!this.clientId || (!this.clientSecret && !this.assertionSigner)) {\n throw new LumoAuthConfigError(\n 'Agent credentials required. Set AGENT_CLIENT_ID and AGENT_CLIENT_SECRET ' +\n '(or AGENT_PRIVATE_KEY for a private key JWT agent), or pass clientId with ' +\n 'clientSecret or privateKey to the constructor.',\n );\n }\n if (this.clientSecret && this.assertionSigner) {\n throw new LumoAuthConfigError(\n 'Pass clientSecret or privateKey, not both: an agent authenticates with one method.',\n );\n }\n\n const tokenProvider = () => this.getAccessToken();\n const http = new HttpClient({\n baseUrl: this.baseUrl,\n token: tokenProvider,\n timeout: options.timeout,\n fetch: options.fetch,\n dpop: this.dpop,\n });\n\n this.agents = new AgentsModule(http, this.orgId);\n this.jit = new JitModule(http, this.orgId);\n this.approvals = new ApprovalsModule(http, this.orgId);\n this.mcp = new McpModule({\n baseUrl: this.baseUrl,\n orgId: this.orgId,\n token: tokenProvider,\n fetch: options.fetch,\n http,\n dpop: this.dpop,\n });\n this.delegation = new DelegationModule({\n baseUrl: this.baseUrl,\n orgId: this.orgId,\n clientId: this.clientId,\n clientSecret: this.clientSecret,\n redirectUri: options.redirectUri,\n agentToken: tokenProvider,\n fetch: options.fetch,\n dpop: this.dpop,\n });\n }\n\n // ── Authentication ────────────────────────────────────────────────\n\n /**\n * Authenticate with the client-credentials flow. Called automatically\n * by every API method — invoke it directly only to fail fast at\n * startup or to request non-default scopes.\n */\n async authenticate(scopes?: string[]): Promise<string> {\n const form: Record<string, string> = {\n grant_type: 'client_credentials',\n client_id: this.clientId,\n };\n if (this.assertionSigner) {\n form.client_assertion_type = CLIENT_ASSERTION_TYPE;\n form.client_assertion = this.createClientAssertion();\n } else {\n form.client_secret = this.clientSecret;\n }\n const requested = scopes ?? this.scopes;\n if (requested?.length) form.scope = requested.join(' ');\n\n const url = `${this.baseUrl}${buildPath(ROUTES['oauth.token'].path, { orgId: this.requireOrgId() })}`;\n const init: RequestInit = {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams(form),\n };\n let res: Response;\n try {\n // With a DPoP signer the proof binds the new token to our key; a\n // `use_dpop_nonce` answer is retried once with the server's nonce.\n res = this.dpop\n ? await fetchWithDpop(this.fetchFn, url, init, this.dpop)\n : await this.fetchFn(url, init);\n } catch (error) {\n throw new LumoAuthNetworkError(\n `Agent authentication failed: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n\n const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n if (!res.ok || typeof body.access_token !== 'string') {\n throw new LumoAuthApiError(\n typeof body.error_description === 'string'\n ? body.error_description\n : `Agent authentication failed (HTTP ${res.status})`,\n typeof body.error === 'string' ? body.error : 'AUTHENTICATION_ERROR',\n res.status,\n body,\n );\n }\n\n const expiresIn = typeof body.expires_in === 'number' ? body.expires_in : 3600;\n this.token = {\n accessToken: body.access_token,\n tokenType: typeof body.token_type === 'string' ? body.token_type : 'Bearer',\n refreshAt: Date.now() + expiresIn * 1000 - TOKEN_REFRESH_BUFFER_MS,\n scopes: typeof body.scope === 'string' ? body.scope.split(' ').filter(Boolean) : [],\n };\n return this.token.accessToken;\n }\n\n /**\n * `token_type` of the last successful authentication: `DPoP` when the\n * token is sender-constrained, otherwise `Bearer`; `null` before the\n * first sign-in. Present the token with that `Authorization` scheme.\n */\n get tokenType(): string | null {\n return this.token?.tokenType ?? null;\n }\n\n /**\n * A new `private_key_jwt` client assertion for this agent (single-use),\n * addressed to `issuer` or `{baseUrl}/orgs/{orgId}/api/v1`.\n */\n createClientAssertion(): string {\n if (!this.assertionSigner) {\n throw new LumoAuthConfigError('This agent signs no client assertions: create it with privateKey.');\n }\n const audience = this.issuer ?? issuerFor(this.baseUrl, this.requireOrgId());\n return this.assertionSigner.create(this.clientId, audience);\n }\n\n /** The client assertion signer this agent was configured with, if any. */\n get clientAssertionSigner(): ClientAssertionSigner | undefined {\n return this.assertionSigner;\n }\n\n /** The DPoP proof signer this agent was configured with, if any. */\n get dpopSigner(): DpopProofProvider | undefined {\n return this.dpop;\n }\n\n /**\n * The current access token, re-authenticating transparently when it is\n * missing or within 60 s of expiry. Concurrent callers share one\n * in-flight token request.\n */\n async getAccessToken(): Promise<string> {\n if (this.token && Date.now() < this.token.refreshAt) {\n return this.token.accessToken;\n }\n this.refreshPromise ??= this.authenticate(\n this.token?.scopes.length ? this.token.scopes : undefined,\n ).finally(() => {\n this.refreshPromise = null;\n });\n return this.refreshPromise;\n }\n\n /** Scopes granted by the last successful authentication. */\n get tokenScopes(): string[] {\n return this.token ? [...this.token.scopes] : [];\n }\n\n // ── Ask API & self-inspection (delegates to `agents`) ─────────────\n\n /** Preflight check: is the agent authorised to perform `action`? */\n async ask(action: string, context?: Record<string, unknown>): Promise<AgentAskResult> {\n return this.agents.ask(action, context);\n }\n\n /** Convenience wrapper: `true` when `action` is allowed. */\n async isAllowed(action: string, context?: Record<string, unknown>): Promise<boolean> {\n return this.agents.isAllowed(action, context);\n }\n\n /**\n * May this agent run `tool` on the registered MCP server `serverId`?\n * A deny returns `{ allowed: false }` and does not throw.\n */\n async authorizeMcpTool(serverId: string, tool: string): Promise<AgentMcpToolDecision> {\n return this.agents.authorizeMcpTool(serverId, tool);\n }\n\n /** The agent's own identity, capabilities, and workspace. */\n async getCurrentAgent(): Promise<AgentIdentity> {\n return this.agents.me();\n }\n\n /** The agent's declared capability slugs. */\n async capabilities(): Promise<string[]> {\n return this.agents.capabilities();\n }\n\n /** The agent's budget policy (empty object when no policy is set). */\n async budget(): Promise<AgentBudget> {\n return this.agents.budget();\n }\n\n /**\n * Report the model tokens and cost that the agent just used, for example\n * the `usage` that the model provider returned. LumoAuth does not see\n * model calls, so token and cost limits count only reported usage. The\n * result's `budget.exhausted` says whether the next metered call (Ask,\n * token or JIT request) will get 429.\n *\n * ```ts\n * const resp = await llm.chat(...);\n * const { budget } = await agent.reportUsage({ tokens: resp.usage.total_tokens, costUsd: 0.0042 });\n * if (budget.exhausted) throw new Error('budget spent');\n * ```\n */\n async reportUsage(report: UsageReport): Promise<UsageReportResult> {\n return this.agents.reportUsage(report);\n }\n\n // ── Internal ──────────────────────────────────────────────────────\n\n private requireOrgId(): string {\n if (!this.orgId) {\n throw new LumoAuthConfigError(\n 'orgId is required — pass it to the LumoAgent constructor or set LUMOAUTH_ORG_ID.',\n );\n }\n return this.orgId;\n }\n}\n","import {\n createPrivateKey,\n createPublicKey,\n generateKeyPairSync,\n randomBytes,\n sign as cryptoSign,\n constants as cryptoConstants,\n type KeyObject,\n} from 'node:crypto';\n\n/**\n * `private_key_jwt` client assertions (RFC 7523 §2.2, OpenID Connect Core §9).\n *\n * A LumoAuth agent registered with the **Private key JWT** identity type has\n * no client secret. Whenever it needs a token, it signs a short-lived JWT with\n * its private key and sends that instead:\n *\n * ```ts\n * const agent = new LumoAgent({\n * clientId: 'agt_0123456789abcdef',\n * privateKey: ClientAssertionSigner.fromPem(process.env.AGENT_PRIVATE_KEY!, { keyId: 'agent-2026-11' }),\n * });\n * ```\n *\n * Register `signer.jwks` (the public key only) on the agent.\n *\n * What the server checks, and what `create()` produces:\n * - header `alg` (ES256, ES384, ES512, EdDSA, RS256–RS512 or PS256–PS512),\n * `kid` and `typ: client-authentication+jwt`;\n * - `iss` = `sub` = the agent ID, `aud` = the organization's issuer\n * identifier alone (not the token endpoint URL);\n * - `iat` now, `exp` at most 10 minutes later (60 s by default) and a random\n * `jti`: every assertion is single-use, so sign a new one per request.\n */\n\n/** `client_assertion_type` for a JWT client assertion. */\nexport const CLIENT_ASSERTION_TYPE = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';\n/** The `typ` header of a client-authentication JWT. */\nexport const CLIENT_ASSERTION_TYP = 'client-authentication+jwt';\n/** The longest validity LumoAuth accepts for an assertion, in seconds. */\nexport const MAX_ASSERTION_LIFETIME_SECONDS = 600;\n\nexport type ClientAssertionAlgorithm =\n | 'ES256'\n | 'ES384'\n | 'ES512'\n | 'EdDSA'\n | 'RS256'\n | 'RS384'\n | 'RS512'\n | 'PS256'\n | 'PS384'\n | 'PS512';\n\nconst RSA_ALGORITHMS: readonly ClientAssertionAlgorithm[] = ['RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512'];\nconst EC_ALGORITHM_BY_CURVE: Record<string, ClientAssertionAlgorithm> = {\n prime256v1: 'ES256',\n 'P-256': 'ES256',\n secp384r1: 'ES384',\n 'P-384': 'ES384',\n secp521r1: 'ES512',\n 'P-521': 'ES512',\n};\n\nexport interface ClientAssertionSignerOptions {\n /** PEM private key (PKCS#8, SEC 1 or PKCS#1): EC P-256/P-384/P-521, Ed25519 or RSA ≥ 2048 bits. */\n privateKeyPem?: string;\n /** A Node `KeyObject` private key, as an alternative to `privateKeyPem`. */\n privateKey?: KeyObject;\n /** `kid` of the registered public key. Required by the server when the agent has several keys. */\n keyId?: string;\n /** JWS algorithm. Defaults to the key's natural one (ES256/ES384/ES512, EdDSA, RS256); RSA keys may also use RS384/RS512/PS256/PS384/PS512. */\n algorithm?: ClientAssertionAlgorithm;\n /** Seconds until `exp`, 1–600. Default 60. */\n lifetimeSeconds?: number;\n /** Clock override in epoch seconds (tests only). */\n now?: () => number;\n}\n\n/** A public JWK as registered on the agent. */\nexport interface ClientAssertionJwk {\n kty: string;\n kid?: string;\n alg: ClientAssertionAlgorithm;\n use: 'sig';\n crv?: string;\n x?: string;\n y?: string;\n n?: string;\n e?: string;\n}\n\nexport class ClientAssertionSigner {\n /** The JWS algorithm the assertions are signed with. */\n readonly algorithm: ClientAssertionAlgorithm;\n /** `kid` put in every assertion header, if set. */\n readonly keyId: string | undefined;\n /** Seconds until `exp`. */\n readonly lifetimeSeconds: number;\n\n private readonly key: KeyObject;\n private readonly now: () => number;\n\n /** Generate a new key: ES256 (default), ES384, ES512, EdDSA, or an RSA algorithm (2048-bit key). */\n static generate(algorithm: ClientAssertionAlgorithm = 'ES256', keyId?: string): ClientAssertionSigner {\n let privateKey: KeyObject;\n if (algorithm === 'ES256' || algorithm === 'ES384' || algorithm === 'ES512') {\n const namedCurve = { ES256: 'P-256', ES384: 'P-384', ES512: 'P-521' }[algorithm];\n privateKey = generateKeyPairSync('ec', { namedCurve }).privateKey;\n } else if (algorithm === 'EdDSA') {\n privateKey = generateKeyPairSync('ed25519').privateKey;\n } else if (RSA_ALGORITHMS.includes(algorithm)) {\n privateKey = generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey;\n } else {\n throw new Error(`Unsupported client assertion algorithm: ${String(algorithm)}`);\n }\n return new ClientAssertionSigner({ privateKey, keyId, algorithm });\n }\n\n /** Load a PEM private key. */\n static fromPem(pem: string, options: Omit<ClientAssertionSignerOptions, 'privateKeyPem' | 'privateKey'> = {}): ClientAssertionSigner {\n return new ClientAssertionSigner({ ...options, privateKeyPem: pem });\n }\n\n constructor(options: ClientAssertionSignerOptions) {\n if (options.privateKey) {\n this.key = options.privateKey;\n } else if (options.privateKeyPem) {\n this.key = createPrivateKey(options.privateKeyPem);\n } else {\n throw new Error('ClientAssertionSigner needs privateKeyPem or privateKey');\n }\n if (this.key.type !== 'private') {\n throw new Error('ClientAssertionSigner needs a private key');\n }\n const natural = naturalAlgorithm(this.key);\n const chosen = options.algorithm ?? natural;\n if (this.key.asymmetricKeyType === 'rsa') {\n if (!RSA_ALGORITHMS.includes(chosen)) {\n throw new Error(`${chosen} does not fit an RSA key; use one of ${RSA_ALGORITHMS.join(', ')}`);\n }\n const bits = this.key.asymmetricKeyDetails?.modulusLength ?? 0;\n if (bits < 2048) throw new Error('RSA keys must be at least 2048 bits');\n } else if (chosen !== natural) {\n throw new Error(`${chosen} does not fit this key; it signs with ${natural}`);\n }\n const lifetime = options.lifetimeSeconds ?? 60;\n if (!Number.isInteger(lifetime) || lifetime < 1 || lifetime > MAX_ASSERTION_LIFETIME_SECONDS) {\n throw new Error(`lifetimeSeconds must be an integer from 1 to ${MAX_ASSERTION_LIFETIME_SECONDS}`);\n }\n this.algorithm = chosen;\n this.keyId = options.keyId;\n this.lifetimeSeconds = lifetime;\n this.now = options.now ?? (() => Math.floor(Date.now() / 1000));\n }\n\n /** Sign one assertion for `clientId` (the agent ID) and `audience` (the organization's issuer). */\n create(clientId: string, audience: string): string {\n if (!clientId || !audience) {\n throw new Error('clientId and audience are required for a client assertion');\n }\n const iat = this.now();\n const header: Record<string, unknown> = { alg: this.algorithm, typ: CLIENT_ASSERTION_TYP };\n if (this.keyId) header.kid = this.keyId;\n const claims = {\n iss: clientId,\n sub: clientId,\n aud: audience,\n iat,\n exp: iat + this.lifetimeSeconds,\n jti: randomBytes(24).toString('base64url'),\n };\n const signingInput = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(claims))}`;\n return `${signingInput}.${signAssertion(this.algorithm, Buffer.from(signingInput, 'utf8'), this.key).toString('base64url')}`;\n }\n\n /** The public key as a JWK with `kid` (when set), `alg` and `use: \"sig\"`. */\n get jwk(): ClientAssertionJwk {\n const pub = createPublicKey(this.key).export({ format: 'jwk' }) as Record<string, unknown>;\n const out: Record<string, unknown> = { kty: pub.kty };\n for (const member of ['crv', 'x', 'y', 'n', 'e'] as const) {\n if (typeof pub[member] === 'string') out[member] = pub[member];\n }\n if (this.keyId) out.kid = this.keyId;\n out.alg = this.algorithm;\n out.use = 'sig';\n return out as unknown as ClientAssertionJwk;\n }\n\n /** `{ keys: [jwk] }`: what to register on the agent. */\n get jwks(): { keys: ClientAssertionJwk[] } {\n return { keys: [this.jwk] };\n }\n\n /** The private key as PKCS#8 PEM, for your secret store. */\n get privateKeyPem(): string {\n return this.key.export({ type: 'pkcs8', format: 'pem' }).toString();\n }\n}\n\n/**\n * The issuer identifier of an organization on `baseUrl`: the `issuer` of\n * `/orgs/{orgId}/api/v1/.well-known/openid-configuration`, and the `aud` a\n * client assertion must carry. On a custom domain the issuer differs; pass it\n * explicitly there.\n */\nexport function issuerFor(baseUrl: string, orgId: string): string {\n return `${baseUrl.replace(/\\/+$/, '')}/orgs/${orgId}/api/v1`;\n}\n\nfunction naturalAlgorithm(key: KeyObject): ClientAssertionAlgorithm {\n switch (key.asymmetricKeyType) {\n case 'ec': {\n const curve = String(key.asymmetricKeyDetails?.namedCurve ?? '');\n const alg = EC_ALGORITHM_BY_CURVE[curve];\n if (!alg) throw new Error(`EC keys must use P-256, P-384 or P-521 (got ${curve})`);\n return alg;\n }\n case 'ed25519':\n return 'EdDSA';\n case 'rsa':\n return 'RS256';\n default:\n throw new Error(`Unsupported key type: ${String(key.asymmetricKeyType)}`);\n }\n}\n\nfunction signAssertion(alg: ClientAssertionAlgorithm, data: Buffer, key: KeyObject): Buffer {\n const hash = `sha${alg.slice(2)}`;\n switch (alg) {\n case 'ES256':\n case 'ES384':\n case 'ES512':\n return cryptoSign(hash, data, { key, dsaEncoding: 'ieee-p1363' });\n case 'EdDSA':\n return cryptoSign(null, data, key);\n case 'PS256':\n case 'PS384':\n case 'PS512':\n return cryptoSign(hash, data, {\n key,\n padding: cryptoConstants.RSA_PKCS1_PSS_PADDING,\n saltLength: cryptoConstants.RSA_PSS_SALTLEN_DIGEST,\n });\n default:\n return cryptoSign(hash, data, key);\n }\n}\n\nfunction b64url(text: string): string {\n return Buffer.from(text, 'utf8').toString('base64url');\n}\n","import { createHash, createPublicKey, createPrivateKey, generateKeyPairSync, type KeyObject } from 'node:crypto';\n\n// ─── Types ────────────────────────────────────────────────────────────\n\n/** A public JSON Web Key as published in a JWKS. */\nexport interface AAuthJwk {\n kty: string;\n crv?: string;\n x?: string;\n y?: string;\n n?: string;\n e?: string;\n use?: string;\n kid?: string;\n alg?: string;\n [key: string]: unknown;\n}\n\nexport interface AAuthKeypair {\n /** PKCS#8 PEM-encoded Ed25519 private key. Store in your secret manager. */\n privateKeyPem: string;\n /** SPKI PEM-encoded public key. */\n publicKeyPem: string;\n /** The public key as a JWK (with `use: \"sig\"` and the given `kid`). */\n jwk: AAuthJwk;\n /** A JWKS document ready to publish at `/.well-known/jwks.json`. */\n jwks: { keys: AAuthJwk[] };\n}\n\n// ─── Helpers ──────────────────────────────────────────────────────────\n\nexport function base64UrlEncode(data: Buffer | Uint8Array | string): string {\n return Buffer.from(data).toString('base64url');\n}\n\nexport function base64UrlDecode(data: string): Buffer {\n return Buffer.from(data, 'base64url');\n}\n\n// ─── Key generation ───────────────────────────────────────────────────\n\n/**\n * Generate an Ed25519 key pair suitable for AAuth.\n *\n * Mirrors the Python SDK's `AAuthClient.generate_keypair()`: returns the\n * PKCS#8 private key PEM plus a JWKS document ready to be published at\n * `/.well-known/jwks.json` (or registered inline with LumoAuth).\n *\n * @example\n * ```ts\n * import { generateKeypair } from '@lumoauth/agent';\n *\n * const { privateKeyPem, jwks } = generateKeypair();\n * console.log(JSON.stringify(jwks, null, 2));\n * ```\n */\nexport function generateKeypair(kid = 'key-1'): AAuthKeypair {\n const { privateKey, publicKey } = generateKeyPairSync('ed25519');\n\n const privateKeyPem = privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();\n const publicKeyPem = publicKey.export({ type: 'spki', format: 'pem' }).toString();\n\n const rawJwk = publicKey.export({ format: 'jwk' }) as { kty: string; crv: string; x: string };\n const jwk: AAuthJwk = {\n kty: rawJwk.kty,\n crv: rawJwk.crv,\n x: rawJwk.x,\n use: 'sig',\n kid,\n };\n\n return { privateKeyPem, publicKeyPem, jwk, jwks: { keys: [jwk] } };\n}\n\n/**\n * Compute the RFC 7638 JWK thumbprint (base64url-encoded SHA-256) of a\n * public JWK. LumoAuth uses it as `agent_jkt` in resource tokens and as\n * `cnf_jkt` in the answer of the token verify endpoint. Auth tokens carry\n * the full key in `cnf.jwk`, not the thumbprint.\n */\nexport function jwkThumbprint(jwk: AAuthJwk): string {\n let canonical: string;\n switch (jwk.kty) {\n case 'OKP':\n canonical = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x });\n break;\n case 'EC':\n canonical = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y });\n break;\n case 'RSA':\n canonical = JSON.stringify({ e: jwk.e, kty: jwk.kty, n: jwk.n });\n break;\n default:\n throw new Error(`Unsupported key type for thumbprint: ${jwk.kty}`);\n }\n return createHash('sha256').update(canonical, 'utf8').digest('base64url');\n}\n\n/**\n * Load a PEM private key (Ed25519 or RSA) into a Node.js KeyObject and\n * classify it for the RFC 9421 signing dispatch.\n */\nexport function loadPrivateKey(pem: string): { key: KeyObject; type: 'ed25519' | 'rsa' } {\n const key = createPrivateKey(pem);\n if (key.asymmetricKeyType === 'ed25519') {\n return { key, type: 'ed25519' };\n }\n if (key.asymmetricKeyType === 'rsa' || key.asymmetricKeyType === 'rsa-pss') {\n return { key, type: 'rsa' };\n }\n throw new Error(\n `AAuth requires an Ed25519 or RSA private key (got ${String(key.asymmetricKeyType)}).`\n );\n}\n\n/** Derive the public JWK for a loaded private key. */\nexport function publicJwkFromPrivateKey(pem: string, kid?: string): AAuthJwk {\n const priv = createPrivateKey(pem);\n const pub = createPublicKey(priv);\n const jwk = pub.export({ format: 'jwk' }) as AAuthJwk;\n if (kid) jwk.kid = kid;\n return jwk;\n}\n","import {\n constants,\n createHash,\n randomBytes,\n sign as cryptoSign,\n verify as cryptoVerify,\n type KeyObject,\n} from 'node:crypto';\nimport { loadPrivateKey } from './keys';\n\n/**\n * RFC 9421 HTTP Message Signing, profiled for AAuth.\n *\n * The LumoAuth agent token endpoint enforces a strict profile (AAuth 1.0 §4):\n *\n * - Covered components: `@method @authority @path signature-key\n * content-digest content-type authorization` (plus `@query` if and only if\n * the target URI has a query string). `signature-key` and `authorization`\n * are the values of the `Signature-Key` and `Authorization` request\n * headers, or the empty string when the header is not sent. `@target-uri`\n * is not accepted in place of `@authority` and `@path`.\n * - `Signature-Input` parameters: `created` (required, within ±60 s of the\n * server clock) and a single-use `nonce` (required, base64url of at least\n * 12 random bytes). The server also accepts `expires`, `alg`, `keyid` and\n * `tag`, and refuses any other parameter. This signer sends only\n * `created` and `nonce`.\n * - `Content-Digest` per RFC 9530 with **standard** base64 (`sha-256=:…:`).\n * The header is mandatory and must match the body.\n * - The `Signature` value (`label=:…:`) is sent **base64url** encoded. The\n * server accepts base64url and standard base64.\n * - The algorithm follows the key type: Ed25519 → `ed25519`, RSA →\n * `rsa-pss-sha512` (MGF1-SHA512, 64-byte salt). The server also accepts\n * EC P-256 keys (`ecdsa-p256-sha256`, raw r||s), which this signer does\n * not support. An `alg` parameter is optional (it must then name the\n * algorithm of the key); this signer declares none.\n */\n\n// ─── Constants ────────────────────────────────────────────────────────\n\n/** Covered components required by the AAuth agent token endpoint, in order. */\nexport const AAUTH_COVERED_COMPONENTS = [\n '@method',\n '@authority',\n '@path',\n 'signature-key',\n 'content-digest',\n 'content-type',\n 'authorization',\n] as const;\n\nconst SIGNATURE_LABEL = 'sig1';\n\n// ─── Primitives ───────────────────────────────────────────────────────\n\n/**\n * Compute an RFC 9530 `Content-Digest` header value over the exact body\n * bytes. Uses sha-256 with STANDARD base64 (the server base64-decodes it).\n */\nexport function contentDigestSha256(body: Buffer | Uint8Array | string): string {\n const digest = createHash('sha256').update(body).digest('base64');\n return `sha-256=:${digest}:`;\n}\n\n/** Generate a fresh signature nonce: base64url of 16 random bytes (128 bits). */\nexport function generateNonce(): string {\n return randomBytes(16).toString('base64url');\n}\n\n/**\n * Build the RFC 9421 signature base: one `\"<component>\": <value>` line per\n * covered component in declared order, then the `\"@signature-params\"` line\n * carrying ONLY `created` and `nonce`.\n */\nexport function buildSignatureBase(\n components: readonly string[],\n values: Record<string, string>,\n created: number,\n nonce: string\n): string {\n const lines = components.map((c) => `\"${c}\": ${values[c] ?? ''}`);\n lines.push(`\"@signature-params\": ${signatureParams(components, created, nonce)}`);\n return lines.join('\\n');\n}\n\n/** The `(…);created=…;nonce=\"…\"` parameter string shared by the base and header. */\nexport function signatureParams(\n components: readonly string[],\n created: number,\n nonce: string\n): string {\n const coveredList = components.map((c) => `\"${c}\"`).join(' ');\n return `(${coveredList});created=${created};nonce=\"${nonce}\"`;\n}\n\n/**\n * Sign a signature base with the agent's private key.\n * Ed25519 keys produce `ed25519` signatures; RSA keys produce\n * `rsa-pss-sha512` signatures (MGF1-SHA512, salt length = digest length).\n * Returns the base64url-encoded signature (RFC 9421 profile).\n */\nexport function signSignatureBase(signatureBase: string, privateKey: KeyObject): string {\n const data = Buffer.from(signatureBase, 'utf8');\n let signature: Buffer;\n if (privateKey.asymmetricKeyType === 'ed25519') {\n signature = cryptoSign(null, data, privateKey);\n } else {\n signature = cryptoSign('sha512', data, {\n key: privateKey,\n padding: constants.RSA_PKCS1_PSS_PADDING,\n saltLength: constants.RSA_PSS_SALTLEN_DIGEST, // 64 bytes for SHA-512\n });\n }\n return signature.toString('base64url');\n}\n\n/**\n * Verify a base64url signature over a signature base (resource-server side).\n * Dispatches on key type like the LumoAuth server does, for Ed25519 and RSA\n * keys only: a signature made with an EC P-256 key, which the server also\n * accepts from agents, does not verify here. The signature must be\n * base64url (the form the LumoAuth SDKs send).\n */\nexport function verifySignatureBase(\n signatureBase: string,\n signatureB64url: string,\n publicKey: KeyObject\n): boolean {\n const data = Buffer.from(signatureBase, 'utf8');\n const sig = Buffer.from(signatureB64url, 'base64url');\n if (publicKey.asymmetricKeyType === 'ed25519') {\n return cryptoVerify(null, data, publicKey, sig);\n }\n return cryptoVerify('sha512', data, {\n key: publicKey,\n padding: constants.RSA_PKCS1_PSS_PADDING,\n saltLength: constants.RSA_PSS_SALTLEN_DIGEST,\n }, sig);\n}\n\n// ─── Request signing ──────────────────────────────────────────────────\n\nexport interface SignRequestOptions {\n /** Raw request body. Defaults to the empty body. */\n body?: Buffer | Uint8Array | string;\n /** Media type of the body. Default: `application/json`. */\n contentType?: string;\n /** The `agent+jwt` to present in the `Agent-Auth` header. */\n agentToken?: string;\n /** Value of a covered `Authorization` header, if any (e.g. `Bearer …`). */\n authorization?: string;\n /**\n * Value of a covered `Signature-Key` header, if any. It is also sent as\n * that header. Its label must be `sig1`, the label of `Signature-Input`\n * and `Signature`. `POST /aauth/agent/issue` requires\n * `sig1=jwks_uri;id=\"<agent identifier>\";kid=\"<kid>\"`; the agent token\n * endpoint and `/aauth/token/revoke` need no `Signature-Key`.\n */\n signatureKey?: string;\n /**\n * Override the `created` timestamp (seconds). Testing only — the server\n * rejects timestamps more than 60 s from its clock.\n */\n created?: number;\n /** Override the nonce. Testing only — nonces are single-use server-side. */\n nonce?: string;\n}\n\n/**\n * Create RFC 9421 signature headers for a request to the AAuth agent token\n * endpoint (or any endpoint enforcing the AAuth profile).\n *\n * Byte-compatible with the Python SDK's `AAuthClient.sign_request()`.\n */\nexport function signRequest(\n privateKeyPem: string,\n method: string,\n url: string,\n options: SignRequestOptions = {}\n): Record<string, string> {\n const { key } = loadPrivateKey(privateKeyPem);\n const parsed = new URL(url);\n const authority = parsed.host; // host[:port], lowercased by the URL parser\n const path = parsed.pathname || '/';\n const query = parsed.search; // '' or '?…'\n\n const body = options.body ?? Buffer.alloc(0);\n const contentType = options.contentType ?? 'application/json';\n const contentDigest = contentDigestSha256(body);\n\n const created = options.created ?? Math.floor(Date.now() / 1000);\n const nonce = options.nonce ?? generateNonce();\n\n // @query MUST be covered if and only if the target has a query string.\n const components: string[] = ['@method', '@authority', '@path'];\n if (query !== '') components.push('@query');\n components.push('signature-key', 'content-digest', 'content-type', 'authorization');\n\n const values: Record<string, string> = {\n '@method': method.toUpperCase(),\n '@authority': authority,\n '@path': path,\n 'signature-key': options.signatureKey ?? '',\n 'content-digest': contentDigest,\n 'content-type': contentType,\n authorization: options.authorization ?? '',\n };\n if (query !== '') values['@query'] = query;\n\n const signatureBase = buildSignatureBase(components, values, created, nonce);\n const signature = signSignatureBase(signatureBase, key);\n\n const headers: Record<string, string> = {\n 'Content-Digest': contentDigest,\n 'Content-Type': contentType,\n 'Signature-Input': `${SIGNATURE_LABEL}=${signatureParams(components, created, nonce)}`,\n Signature: `${SIGNATURE_LABEL}=:${signature}:`,\n };\n if (options.agentToken) {\n headers['Agent-Auth'] = `agent_token=${options.agentToken}`;\n }\n if (options.signatureKey) {\n headers['Signature-Key'] = options.signatureKey;\n }\n return headers;\n}\n","import { constants, createPublicKey, verify as cryptoVerify, type KeyObject } from 'node:crypto';\nimport type { AAuthJwk } from './keys';\nimport { AAuthError } from './errors';\n\n/**\n * Auth-token (`auth+jwt`) verification for resource servers.\n *\n * Verifies the JWS signature against the organization's AAuth issuer JWKS\n * (`{issuer}/aauth/jwks.json`), plus `typ`, `iss`, `aud`, and `exp` — the\n * same checks LumoAuth's own `validateAuthToken()` performs (revocation\n * excepted: use `POST {issuer}/aauth/auth/token/verify` for live\n * revocation-aware introspection).\n *\n * NOTE: AAuth auth tokens are proof-of-possession tokens. After verifying\n * the JWT, the resource MUST also verify the request's RFC 9421 signature\n * against the key in `cnf.jwk` (see `verifySignatureBase` and\n * `jwkThumbprint`).\n */\n\n// ─── Types ────────────────────────────────────────────────────────────\n\nexport interface AAuthTokenClaims {\n iss: string;\n aud: string;\n exp: number;\n iat: number;\n jti: string;\n /** The agent's full public JWK. Auth tokens carry no `cnf.jkt`. */\n cnf: { jwk: AAuthJwk };\n /** The agent identifier. Present only when `aud` differs from it. */\n agent?: string;\n /** The delegate (the `sub` of the agent token) that made the request, if any. */\n agent_delegate?: string;\n /** Resource scopes only: openid, profile, email, phone and address are never listed. */\n scope?: string;\n /**\n * The user. A pseudonym for this resource, not the user ID, when the\n * resource's default auth level is `pseudonymous`, or `authorized`\n * without a consent record.\n */\n sub?: string;\n /**\n * Actor chain of an exchanged token: `{ agent, agent_delegate?, sub?,\n * act? }`. `act.agent` names the upstream agent and `act.sub` the\n * upstream user; a nested `act` holds the earlier hops (at most 5).\n */\n act?: Record<string, unknown>;\n [claim: string]: unknown;\n}\n\nexport interface VerifyAuthTokenOptions {\n /** The trusted issuer URL, e.g. `https://app.lumoauth.dev/orgs/acme-corp/api/v1`. */\n issuer: string;\n /** Your resource identifier — must equal the token's `aud`. */\n resource: string;\n /** Pre-fetched issuer JWKS (skips the network fetch). */\n jwks?: { keys: AAuthJwk[] };\n /** Custom fetch implementation. */\n fetch?: typeof globalThis.fetch;\n /** Allowed clock skew in seconds for `exp`. Default 0 (like the server). */\n clockSkew?: number;\n}\n\n// Only asymmetric JWS algorithms; HS* and none are always rejected.\nconst JWS_VERIFIERS: Record<string, (data: Buffer, key: KeyObject, sig: Buffer) => boolean> = {\n RS256: (d, k, s) => cryptoVerify('sha256', d, k, s),\n RS384: (d, k, s) => cryptoVerify('sha384', d, k, s),\n RS512: (d, k, s) => cryptoVerify('sha512', d, k, s),\n PS256: (d, k, s) => cryptoVerify('sha256', d, pss(k), s),\n PS384: (d, k, s) => cryptoVerify('sha384', d, pss(k), s),\n PS512: (d, k, s) => cryptoVerify('sha512', d, pss(k), s),\n ES256: (d, k, s) => cryptoVerify('sha256', d, p1363(k), s),\n ES384: (d, k, s) => cryptoVerify('sha384', d, p1363(k), s),\n ES512: (d, k, s) => cryptoVerify('sha512', d, p1363(k), s),\n EdDSA: (d, k, s) => cryptoVerify(null, d, k, s),\n};\n\nfunction pss(key: KeyObject) {\n return { key, padding: constants.RSA_PKCS1_PSS_PADDING, saltLength: constants.RSA_PSS_SALTLEN_DIGEST };\n}\n\nfunction p1363(key: KeyObject) {\n return { key, dsaEncoding: 'ieee-p1363' as const };\n}\n\nfunction decodeSegment(segment: string): unknown {\n return JSON.parse(Buffer.from(segment, 'base64url').toString('utf8'));\n}\n\n/** Decode a JWT without verifying it. Useful for reading `aud`/`cnf` first. */\nexport function decodeJwt(token: string): { header: Record<string, unknown>; claims: Record<string, unknown> } {\n const parts = token.split('.');\n if (parts.length !== 3) {\n throw new AAuthError('Invalid JWT format', 'invalid_token');\n }\n return {\n header: decodeSegment(parts[0]) as Record<string, unknown>,\n claims: decodeSegment(parts[1]) as Record<string, unknown>,\n };\n}\n\n/**\n * Verify an AAuth auth token (`auth+jwt`) against the issuing\n * organization's JWKS. Returns the verified claims or throws `AAuthError`.\n *\n * @example\n * ```ts\n * import { verifyAuthToken } from '@lumoauth/agent';\n *\n * const claims = await verifyAuthToken(bearer, {\n * issuer: 'https://app.lumoauth.dev/orgs/acme-corp/api/v1',\n * resource: 'https://api.example.com',\n * });\n * // Then enforce PoP: verify the request signature against claims.cnf.jwk.\n * ```\n */\nexport async function verifyAuthToken(\n token: string,\n options: VerifyAuthTokenOptions\n): Promise<AAuthTokenClaims> {\n const parts = token.split('.');\n if (parts.length !== 3) {\n throw new AAuthError('Invalid JWT format', 'invalid_token');\n }\n const header = decodeSegment(parts[0]) as Record<string, unknown>;\n const claims = decodeSegment(parts[1]) as Record<string, unknown>;\n\n if (header.typ !== 'auth+jwt') {\n throw new AAuthError(`Unexpected token type: ${String(header.typ)}`, 'invalid_token');\n }\n const alg = typeof header.alg === 'string' ? header.alg : '';\n const kid = typeof header.kid === 'string' ? header.kid : '';\n if (!alg || !kid) {\n throw new AAuthError('Missing kid or alg in JOSE header', 'invalid_token');\n }\n const verifier = JWS_VERIFIERS[alg];\n if (!verifier) {\n throw new AAuthError(`Disallowed JWS algorithm: ${alg}`, 'invalid_token');\n }\n\n if (claims.iss !== options.issuer) {\n throw new AAuthError('Untrusted issuer', 'invalid_token');\n }\n\n // Resolve the signing key from the issuer JWKS\n const jwks = options.jwks ?? (await fetchIssuerJwks(options.issuer, options.fetch));\n const jwk = jwks.keys.find((k) => k.kid === kid);\n if (!jwk) {\n throw new AAuthError(`Key not found: kid=${kid}`, 'invalid_token');\n }\n assertAlgMatchesKey(alg, jwk);\n\n const publicKey = createPublicKey({ key: jwk as unknown as Record<string, unknown>, format: 'jwk' });\n const data = Buffer.from(`${parts[0]}.${parts[1]}`, 'utf8');\n const signature = Buffer.from(parts[2], 'base64url');\n if (!verifier(data, publicKey, signature)) {\n throw new AAuthError('Signature verification failed', 'invalid_token');\n }\n\n // Temporal + audience checks (post-signature, like the server)\n const now = Math.floor(Date.now() / 1000);\n const skew = options.clockSkew ?? 0;\n if (typeof claims.exp !== 'number' || claims.exp < now - skew) {\n throw new AAuthError('Auth token expired', 'invalid_token');\n }\n if (claims.aud !== options.resource) {\n throw new AAuthError('Invalid audience', 'invalid_token');\n }\n const cnf = claims.cnf as { jwk?: AAuthJwk } | undefined;\n if (!cnf || !cnf.jwk) {\n throw new AAuthError('Missing cnf.jwk claim', 'invalid_token');\n }\n\n return claims as unknown as AAuthTokenClaims;\n}\n\nfunction assertAlgMatchesKey(alg: string, jwk: AAuthJwk): void {\n const compatible =\n (jwk.kty === 'RSA' && (alg.startsWith('RS') || alg.startsWith('PS'))) ||\n (jwk.kty === 'EC' && alg.startsWith('ES')) ||\n (jwk.kty === 'OKP' && alg === 'EdDSA');\n if (!compatible) {\n throw new AAuthError(`Algorithm ${alg} incompatible with key type ${jwk.kty}`, 'invalid_token');\n }\n if (jwk.alg && jwk.alg !== alg) {\n throw new AAuthError(`Algorithm ${alg} does not match key alg ${jwk.alg}`, 'invalid_token');\n }\n}\n\nasync function fetchIssuerJwks(\n issuer: string,\n fetchFn?: typeof globalThis.fetch\n): Promise<{ keys: AAuthJwk[] }> {\n const doFetch = fetchFn ?? globalThis.fetch;\n const url = `${issuer.replace(/\\/+$/, '')}/aauth/jwks.json`;\n const response = await doFetch(url, { headers: { Accept: 'application/json' } });\n if (!response.ok) {\n throw new AAuthError(`Failed to fetch issuer JWKS (HTTP ${response.status})`, 'jwks_fetch_failed', response.status);\n }\n const jwks = (await response.json()) as { keys?: AAuthJwk[] };\n if (!Array.isArray(jwks.keys)) {\n throw new AAuthError('Issuer JWKS is malformed', 'jwks_fetch_failed');\n }\n return { keys: jwks.keys };\n}\n","import { LumoAuthError } from '@lumoauth/shared';\n\n/**\n * Thrown for AAuth protocol failures — OAuth-style `{error,\n * error_description}` bodies from the agent token endpoint, signature\n * problems, and token-verification failures.\n */\nexport class AAuthError extends LumoAuthError {\n constructor(\n message: string,\n /** OAuth-style error code, e.g. `invalid_grant`, `authentication_required`. */\n code: string,\n statusCode?: number,\n /** The parsed response body, when the error came from the server. */\n public readonly body?: unknown\n ) {\n super(message, code, statusCode);\n this.name = 'AAuthError';\n }\n}\n","import { generateKeypair, jwkThumbprint, publicJwkFromPrivateKey, type AAuthJwk, type AAuthKeypair } from './keys';\nimport { signRequest, type SignRequestOptions } from './signing';\nimport { verifyAuthToken, type AAuthTokenClaims, type VerifyAuthTokenOptions } from './verify';\nimport { AAuthError } from './errors';\nimport { LumoAuthConfigError, LumoAuthNetworkError, ROUTES, buildPath } from '@lumoauth/shared';\n\n// ─── Types ────────────────────────────────────────────────────────────\n\nexport interface AAuthClientOptions {\n /** HTTPS URL uniquely identifying the agent (e.g. `https://my-agent.example.com`). */\n agentIdentifier: string;\n /** PEM-encoded Ed25519 (PKCS#8) or RSA private key. */\n privateKeyPem: string;\n /**\n * LumoAuth instance URL. Defaults to `process.env.LUMOAUTH_URL` or\n * `https://app.lumoauth.dev`.\n */\n baseUrl?: string;\n /** Organization ID (slug). Defaults to `process.env.LUMOAUTH_ORG_ID`. */\n orgId?: string;\n /** Key ID matching the JWKS entry registered with LumoAuth. Default `key-1`. */\n kid?: string;\n /** Custom fetch implementation (defaults to the global `fetch`). */\n fetch?: typeof globalThis.fetch;\n /** Request timeout in milliseconds. Default: 30 000 ms. */\n timeout?: number;\n}\n\n/** Successful response from the agent token endpoint. */\nexport interface AAuthTokenResponse {\n requestType: 'auth' | 'code' | 'exchange' | 'refresh';\n /** The `auth+jwt` access token to present to the resource. */\n authToken: string;\n expiresIn: number;\n tokenType: string; // \"auth+jwt\"\n refreshToken?: string;\n}\n\n/** Returned by `requestAuthToken()` when the user must consent first. */\nexport interface AAuthAuthorizationRequired {\n authorizationRequired: true;\n /** Opaque token identifying the pending request (600 s TTL). */\n requestToken: string;\n /** Consent page URL — redirect the user here. */\n authorizationUri: string;\n expiresIn?: number;\n}\n\nexport interface AAuthIssuerMetadata {\n issuer: string;\n aauth_version: string;\n jwks_uri: string;\n agent_token_endpoint: string;\n agent_auth_endpoint: string;\n agent_signing_algs_supported: string[];\n token_signing_algs_supported: string[];\n request_types_supported: string[];\n scopes_supported: string[];\n [key: string]: unknown;\n}\n\nexport interface AAuthAgentMetadata {\n agent: string;\n jwks_uri: string;\n redirect_uris?: string[];\n name?: string;\n [key: string]: unknown;\n}\n\nexport interface AAuthResourceMetadata {\n resource: string;\n jwks_uri: string;\n resource_token_endpoint?: string;\n supported_scopes?: string[];\n [key: string]: unknown;\n}\n\ninterface RawTokenResponse {\n request_type?: string;\n auth_token?: string;\n expires_in?: number;\n token_type?: string;\n refresh_token?: string;\n request_token?: string;\n authorization_uri?: string;\n auth_url?: string;\n error?: string;\n error_description?: string;\n}\n\nfunction envVar(name: string): string | undefined {\n return typeof process !== 'undefined' && process.env ? process.env[name] : undefined;\n}\n\n// ─── Client ───────────────────────────────────────────────────────────\n\n/**\n * Client for the AAuth (Agent Auth) protocol — the Node.js counterpart of\n * the Python SDK's `lumoauth.AAuthClient`.\n *\n * AAuth extends OAuth 2.1 with cryptographic agent identity,\n * proof-of-possession tokens, and RFC 9421 HTTP message signing.\n *\n * @example\n * ```ts\n * import { AAuthClient } from '@lumoauth/agent';\n *\n * const client = new AAuthClient({\n * agentIdentifier: 'https://my-agent.example.com',\n * privateKeyPem: process.env.AGENT_PRIVATE_KEY!,\n * baseUrl: 'https://app.lumoauth.dev',\n * orgId: 'acme-corp',\n * });\n *\n * const result = await client.requestAuthToken({\n * resourceToken, // its `scope` claim names the scope of the auth token\n * agentToken,\n * });\n * if ('authorizationRequired' in result) {\n * // redirect the user to result.authorizationUri, then exchangeCode()\n * } else {\n * const resp = await client.signedRequest('GET', 'https://api.example.com/v1/data', {\n * authToken: result.authToken,\n * });\n * }\n * ```\n */\nexport class AAuthClient {\n /** Generate an Ed25519 key pair suitable for AAuth (parity with Python). */\n static generateKeypair = generateKeypair;\n\n readonly agentIdentifier: string;\n readonly baseUrl: string;\n readonly orgId: string;\n readonly kid: string;\n\n private readonly privateKeyPem: string;\n private readonly fetchFn: typeof globalThis.fetch;\n private readonly timeout: number;\n\n constructor(options: AAuthClientOptions) {\n if (!options.agentIdentifier) {\n throw new LumoAuthConfigError('agentIdentifier is required');\n }\n if (!options.privateKeyPem) {\n throw new LumoAuthConfigError('privateKeyPem is required');\n }\n this.agentIdentifier = options.agentIdentifier;\n this.privateKeyPem = options.privateKeyPem;\n this.baseUrl = (options.baseUrl ?? envVar('LUMOAUTH_URL') ?? 'https://app.lumoauth.dev').replace(/\\/+$/, '');\n this.orgId = options.orgId ?? envVar('LUMOAUTH_ORG_ID') ?? '';\n this.kid = options.kid ?? 'key-1';\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.timeout = options.timeout ?? 30_000;\n }\n\n /** The organization's AAuth issuer URL: `{baseUrl}/orgs/{orgId}/api/v1`. */\n get issuer(): string {\n return `${this.baseUrl}/orgs/${this.orgId}/api/v1`;\n }\n\n /** The agent's public JWK derived from its private key. */\n get publicJwk(): AAuthJwk {\n return publicJwkFromPrivateKey(this.privateKeyPem, this.kid);\n }\n\n /**\n * RFC 7638 thumbprint of the agent's public key. A resource names this\n * value as `agent_jkt` when it asks for a resource token for the agent.\n */\n get publicJwkThumbprint(): string {\n return jwkThumbprint(this.publicJwk);\n }\n\n // ─── HTTP Message Signing ─────────────────────────────────────────\n\n /**\n * Create RFC 9421 signature headers for a request per the AAuth profile.\n * See `signRequest()` in `signing.ts` for the exact contract.\n */\n signRequest(method: string, url: string, options: SignRequestOptions = {}): Record<string, string> {\n return signRequest(this.privateKeyPem, method, url, options);\n }\n\n // ─── Token flows ──────────────────────────────────────────────────\n\n /**\n * Request an auth token (`request_type=auth` — direct authorization).\n *\n * Presents the resource token in the body and the agent token in the\n * `Agent-Auth` header (never in the body), signed with the key in the\n * agent token's `cnf`. If the server requires user consent it answers\n * 200 with `request_token` and `authorization_uri`, returned here as\n * `{ authorizationRequired: true, requestToken, authorizationUri }` —\n * redirect the user, then call `exchangeCode()` with the code delivered\n * to your `redirectUri`.\n */\n async requestAuthToken(params: {\n /** Resource token (`resource+jwt`) obtained from the target resource. */\n resourceToken: string;\n /**\n * Sent as the body field `scope`, which the server ignores for\n * `request_type=auth`: the scope of the auth token comes from the\n * resource token's `scope` claim.\n */\n scope?: string;\n /** The `agent+jwt` presented in `Agent-Auth`. */\n agentToken: string;\n /**\n * Redirect URI, required when the user has to consent (the server\n * answers 400 `invalid_request` without it). It must be registered\n * for the agent.\n */\n redirectUri?: string;\n }): Promise<AAuthTokenResponse | AAuthAuthorizationRequired> {\n this.requireAgentToken(params.agentToken);\n const body: Record<string, unknown> = {\n request_type: 'auth',\n resource_token: params.resourceToken,\n };\n if (params.scope) body.scope = params.scope;\n if (params.redirectUri) body.redirect_uri = params.redirectUri;\n\n const data = await this.tokenRequest(body, params.agentToken);\n\n if (!data.auth_token && (data.request_token || data.authorization_uri || data.auth_url)) {\n return {\n authorizationRequired: true,\n requestToken: data.request_token ?? '',\n authorizationUri: data.authorization_uri ?? data.auth_url ?? '',\n expiresIn: data.expires_in,\n };\n }\n return this.mapTokenResponse(data);\n }\n\n /**\n * Build the user-consent URL for a pending request token\n * (`GET {issuer}/aauth/agent/auth?request_token=…`). Prefer the\n * `authorizationUri` returned by `requestAuthToken()` when present.\n */\n buildConsentUrl(requestToken: string): string {\n return `${this.routeUrl('aauth.agentAuth')}?request_token=${encodeURIComponent(requestToken)}`;\n }\n\n /**\n * Exchange an authorization code for tokens (`request_type=code`) after\n * user consent. `redirectUri` must be the exact URI the code was\n * delivered to.\n */\n async exchangeCode(params: {\n code: string;\n redirectUri: string;\n agentToken: string;\n }): Promise<AAuthTokenResponse> {\n this.requireAgentToken(params.agentToken);\n const data = await this.tokenRequest(\n { request_type: 'code', code: params.code, redirect_uri: params.redirectUri },\n params.agentToken\n );\n return this.mapTokenResponse(data);\n }\n\n /**\n * Multi-hop token exchange (`request_type=exchange`): trade an upstream\n * auth token plus a downstream resource token for a new auth token with\n * an `act` actor chain (`act.agent` names the upstream agent, `act.sub`\n * the upstream user; at most 5 hops). Requires token exchange to be\n * enabled for the agent.\n */\n async exchangeToken(params: {\n /** The upstream `auth+jwt` addressed to this agent. */\n authToken: string;\n /** Resource token issued by the downstream resource to this agent. */\n resourceToken: string;\n agentToken: string;\n }): Promise<AAuthTokenResponse> {\n this.requireAgentToken(params.agentToken);\n const data = await this.tokenRequest(\n {\n request_type: 'exchange',\n auth_token: params.authToken,\n resource_token: params.resourceToken,\n },\n params.agentToken\n );\n return this.mapTokenResponse(data);\n }\n\n /**\n * Refresh an auth token (`request_type=refresh`). A resource token from\n * the same resource as the original grant is required. The scopes of\n * that grant are the ceiling: the resource token's `scope` claim may\n * narrow them, and `scope` narrows the result once more. A refresh never\n * widens the scope. The response carries no new refresh token (refresh\n * tokens are not rotated).\n */\n async refresh(params: {\n refreshToken: string;\n /** Resource token from the resource that the refresh token was granted for. */\n resourceToken: string;\n /**\n * Optional space-delimited scope. It narrows only: every scope must\n * be in the grant (and in the resource token's scope, when it has\n * one). A scope outside the grant is refused with 400\n * `invalid_scope`.\n */\n scope?: string;\n agentToken: string;\n }): Promise<AAuthTokenResponse> {\n this.requireAgentToken(params.agentToken);\n const body: Record<string, unknown> = {\n request_type: 'refresh',\n refresh_token: params.refreshToken,\n resource_token: params.resourceToken,\n };\n if (params.scope) body.scope = params.scope;\n const data = await this.tokenRequest(body, params.agentToken);\n return this.mapTokenResponse(data);\n }\n\n /**\n * Revoke an auth token (by its `jti`) or a refresh token (by value).\n * Always resolves `{ revoked: true }` — the server does not reveal\n * whether the token existed.\n */\n async revoke(params: {\n /** A refresh-token value, or an auth token's `jti`. */\n token: string;\n tokenType?: 'auth_token' | 'refresh_token';\n agentToken: string;\n }): Promise<{ revoked: boolean }> {\n this.requireAgentToken(params.agentToken);\n const url = this.routeUrl('aauth.tokenRevoke');\n const data = await this.signedPost(url, {\n token: params.token,\n token_type: params.tokenType ?? 'auth_token',\n }, params.agentToken);\n return { revoked: Boolean((data as { revoked?: boolean }).revoked ?? true) };\n }\n\n // ─── Signed requests to protected resources ───────────────────────\n\n /**\n * Make a signed, authenticated request to a protected resource.\n *\n * Carries the auth token as `Authorization: Bearer …` **and** an RFC\n * 9421 signature proving possession of the key bound in the token's\n * `cnf.jwk`. The signature covers the `authorization` component, so the\n * resource can verify both together.\n *\n * Returns the raw `fetch` Response.\n */\n async signedRequest(\n method: string,\n url: string,\n options: {\n /** The AAuth `auth+jwt` access token. */\n authToken: string;\n /** JSON body (for POST/PUT). */\n data?: unknown;\n /** Extra headers (not covered by the signature). */\n headers?: Record<string, string>;\n }\n ): Promise<Response> {\n const bodyStr = options.data != null ? JSON.stringify(options.data) : '';\n const authorization = `Bearer ${options.authToken}`;\n const sigHeaders = this.signRequest(method, url, { body: bodyStr, authorization });\n\n return this.doFetch(url, {\n method: method.toUpperCase(),\n headers: { Authorization: authorization, ...sigHeaders, ...(options.headers ?? {}) },\n body: bodyStr !== '' ? bodyStr : undefined,\n });\n }\n\n // ─── Verification (resource-server side) ──────────────────────────\n\n /**\n * Verify an `auth+jwt` against this organization's issuer JWKS.\n * See `verifyAuthToken()` for details (PoP still required!).\n */\n async verifyAuthToken(\n token: string,\n options: Omit<VerifyAuthTokenOptions, 'issuer' | 'fetch'> & { issuer?: string }\n ): Promise<AAuthTokenClaims> {\n return verifyAuthToken(token, {\n issuer: options.issuer ?? this.issuer,\n fetch: this.fetchFn,\n ...options,\n });\n }\n\n // ─── Discovery ────────────────────────────────────────────────────\n\n /** Fetch `{issuer}/.well-known/aauth-issuer`. */\n async discoverIssuer(): Promise<AAuthIssuerMetadata> {\n return this.getJson<AAuthIssuerMetadata>(this.routeUrl('aauth.issuerMetadata'));\n }\n\n /** Fetch `{issuer}/.well-known/aauth-agent` — metadata for all active agents. */\n async discoverAgents(): Promise<AAuthAgentMetadata[]> {\n return this.getJson<AAuthAgentMetadata[]>(this.routeUrl('aauth.agentMetadata'));\n }\n\n /** Fetch `{resourceUrl}/.well-known/aauth-resource` from a resource server. */\n async discoverResource(resourceUrl: string): Promise<AAuthResourceMetadata | AAuthResourceMetadata[]> {\n const base = resourceUrl.replace(/\\/+$/, '');\n return this.getJson<AAuthResourceMetadata | AAuthResourceMetadata[]>(`${base}/.well-known/aauth-resource`);\n }\n\n // ─── Internals ────────────────────────────────────────────────────\n\n private requireAgentToken(agentToken: string): void {\n if (!agentToken) {\n throw new AAuthError(\n 'agentToken is required — the /agent/token endpoint authenticates the agent via the Agent-Auth header.',\n 'invalid_request'\n );\n }\n }\n\n private tokenUrl(): string {\n return this.routeUrl('aauth.agentToken');\n }\n\n /** Absolute URL for an org-scoped route from the shared registry. */\n private routeUrl(name: keyof typeof ROUTES): string {\n return `${this.baseUrl}${buildPath(ROUTES[name].path, { orgId: this.orgId })}`;\n }\n\n private async tokenRequest(body: Record<string, unknown>, agentToken: string): Promise<RawTokenResponse> {\n return (await this.signedPost(this.tokenUrl(), body, agentToken)) as RawTokenResponse;\n }\n\n private async signedPost(url: string, body: Record<string, unknown>, agentToken: string): Promise<unknown> {\n if (!this.orgId) {\n throw new LumoAuthConfigError('orgId is required for AAuth token operations');\n }\n const bodyStr = JSON.stringify(body);\n const headers = this.signRequest('POST', url, { body: bodyStr, agentToken });\n\n const response = await this.doFetch(url, { method: 'POST', headers, body: bodyStr });\n const text = await response.text();\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = undefined;\n }\n\n if (!response.ok) {\n const err = (parsed ?? {}) as { error?: string; error_description?: string };\n throw new AAuthError(\n err.error_description ?? err.error ?? `AAuth request failed: HTTP ${response.status}`,\n err.error ?? 'aauth_error',\n response.status,\n parsed ?? text\n );\n }\n return parsed ?? {};\n }\n\n private mapTokenResponse(data: RawTokenResponse): AAuthTokenResponse {\n if (!data.auth_token) {\n throw new AAuthError('Token response missing auth_token', 'invalid_response', undefined, data);\n }\n const result: AAuthTokenResponse = {\n requestType: (data.request_type ?? 'auth') as AAuthTokenResponse['requestType'],\n authToken: data.auth_token,\n expiresIn: data.expires_in ?? 0,\n tokenType: data.token_type ?? 'auth+jwt',\n };\n if (data.refresh_token) result.refreshToken = data.refresh_token;\n return result;\n }\n\n private async getJson<T>(url: string): Promise<T> {\n const response = await this.doFetch(url, { headers: { Accept: 'application/json' } });\n if (!response.ok) {\n throw new AAuthError(`Discovery request failed: HTTP ${response.status}`, 'discovery_failed', response.status);\n }\n return (await response.json()) as T;\n }\n\n private async doFetch(url: string, init: RequestInit): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n try {\n return await this.fetchFn(url, { ...init, signal: controller.signal });\n } catch (error) {\n if (error instanceof DOMException && error.name === 'AbortError') {\n throw new LumoAuthNetworkError(`Request to ${url} timed out after ${this.timeout}ms`, error);\n }\n throw new LumoAuthNetworkError(\n `Network request to ${url} failed: ${error instanceof Error ? error.message : String(error)}`,\n error\n );\n } finally {\n clearTimeout(timeoutId);\n }\n }\n}\n\nexport type { AAuthKeypair };\n","import {\n createHash,\n createPrivateKey,\n createPublicKey,\n generateKeyPairSync,\n randomBytes,\n sign as cryptoSign,\n type KeyObject,\n} from 'node:crypto';\nimport { dpopHtu, type DpopProofProvider, type DpopProofRequest } from '@lumoauth/shared';\nimport { jwkThumbprint, type AAuthJwk } from './keys';\n\n/**\n * RFC 9449 DPoP proof signing.\n *\n * A `DpopProofSigner` holds the agent's DPoP key and mints proof JWTs for\n * the token endpoint, the attestation endpoint and resource requests. The\n * LumoAuth server (`DPoPService`) accepts ES256/ES384/ES512, RS256/RS384/\n * RS512, PS256/PS384/PS512 and EdDSA; this signer produces ES256 (P-256,\n * the default), EdDSA (Ed25519, so the AAuth key can double as the DPoP\n * key) and RS256.\n *\n * Proof contents, as the server checks them:\n * - header `typ: \"dpop+jwt\"`, `alg`, `jwk` (public members only);\n * - `jti` 32 random characters, `htm` upper-case method, `htu` the URL\n * without query or fragment, `iat` now (the server allows 60 s ahead and\n * 300 s behind);\n * - `ath` = base64url(SHA-256(access token)) on resource requests;\n * - `nonce` when the server handed one out (`DPoP-Nonce`). The signer\n * remembers the latest nonce per origin, so `fetchWithDpop` only has to\n * retry once after a `use_dpop_nonce` answer.\n */\n\nexport type DpopAlgorithm = 'ES256' | 'EdDSA' | 'RS256';\n\nexport interface DpopProofSignerOptions {\n /** PEM (PKCS#8) private key: EC P-256, Ed25519 or RSA. */\n privateKeyPem?: string;\n /** A Node `KeyObject` private key, as an alternative to `privateKeyPem`. */\n privateKey?: KeyObject;\n /** Clock override in epoch seconds (tests only). */\n now?: () => number;\n}\n\n/** The public JWK carried in a DPoP proof header. */\nexport type DpopJwk = AAuthJwk;\n\nexport class DpopProofSigner implements DpopProofProvider {\n /** The JWS algorithm the proofs are signed with. */\n readonly algorithm: DpopAlgorithm;\n /** The public key as a JWK, with public members only. */\n readonly jwk: DpopJwk;\n /** RFC 7638 thumbprint of `jwk`: the `cnf.jkt` value of bound tokens. */\n readonly thumbprint: string;\n\n private readonly key: KeyObject;\n private readonly now: () => number;\n private readonly nonces = new Map<string, string>();\n\n /**\n * Generate a fresh key. ES256 (P-256) by default; pass `'EdDSA'` for an\n * Ed25519 key or `'RS256'` for a 2048-bit RSA key.\n */\n static generate(algorithm: DpopAlgorithm = 'ES256'): DpopProofSigner {\n let privateKey: KeyObject;\n switch (algorithm) {\n case 'ES256':\n privateKey = generateKeyPairSync('ec', { namedCurve: 'P-256' }).privateKey;\n break;\n case 'EdDSA':\n privateKey = generateKeyPairSync('ed25519').privateKey;\n break;\n case 'RS256':\n privateKey = generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey;\n break;\n default:\n throw new Error(`Unsupported DPoP algorithm: ${String(algorithm)}`);\n }\n return new DpopProofSigner({ privateKey });\n }\n\n constructor(options: DpopProofSignerOptions) {\n if (options.privateKey) {\n this.key = options.privateKey;\n } else if (options.privateKeyPem) {\n this.key = createPrivateKey(options.privateKeyPem);\n } else {\n throw new Error('DpopProofSigner needs privateKeyPem or privateKey');\n }\n if (this.key.type !== 'private') {\n throw new Error('DpopProofSigner needs a private key');\n }\n this.algorithm = algorithmFor(this.key);\n this.now = options.now ?? (() => Math.floor(Date.now() / 1000));\n\n const pub = createPublicKey(this.key).export({ format: 'jwk' }) as Record<string, unknown>;\n this.jwk = publicMembers(pub);\n this.thumbprint = jwkThumbprint(this.jwk);\n }\n\n /** The private key as PKCS#8 PEM, for your secret store. */\n get privateKeyPem(): string {\n return this.key.export({ type: 'pkcs8', format: 'pem' }).toString();\n }\n\n /** Create one proof JWT. See the file comment for the claims. */\n createProof(input: DpopProofRequest): string {\n const method = input.method.toUpperCase();\n const htu = dpopHtu(input.url);\n const nonce = input.nonce ?? this.getNonce(input.url);\n\n const header: Record<string, unknown> = { typ: 'dpop+jwt', alg: this.algorithm, jwk: this.jwk };\n const claims: Record<string, unknown> = {\n jti: randomBytes(24).toString('base64url'),\n htm: method,\n htu,\n iat: this.now(),\n };\n if (input.accessToken) claims.ath = dpopAth(input.accessToken);\n if (nonce) claims.nonce = nonce;\n\n const signingInput = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(claims))}`;\n const signature = signJws(this.algorithm, Buffer.from(signingInput, 'utf8'), this.key);\n return `${signingInput}.${signature.toString('base64url')}`;\n }\n\n /** Remember the latest server nonce for the origin of `url`. */\n setNonce(url: string, nonce: string): void {\n this.nonces.set(originOf(url), nonce);\n }\n\n /** The remembered nonce for the origin of `url`, if any. */\n getNonce(url: string): string | undefined {\n return this.nonces.get(originOf(url));\n }\n\n /** Forget every remembered nonce. */\n clearNonces(): void {\n this.nonces.clear();\n }\n}\n\n/** `ath` for an access token: base64url(SHA-256(token)). */\nexport function dpopAth(accessToken: string): string {\n return createHash('sha256').update(accessToken, 'ascii').digest('base64url');\n}\n\n/** Sign a JWS signing input with the algorithm's node:crypto settings. */\nexport function signJws(alg: DpopAlgorithm, data: Buffer, key: KeyObject): Buffer {\n switch (alg) {\n case 'ES256':\n return cryptoSign('sha256', data, { key, dsaEncoding: 'ieee-p1363' });\n case 'EdDSA':\n return cryptoSign(null, data, key);\n case 'RS256':\n return cryptoSign('sha256', data, key);\n default:\n throw new Error(`Unsupported DPoP algorithm: ${String(alg)}`);\n }\n}\n\nfunction algorithmFor(key: KeyObject): DpopAlgorithm {\n switch (key.asymmetricKeyType) {\n case 'ec': {\n const curve = key.asymmetricKeyDetails?.namedCurve;\n if (curve !== 'prime256v1' && curve !== 'P-256') {\n throw new Error(`DPoP EC keys must use P-256 (got ${String(curve)})`);\n }\n return 'ES256';\n }\n case 'ed25519':\n return 'EdDSA';\n case 'rsa':\n return 'RS256';\n default:\n throw new Error(`Unsupported DPoP key type: ${String(key.asymmetricKeyType)}`);\n }\n}\n\nfunction publicMembers(jwk: Record<string, unknown>): DpopJwk {\n const out: Record<string, unknown> = { kty: jwk.kty };\n for (const member of ['crv', 'x', 'y', 'n', 'e'] as const) {\n if (typeof jwk[member] === 'string') out[member] = jwk[member];\n }\n return out as DpopJwk;\n}\n\nfunction originOf(url: string): string {\n return new URL(url).origin;\n}\n\nfunction b64url(text: string): string {\n return Buffer.from(text, 'utf8').toString('base64url');\n}\n","import {\n LumoAuthApiError,\n LumoAuthConfigError,\n LumoAuthNetworkError,\n fetchWithDpop,\n type DpopProofProvider,\n} from '@lumoauth/shared';\n\n/**\n * Workload attestation: `POST {issuer}/agents/{agentId}/attest`.\n *\n * The agent's runtime presents a cloud-issued OIDC token (GitHub Actions,\n * GCP, AWS, Kubernetes, Azure, SPIFFE, …) and gets a short-lived LumoAuth\n * access token for the agent, with no client secret in the environment.\n * With a `dpop` signer the request carries an RFC 9449 proof and the token\n * comes back sender-constrained (`tokenType: \"DPoP\"`).\n *\n * NOTE: this endpoint is not yet in sdk-contract/routes.json, so the path\n * is built here rather than taken from the shared route registry.\n */\n\nexport interface AttestWorkloadOptions {\n /** LumoAuth instance URL. Defaults to `LUMOAUTH_URL` or `https://app.lumoauth.dev`. */\n baseUrl?: string;\n /** Organization slug. Defaults to `LUMOAUTH_ORG_ID`. */\n orgId?: string;\n /** The agent id (`agt_…`). */\n agentId: string;\n /** The workload's OIDC token. */\n attestationToken: string;\n /** DPoP proof signer; the returned token is bound to its key. */\n dpop?: DpopProofProvider;\n /** Custom fetch implementation. */\n fetch?: typeof globalThis.fetch;\n}\n\nexport interface AttestWorkloadResult {\n accessToken: string;\n /** `DPoP` when bound to the signer's key, otherwise `Bearer`. */\n tokenType: string;\n expiresIn: number | null;\n /** Space-separated agent capabilities. */\n scope: string | null;\n /** The verified workload identity (`provider`, `subject`, `issuer`, …). */\n identity: Record<string, unknown>;\n}\n\nfunction envVar(name: string): string | undefined {\n return typeof process !== 'undefined' && process.env ? process.env[name] : undefined;\n}\n\nexport async function attestWorkload(options: AttestWorkloadOptions): Promise<AttestWorkloadResult> {\n const baseUrl = (options.baseUrl ?? envVar('LUMOAUTH_URL') ?? 'https://app.lumoauth.dev').replace(/\\/+$/, '');\n const orgId = options.orgId ?? envVar('LUMOAUTH_ORG_ID') ?? '';\n if (!orgId) {\n throw new LumoAuthConfigError('attestWorkload requires orgId (or LUMOAUTH_ORG_ID).');\n }\n if (!options.agentId || !options.attestationToken) {\n throw new LumoAuthConfigError('attestWorkload requires agentId and attestationToken.');\n }\n const url = `${baseUrl}/orgs/${encodeURIComponent(orgId)}/api/v1/agents/${encodeURIComponent(options.agentId)}/attest`;\n const fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n const init: RequestInit = {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Accept: 'application/json' },\n body: JSON.stringify({ attestation_token: options.attestationToken }),\n };\n\n let res: Response;\n try {\n res = options.dpop ? await fetchWithDpop(fetchFn, url, init, options.dpop) : await fetchFn(url, init);\n } catch (error) {\n throw new LumoAuthNetworkError(\n `Agent attestation failed: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n\n const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n if (!res.ok || typeof body.access_token !== 'string') {\n throw new LumoAuthApiError(\n typeof body.error_description === 'string'\n ? body.error_description\n : `Agent attestation failed (HTTP ${res.status})`,\n typeof body.error === 'string' ? body.error : 'ATTESTATION_ERROR',\n res.status,\n body,\n );\n }\n return {\n accessToken: body.access_token,\n tokenType: typeof body.token_type === 'string' ? body.token_type : 'Bearer',\n expiresIn: typeof body.expires_in === 'number' ? body.expires_in : null,\n scope: typeof body.scope === 'string' ? body.scope : null,\n identity: typeof body.identity === 'object' && body.identity !== null ? (body.identity as Record<string, unknown>) : {},\n };\n}\n","import { constants, createHash, createPublicKey, verify as cryptoVerify, type KeyObject } from 'node:crypto';\nimport { DPOP_SCHEME, LumoAuthError, dpopHtu } from '@lumoauth/shared';\nimport { jwkThumbprint, type AAuthJwk } from './keys';\n\n/**\n * Local verification of LumoAuth core access tokens (`at+jwt`, RFC 9068).\n *\n * This is the token an MCP server or any other resource server receives\n * from an agent or a delegated user: a token-exchange result with `aud` set\n * to the resource URI, or an agent's client-credentials token. (AAuth\n * `auth+jwt` tokens are a different format; see `verifyAuthToken`.)\n *\n * Checks, in order: compact JWS shape; `typ` is `at+jwt` or\n * `application/at+jwt`; `alg` is an asymmetric JWS algorithm (`none` and\n * HMAC are refused); `kid` resolves in the issuer's JWKS, which is read from\n * `{issuer}/.well-known/openid-configuration` → `jwks_uri` and cached, with\n * one refetch on an unknown `kid`; signature; `iss`; `aud` contains the\n * resource; `exp` / `nbf` with a clock skew (default 60 s); `token_use` is\n * not `test`; and, when the token carries `cnf.jkt`, the RFC 9449 proof\n * binding of the incoming request.\n */\n\n// ─── Types ────────────────────────────────────────────────────────────\n\n/** OAuth Actor Profile actor object (`act` claim), nested for chains. */\nexport interface ActorClaim {\n /** `agent_agt_…` for an agent, a user id for a user. */\n sub: string;\n iss?: string;\n /** Entity classification, e.g. `ai_agent` or `user`. */\n sub_profile?: string;\n name?: string;\n act?: ActorClaim;\n [claim: string]: unknown;\n}\n\nexport interface AccessTokenClaims {\n iss: string;\n /** `agent_agt_…` for an agent, the user id for a delegated token. */\n sub: string;\n aud: string | string[];\n exp: number;\n iat: number;\n nbf?: number;\n jti: string;\n /** Space-separated scopes. */\n scope?: string;\n is_agent?: boolean;\n capabilities?: string[];\n act?: ActorClaim;\n cnf?: { jkt?: string; [member: string]: unknown };\n token_use?: string;\n client_id?: string;\n name?: string;\n [claim: string]: unknown;\n}\n\n/** Pluggable replay cache for DPoP `jti` values. */\nexport interface DpopReplayCache {\n /**\n * Record `key` for `ttlSeconds`. Return `true` when it was not seen\n * before, `false` when it was (a replay).\n */\n add(key: string, ttlSeconds: number): boolean | Promise<boolean>;\n}\n\n/** The DPoP proof of an incoming request, for the binding check. */\nexport interface IncomingDpopProof {\n /** HTTP method of the incoming request. */\n method: string;\n /** Full URL of the incoming request (the public one, behind any proxy). */\n url: string;\n /** The `DPoP` request header. */\n proof?: string | null;\n /**\n * The scheme of the `Authorization` header (`DPoP` or `Bearer`). A\n * DPoP-bound token must arrive with the `DPoP` scheme.\n */\n authorizationScheme?: string | null;\n /** The nonce this resource server expects in the proof, if it issues any. */\n nonce?: string;\n}\n\nexport interface VerifyAccessTokenOptions {\n /** The trusted issuer, e.g. `https://app.lumoauth.dev/orgs/acme-corp/api/v1`. */\n issuer: string;\n /** This resource server's URI. The token's `aud` must contain it. */\n resource: string;\n /** Pre-fetched issuer JWKS (no network). */\n jwks?: { keys: AAuthJwk[] };\n /** Custom fetch implementation. */\n fetch?: typeof globalThis.fetch;\n /** Allowed clock skew in seconds for `exp` and `nbf`. Default 60. */\n clockSkew?: number;\n /** Refuse tokens that are not DPoP-bound (no `cnf.jkt`). Default false. */\n requireDpop?: boolean;\n /** The incoming request's proof. Required when the token has `cnf.jkt`. */\n dpop?: IncomingDpopProof;\n /** Replay cache for proof `jti`s. Default: in-memory, 300 s. */\n replayCache?: DpopReplayCache;\n /** JWKS cache. Default: one shared per process, keyed by issuer. */\n jwksCache?: JwksCache;\n}\n\n/** Thrown when an access token or its DPoP binding is refused. */\nexport class AccessTokenError extends LumoAuthError {\n constructor(\n message: string,\n /** `invalid_token`, `invalid_dpop_proof` or `jwks_fetch_failed`. */\n code: 'invalid_token' | 'invalid_dpop_proof' | 'jwks_fetch_failed',\n statusCode = 401,\n ) {\n super(message, code, statusCode);\n this.name = 'AccessTokenError';\n }\n}\n\n// ─── Constants ────────────────────────────────────────────────────────\n\nconst AT_JWT_TYPES = new Set(['at+jwt', 'application/at+jwt']);\nconst DPOP_PROOF_TYP = 'dpop+jwt';\n/** Server window for a proof's `iat`: 60 s ahead, 300 s behind. */\nconst DPOP_IAT_FUTURE_SECONDS = 60;\nconst DPOP_IAT_PAST_SECONDS = 300;\nconst DPOP_JTI_TTL_SECONDS = 300;\nconst DPOP_JTI_MIN_LENGTH = 16;\n/** Do not hammer the JWKS endpoint on a stream of unknown kids. */\nconst JWKS_REFETCH_INTERVAL_MS = 30_000;\n\nconst JWS_VERIFIERS: Record<string, (data: Buffer, key: KeyObject, sig: Buffer) => boolean> = {\n RS256: (d, k, s) => cryptoVerify('sha256', d, k, s),\n RS384: (d, k, s) => cryptoVerify('sha384', d, k, s),\n RS512: (d, k, s) => cryptoVerify('sha512', d, k, s),\n PS256: (d, k, s) => cryptoVerify('sha256', d, pss(k), s),\n PS384: (d, k, s) => cryptoVerify('sha384', d, pss(k), s),\n PS512: (d, k, s) => cryptoVerify('sha512', d, pss(k), s),\n ES256: (d, k, s) => cryptoVerify('sha256', d, p1363(k), s),\n ES384: (d, k, s) => cryptoVerify('sha384', d, p1363(k), s),\n ES512: (d, k, s) => cryptoVerify('sha512', d, p1363(k), s),\n EdDSA: (d, k, s) => cryptoVerify(null, d, k, s),\n};\n\n/** Key type (and curve) each DPoP proof algorithm must be paired with. */\nconst DPOP_ALG_KEYS: Record<string, { kty: string; crv?: string }> = {\n ES256: { kty: 'EC', crv: 'P-256' },\n ES384: { kty: 'EC', crv: 'P-384' },\n ES512: { kty: 'EC', crv: 'P-521' },\n RS256: { kty: 'RSA' },\n RS384: { kty: 'RSA' },\n RS512: { kty: 'RSA' },\n PS256: { kty: 'RSA' },\n PS384: { kty: 'RSA' },\n PS512: { kty: 'RSA' },\n EdDSA: { kty: 'OKP', crv: 'Ed25519' },\n};\n\nfunction pss(key: KeyObject) {\n return { key, padding: constants.RSA_PKCS1_PSS_PADDING, saltLength: constants.RSA_PSS_SALTLEN_DIGEST };\n}\n\nfunction p1363(key: KeyObject) {\n return { key, dsaEncoding: 'ieee-p1363' as const };\n}\n\n// ─── JWKS cache ───────────────────────────────────────────────────────\n\n/** Per-issuer JWKS cache with discovery and a throttled refetch on unknown `kid`. */\nexport class JwksCache {\n private readonly entries = new Map<string, { keys: AAuthJwk[]; missRefetchAt: number }>();\n\n constructor(private readonly fetchFn?: typeof globalThis.fetch) {}\n\n /**\n * Find `kid` in the issuer's JWKS. An unknown `kid` triggers one refetch\n * (a key rotation); repeated misses refetch at most every 30 s, so a\n * stream of bogus tokens cannot hammer the JWKS endpoint.\n */\n async find(issuer: string, kid: string, fetchFn?: typeof globalThis.fetch): Promise<AAuthJwk | undefined> {\n const doFetch = fetchFn ?? this.fetchFn ?? globalThis.fetch;\n let entry = this.entries.get(issuer);\n if (!entry) {\n entry = { keys: await fetchJwks(issuer, doFetch), missRefetchAt: 0 };\n this.entries.set(issuer, entry);\n }\n let jwk = entry.keys.find((k) => k.kid === kid);\n if (!jwk && Date.now() - entry.missRefetchAt >= JWKS_REFETCH_INTERVAL_MS) {\n entry = { keys: await fetchJwks(issuer, doFetch), missRefetchAt: Date.now() };\n this.entries.set(issuer, entry);\n jwk = entry.keys.find((k) => k.kid === kid);\n }\n return jwk;\n }\n\n /** Drop the cached keys of one issuer, or of all when omitted. */\n clear(issuer?: string): void {\n if (issuer) this.entries.delete(issuer);\n else this.entries.clear();\n }\n}\n\nasync function fetchJwks(issuer: string, doFetch: typeof globalThis.fetch): Promise<AAuthJwk[]> {\n const base = issuer.replace(/\\/+$/, '');\n const discovery = await doFetch(`${base}/.well-known/openid-configuration`, {\n headers: { Accept: 'application/json' },\n });\n if (!discovery.ok) {\n throw new AccessTokenError(`Failed to fetch issuer discovery (HTTP ${discovery.status})`, 'jwks_fetch_failed', 503);\n }\n const metadata = (await discovery.json()) as { jwks_uri?: unknown };\n const jwksUri = typeof metadata.jwks_uri === 'string' ? metadata.jwks_uri : `${base}/.well-known/jwks.json`;\n\n const response = await doFetch(jwksUri, { headers: { Accept: 'application/json' } });\n if (!response.ok) {\n throw new AccessTokenError(`Failed to fetch issuer JWKS (HTTP ${response.status})`, 'jwks_fetch_failed', 503);\n }\n const jwks = (await response.json()) as { keys?: unknown };\n if (!Array.isArray(jwks.keys)) {\n throw new AccessTokenError('Issuer JWKS is malformed', 'jwks_fetch_failed', 503);\n }\n return jwks.keys as AAuthJwk[];\n}\n\nconst sharedJwksCache = new JwksCache();\n\n// ─── Replay cache ─────────────────────────────────────────────────────\n\n/** In-memory `jti` replay cache. One process only; use a shared store across replicas. */\nexport class InMemoryDpopReplayCache implements DpopReplayCache {\n private readonly seen = new Map<string, number>();\n\n constructor(private readonly now: () => number = () => Date.now()) {}\n\n add(key: string, ttlSeconds: number): boolean {\n const now = this.now();\n if (this.seen.size > 0 && this.seen.size % 256 === 0) this.prune(now);\n const expiresAt = this.seen.get(key);\n if (expiresAt !== undefined && expiresAt > now) return false;\n this.seen.set(key, now + ttlSeconds * 1000);\n return true;\n }\n\n private prune(now: number): void {\n for (const [key, expiresAt] of this.seen) {\n if (expiresAt <= now) this.seen.delete(key);\n }\n }\n}\n\nconst sharedReplayCache = new InMemoryDpopReplayCache();\n\n// ─── Helpers ──────────────────────────────────────────────────────────\n\nfunction decodeSegment(segment: string): unknown {\n try {\n return JSON.parse(Buffer.from(segment, 'base64url').toString('utf8'));\n } catch {\n throw new AccessTokenError('Invalid JWT encoding', 'invalid_token');\n }\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Split an `Authorization` header into scheme and credential. */\nexport function parseAuthorizationHeader(\n header: string | null | undefined,\n): { scheme: string; token: string } | null {\n if (!header) return null;\n const match = /^\\s*([A-Za-z][A-Za-z0-9+.-]*)\\s+(\\S+)\\s*$/.exec(header);\n return match ? { scheme: match[1], token: match[2] } : null;\n}\n\n/** The scopes of a verified token, as an array. */\nexport function accessTokenScopes(claims: AccessTokenClaims): string[] {\n return typeof claims.scope === 'string' ? claims.scope.split(' ').filter(Boolean) : [];\n}\n\n// ─── Access token verification ────────────────────────────────────────\n\n/**\n * Verify a LumoAuth `at+jwt` access token. Returns the claims or throws\n * `AccessTokenError`.\n *\n * @example\n * ```ts\n * const claims = await verifyAccessToken(token, {\n * issuer: 'https://app.lumoauth.dev/orgs/acme-corp/api/v1',\n * resource: 'https://mcp.example.com/mcp',\n * dpop: { method: req.method, url, proof: req.headers.dpop, authorizationScheme: 'DPoP' },\n * });\n * ```\n */\nexport async function verifyAccessToken(\n token: string,\n options: VerifyAccessTokenOptions,\n): Promise<AccessTokenClaims> {\n if (typeof token !== 'string' || token === '') {\n throw new AccessTokenError('Missing access token', 'invalid_token');\n }\n const parts = token.split('.');\n if (parts.length !== 3) {\n throw new AccessTokenError('Invalid JWT format', 'invalid_token');\n }\n const header = decodeSegment(parts[0]);\n const claims = decodeSegment(parts[1]);\n if (!isObject(header) || !isObject(claims)) {\n throw new AccessTokenError('Invalid JWT format', 'invalid_token');\n }\n\n if (typeof header.typ !== 'string' || !AT_JWT_TYPES.has(header.typ)) {\n throw new AccessTokenError(`Unexpected token type: ${String(header.typ)}`, 'invalid_token');\n }\n const alg = typeof header.alg === 'string' ? header.alg : '';\n const kid = typeof header.kid === 'string' ? header.kid : '';\n if (!alg || !kid) {\n throw new AccessTokenError('Missing kid or alg in JOSE header', 'invalid_token');\n }\n const verifier = JWS_VERIFIERS[alg];\n if (!verifier) {\n throw new AccessTokenError(`Disallowed JWS algorithm: ${alg}`, 'invalid_token');\n }\n\n if (claims.iss !== options.issuer) {\n throw new AccessTokenError('Untrusted issuer', 'invalid_token');\n }\n\n // Resolve the signing key.\n let jwk: AAuthJwk | undefined;\n if (options.jwks) {\n jwk = options.jwks.keys.find((k) => k.kid === kid);\n } else {\n const cache = options.jwksCache ?? sharedJwksCache;\n jwk = await cache.find(options.issuer, kid, options.fetch);\n }\n if (!jwk) {\n throw new AccessTokenError(`Key not found: kid=${kid}`, 'invalid_token');\n }\n assertAlgMatchesKey(alg, jwk);\n\n const publicKey = createPublicKey({ key: jwk as unknown as Record<string, unknown>, format: 'jwk' });\n const data = Buffer.from(`${parts[0]}.${parts[1]}`, 'utf8');\n const signature = Buffer.from(parts[2], 'base64url');\n if (!verifier(data, publicKey, signature)) {\n throw new AccessTokenError('Signature verification failed', 'invalid_token');\n }\n\n // Temporal and audience checks.\n const now = Math.floor(Date.now() / 1000);\n const skew = options.clockSkew ?? 60;\n if (typeof claims.exp !== 'number' || claims.exp < now - skew) {\n throw new AccessTokenError('Access token expired', 'invalid_token');\n }\n if (claims.nbf !== undefined && (typeof claims.nbf !== 'number' || claims.nbf > now + skew)) {\n throw new AccessTokenError('Access token not yet valid', 'invalid_token');\n }\n const aud = claims.aud;\n const audiences = typeof aud === 'string' ? [aud] : Array.isArray(aud) ? aud : [];\n if (!audiences.includes(options.resource)) {\n throw new AccessTokenError('Invalid audience', 'invalid_token');\n }\n if (typeof claims.sub !== 'string' || claims.sub === '') {\n throw new AccessTokenError('Missing sub claim', 'invalid_token');\n }\n if (claims.token_use === 'test') {\n throw new AccessTokenError('Test tokens are not accepted by resource servers', 'invalid_token');\n }\n\n // DPoP binding (RFC 9449 §7.1).\n const cnf = isObject(claims.cnf) ? claims.cnf : undefined;\n const jkt = typeof cnf?.jkt === 'string' ? cnf.jkt : undefined;\n if (jkt) {\n await verifyDpopBinding(token, jkt, options);\n } else if (options.requireDpop) {\n throw new AccessTokenError('Access token is not DPoP-bound', 'invalid_token');\n } else if (options.dpop?.authorizationScheme && options.dpop.authorizationScheme.toLowerCase() === DPOP_SCHEME.toLowerCase()) {\n throw new AccessTokenError('Access token is not DPoP-bound but was presented with the DPoP scheme', 'invalid_token');\n }\n\n return claims as unknown as AccessTokenClaims;\n}\n\nasync function verifyDpopBinding(token: string, jkt: string, options: VerifyAccessTokenOptions): Promise<void> {\n const incoming = options.dpop;\n if (!incoming) {\n throw new AccessTokenError(\n 'Access token is DPoP-bound: pass the incoming request (method, url, proof, authorizationScheme) in `dpop`',\n 'invalid_dpop_proof',\n );\n }\n if ((incoming.authorizationScheme ?? '').toLowerCase() !== DPOP_SCHEME.toLowerCase()) {\n throw new AccessTokenError('DPoP-bound access token must be presented with the DPoP scheme', 'invalid_token');\n }\n if (!incoming.proof) {\n throw new AccessTokenError('DPoP proof required for sender-constrained token', 'invalid_dpop_proof');\n }\n const proof = await verifyDpopProof(incoming.proof, {\n method: incoming.method,\n url: incoming.url,\n accessToken: token,\n nonce: incoming.nonce,\n replayCache: options.replayCache,\n });\n if (proof.thumbprint !== jkt) {\n throw new AccessTokenError('DPoP key does not match token binding', 'invalid_dpop_proof');\n }\n}\n\nfunction assertAlgMatchesKey(alg: string, jwk: AAuthJwk): void {\n const compatible =\n (jwk.kty === 'RSA' && (alg.startsWith('RS') || alg.startsWith('PS'))) ||\n (jwk.kty === 'EC' && alg.startsWith('ES')) ||\n (jwk.kty === 'OKP' && alg === 'EdDSA');\n if (!compatible) {\n throw new AccessTokenError(`Algorithm ${alg} incompatible with key type ${jwk.kty}`, 'invalid_token');\n }\n if (jwk.alg && jwk.alg !== alg) {\n throw new AccessTokenError(`Algorithm ${alg} does not match key alg ${jwk.alg}`, 'invalid_token');\n }\n}\n\n// ─── DPoP proof verification (resource side) ──────────────────────────\n\nexport interface VerifyDpopProofOptions {\n /** Method of the incoming request. */\n method: string;\n /** Full URL of the incoming request. */\n url: string;\n /** The presented access token, when the proof must carry `ath`. */\n accessToken?: string;\n /** Expected `nonce`, when this server issues nonces. */\n nonce?: string;\n /** Replay cache for `jti`. Default: in-memory, 300 s. */\n replayCache?: DpopReplayCache;\n /** Clock override in epoch seconds (tests only). */\n now?: () => number;\n}\n\nexport interface VerifiedDpopProof {\n /** The proof's public key. */\n jwk: AAuthJwk;\n /** RFC 7638 thumbprint of `jwk`. Compare with the token's `cnf.jkt`. */\n thumbprint: string;\n claims: { jti: string; htm: string; htu: string; iat: number; ath?: string; nonce?: string; [claim: string]: unknown };\n}\n\n/**\n * Verify a DPoP proof JWT against the incoming request, the same way the\n * LumoAuth server does: header (`typ`, allow-listed `alg`, public `jwk`\n * matching the algorithm), signature, `htm`, `htu` (scheme, host, port,\n * path; query and fragment ignored), `iat` window, `jti` replay, `ath` when\n * an access token is given, `nonce` when one is expected.\n */\nexport async function verifyDpopProof(proof: string, options: VerifyDpopProofOptions): Promise<VerifiedDpopProof> {\n const parts = proof.split('.');\n if (parts.length !== 3) {\n throw new AccessTokenError('Invalid DPoP proof format', 'invalid_dpop_proof');\n }\n let header: unknown;\n let claims: unknown;\n try {\n header = decodeSegment(parts[0]);\n claims = decodeSegment(parts[1]);\n } catch {\n throw new AccessTokenError('Invalid DPoP proof encoding', 'invalid_dpop_proof');\n }\n if (!isObject(header) || !isObject(claims)) {\n throw new AccessTokenError('Invalid DPoP proof format', 'invalid_dpop_proof');\n }\n if (header.typ !== DPOP_PROOF_TYP) {\n throw new AccessTokenError('DPoP proof typ must be dpop+jwt', 'invalid_dpop_proof');\n }\n const alg = typeof header.alg === 'string' ? header.alg : '';\n const expectedKey = DPOP_ALG_KEYS[alg];\n if (!expectedKey) {\n throw new AccessTokenError(`Disallowed DPoP proof algorithm: ${alg || '(none)'}`, 'invalid_dpop_proof');\n }\n const jwk = header.jwk;\n if (!isObject(jwk) || typeof jwk.kty !== 'string') {\n throw new AccessTokenError('DPoP proof is missing its jwk', 'invalid_dpop_proof');\n }\n if ('d' in jwk) {\n throw new AccessTokenError('DPoP proof jwk must not carry private members', 'invalid_dpop_proof');\n }\n if (jwk.kty !== expectedKey.kty || (expectedKey.crv && jwk.crv !== expectedKey.crv)) {\n throw new AccessTokenError(`DPoP proof jwk does not match ${alg}`, 'invalid_dpop_proof');\n }\n if (typeof jwk.alg === 'string' && jwk.alg !== alg) {\n throw new AccessTokenError('DPoP proof jwk alg does not match the header', 'invalid_dpop_proof');\n }\n\n let publicKey: KeyObject;\n try {\n publicKey = createPublicKey({ key: jwk as Record<string, unknown>, format: 'jwk' });\n } catch {\n throw new AccessTokenError('DPoP proof jwk is not a valid public key', 'invalid_dpop_proof');\n }\n const data = Buffer.from(`${parts[0]}.${parts[1]}`, 'utf8');\n const signature = Buffer.from(parts[2], 'base64url');\n let valid = false;\n try {\n valid = JWS_VERIFIERS[alg](data, publicKey, signature);\n } catch {\n valid = false;\n }\n if (!valid) {\n throw new AccessTokenError('DPoP proof signature verification failed', 'invalid_dpop_proof');\n }\n\n if (typeof claims.htm !== 'string' || claims.htm.toUpperCase() !== options.method.toUpperCase()) {\n throw new AccessTokenError('DPoP proof htm does not match the request method', 'invalid_dpop_proof');\n }\n if (typeof claims.htu !== 'string' || !htuMatches(claims.htu, options.url)) {\n throw new AccessTokenError('DPoP proof htu does not match the request URL', 'invalid_dpop_proof');\n }\n const now = options.now ? options.now() : Math.floor(Date.now() / 1000);\n if (typeof claims.iat !== 'number' || claims.iat > now + DPOP_IAT_FUTURE_SECONDS || claims.iat < now - DPOP_IAT_PAST_SECONDS) {\n throw new AccessTokenError('DPoP proof iat is outside the accepted window', 'invalid_dpop_proof');\n }\n if (typeof claims.jti !== 'string' || claims.jti.length < DPOP_JTI_MIN_LENGTH) {\n throw new AccessTokenError('DPoP proof jti is missing or too short', 'invalid_dpop_proof');\n }\n if (options.nonce !== undefined && claims.nonce !== options.nonce) {\n throw new AccessTokenError('DPoP proof nonce does not match', 'invalid_dpop_proof');\n }\n if (options.accessToken !== undefined) {\n const expectedAth = createHash('sha256').update(options.accessToken, 'ascii').digest('base64url');\n if (claims.ath !== expectedAth) {\n throw new AccessTokenError('DPoP proof ath does not match the access token', 'invalid_dpop_proof');\n }\n }\n\n const thumbprint = jwkThumbprint(jwk as AAuthJwk);\n const cache = options.replayCache ?? sharedReplayCache;\n if (!(await cache.add(`${thumbprint}:${claims.jti}`, DPOP_JTI_TTL_SECONDS))) {\n throw new AccessTokenError('DPoP proof jti was already used', 'invalid_dpop_proof');\n }\n\n return { jwk: jwk as AAuthJwk, thumbprint, claims: claims as VerifiedDpopProof['claims'] };\n}\n\nfunction htuMatches(htu: string, requestUrl: string): boolean {\n try {\n return dpopHtu(htu) === dpopHtu(requestUrl);\n } catch {\n return false;\n }\n}\n\n// ─── Verifier factory ─────────────────────────────────────────────────\n\nexport interface AccessTokenVerifierOptions extends Omit<VerifyAccessTokenOptions, 'dpop' | 'jwksCache' | 'replayCache'> {\n /** Replay cache for proof `jti`s. Default: one in-memory cache per verifier. */\n replayCache?: DpopReplayCache;\n}\n\n/** A request as a resource server sees it, for `verifyRequest`. */\nexport interface IncomingRequest {\n method: string;\n /** The full public URL of the request. */\n url: string;\n /** `Authorization` and `DPoP` headers, any case; or a `Headers` object. */\n headers: Headers | Record<string, string | string[] | undefined>;\n /** Expected nonce, when this server issues nonces. */\n nonce?: string;\n}\n\nexport interface AccessTokenVerifier {\n /** Verify a token; `dpop` is the incoming request when the token may be bound. */\n verify(token: string, dpop?: IncomingDpopProof): Promise<AccessTokenClaims>;\n /** Read `Authorization` (+ `DPoP`) from a request and verify. */\n verifyRequest(request: IncomingRequest): Promise<AccessTokenClaims>;\n /** Drop the cached JWKS. */\n clearCache(): void;\n}\n\n/**\n * A verifier with its own JWKS and replay caches, for a long-running\n * resource server.\n *\n * @example\n * ```ts\n * const verifier = createAccessTokenVerifier({\n * issuer: 'https://app.lumoauth.dev/orgs/acme-corp/api/v1',\n * resource: 'https://mcp.example.com/mcp',\n * });\n * const claims = await verifier.verifyRequest({ method: req.method, url, headers: req.headers });\n * ```\n */\nexport function createAccessTokenVerifier(options: AccessTokenVerifierOptions): AccessTokenVerifier {\n const jwksCache = new JwksCache(options.fetch);\n const replayCache = options.replayCache ?? new InMemoryDpopReplayCache();\n const base: VerifyAccessTokenOptions = { ...options, jwksCache, replayCache };\n\n return {\n verify: (token, dpop) => verifyAccessToken(token, dpop ? { ...base, dpop } : base),\n verifyRequest: async (request) => {\n const authorization = parseAuthorizationHeader(headerValue(request.headers, 'authorization'));\n if (!authorization) {\n throw new AccessTokenError('Missing or malformed Authorization header', 'invalid_token');\n }\n if (!['bearer', 'dpop'].includes(authorization.scheme.toLowerCase())) {\n throw new AccessTokenError(`Unsupported authorization scheme: ${authorization.scheme}`, 'invalid_token');\n }\n return verifyAccessToken(authorization.token, {\n ...base,\n dpop: {\n method: request.method,\n url: request.url,\n proof: headerValue(request.headers, 'dpop'),\n authorizationScheme: authorization.scheme,\n nonce: request.nonce,\n },\n });\n },\n clearCache: () => jwksCache.clear(),\n };\n}\n\nfunction headerValue(headers: IncomingRequest['headers'], name: string): string | null {\n if (typeof Headers !== 'undefined' && headers instanceof Headers) {\n return headers.get(name);\n }\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === name) {\n if (Array.isArray(value)) return value[0] ?? null;\n return value ?? null;\n }\n }\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAoBO;;;ACpBP,yBAQO;AA4BA,IAAM,wBAAwB;AAE9B,IAAM,uBAAuB;AAE7B,IAAM,iCAAiC;AAc9C,IAAM,iBAAsD,CAAC,SAAS,SAAS,SAAS,SAAS,SAAS,OAAO;AACjH,IAAM,wBAAkE;AAAA,EACpE,YAAY;AAAA,EACZ,SAAS;AAAA,EACT,WAAW;AAAA,EACX,SAAS;AAAA,EACT,WAAW;AAAA,EACX,SAAS;AACb;AA8BO,IAAM,wBAAN,MAAM,uBAAsB;AAAA;AAAA,EAY/B,OAAO,SAAS,YAAsC,SAAS,OAAuC;AAClG,QAAI;AACJ,QAAI,cAAc,WAAW,cAAc,WAAW,cAAc,SAAS;AACzE,YAAM,aAAa,EAAE,OAAO,SAAS,OAAO,SAAS,OAAO,QAAQ,EAAE,SAAS;AAC/E,uBAAa,wCAAo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,KAAK,QAAQ;AAAA,UACb,OAAO,YAAY,QAAQ,SAAS,MAAM;AAAA,UAC1C,qBAAqB,cAAc;AAAA,UACnC,OAAO,QAAQ;AAAA,QACnB;AAAA,MACJ,CAAC;AAAA,IACL;AAAA,IACA,YAAY,MAAM,UAAU,MAAM;AAAA,EACtC;AACJ;AAEA,SAAS,YAAY,SAAqC,MAA6B;AACnF,MAAI,OAAO,YAAY,eAAe,mBAAmB,SAAS;AAC9D,WAAO,QAAQ,IAAI,IAAI;AAAA,EAC3B;AACA,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,OAAO,GAAG;AAChD,QAAI,IAAI,YAAY,MAAM,MAAM;AAC5B,UAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,CAAC,KAAK;AAC7C,aAAO,SAAS;AAAA,IACpB;AAAA,EACJ;AACA,SAAO;AACX;;;AVvgBA,IAAAM,iBA4BO;","names":["cryptoSign","cryptoConstants","import_node_crypto","import_node_crypto","cryptoSign","cryptoVerify","import_node_crypto","import_shared","cryptoVerify","import_shared","envVar","import_node_crypto","import_shared","b64url","cryptoSign","import_shared","import_shared","envVar","import_node_crypto","import_shared","JWS_VERIFIERS","cryptoVerify","pss","p1363","decodeSegment","assertAlgMatchesKey","import_shared"]}