@lumoauth/agent 0.0.0-stage → 1.1.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/LICENSE +21 -0
- package/README.md +389 -2
- package/dist/index.d.mts +539 -0
- package/dist/index.d.ts +539 -0
- package/dist/index.js +770 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +747 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +50 -5
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/agent.ts","../src/keys.ts","../src/signing.ts","../src/verify.ts","../src/errors.ts","../src/client.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\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} 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 type AgentAskResult,\n type AgentIdentity,\n type AgentBudget,\n} from '@lumoauth/shared';\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 /** 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\ninterface TokenState {\n accessToken: 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 /** Token exchange for secured MCP servers. */\n readonly mcp: McpModule;\n\n private readonly clientSecret: string;\n private readonly scopes: string[] | undefined;\n private readonly fetchFn: typeof globalThis.fetch;\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 this.clientSecret = options.clientSecret ?? envVar('AGENT_CLIENT_SECRET') ?? '';\n this.scopes = options.scopes;\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n\n if (!this.clientId || !this.clientSecret) {\n throw new LumoAuthConfigError(\n 'Agent credentials required. Set AGENT_CLIENT_ID and AGENT_CLIENT_SECRET ' +\n 'environment variables or pass clientId/clientSecret to the constructor.',\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 });\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 });\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 });\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 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 let res: Response;\n try {\n res = await this.fetchFn(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams(form),\n });\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 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 * 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 /** 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 // ── 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 { 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"],"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;;;ACAA,oBAeO;AAiCP,SAAS,OAAO,MAAkC;AAC9C,SAAO,OAAO,YAAY,eAAe,QAAQ,MAAM,QAAQ,IAAI,IAAI,IAAI;AAC/E;AAGA,I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AAM,KAAK;AAAA,MAC/F;AACA,YAAM,IAAI;AAAA,QACN,sBAAsB,GAAG,YAAY,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,QAC3F;AAAA,MACJ;AAAA,IACJ,UAAE;AACE,mBAAa,SAAS;AAAA,IAC1B;AAAA,EACJ;AACJ;AAAA;AAlWa,YAEF,kBAAkB;;;AN7E7B,IAAAC,iBAmBO;","names":["import_node_crypto","cryptoSign","cryptoVerify","import_node_crypto","import_shared","cryptoVerify","import_shared","envVar","import_shared"]}
|