@usecontextlayer/cli 0.16.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +4 -4
  2. package/dist/auth-BL9AxZGb.mjs +1214 -0
  3. package/dist/auth-BL9AxZGb.mjs.map +1 -0
  4. package/dist/auth.d.mts +17 -2
  5. package/dist/auth.d.mts.map +1 -1
  6. package/dist/auth.mjs +1 -2
  7. package/dist/cli.mjs +153 -195
  8. package/dist/cli.mjs.map +1 -1
  9. package/dist/database-codegen-C5TEhR5_.mjs +24 -0
  10. package/dist/database-codegen-C5TEhR5_.mjs.map +1 -0
  11. package/dist/database-dialect-BLWWgYGo.mjs +56 -0
  12. package/dist/database-dialect-BLWWgYGo.mjs.map +1 -0
  13. package/dist/database.d.mts +35 -0
  14. package/dist/database.d.mts.map +1 -0
  15. package/dist/database.mjs +32 -0
  16. package/dist/database.mjs.map +1 -0
  17. package/dist/databases-SvX3IgqC.mjs +23 -0
  18. package/dist/databases-SvX3IgqC.mjs.map +1 -0
  19. package/dist/env-C_tllJ4u.mjs +98 -0
  20. package/dist/env-C_tllJ4u.mjs.map +1 -0
  21. package/dist/local-databases-ChvVgJH6.mjs +1 -0
  22. package/dist/local-databases-DVI3ngFq.mjs +53 -0
  23. package/dist/local-databases-DVI3ngFq.mjs.map +1 -0
  24. package/dist/{resources-B-EYHG1j.mjs → resources-BhJbHzU0.mjs} +24 -175
  25. package/dist/resources-BhJbHzU0.mjs.map +1 -0
  26. package/dist/{auth-DOsE8GwJ.mjs → schemas-D9UReYiT.mjs} +37 -1212
  27. package/dist/schemas-D9UReYiT.mjs.map +1 -0
  28. package/dist/schemas-DeaNWrS-.d.mts +2213 -0
  29. package/dist/schemas-DeaNWrS-.d.mts.map +1 -0
  30. package/dist/template.tar.gz +0 -0
  31. package/dist/vite.d.mts +5 -4330
  32. package/dist/vite.d.mts.map +1 -1
  33. package/dist/vite.mjs +16 -67
  34. package/dist/vite.mjs.map +1 -1
  35. package/package.json +12 -7
  36. package/dist/auth-DOsE8GwJ.mjs.map +0 -1
  37. package/dist/resources-B-EYHG1j.mjs.map +0 -1
  38. package/dist/rolldown-runtime-EAsCxrDo.mjs +0 -14
  39. package/dist/template/AGENTS.md +0 -13
  40. package/dist/template/README.md +0 -46
  41. package/dist/template/app/root.tsx +0 -66
  42. package/dist/template/app/routes/home.tsx +0 -25
  43. package/dist/template/databases/updates/drizzle.config.ts +0 -8
  44. package/dist/template/databases/updates/migrations/0000_create_updates.sql +0 -6
  45. package/dist/template/databases/updates/migrations/meta/0000_snapshot.json +0 -14
  46. package/dist/template/databases/updates/migrations/meta/_journal.json +0 -13
  47. package/dist/template/databases/updates/migrations/migrations.js +0 -10
  48. package/dist/template/databases/updates/schema.ts +0 -8
  49. package/dist/template/public/slate.json +0 -4
  50. package/dist/template/vite.config.ts +0 -9
  51. package/dist/template/workers/app.ts +0 -8
  52. package/dist/template/workers/local-resources/index.ts +0 -6
  53. package/dist/template/workers/local-resources/wrangler.jsonc +0 -19
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-BL9AxZGb.mjs","names":["USER_AGENT","ERR_INVALID_ARG_VALUE","ERR_INVALID_ARG_TYPE","CodedTypeError","allowInsecureRequests","customFetch","decoder","signal","performDiscovery","assertString","ClientSecretPost","None","oauth.ClientSecretPost","oauth.None","oauth.customFetch","oauth.ResponseBodyError","oauth.AuthorizationResponseError","oauth.WWWAuthenticateChallengeError","oauth.OperationProcessingError","oauth.HTTP_REQUEST_FORBIDDEN","oauth.REQUEST_PROTOCOL_FORBIDDEN","oauth.RESPONSE_IS_NOT_CONFORM","oauth.RESPONSE_IS_NOT_JSON","oauth.PARSE_ERROR","oauth.INVALID_RESPONSE","oauth.JWT_CLAIM_COMPARISON","oauth.JSON_ATTRIBUTE_COMPARISON","oauth.JWT_TIMESTAMP_CHECK","oauth.UnsupportedOperationError","oauth.UNSUPPORTED_OPERATION","oauth.discoveryRequest","oauth.allowInsecureRequests","oauth.processDiscoveryResponse","oauth._nodiscoverycheck","oauth.clockSkew","oauth.clockTolerance","oauth._expectedIssuer","oauth.getValidatedIdTokenClaims","oauth.jweDecrypt","oauth.deviceCodeGrantRequest","oauth.processDeviceCodeResponse","oauth\n .deviceAuthorizationRequest","oauth.processDeviceAuthorizationResponse","oauth\n .refreshTokenGrantRequest","oauth.processRefreshTokenResponse","oauth.isDPoPNonceError","z.object","z.string","z.number","z.url","oauth.discovery","oauth.None","oauth.allowInsecureRequests","oauth.initiateDeviceAuthorization","oauth.pollDeviceAuthorizationGrant","oauth\n\t\t\t\t.refreshTokenGrant","oauth.ResponseBodyError","z\n\t\t.object","z.array"],"sources":["../../../node_modules/.pnpm/oauth4webapi@3.8.8/node_modules/oauth4webapi/build/index.js","../../../node_modules/.pnpm/openid-client@6.8.8/node_modules/openid-client/build/index.js","../auth.ts"],"sourcesContent":["let USER_AGENT;\nif (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {\n const NAME = 'oauth4webapi';\n const VERSION = 'v3.8.8';\n USER_AGENT = `${NAME}/${VERSION}`;\n}\nfunction looseInstanceOf(input, expected) {\n if (input == null) {\n return false;\n }\n try {\n return (input instanceof expected ||\n Object.getPrototypeOf(input)[Symbol.toStringTag] === expected.prototype[Symbol.toStringTag]);\n }\n catch {\n return false;\n }\n}\nconst ERR_INVALID_ARG_VALUE = 'ERR_INVALID_ARG_VALUE';\nconst ERR_INVALID_ARG_TYPE = 'ERR_INVALID_ARG_TYPE';\nfunction CodedTypeError(message, code, cause) {\n const err = new TypeError(message, { cause });\n Object.assign(err, { code });\n return err;\n}\nexport const allowInsecureRequests = Symbol();\nexport const clockSkew = Symbol();\nexport const clockTolerance = Symbol();\nexport const customFetch = Symbol();\nexport const modifyAssertion = Symbol();\nexport const jweDecrypt = Symbol();\nexport const jwksCache = Symbol();\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\nfunction buf(input) {\n if (typeof input === 'string') {\n return encoder.encode(input);\n }\n return decoder.decode(input);\n}\nlet encodeBase64Url;\nif (Uint8Array.prototype.toBase64) {\n encodeBase64Url = (input) => {\n if (input instanceof ArrayBuffer) {\n input = new Uint8Array(input);\n }\n return input.toBase64({ alphabet: 'base64url', omitPadding: true });\n };\n}\nelse {\n const CHUNK_SIZE = 0x8000;\n encodeBase64Url = (input) => {\n if (input instanceof ArrayBuffer) {\n input = new Uint8Array(input);\n }\n const arr = [];\n for (let i = 0; i < input.byteLength; i += CHUNK_SIZE) {\n arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));\n }\n return btoa(arr.join('')).replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n };\n}\nlet decodeBase64Url;\nif (Uint8Array.fromBase64) {\n decodeBase64Url = (input) => {\n try {\n return Uint8Array.fromBase64(input, { alphabet: 'base64url' });\n }\n catch (cause) {\n throw CodedTypeError('The input to be decoded is not correctly encoded.', ERR_INVALID_ARG_VALUE, cause);\n }\n };\n}\nelse {\n decodeBase64Url = (input) => {\n try {\n const binary = atob(input.replace(/-/g, '+').replace(/_/g, '/').replace(/\\s/g, ''));\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n }\n catch (cause) {\n throw CodedTypeError('The input to be decoded is not correctly encoded.', ERR_INVALID_ARG_VALUE, cause);\n }\n };\n}\nfunction b64u(input) {\n if (typeof input === 'string') {\n return decodeBase64Url(input);\n }\n return encodeBase64Url(input);\n}\nexport class UnsupportedOperationError extends Error {\n code;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = UNSUPPORTED_OPERATION;\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nexport class OperationProcessingError extends Error {\n code;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n if (options?.code) {\n this.code = options?.code;\n }\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nfunction OPE(message, code, cause) {\n return new OperationProcessingError(message, { code, cause });\n}\nasync function calculateJwkThumbprint(jwk) {\n let components;\n switch (jwk.kty) {\n case 'EC':\n components = {\n crv: jwk.crv,\n kty: jwk.kty,\n x: jwk.x,\n y: jwk.y,\n };\n break;\n case 'OKP':\n components = {\n crv: jwk.crv,\n kty: jwk.kty,\n x: jwk.x,\n };\n break;\n case 'AKP':\n components = {\n alg: jwk.alg,\n kty: jwk.kty,\n pub: jwk.pub,\n };\n break;\n case 'RSA':\n components = {\n e: jwk.e,\n kty: jwk.kty,\n n: jwk.n,\n };\n break;\n default:\n throw new UnsupportedOperationError('unsupported JWK key type', { cause: jwk });\n }\n return b64u(await crypto.subtle.digest('SHA-256', buf(JSON.stringify(components))));\n}\nfunction assertCryptoKey(key, it) {\n if (!(key instanceof CryptoKey)) {\n throw CodedTypeError(`${it} must be a CryptoKey`, ERR_INVALID_ARG_TYPE);\n }\n}\nfunction assertPrivateKey(key, it) {\n assertCryptoKey(key, it);\n if (key.type !== 'private') {\n throw CodedTypeError(`${it} must be a private CryptoKey`, ERR_INVALID_ARG_VALUE);\n }\n}\nfunction assertPublicKey(key, it) {\n assertCryptoKey(key, it);\n if (key.type !== 'public') {\n throw CodedTypeError(`${it} must be a public CryptoKey`, ERR_INVALID_ARG_VALUE);\n }\n}\nfunction normalizeTyp(value) {\n return value.toLowerCase().replace(/^application\\//, '');\n}\nfunction isJsonObject(input) {\n if (input === null || typeof input !== 'object' || Array.isArray(input)) {\n return false;\n }\n return true;\n}\nfunction prepareHeaders(input) {\n if (looseInstanceOf(input, Headers)) {\n input = Object.fromEntries(input.entries());\n }\n const headers = new Headers(input ?? {});\n if (USER_AGENT && !headers.has('user-agent')) {\n headers.set('user-agent', USER_AGENT);\n }\n if (headers.has('authorization')) {\n throw CodedTypeError('\"options.headers\" must not include the \"authorization\" header name', ERR_INVALID_ARG_VALUE);\n }\n return headers;\n}\nfunction signal(url, value) {\n if (value !== undefined) {\n if (typeof value === 'function') {\n value = value(url.href);\n }\n if (!(value instanceof AbortSignal)) {\n throw CodedTypeError('\"options.signal\" must return or be an instance of AbortSignal', ERR_INVALID_ARG_TYPE);\n }\n return value;\n }\n return undefined;\n}\nfunction replaceDoubleSlash(pathname) {\n if (pathname.includes('//')) {\n return pathname.replace('//', '/');\n }\n return pathname;\n}\nfunction prependWellKnown(url, wellKnown, allowTerminatingSlash = false) {\n if (url.pathname === '/') {\n url.pathname = wellKnown;\n }\n else {\n url.pathname = replaceDoubleSlash(`${wellKnown}/${allowTerminatingSlash ? url.pathname : url.pathname.replace(/(\\/)$/, '')}`);\n }\n return url;\n}\nfunction appendWellKnown(url, wellKnown) {\n url.pathname = replaceDoubleSlash(`${url.pathname}/${wellKnown}`);\n return url;\n}\nasync function performDiscovery(input, urlName, transform, options) {\n if (!(input instanceof URL)) {\n throw CodedTypeError(`\"${urlName}\" must be an instance of URL`, ERR_INVALID_ARG_TYPE);\n }\n checkProtocol(input, options?.[allowInsecureRequests] !== true);\n const url = transform(new URL(input.href));\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n return (options?.[customFetch] || fetch)(url.href, {\n body: undefined,\n headers: Object.fromEntries(headers.entries()),\n method: 'GET',\n redirect: 'manual',\n signal: signal(url, options?.signal),\n });\n}\nexport async function discoveryRequest(issuerIdentifier, options) {\n return performDiscovery(issuerIdentifier, 'issuerIdentifier', (url) => {\n switch (options?.algorithm) {\n case undefined:\n case 'oidc':\n appendWellKnown(url, '.well-known/openid-configuration');\n break;\n case 'oauth2':\n prependWellKnown(url, '.well-known/oauth-authorization-server');\n break;\n default:\n throw CodedTypeError('\"options.algorithm\" must be \"oidc\" (default), or \"oauth2\"', ERR_INVALID_ARG_VALUE);\n }\n return url;\n }, options);\n}\nfunction assertNumber(input, allow0, it, code, cause) {\n try {\n if (typeof input !== 'number' || !Number.isFinite(input)) {\n throw CodedTypeError(`${it} must be a number`, ERR_INVALID_ARG_TYPE, cause);\n }\n if (input > 0)\n return;\n if (allow0) {\n if (input !== 0) {\n throw CodedTypeError(`${it} must be a non-negative number`, ERR_INVALID_ARG_VALUE, cause);\n }\n return;\n }\n throw CodedTypeError(`${it} must be a positive number`, ERR_INVALID_ARG_VALUE, cause);\n }\n catch (err) {\n if (code) {\n throw OPE(err.message, code, cause);\n }\n throw err;\n }\n}\nfunction assertString(input, it, code, cause) {\n try {\n if (typeof input !== 'string') {\n throw CodedTypeError(`${it} must be a string`, ERR_INVALID_ARG_TYPE, cause);\n }\n if (input.length === 0) {\n throw CodedTypeError(`${it} must not be empty`, ERR_INVALID_ARG_VALUE, cause);\n }\n }\n catch (err) {\n if (code) {\n throw OPE(err.message, code, cause);\n }\n throw err;\n }\n}\nexport async function processDiscoveryResponse(expectedIssuerIdentifier, response) {\n const expected = expectedIssuerIdentifier;\n if (!(expected instanceof URL) && expected !== _nodiscoverycheck) {\n throw CodedTypeError('\"expectedIssuerIdentifier\" must be an instance of URL', ERR_INVALID_ARG_TYPE);\n }\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n if (response.status !== 200) {\n throw OPE('\"response\" is not a conform Authorization Server Metadata response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);\n }\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.issuer, '\"response\" body \"issuer\" property', INVALID_RESPONSE, { body: json });\n if (expected !== _nodiscoverycheck && new URL(json.issuer).href !== expected.href) {\n throw OPE('\"response\" body \"issuer\" property does not match the expected value', JSON_ATTRIBUTE_COMPARISON, { expected: expected.href, body: json, attribute: 'issuer' });\n }\n return json;\n}\nfunction assertApplicationJson(response) {\n assertContentType(response, 'application/json');\n}\nfunction notJson(response, ...types) {\n let msg = '\"response\" content-type must be ';\n if (types.length > 2) {\n const last = types.pop();\n msg += `${types.join(', ')}, or ${last}`;\n }\n else if (types.length === 2) {\n msg += `${types[0]} or ${types[1]}`;\n }\n else {\n msg += types[0];\n }\n return OPE(msg, RESPONSE_IS_NOT_JSON, response);\n}\nfunction assertContentTypes(response, ...types) {\n if (!types.includes(getContentType(response))) {\n throw notJson(response, ...types);\n }\n}\nfunction assertContentType(response, contentType) {\n if (getContentType(response) !== contentType) {\n throw notJson(response, contentType);\n }\n}\nfunction randomBytes() {\n return b64u(crypto.getRandomValues(new Uint8Array(32)));\n}\nexport function generateRandomCodeVerifier() {\n return randomBytes();\n}\nexport function generateRandomState() {\n return randomBytes();\n}\nexport function generateRandomNonce() {\n return randomBytes();\n}\nexport async function calculatePKCECodeChallenge(codeVerifier) {\n assertString(codeVerifier, 'codeVerifier');\n return b64u(await crypto.subtle.digest('SHA-256', buf(codeVerifier)));\n}\nfunction getKeyAndKid(input) {\n if (input instanceof CryptoKey) {\n return { key: input };\n }\n if (!(input?.key instanceof CryptoKey)) {\n return {};\n }\n if (input.kid !== undefined) {\n assertString(input.kid, '\"kid\"');\n }\n return {\n key: input.key,\n kid: input.kid,\n };\n}\nfunction psAlg(key) {\n switch (key.algorithm.hash.name) {\n case 'SHA-256':\n return 'PS256';\n case 'SHA-384':\n return 'PS384';\n case 'SHA-512':\n return 'PS512';\n default:\n throw new UnsupportedOperationError('unsupported RsaHashedKeyAlgorithm hash name', {\n cause: key,\n });\n }\n}\nfunction rsAlg(key) {\n switch (key.algorithm.hash.name) {\n case 'SHA-256':\n return 'RS256';\n case 'SHA-384':\n return 'RS384';\n case 'SHA-512':\n return 'RS512';\n default:\n throw new UnsupportedOperationError('unsupported RsaHashedKeyAlgorithm hash name', {\n cause: key,\n });\n }\n}\nfunction esAlg(key) {\n switch (key.algorithm.namedCurve) {\n case 'P-256':\n return 'ES256';\n case 'P-384':\n return 'ES384';\n case 'P-521':\n return 'ES512';\n default:\n throw new UnsupportedOperationError('unsupported EcKeyAlgorithm namedCurve', { cause: key });\n }\n}\nfunction keyToJws(key) {\n switch (key.algorithm.name) {\n case 'RSA-PSS':\n return psAlg(key);\n case 'RSASSA-PKCS1-v1_5':\n return rsAlg(key);\n case 'ECDSA':\n return esAlg(key);\n case 'Ed25519':\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n return key.algorithm.name;\n case 'EdDSA':\n return 'Ed25519';\n default:\n throw new UnsupportedOperationError('unsupported CryptoKey algorithm name', { cause: key });\n }\n}\nfunction getClockSkew(client) {\n const skew = client?.[clockSkew];\n return typeof skew === 'number' && Number.isFinite(skew) ? skew : 0;\n}\nfunction getClockTolerance(client) {\n const tolerance = client?.[clockTolerance];\n return typeof tolerance === 'number' && Number.isFinite(tolerance) && Math.sign(tolerance) !== -1\n ? tolerance\n : 30;\n}\nfunction epochTime() {\n return Math.floor(Date.now() / 1000);\n}\nfunction assertAs(as) {\n if (typeof as !== 'object' || as === null) {\n throw CodedTypeError('\"as\" must be an object', ERR_INVALID_ARG_TYPE);\n }\n assertString(as.issuer, '\"as.issuer\"');\n}\nfunction assertClient(client) {\n if (typeof client !== 'object' || client === null) {\n throw CodedTypeError('\"client\" must be an object', ERR_INVALID_ARG_TYPE);\n }\n assertString(client.client_id, '\"client.client_id\"');\n}\nfunction formUrlEncode(token) {\n return encodeURIComponent(token).replace(/(?:[-_.!~*'()]|%20)/g, (substring) => {\n switch (substring) {\n case '-':\n case '_':\n case '.':\n case '!':\n case '~':\n case '*':\n case \"'\":\n case '(':\n case ')':\n return `%${substring.charCodeAt(0).toString(16).toUpperCase()}`;\n case '%20':\n return '+';\n default:\n throw new Error();\n }\n });\n}\nexport function ClientSecretPost(clientSecret) {\n assertString(clientSecret, '\"clientSecret\"');\n return (_as, client, body, _headers) => {\n body.set('client_id', client.client_id);\n body.set('client_secret', clientSecret);\n };\n}\nexport function ClientSecretBasic(clientSecret) {\n assertString(clientSecret, '\"clientSecret\"');\n return (_as, client, _body, headers) => {\n const username = formUrlEncode(client.client_id);\n const password = formUrlEncode(clientSecret);\n const credentials = btoa(`${username}:${password}`);\n headers.set('authorization', `Basic ${credentials}`);\n };\n}\nfunction clientAssertionPayload(as, client) {\n const now = epochTime() + getClockSkew(client);\n return {\n jti: randomBytes(),\n aud: as.issuer,\n exp: now + 60,\n iat: now,\n nbf: now,\n iss: client.client_id,\n sub: client.client_id,\n };\n}\nexport function PrivateKeyJwt(clientPrivateKey, options) {\n const { key, kid } = getKeyAndKid(clientPrivateKey);\n assertPrivateKey(key, '\"clientPrivateKey.key\"');\n return async (as, client, body, _headers) => {\n const header = { alg: keyToJws(key), kid };\n const payload = clientAssertionPayload(as, client);\n options?.[modifyAssertion]?.(header, payload);\n body.set('client_id', client.client_id);\n body.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer');\n body.set('client_assertion', await signJwt(header, payload, key));\n };\n}\nexport function ClientSecretJwt(clientSecret, options) {\n assertString(clientSecret, '\"clientSecret\"');\n const modify = options?.[modifyAssertion];\n let key;\n return async (as, client, body, _headers) => {\n key ||= await crypto.subtle.importKey('raw', buf(clientSecret), { hash: 'SHA-256', name: 'HMAC' }, false, ['sign']);\n const header = { alg: 'HS256' };\n const payload = clientAssertionPayload(as, client);\n modify?.(header, payload);\n const data = `${b64u(buf(JSON.stringify(header)))}.${b64u(buf(JSON.stringify(payload)))}`;\n const hmac = await crypto.subtle.sign(key.algorithm, key, buf(data));\n body.set('client_id', client.client_id);\n body.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer');\n body.set('client_assertion', `${data}.${b64u(new Uint8Array(hmac))}`);\n };\n}\nexport function None() {\n return (_as, client, body, _headers) => {\n body.set('client_id', client.client_id);\n };\n}\nexport function TlsClientAuth() {\n return None();\n}\nasync function signJwt(header, payload, key) {\n if (!key.usages.includes('sign')) {\n throw CodedTypeError('CryptoKey instances used for signing assertions must include \"sign\" in their \"usages\"', ERR_INVALID_ARG_VALUE);\n }\n const input = `${b64u(buf(JSON.stringify(header)))}.${b64u(buf(JSON.stringify(payload)))}`;\n const signature = b64u(await crypto.subtle.sign(keyToSubtle(key), key, buf(input)));\n return `${input}.${signature}`;\n}\nexport async function issueRequestObject(as, client, parameters, privateKey, options) {\n assertAs(as);\n assertClient(client);\n parameters = new URLSearchParams(parameters);\n const { key, kid } = getKeyAndKid(privateKey);\n assertPrivateKey(key, '\"privateKey.key\"');\n parameters.set('client_id', client.client_id);\n const now = epochTime() + getClockSkew(client);\n const claims = {\n ...Object.fromEntries(parameters.entries()),\n jti: randomBytes(),\n aud: as.issuer,\n exp: now + 60,\n iat: now,\n nbf: now,\n iss: client.client_id,\n };\n let resource;\n if (parameters.has('resource') &&\n (resource = parameters.getAll('resource')) &&\n resource.length > 1) {\n claims.resource = resource;\n }\n {\n let value = parameters.get('max_age');\n if (value !== null) {\n claims.max_age = parseInt(value, 10);\n assertNumber(claims.max_age, true, '\"max_age\" parameter');\n }\n }\n {\n let value = parameters.get('claims');\n if (value !== null) {\n try {\n claims.claims = JSON.parse(value);\n }\n catch (cause) {\n throw OPE('failed to parse the \"claims\" parameter as JSON', PARSE_ERROR, cause);\n }\n if (!isJsonObject(claims.claims)) {\n throw CodedTypeError('\"claims\" parameter must be a JSON with a top level object', ERR_INVALID_ARG_VALUE);\n }\n }\n }\n {\n let value = parameters.get('authorization_details');\n if (value !== null) {\n try {\n claims.authorization_details = JSON.parse(value);\n }\n catch (cause) {\n throw OPE('failed to parse the \"authorization_details\" parameter as JSON', PARSE_ERROR, cause);\n }\n if (!Array.isArray(claims.authorization_details)) {\n throw CodedTypeError('\"authorization_details\" parameter must be a JSON with a top level array', ERR_INVALID_ARG_VALUE);\n }\n }\n }\n const header = {\n alg: keyToJws(key),\n typ: 'oauth-authz-req+jwt',\n kid,\n };\n options?.[modifyAssertion]?.(header, claims);\n return signJwt(header, claims, key);\n}\nlet jwkCache;\nasync function getSetPublicJwkCache(key, alg) {\n const { kty, e, n, x, y, crv, pub } = await crypto.subtle.exportKey('jwk', key);\n const jwk = { kty, e, n, x, y, crv, pub };\n if (kty === 'AKP')\n jwk.alg = alg;\n jwkCache.set(key, jwk);\n return jwk;\n}\nasync function publicJwk(key, alg) {\n jwkCache ||= new WeakMap();\n return jwkCache.get(key) || getSetPublicJwkCache(key, alg);\n}\nconst URLParse = URL.parse\n ?\n (url, base) => URL.parse(url, base)\n : (url, base) => {\n try {\n return new URL(url, base);\n }\n catch {\n return null;\n }\n };\nexport function checkProtocol(url, enforceHttps) {\n if (enforceHttps && url.protocol !== 'https:') {\n throw OPE('only requests to HTTPS are allowed', HTTP_REQUEST_FORBIDDEN, url);\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n throw OPE('only HTTP and HTTPS requests are allowed', REQUEST_PROTOCOL_FORBIDDEN, url);\n }\n}\nfunction validateEndpoint(value, endpoint, useMtlsAlias, enforceHttps) {\n let url;\n if (typeof value !== 'string' || !(url = URLParse(value))) {\n throw OPE(`authorization server metadata does not contain a valid ${useMtlsAlias ? `\"as.mtls_endpoint_aliases.${endpoint}\"` : `\"as.${endpoint}\"`}`, value === undefined ? MISSING_SERVER_METADATA : INVALID_SERVER_METADATA, { attribute: useMtlsAlias ? `mtls_endpoint_aliases.${endpoint}` : endpoint });\n }\n checkProtocol(url, enforceHttps);\n return url;\n}\nexport function resolveEndpoint(as, endpoint, useMtlsAlias, enforceHttps) {\n if (useMtlsAlias && as.mtls_endpoint_aliases && endpoint in as.mtls_endpoint_aliases) {\n return validateEndpoint(as.mtls_endpoint_aliases[endpoint], endpoint, useMtlsAlias, enforceHttps);\n }\n return validateEndpoint(as[endpoint], endpoint, useMtlsAlias, enforceHttps);\n}\nexport async function pushedAuthorizationRequest(as, client, clientAuthentication, parameters, options) {\n assertAs(as);\n assertClient(client);\n const url = resolveEndpoint(as, 'pushed_authorization_request_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(parameters);\n body.set('client_id', client.client_id);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n if (options?.DPoP !== undefined) {\n assertDPoP(options.DPoP);\n await options.DPoP.addProof(url, headers, 'POST');\n }\n const response = await authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n options?.DPoP?.cacheNonce(response, url);\n return response;\n}\nclass DPoPHandler {\n #header;\n #privateKey;\n #publicKey;\n #clockSkew;\n #modifyAssertion;\n #map;\n #jkt;\n constructor(client, keyPair, options) {\n assertPrivateKey(keyPair?.privateKey, '\"DPoP.privateKey\"');\n assertPublicKey(keyPair?.publicKey, '\"DPoP.publicKey\"');\n if (!keyPair.publicKey.extractable) {\n throw CodedTypeError('\"DPoP.publicKey.extractable\" must be true', ERR_INVALID_ARG_VALUE);\n }\n this.#modifyAssertion = options?.[modifyAssertion];\n this.#clockSkew = getClockSkew(client);\n this.#privateKey = keyPair.privateKey;\n this.#publicKey = keyPair.publicKey;\n branded.add(this);\n }\n #get(key) {\n this.#map ||= new Map();\n let item = this.#map.get(key);\n if (item) {\n this.#map.delete(key);\n this.#map.set(key, item);\n }\n return item;\n }\n #set(key, val) {\n this.#map ||= new Map();\n this.#map.delete(key);\n if (this.#map.size === 100) {\n this.#map.delete(this.#map.keys().next().value);\n }\n this.#map.set(key, val);\n }\n async calculateThumbprint() {\n if (!this.#jkt) {\n const jwk = await crypto.subtle.exportKey('jwk', this.#publicKey);\n this.#jkt ||= await calculateJwkThumbprint(jwk);\n }\n return this.#jkt;\n }\n async addProof(url, headers, htm, accessToken) {\n const alg = keyToJws(this.#privateKey);\n this.#header ||= {\n alg,\n typ: 'dpop+jwt',\n jwk: await publicJwk(this.#publicKey, alg),\n };\n const nonce = this.#get(url.origin);\n const now = epochTime() + this.#clockSkew;\n const payload = {\n iat: now,\n jti: randomBytes(),\n htm,\n nonce,\n htu: `${url.origin}${url.pathname}`,\n ath: accessToken\n ? b64u(await crypto.subtle.digest('SHA-256', buf(accessToken)))\n : undefined,\n };\n this.#modifyAssertion?.(this.#header, payload);\n headers.set('dpop', await signJwt(this.#header, payload, this.#privateKey));\n }\n cacheNonce(response, url) {\n try {\n const nonce = response.headers.get('dpop-nonce');\n if (nonce) {\n this.#set(url.origin, nonce);\n }\n }\n catch { }\n }\n}\nexport function isDPoPNonceError(err) {\n if (err instanceof WWWAuthenticateChallengeError) {\n return err.cause.some((challenge) => challenge.scheme === 'dpop' && challenge.parameters.error === 'use_dpop_nonce');\n }\n if (err instanceof ResponseBodyError) {\n return err.error === 'use_dpop_nonce';\n }\n return false;\n}\nexport function DPoP(client, keyPair, options) {\n return new DPoPHandler(client, keyPair, options);\n}\nexport class ResponseBodyError extends Error {\n cause;\n code;\n error;\n status;\n error_description;\n response;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = RESPONSE_BODY_ERROR;\n this.cause = options.cause;\n this.error = options.cause.error;\n this.status = options.response.status;\n this.error_description = options.cause.error_description;\n Object.defineProperty(this, 'response', { enumerable: false, value: options.response });\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nexport class AuthorizationResponseError extends Error {\n cause;\n code;\n error;\n error_description;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = AUTHORIZATION_RESPONSE_ERROR;\n this.cause = options.cause;\n this.error = options.cause.get('error');\n this.error_description = options.cause.get('error_description') ?? undefined;\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nexport class WWWAuthenticateChallengeError extends Error {\n cause;\n code;\n response;\n status;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = WWW_AUTHENTICATE_CHALLENGE;\n this.cause = options.cause;\n this.status = options.response.status;\n this.response = options.response;\n Object.defineProperty(this, 'response', { enumerable: false });\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nconst tokenMatch = \"[a-zA-Z0-9!#$%&\\\\'\\\\*\\\\+\\\\-\\\\.\\\\^_`\\\\|~]+\";\nconst token68Match = '[a-zA-Z0-9\\\\-\\\\._\\\\~\\\\+\\\\/]+={0,2}';\nconst quotedMatch = '\"((?:[^\"\\\\\\\\]|\\\\\\\\[\\\\s\\\\S])*)\"';\nconst quotedParamMatcher = '(' + tokenMatch + ')\\\\s*=\\\\s*' + quotedMatch;\nconst paramMatcher = '(' + tokenMatch + ')\\\\s*=\\\\s*(' + tokenMatch + ')';\nconst schemeRE = new RegExp('^[,\\\\s]*(' + tokenMatch + ')');\nconst quotedParamRE = new RegExp('^[,\\\\s]*' + quotedParamMatcher + '[,\\\\s]*(.*)');\nconst unquotedParamRE = new RegExp('^[,\\\\s]*' + paramMatcher + '[,\\\\s]*(.*)');\nconst token68ParamRE = new RegExp('^(' + token68Match + ')(?:$|[,\\\\s])(.*)');\nfunction parseWwwAuthenticateChallenges(response) {\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n const header = response.headers.get('www-authenticate');\n if (header === null) {\n return undefined;\n }\n const challenges = [];\n let rest = header;\n while (rest) {\n let match = rest.match(schemeRE);\n const scheme = match?.['1'].toLowerCase();\n if (!scheme) {\n return undefined;\n }\n const afterScheme = rest.substring(match[0].length);\n if (afterScheme && !afterScheme.match(/^[\\s,]/)) {\n return undefined;\n }\n const spaceMatch = afterScheme.match(/^\\s+(.*)$/);\n const hasParameters = !!spaceMatch;\n rest = spaceMatch ? spaceMatch[1] : undefined;\n const parameters = {};\n let token68;\n if (hasParameters) {\n while (rest) {\n let key;\n let value;\n if ((match = rest.match(quotedParamRE))) {\n ;\n [, key, value, rest] = match;\n if (value.includes('\\\\')) {\n value = value.replace(/\\\\([\\s\\S])/g, '$1');\n }\n parameters[key.toLowerCase()] = value;\n continue;\n }\n if ((match = rest.match(unquotedParamRE))) {\n ;\n [, key, value, rest] = match;\n parameters[key.toLowerCase()] = value;\n continue;\n }\n if ((match = rest.match(token68ParamRE))) {\n if (Object.keys(parameters).length) {\n break;\n }\n ;\n [, token68, rest] = match;\n break;\n }\n return undefined;\n }\n }\n else {\n rest = afterScheme || undefined;\n }\n const challenge = { scheme, parameters };\n if (token68) {\n challenge.token68 = token68;\n }\n challenges.push(challenge);\n }\n if (!challenges.length) {\n return undefined;\n }\n return challenges;\n}\nexport async function processPushedAuthorizationResponse(as, client, response) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 201, 'Pushed Authorization Request Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.request_uri, '\"response\" body \"request_uri\" property', INVALID_RESPONSE, {\n body: json,\n });\n let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;\n assertNumber(expiresIn, true, '\"response\" body \"expires_in\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.expires_in = expiresIn;\n return json;\n}\nasync function parseOAuthResponseErrorBody(response) {\n if (response.status > 399 && response.status < 500) {\n assertReadableResponse(response);\n assertApplicationJson(response);\n try {\n const json = await response.clone().json();\n if (isJsonObject(json) && typeof json.error === 'string' && json.error.length) {\n return json;\n }\n }\n catch { }\n }\n return undefined;\n}\nasync function checkOAuthBodyError(response, expected, label) {\n if (response.status !== expected) {\n checkAuthenticationChallenges(response);\n let err;\n if ((err = await parseOAuthResponseErrorBody(response))) {\n await response.body?.cancel();\n throw new ResponseBodyError('server responded with an error in the response body', {\n cause: err,\n response,\n });\n }\n throw OPE(`\"response\" is not a conform ${label} response (unexpected HTTP status code)`, RESPONSE_IS_NOT_CONFORM, response);\n }\n}\nfunction assertDPoP(option) {\n if (!branded.has(option)) {\n throw CodedTypeError('\"options.DPoP\" is not a valid DPoPHandle', ERR_INVALID_ARG_VALUE);\n }\n}\nasync function resourceRequest(accessToken, method, url, headers, body, options) {\n assertString(accessToken, '\"accessToken\"');\n if (!(url instanceof URL)) {\n throw CodedTypeError('\"url\" must be an instance of URL', ERR_INVALID_ARG_TYPE);\n }\n checkProtocol(url, options?.[allowInsecureRequests] !== true);\n headers = prepareHeaders(headers);\n if (options?.DPoP) {\n assertDPoP(options.DPoP);\n await options.DPoP.addProof(url, headers, method.toUpperCase(), accessToken);\n }\n headers.set('authorization', `${headers.has('dpop') ? 'DPoP' : 'Bearer'} ${accessToken}`);\n const response = await (options?.[customFetch] || fetch)(url.href, {\n duplex: looseInstanceOf(body, ReadableStream) ? 'half' : undefined,\n body,\n headers: Object.fromEntries(headers.entries()),\n method,\n redirect: 'manual',\n signal: signal(url, options?.signal),\n });\n options?.DPoP?.cacheNonce(response, url);\n return response;\n}\nexport async function protectedResourceRequest(accessToken, method, url, headers, body, options) {\n const response = await resourceRequest(accessToken, method, url, headers, body, options);\n checkAuthenticationChallenges(response);\n return response;\n}\nexport async function userInfoRequest(as, client, accessToken, options) {\n assertAs(as);\n assertClient(client);\n const url = resolveEndpoint(as, 'userinfo_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const headers = prepareHeaders(options?.headers);\n if (client.userinfo_signed_response_alg) {\n headers.set('accept', 'application/jwt');\n }\n else {\n headers.set('accept', 'application/json');\n headers.append('accept', 'application/jwt');\n }\n return resourceRequest(accessToken, 'GET', url, headers, null, {\n ...options,\n [clockSkew]: getClockSkew(client),\n });\n}\nlet jwksMap;\nlet jwksRequests;\nlet jwksKeys;\nfunction setJwksCache(as, jwks, uat, cache) {\n jwksMap ||= new WeakMap();\n jwksMap.set(as, {\n jwks,\n uat,\n get age() {\n return epochTime() - this.uat;\n },\n });\n if (cache) {\n Object.assign(cache, { jwks: structuredClone(jwks), uat });\n }\n}\nfunction isFreshJwksCache(input) {\n if (typeof input !== 'object' || input === null) {\n return false;\n }\n if (!('uat' in input) || typeof input.uat !== 'number' || epochTime() - input.uat >= 300) {\n return false;\n }\n if (!('jwks' in input) ||\n !isJsonObject(input.jwks) ||\n !Array.isArray(input.jwks.keys) ||\n !Array.prototype.every.call(input.jwks.keys, isJsonObject)) {\n return false;\n }\n return true;\n}\nfunction clearJwksCache(as, cache) {\n jwksMap?.delete(as);\n delete cache?.jwks;\n delete cache?.uat;\n}\nasync function getPublicSigKeyFromIssuerJwksUri(as, options, header) {\n const { alg, kid } = header;\n checkSupportedJwsAlg(header);\n if (!jwksMap?.has(as) && isFreshJwksCache(options?.[jwksCache])) {\n setJwksCache(as, options?.[jwksCache].jwks, options?.[jwksCache].uat);\n }\n let jwks;\n let age;\n if (jwksMap?.has(as)) {\n ;\n ({ jwks, age } = jwksMap.get(as));\n if (age >= 300) {\n clearJwksCache(as, options?.[jwksCache]);\n return getPublicSigKeyFromIssuerJwksUri(as, options, header);\n }\n }\n else {\n const downloaded = await jwksRequest(as, options);\n jwks = downloaded.jwks;\n age = epochTime() - downloaded.uat;\n setJwksCache(as, jwks, downloaded.uat, options?.[jwksCache]);\n }\n let kty;\n switch (alg.slice(0, 2)) {\n case 'RS':\n case 'PS':\n kty = 'RSA';\n break;\n case 'ES':\n kty = 'EC';\n break;\n case 'Ed':\n kty = 'OKP';\n break;\n case 'ML':\n kty = 'AKP';\n break;\n default:\n throw new UnsupportedOperationError('unsupported JWS algorithm', { cause: { alg } });\n }\n const candidates = jwks.keys.filter((jwk) => {\n if (jwk.kty !== kty) {\n return false;\n }\n if (kid !== undefined && kid !== jwk.kid) {\n return false;\n }\n if (jwk.alg !== undefined && alg !== jwk.alg) {\n return false;\n }\n if (jwk.use !== undefined && jwk.use !== 'sig') {\n return false;\n }\n if (jwk.key_ops?.includes('verify') === false) {\n return false;\n }\n switch (true) {\n case alg === 'ES256' && jwk.crv !== 'P-256':\n case alg === 'ES384' && jwk.crv !== 'P-384':\n case alg === 'ES512' && jwk.crv !== 'P-521':\n case alg === 'Ed25519' && jwk.crv !== 'Ed25519':\n case alg === 'EdDSA' && jwk.crv !== 'Ed25519':\n return false;\n }\n return true;\n });\n const { 0: jwk, length } = candidates;\n if (!length) {\n if (age >= 60) {\n clearJwksCache(as, options?.[jwksCache]);\n return getPublicSigKeyFromIssuerJwksUri(as, options, header);\n }\n throw OPE('error when selecting a JWT verification key, no applicable keys found', KEY_SELECTION, { header, candidates, jwks_uri: new URL(as.jwks_uri) });\n }\n if (length !== 1) {\n throw OPE('error when selecting a JWT verification key, multiple applicable keys found, a \"kid\" JWT Header Parameter is required', KEY_SELECTION, { header, candidates, jwks_uri: new URL(as.jwks_uri) });\n }\n jwksKeys ||= new WeakMap();\n let keys = jwksKeys.get(jwk);\n if (!keys) {\n keys = new Map();\n jwksKeys.set(jwk, keys);\n }\n let key = keys.get(alg);\n if (!key) {\n key = importJwk(alg, jwk).catch((cause) => {\n keys.delete(alg);\n throw cause;\n });\n keys.set(alg, key);\n }\n return key;\n}\nexport const skipSubjectCheck = Symbol();\nexport function getContentType(input) {\n return input.headers.get('content-type')?.split(';')[0];\n}\nexport async function processUserInfoResponse(as, client, expectedSubject, response, options) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n checkAuthenticationChallenges(response);\n if (response.status !== 200) {\n throw OPE('\"response\" is not a conform UserInfo Endpoint response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);\n }\n assertReadableResponse(response);\n let json;\n if (getContentType(response) === 'application/jwt') {\n const { claims, jwt } = await validateJwt(await response.text(), checkSigningAlgorithm.bind(undefined, client.userinfo_signed_response_alg, as.userinfo_signing_alg_values_supported, undefined), getClockSkew(client), getClockTolerance(client), options?.[jweDecrypt])\n .then(validateOptionalAudience.bind(undefined, client.client_id))\n .then(validateOptionalIssuer.bind(undefined, as));\n jwtRefs.set(response, jwt);\n json = claims;\n }\n else {\n if (client.userinfo_signed_response_alg) {\n throw OPE('JWT UserInfo Response expected', JWT_USERINFO_EXPECTED, response);\n }\n json = await getResponseJsonBody(response);\n }\n assertString(json.sub, '\"response\" body \"sub\" property', INVALID_RESPONSE, { body: json });\n switch (expectedSubject) {\n case skipSubjectCheck:\n break;\n default:\n assertString(expectedSubject, '\"expectedSubject\"');\n if (json.sub !== expectedSubject) {\n throw OPE('unexpected \"response\" body \"sub\" property value', JSON_ATTRIBUTE_COMPARISON, {\n expected: expectedSubject,\n body: json,\n attribute: 'sub',\n });\n }\n }\n return json;\n}\nasync function authenticatedRequest(as, client, clientAuthentication, url, body, headers, options) {\n await clientAuthentication(as, client, body, headers);\n headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');\n return (options?.[customFetch] || fetch)(url.href, {\n body,\n headers: Object.fromEntries(headers.entries()),\n method: 'POST',\n redirect: 'manual',\n signal: signal(url, options?.signal),\n });\n}\nasync function tokenEndpointRequest(as, client, clientAuthentication, grantType, parameters, options) {\n const url = resolveEndpoint(as, 'token_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n parameters.set('grant_type', grantType);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n if (options?.DPoP !== undefined) {\n assertDPoP(options.DPoP);\n await options.DPoP.addProof(url, headers, 'POST');\n }\n const response = await authenticatedRequest(as, client, clientAuthentication, url, parameters, headers, options);\n options?.DPoP?.cacheNonce(response, url);\n return response;\n}\nexport async function refreshTokenGrantRequest(as, client, clientAuthentication, refreshToken, options) {\n assertAs(as);\n assertClient(client);\n assertString(refreshToken, '\"refreshToken\"');\n const parameters = new URLSearchParams(options?.additionalParameters);\n parameters.set('refresh_token', refreshToken);\n return tokenEndpointRequest(as, client, clientAuthentication, 'refresh_token', parameters, options);\n}\nconst idTokenClaims = new WeakMap();\nconst jwtRefs = new WeakMap();\nexport function getValidatedIdTokenClaims(ref) {\n if (!ref.id_token) {\n return undefined;\n }\n const claims = idTokenClaims.get(ref);\n if (!claims) {\n throw CodedTypeError('\"ref\" was already garbage collected or did not resolve from the proper sources', ERR_INVALID_ARG_VALUE);\n }\n return claims;\n}\nexport async function validateApplicationLevelSignature(as, ref, options) {\n assertAs(as);\n if (!jwtRefs.has(ref)) {\n throw CodedTypeError('\"ref\" does not contain a processed JWT Response to verify the signature of', ERR_INVALID_ARG_VALUE);\n }\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = jwtRefs.get(ref).split('.');\n const header = JSON.parse(buf(b64u(protectedHeader)));\n if (header.alg.startsWith('HS')) {\n throw new UnsupportedOperationError('unsupported JWS algorithm', { cause: { alg: header.alg } });\n }\n let key;\n key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);\n await validateJwsSignature(protectedHeader, payload, key, b64u(encodedSignature));\n}\nasync function processGenericAccessTokenResponse(as, client, response, additionalRequiredIdTokenClaims, decryptFn, recognizedTokenTypes) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Token Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.access_token, '\"response\" body \"access_token\" property', INVALID_RESPONSE, {\n body: json,\n });\n assertString(json.token_type, '\"response\" body \"token_type\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.token_type = json.token_type.toLowerCase();\n if (json.expires_in !== undefined) {\n let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;\n assertNumber(expiresIn, true, '\"response\" body \"expires_in\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.expires_in = expiresIn;\n }\n if (json.refresh_token !== undefined) {\n assertString(json.refresh_token, '\"response\" body \"refresh_token\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n if (json.scope !== undefined && typeof json.scope !== 'string') {\n throw OPE('\"response\" body \"scope\" property must be a string', INVALID_RESPONSE, { body: json });\n }\n if (json.id_token !== undefined) {\n assertString(json.id_token, '\"response\" body \"id_token\" property', INVALID_RESPONSE, {\n body: json,\n });\n const requiredClaims = [];\n if (client.require_auth_time === true) {\n requiredClaims.push('auth_time');\n }\n if (client.default_max_age !== undefined) {\n assertNumber(client.default_max_age, true, '\"client.default_max_age\"');\n requiredClaims.push('auth_time');\n }\n if (additionalRequiredIdTokenClaims?.length) {\n requiredClaims.push(...additionalRequiredIdTokenClaims);\n }\n const { claims, jwt } = await validateIdTokenClaims(as, client, json.id_token, requiredClaims, decryptFn);\n validateIdTokenAuthorizedParty(client, claims);\n validateIdTokenAuthTimeClaim(claims);\n jwtRefs.set(response, jwt);\n idTokenClaims.set(json, claims);\n }\n if (recognizedTokenTypes?.[json.token_type] !== undefined) {\n recognizedTokenTypes[json.token_type](response, json);\n }\n else if (json.token_type !== 'dpop' && json.token_type !== 'bearer') {\n throw new UnsupportedOperationError('unsupported `token_type` value', { cause: { body: json } });\n }\n return json;\n}\nfunction checkAuthenticationChallenges(response) {\n let challenges;\n if ((challenges = parseWwwAuthenticateChallenges(response))) {\n throw new WWWAuthenticateChallengeError('server responded with a challenge in the WWW-Authenticate HTTP Header', { cause: challenges, response });\n }\n}\nexport async function processRefreshTokenResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nfunction validateOptionalAudience(expected, result) {\n if (result.claims.aud !== undefined) {\n return validateAudience(expected, result);\n }\n return result;\n}\nfunction validateAudience(expected, result) {\n if (Array.isArray(result.claims.aud)) {\n if (!result.claims.aud.includes(expected)) {\n throw OPE('unexpected JWT \"aud\" (audience) claim value', JWT_CLAIM_COMPARISON, {\n expected,\n claims: result.claims,\n claim: 'aud',\n });\n }\n }\n else if (result.claims.aud !== expected) {\n throw OPE('unexpected JWT \"aud\" (audience) claim value', JWT_CLAIM_COMPARISON, {\n expected,\n claims: result.claims,\n claim: 'aud',\n });\n }\n return result;\n}\nfunction validateOptionalIssuer(as, result) {\n if (result.claims.iss !== undefined) {\n return validateIssuer(as, result);\n }\n return result;\n}\nfunction validateIssuer(as, result) {\n const expected = as[_expectedIssuer]?.(result) ?? as.issuer;\n if (result.claims.iss !== expected) {\n throw OPE('unexpected JWT \"iss\" (issuer) claim value', JWT_CLAIM_COMPARISON, {\n expected,\n claims: result.claims,\n claim: 'iss',\n });\n }\n return result;\n}\nconst branded = new WeakSet();\nfunction brand(searchParams) {\n branded.add(searchParams);\n return searchParams;\n}\nexport const nopkce = Symbol();\nexport async function authorizationCodeGrantRequest(as, client, clientAuthentication, callbackParameters, redirectUri, codeVerifier, options) {\n assertAs(as);\n assertClient(client);\n if (!branded.has(callbackParameters)) {\n throw CodedTypeError('\"callbackParameters\" must be an instance of URLSearchParams obtained from \"validateAuthResponse()\", or \"validateJwtAuthResponse()', ERR_INVALID_ARG_VALUE);\n }\n assertString(redirectUri, '\"redirectUri\"');\n const code = getURLSearchParameter(callbackParameters, 'code');\n if (!code) {\n throw OPE('no authorization code in \"callbackParameters\"', INVALID_RESPONSE);\n }\n const parameters = new URLSearchParams(options?.additionalParameters);\n parameters.set('redirect_uri', redirectUri);\n parameters.set('code', code);\n if (codeVerifier !== nopkce) {\n assertString(codeVerifier, '\"codeVerifier\"');\n parameters.set('code_verifier', codeVerifier);\n }\n return tokenEndpointRequest(as, client, clientAuthentication, 'authorization_code', parameters, options);\n}\nconst jwtClaimNames = {\n aud: 'audience',\n c_hash: 'code hash',\n client_id: 'client id',\n exp: 'expiration time',\n iat: 'issued at',\n iss: 'issuer',\n jti: 'jwt id',\n nonce: 'nonce',\n s_hash: 'state hash',\n sub: 'subject',\n ath: 'access token hash',\n htm: 'http method',\n htu: 'http uri',\n cnf: 'confirmation',\n auth_time: 'authentication time',\n};\nfunction validatePresence(required, result) {\n for (const claim of required) {\n if (result.claims[claim] === undefined) {\n throw OPE(`JWT \"${claim}\" (${jwtClaimNames[claim]}) claim missing`, INVALID_RESPONSE, {\n claims: result.claims,\n });\n }\n }\n return result;\n}\nfunction validateStringClaim(claim, result) {\n if (typeof result.claims[claim] !== 'string') {\n throw OPE(`unexpected JWT \"${claim}\" (${jwtClaimNames[claim]}) claim type`, INVALID_RESPONSE, {\n claims: result.claims,\n });\n }\n return result;\n}\nfunction validateIdTokenClaims(as, client, idToken, requiredClaims, decryptFn) {\n return validateJwt(idToken, checkSigningAlgorithm.bind(undefined, client.id_token_signed_response_alg, as.id_token_signing_alg_values_supported, 'RS256'), getClockSkew(client), getClockTolerance(client), decryptFn)\n .then(validatePresence.bind(undefined, ['aud', 'exp', 'iat', 'iss', 'sub', ...requiredClaims]))\n .then(validateIssuer.bind(undefined, as))\n .then(validateAudience.bind(undefined, client.client_id))\n .then(validateStringClaim.bind(undefined, 'sub'));\n}\nfunction resolveIdTokenMaxAge(client, maxAge) {\n if (maxAge === skipAuthTimeCheck) {\n return maxAge;\n }\n const fromClient = maxAge === undefined;\n if (fromClient) {\n maxAge = client.default_max_age;\n }\n if (maxAge === undefined) {\n return skipAuthTimeCheck;\n }\n assertNumber(maxAge, true, fromClient ? '\"client.default_max_age\"' : '\"maxAge\" argument');\n return maxAge;\n}\nfunction validateIdTokenAuthTimeClaim(claims) {\n if (claims.auth_time !== undefined) {\n assertNumber(claims.auth_time, true, 'ID Token \"auth_time\" (authentication time)', INVALID_RESPONSE, { claims });\n }\n}\nfunction validateIdTokenAuthTime(client, claims, maxAge) {\n if (maxAge === skipAuthTimeCheck) {\n return;\n }\n const now = epochTime() + getClockSkew(client);\n const tolerance = getClockTolerance(client);\n if (claims.auth_time + maxAge < now - tolerance) {\n throw OPE('too much time has elapsed since the last End-User authentication', JWT_TIMESTAMP_CHECK, { claims, now, tolerance, claim: 'auth_time' });\n }\n}\nfunction validateIdTokenNonce(claims, expectedNonce) {\n const expected = expectedNonce === expectNoNonce ? undefined : expectedNonce;\n if (claims.nonce !== expected) {\n throw OPE('unexpected ID Token \"nonce\" claim value', JWT_CLAIM_COMPARISON, {\n expected,\n claims,\n claim: 'nonce',\n });\n }\n}\nfunction validateIdTokenAuthorizedParty(client, claims) {\n if (Array.isArray(claims.aud) && claims.aud.length !== 1) {\n if (claims.azp === undefined) {\n throw OPE('ID Token \"aud\" (audience) claim includes additional untrusted audiences', JWT_CLAIM_COMPARISON, { claims, claim: 'aud' });\n }\n if (claims.azp !== client.client_id) {\n throw OPE('unexpected ID Token \"azp\" (authorized party) claim value', JWT_CLAIM_COMPARISON, {\n expected: client.client_id,\n claims,\n claim: 'azp',\n });\n }\n }\n}\nexport const expectNoNonce = Symbol();\nexport const skipAuthTimeCheck = Symbol();\nexport async function processAuthorizationCodeResponse(as, client, response, options) {\n if (typeof options?.expectedNonce === 'string' ||\n typeof options?.maxAge === 'number' ||\n options?.requireIdToken) {\n return processAuthorizationCodeOpenIDResponse(as, client, response, options.expectedNonce, options.maxAge, options[jweDecrypt], options.recognizedTokenTypes);\n }\n return processAuthorizationCodeOAuth2Response(as, client, response, options?.maxAge, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nasync function processAuthorizationCodeOpenIDResponse(as, client, response, expectedNonce, maxAge, decryptFn, recognizedTokenTypes) {\n const additionalRequiredClaims = [];\n switch (expectedNonce) {\n case undefined:\n expectedNonce = expectNoNonce;\n break;\n case expectNoNonce:\n break;\n default:\n assertString(expectedNonce, '\"expectedNonce\" argument');\n additionalRequiredClaims.push('nonce');\n }\n maxAge = resolveIdTokenMaxAge(client, maxAge);\n if (maxAge !== skipAuthTimeCheck) {\n additionalRequiredClaims.push('auth_time');\n }\n const result = await processGenericAccessTokenResponse(as, client, response, additionalRequiredClaims, decryptFn, recognizedTokenTypes);\n assertString(result.id_token, '\"response\" body \"id_token\" property', INVALID_RESPONSE, {\n body: result,\n });\n const claims = getValidatedIdTokenClaims(result);\n validateIdTokenAuthTime(client, claims, maxAge);\n validateIdTokenNonce(claims, expectedNonce);\n return result;\n}\nasync function processAuthorizationCodeOAuth2Response(as, client, response, maxAge, decryptFn, recognizedTokenTypes) {\n const result = await processGenericAccessTokenResponse(as, client, response, undefined, decryptFn, recognizedTokenTypes);\n const claims = getValidatedIdTokenClaims(result);\n if (claims) {\n validateIdTokenAuthTime(client, claims, resolveIdTokenMaxAge(client, maxAge));\n validateIdTokenNonce(claims, expectNoNonce);\n }\n return result;\n}\nexport const WWW_AUTHENTICATE_CHALLENGE = 'OAUTH_WWW_AUTHENTICATE_CHALLENGE';\nexport const RESPONSE_BODY_ERROR = 'OAUTH_RESPONSE_BODY_ERROR';\nexport const UNSUPPORTED_OPERATION = 'OAUTH_UNSUPPORTED_OPERATION';\nexport const AUTHORIZATION_RESPONSE_ERROR = 'OAUTH_AUTHORIZATION_RESPONSE_ERROR';\nexport const JWT_USERINFO_EXPECTED = 'OAUTH_JWT_USERINFO_EXPECTED';\nexport const PARSE_ERROR = 'OAUTH_PARSE_ERROR';\nexport const INVALID_RESPONSE = 'OAUTH_INVALID_RESPONSE';\nexport const INVALID_REQUEST = 'OAUTH_INVALID_REQUEST';\nexport const RESPONSE_IS_NOT_JSON = 'OAUTH_RESPONSE_IS_NOT_JSON';\nexport const RESPONSE_IS_NOT_CONFORM = 'OAUTH_RESPONSE_IS_NOT_CONFORM';\nexport const HTTP_REQUEST_FORBIDDEN = 'OAUTH_HTTP_REQUEST_FORBIDDEN';\nexport const REQUEST_PROTOCOL_FORBIDDEN = 'OAUTH_REQUEST_PROTOCOL_FORBIDDEN';\nexport const JWT_TIMESTAMP_CHECK = 'OAUTH_JWT_TIMESTAMP_CHECK_FAILED';\nexport const JWT_CLAIM_COMPARISON = 'OAUTH_JWT_CLAIM_COMPARISON_FAILED';\nexport const JSON_ATTRIBUTE_COMPARISON = 'OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED';\nexport const KEY_SELECTION = 'OAUTH_KEY_SELECTION_FAILED';\nexport const MISSING_SERVER_METADATA = 'OAUTH_MISSING_SERVER_METADATA';\nexport const INVALID_SERVER_METADATA = 'OAUTH_INVALID_SERVER_METADATA';\nfunction checkJwtType(expected, result) {\n if (typeof result.header.typ !== 'string' || normalizeTyp(result.header.typ) !== expected) {\n throw OPE('unexpected JWT \"typ\" header parameter value', INVALID_RESPONSE, {\n header: result.header,\n });\n }\n return result;\n}\nexport async function clientCredentialsGrantRequest(as, client, clientAuthentication, parameters, options) {\n assertAs(as);\n assertClient(client);\n return tokenEndpointRequest(as, client, clientAuthentication, 'client_credentials', new URLSearchParams(parameters), options);\n}\nexport async function genericTokenEndpointRequest(as, client, clientAuthentication, grantType, parameters, options) {\n assertAs(as);\n assertClient(client);\n assertString(grantType, '\"grantType\"');\n return tokenEndpointRequest(as, client, clientAuthentication, grantType, new URLSearchParams(parameters), options);\n}\nexport async function processGenericTokenEndpointResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nexport async function processClientCredentialsResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nexport async function revocationRequest(as, client, clientAuthentication, token, options) {\n assertAs(as);\n assertClient(client);\n assertString(token, '\"token\"');\n const url = resolveEndpoint(as, 'revocation_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(options?.additionalParameters);\n body.set('token', token);\n const headers = prepareHeaders(options?.headers);\n headers.delete('accept');\n return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n}\nexport async function processRevocationResponse(response) {\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Revocation Endpoint');\n return undefined;\n}\nfunction assertReadableResponse(response) {\n if (response.bodyUsed) {\n throw CodedTypeError('\"response\" body has been used already', ERR_INVALID_ARG_VALUE);\n }\n}\nexport async function introspectionRequest(as, client, clientAuthentication, token, options) {\n assertAs(as);\n assertClient(client);\n assertString(token, '\"token\"');\n const url = resolveEndpoint(as, 'introspection_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(options?.additionalParameters);\n body.set('token', token);\n const headers = prepareHeaders(options?.headers);\n if (options?.requestJwtResponse ?? client.introspection_signed_response_alg) {\n headers.set('accept', 'application/token-introspection+jwt');\n }\n else {\n headers.set('accept', 'application/json');\n }\n return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n}\nexport async function processIntrospectionResponse(as, client, response, options) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Introspection Endpoint');\n let json;\n if (getContentType(response) === 'application/token-introspection+jwt') {\n assertReadableResponse(response);\n const { claims, jwt } = await validateJwt(await response.text(), checkSigningAlgorithm.bind(undefined, client.introspection_signed_response_alg, as.introspection_signing_alg_values_supported, 'RS256'), getClockSkew(client), getClockTolerance(client), options?.[jweDecrypt])\n .then(checkJwtType.bind(undefined, 'token-introspection+jwt'))\n .then(validatePresence.bind(undefined, ['aud', 'iat', 'iss']))\n .then(validateIssuer.bind(undefined, as))\n .then(validateAudience.bind(undefined, client.client_id));\n jwtRefs.set(response, jwt);\n if (!isJsonObject(claims.token_introspection)) {\n throw OPE('JWT \"token_introspection\" claim must be a JSON object', INVALID_RESPONSE, {\n claims,\n });\n }\n json = claims.token_introspection;\n }\n else {\n assertReadableResponse(response);\n json = await getResponseJsonBody(response);\n }\n if (typeof json.active !== 'boolean') {\n throw OPE('\"response\" body \"active\" property must be a boolean', INVALID_RESPONSE, {\n body: json,\n });\n }\n return json;\n}\nasync function jwksRequest(as, options) {\n assertAs(as);\n const url = resolveEndpoint(as, 'jwks_uri', false, options?.[allowInsecureRequests] !== true);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n headers.append('accept', 'application/jwk-set+json');\n const requestHeaders = Object.fromEntries(headers.entries());\n const headersKey = JSON.stringify(requestHeaders);\n const fetcher = options?.[customFetch] || fetch;\n const requestSignal = signal(url, options?.signal);\n jwksRequests ||= new WeakMap();\n const requests = jwksRequests.get(as) ?? new Set();\n for (const pending of requests) {\n if (pending.url === url.href &&\n pending.headers === headersKey &&\n pending.fetch === fetcher &&\n pending.signal === requestSignal) {\n return pending.promise;\n }\n }\n const pending = {\n url: url.href,\n headers: headersKey,\n fetch: fetcher,\n signal: requestSignal,\n promise: Promise.resolve()\n .then(() => fetcher(url.href, {\n body: undefined,\n headers: requestHeaders,\n method: 'GET',\n redirect: 'manual',\n signal: requestSignal,\n }))\n .then(processJwksResponse)\n .then((jwks) => {\n const uat = epochTime();\n setJwksCache(as, jwks, uat);\n return { jwks, uat };\n })\n .finally(() => {\n requests.delete(pending);\n if (!requests.size) {\n jwksRequests.delete(as);\n }\n }),\n };\n requests.add(pending);\n jwksRequests.set(as, requests);\n return pending.promise;\n}\nasync function processJwksResponse(response) {\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n if (response.status !== 200) {\n throw OPE('\"response\" is not a conform JSON Web Key Set response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);\n }\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response, (response) => assertContentTypes(response, 'application/json', 'application/jwk-set+json'));\n if (!Array.isArray(json.keys)) {\n throw OPE('\"response\" body \"keys\" property must be an array', INVALID_RESPONSE, { body: json });\n }\n if (!Array.prototype.every.call(json.keys, isJsonObject)) {\n throw OPE('\"response\" body \"keys\" property members must be JWK formatted objects', INVALID_RESPONSE, { body: json });\n }\n return json;\n}\nfunction supported(alg) {\n switch (alg) {\n case 'PS256':\n case 'ES256':\n case 'RS256':\n case 'PS384':\n case 'ES384':\n case 'RS384':\n case 'PS512':\n case 'ES512':\n case 'RS512':\n case 'Ed25519':\n case 'EdDSA':\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n return true;\n default:\n return false;\n }\n}\nfunction checkSupportedJwsAlg(header) {\n if (!supported(header.alg)) {\n throw new UnsupportedOperationError('unsupported JWS \"alg\" identifier', {\n cause: { alg: header.alg },\n });\n }\n}\nfunction checkRsaKeyAlgorithm(key) {\n const { algorithm } = key;\n if (typeof algorithm.modulusLength !== 'number' || algorithm.modulusLength < 2048) {\n throw new UnsupportedOperationError(`unsupported ${algorithm.name} modulusLength`, {\n cause: key,\n });\n }\n}\nfunction ecdsaHashName(key) {\n const { algorithm } = key;\n switch (algorithm.namedCurve) {\n case 'P-256':\n return 'SHA-256';\n case 'P-384':\n return 'SHA-384';\n case 'P-521':\n return 'SHA-512';\n default:\n throw new UnsupportedOperationError('unsupported ECDSA namedCurve', { cause: key });\n }\n}\nfunction keyToSubtle(key) {\n switch (key.algorithm.name) {\n case 'ECDSA':\n return {\n name: key.algorithm.name,\n hash: ecdsaHashName(key),\n };\n case 'RSA-PSS': {\n checkRsaKeyAlgorithm(key);\n switch (key.algorithm.hash.name) {\n case 'SHA-256':\n case 'SHA-384':\n case 'SHA-512':\n return {\n name: key.algorithm.name,\n saltLength: parseInt(key.algorithm.hash.name.slice(-3), 10) >> 3,\n };\n default:\n throw new UnsupportedOperationError('unsupported RSA-PSS hash name', { cause: key });\n }\n }\n case 'RSASSA-PKCS1-v1_5':\n checkRsaKeyAlgorithm(key);\n return key.algorithm.name;\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n case 'Ed25519':\n return key.algorithm.name;\n }\n throw new UnsupportedOperationError('unsupported CryptoKey algorithm name', { cause: key });\n}\nasync function validateJwsSignature(protectedHeader, payload, key, signature) {\n const data = buf(`${protectedHeader}.${payload}`);\n const algorithm = keyToSubtle(key);\n const verified = await crypto.subtle.verify(algorithm, key, signature, data);\n if (!verified) {\n throw OPE('JWT signature verification failed', INVALID_RESPONSE, {\n key,\n data,\n signature,\n algorithm,\n });\n }\n}\nasync function validateJwt(jws, checkAlg, clockSkew, clockTolerance, decryptJwt) {\n let { 0: protectedHeader, 1: payload, length } = jws.split('.');\n if (length === 5) {\n if (decryptJwt !== undefined) {\n jws = await decryptJwt(jws);\n ({ 0: protectedHeader, 1: payload, length } = jws.split('.'));\n }\n else {\n throw new UnsupportedOperationError('JWE decryption is not configured', { cause: jws });\n }\n }\n if (length !== 3) {\n throw OPE('Invalid JWT', INVALID_RESPONSE, jws);\n }\n let header;\n try {\n header = JSON.parse(buf(b64u(protectedHeader)));\n }\n catch (cause) {\n throw OPE('failed to parse JWT Header body as base64url encoded JSON', PARSE_ERROR, cause);\n }\n if (!isJsonObject(header)) {\n throw OPE('JWT Header must be a top level object', INVALID_RESPONSE, jws);\n }\n checkAlg(header);\n if (header.crit !== undefined) {\n throw new UnsupportedOperationError('no JWT \"crit\" header parameter extensions are supported', {\n cause: { header },\n });\n }\n let claims;\n try {\n claims = JSON.parse(buf(b64u(payload)));\n }\n catch (cause) {\n throw OPE('failed to parse JWT Payload body as base64url encoded JSON', PARSE_ERROR, cause);\n }\n if (!isJsonObject(claims)) {\n throw OPE('JWT Payload must be a top level object', INVALID_RESPONSE, jws);\n }\n const now = epochTime() + clockSkew;\n if (claims.exp !== undefined) {\n if (typeof claims.exp !== 'number') {\n throw OPE('unexpected JWT \"exp\" (expiration time) claim type', INVALID_RESPONSE, { claims });\n }\n if (claims.exp <= now - clockTolerance) {\n throw OPE('unexpected JWT \"exp\" (expiration time) claim value, expiration is past current timestamp', JWT_TIMESTAMP_CHECK, { claims, now, tolerance: clockTolerance, claim: 'exp' });\n }\n }\n if (claims.iat !== undefined) {\n if (typeof claims.iat !== 'number') {\n throw OPE('unexpected JWT \"iat\" (issued at) claim type', INVALID_RESPONSE, { claims });\n }\n }\n if (claims.iss !== undefined) {\n if (typeof claims.iss !== 'string') {\n throw OPE('unexpected JWT \"iss\" (issuer) claim type', INVALID_RESPONSE, { claims });\n }\n }\n if (claims.nbf !== undefined) {\n if (typeof claims.nbf !== 'number') {\n throw OPE('unexpected JWT \"nbf\" (not before) claim type', INVALID_RESPONSE, { claims });\n }\n if (claims.nbf > now + clockTolerance) {\n throw OPE('unexpected JWT \"nbf\" (not before) claim value', JWT_TIMESTAMP_CHECK, {\n claims,\n now,\n tolerance: clockTolerance,\n claim: 'nbf',\n });\n }\n }\n if (claims.aud !== undefined) {\n if (typeof claims.aud !== 'string' && !Array.isArray(claims.aud)) {\n throw OPE('unexpected JWT \"aud\" (audience) claim type', INVALID_RESPONSE, { claims });\n }\n }\n return { header, claims, jwt: jws };\n}\nexport async function validateJwtAuthResponse(as, client, parameters, expectedState, options) {\n assertAs(as);\n assertClient(client);\n if (parameters instanceof URL) {\n parameters = parameters.searchParams;\n }\n if (!(parameters instanceof URLSearchParams)) {\n throw CodedTypeError('\"parameters\" must be an instance of URLSearchParams, or URL', ERR_INVALID_ARG_TYPE);\n }\n const response = getURLSearchParameter(parameters, 'response');\n if (!response) {\n throw OPE('\"parameters\" does not contain a JARM response', INVALID_RESPONSE);\n }\n const { claims, header, jwt } = await validateJwt(response, checkSigningAlgorithm.bind(undefined, client.authorization_signed_response_alg, as.authorization_signing_alg_values_supported, 'RS256'), getClockSkew(client), getClockTolerance(client), options?.[jweDecrypt])\n .then(validatePresence.bind(undefined, ['aud', 'exp', 'iss']))\n .then(validateIssuer.bind(undefined, as))\n .then(validateAudience.bind(undefined, client.client_id));\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = jwt.split('.');\n const signature = b64u(encodedSignature);\n const key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);\n await validateJwsSignature(protectedHeader, payload, key, signature);\n const result = new URLSearchParams();\n for (const [key, value] of Object.entries(claims)) {\n if (typeof value === 'string' && key !== 'aud') {\n result.set(key, value);\n }\n }\n return validateAuthResponse(as, client, result, expectedState);\n}\nasync function idTokenHash(data, header, claimName) {\n let algorithm;\n switch (header.alg) {\n case 'RS256':\n case 'PS256':\n case 'ES256':\n algorithm = 'SHA-256';\n break;\n case 'RS384':\n case 'PS384':\n case 'ES384':\n algorithm = 'SHA-384';\n break;\n case 'RS512':\n case 'PS512':\n case 'ES512':\n case 'Ed25519':\n case 'EdDSA':\n algorithm = 'SHA-512';\n break;\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n algorithm = { name: 'cSHAKE256', length: 512, outputLength: 512 };\n break;\n default:\n throw new UnsupportedOperationError(`unsupported JWS algorithm for ${claimName} calculation`, { cause: { alg: header.alg } });\n }\n const digest = await crypto.subtle.digest(algorithm, buf(data));\n return b64u(digest.slice(0, digest.byteLength / 2));\n}\nasync function idTokenHashMatches(data, actual, header, claimName) {\n const expected = await idTokenHash(data, header, claimName);\n return actual === expected;\n}\nexport async function validateDetachedSignatureResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options) {\n return validateHybridResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options, true);\n}\nexport async function validateCodeIdTokenResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options) {\n return validateHybridResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options, false);\n}\nasync function consumeStream(request) {\n if (request.bodyUsed) {\n throw CodedTypeError('form_post Request instances must contain a readable body', ERR_INVALID_ARG_VALUE, { cause: request });\n }\n return request.text();\n}\nexport async function formPostResponse(request) {\n if (request.method !== 'POST') {\n throw CodedTypeError('form_post responses are expected to use the POST method', ERR_INVALID_ARG_VALUE, { cause: request });\n }\n if (getContentType(request) !== 'application/x-www-form-urlencoded') {\n throw CodedTypeError('form_post responses are expected to use the application/x-www-form-urlencoded content-type', ERR_INVALID_ARG_VALUE, { cause: request });\n }\n return consumeStream(request);\n}\nasync function validateHybridResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options, fapi) {\n assertAs(as);\n assertClient(client);\n if (parameters instanceof URL) {\n if (!parameters.hash.length) {\n throw CodedTypeError('\"parameters\" as an instance of URL must contain a hash (fragment) with the Authorization Response parameters', ERR_INVALID_ARG_VALUE);\n }\n parameters = new URLSearchParams(parameters.hash.slice(1));\n }\n else if (looseInstanceOf(parameters, Request)) {\n parameters = new URLSearchParams(await formPostResponse(parameters));\n }\n else if (parameters instanceof URLSearchParams) {\n parameters = new URLSearchParams(parameters);\n }\n else {\n throw CodedTypeError('\"parameters\" must be an instance of URLSearchParams, URL, or Response', ERR_INVALID_ARG_TYPE);\n }\n const id_token = getURLSearchParameter(parameters, 'id_token');\n parameters.delete('id_token');\n switch (expectedState) {\n case undefined:\n case expectNoState:\n break;\n default:\n assertString(expectedState, '\"expectedState\" argument');\n }\n const result = validateAuthResponse({\n ...as,\n authorization_response_iss_parameter_supported: false,\n }, client, parameters, expectedState);\n if (!id_token) {\n throw OPE('\"parameters\" does not contain an ID Token', INVALID_RESPONSE);\n }\n const code = getURLSearchParameter(parameters, 'code');\n if (!code) {\n throw OPE('\"parameters\" does not contain an Authorization Code', INVALID_RESPONSE);\n }\n const requiredClaims = ['nonce', 'c_hash'];\n const state = parameters.get('state');\n if (fapi && (typeof expectedState === 'string' || state !== null)) {\n requiredClaims.push('s_hash');\n }\n maxAge = resolveIdTokenMaxAge(client, maxAge);\n if (client.require_auth_time || maxAge !== skipAuthTimeCheck) {\n requiredClaims.push('auth_time');\n }\n const { claims, header, jwt } = await validateIdTokenClaims(as, client, id_token, requiredClaims, options?.[jweDecrypt]);\n const clockSkew = getClockSkew(client);\n const now = epochTime() + clockSkew;\n if (claims.iat < now - 3600) {\n throw OPE('unexpected JWT \"iat\" (issued at) claim value, it is too far in the past', JWT_TIMESTAMP_CHECK, { now, claims, claim: 'iat' });\n }\n assertString(claims.c_hash, 'ID Token \"c_hash\" (code hash) claim value', INVALID_RESPONSE, {\n claims,\n });\n validateIdTokenAuthTimeClaim(claims);\n validateIdTokenAuthTime(client, claims, maxAge);\n assertString(expectedNonce, '\"expectedNonce\" argument');\n validateIdTokenNonce(claims, expectedNonce);\n validateIdTokenAuthorizedParty(client, claims);\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = jwt.split('.');\n const signature = b64u(encodedSignature);\n const key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);\n await validateJwsSignature(protectedHeader, payload, key, signature);\n if ((await idTokenHashMatches(code, claims.c_hash, header, 'c_hash')) !== true) {\n throw OPE('invalid ID Token \"c_hash\" (code hash) claim value', JWT_CLAIM_COMPARISON, {\n code,\n alg: header.alg,\n claim: 'c_hash',\n claims,\n });\n }\n if ((fapi && state !== null) || claims.s_hash !== undefined) {\n assertString(claims.s_hash, 'ID Token \"s_hash\" (state hash) claim value', INVALID_RESPONSE, {\n claims,\n });\n assertString(state, '\"state\" response parameter', INVALID_RESPONSE, { parameters });\n if ((await idTokenHashMatches(state, claims.s_hash, header, 's_hash')) !== true) {\n throw OPE('invalid ID Token \"s_hash\" (state hash) claim value', JWT_CLAIM_COMPARISON, {\n state,\n alg: header.alg,\n claim: 's_hash',\n claims,\n });\n }\n }\n return result;\n}\nfunction checkSigningAlgorithm(client, issuer, fallback, header) {\n if (client !== undefined) {\n if (typeof client === 'string' ? header.alg !== client : !client.includes(header.alg)) {\n throw OPE('unexpected JWT \"alg\" header parameter', INVALID_RESPONSE, {\n header,\n expected: client,\n reason: 'client configuration',\n });\n }\n return;\n }\n if (Array.isArray(issuer)) {\n if (!issuer.includes(header.alg)) {\n throw OPE('unexpected JWT \"alg\" header parameter', INVALID_RESPONSE, {\n header,\n expected: issuer,\n reason: 'authorization server metadata',\n });\n }\n return;\n }\n if (fallback !== undefined) {\n if (typeof fallback === 'string'\n ? header.alg !== fallback\n : typeof fallback === 'function'\n ? !fallback(header.alg)\n : !fallback.includes(header.alg)) {\n throw OPE('unexpected JWT \"alg\" header parameter', INVALID_RESPONSE, {\n header,\n expected: fallback,\n reason: 'default value',\n });\n }\n return;\n }\n throw OPE('missing client or server configuration to verify used JWT \"alg\" header parameter', undefined, { client, issuer, fallback });\n}\nfunction getURLSearchParameter(parameters, name) {\n const { 0: value, length } = parameters.getAll(name);\n if (length > 1) {\n throw OPE(`\"${name}\" parameter must be provided only once`, INVALID_RESPONSE);\n }\n return value;\n}\nexport const skipStateCheck = Symbol();\nexport const expectNoState = Symbol();\nexport function validateAuthResponse(as, client, parameters, expectedState) {\n assertAs(as);\n assertClient(client);\n if (parameters instanceof URL) {\n parameters = parameters.searchParams;\n }\n if (!(parameters instanceof URLSearchParams)) {\n throw CodedTypeError('\"parameters\" must be an instance of URLSearchParams, or URL', ERR_INVALID_ARG_TYPE);\n }\n if (getURLSearchParameter(parameters, 'response')) {\n throw OPE('\"parameters\" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()', INVALID_RESPONSE, { parameters });\n }\n const iss = getURLSearchParameter(parameters, 'iss');\n const state = getURLSearchParameter(parameters, 'state');\n if (!iss && as.authorization_response_iss_parameter_supported) {\n throw OPE('response parameter \"iss\" (issuer) missing', INVALID_RESPONSE, { parameters });\n }\n if (iss && iss !== as.issuer) {\n throw OPE('unexpected \"iss\" (issuer) response parameter value', INVALID_RESPONSE, {\n expected: as.issuer,\n parameters,\n });\n }\n switch (expectedState) {\n case undefined:\n case expectNoState:\n if (state !== undefined) {\n throw OPE('unexpected \"state\" response parameter encountered', INVALID_RESPONSE, {\n expected: undefined,\n parameters,\n });\n }\n break;\n case skipStateCheck:\n break;\n default:\n assertString(expectedState, '\"expectedState\" argument');\n if (state !== expectedState) {\n throw OPE(state === undefined\n ? 'response parameter \"state\" missing'\n : 'unexpected \"state\" response parameter value', INVALID_RESPONSE, { expected: expectedState, parameters });\n }\n }\n const error = getURLSearchParameter(parameters, 'error');\n if (error) {\n throw new AuthorizationResponseError('authorization response from the server is an error', {\n cause: parameters,\n });\n }\n const id_token = getURLSearchParameter(parameters, 'id_token');\n const token = getURLSearchParameter(parameters, 'token');\n if (id_token !== undefined || token !== undefined) {\n throw new UnsupportedOperationError('implicit and hybrid flows are not supported');\n }\n return brand(new URLSearchParams(parameters));\n}\nfunction algToSubtle(alg) {\n switch (alg) {\n case 'PS256':\n case 'PS384':\n case 'PS512':\n return { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` };\n case 'RS256':\n case 'RS384':\n case 'RS512':\n return { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` };\n case 'ES256':\n case 'ES384':\n return { name: 'ECDSA', namedCurve: `P-${alg.slice(-3)}` };\n case 'ES512':\n return { name: 'ECDSA', namedCurve: 'P-521' };\n case 'EdDSA':\n return 'Ed25519';\n case 'Ed25519':\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n return alg;\n default:\n throw new UnsupportedOperationError('unsupported JWS algorithm', { cause: { alg } });\n }\n}\nasync function importJwk(alg, jwk) {\n const { ext, key_ops, use, ...key } = jwk;\n return crypto.subtle.importKey('jwk', key, algToSubtle(alg), true, ['verify']);\n}\nexport async function deviceAuthorizationRequest(as, client, clientAuthentication, parameters, options) {\n assertAs(as);\n assertClient(client);\n const url = resolveEndpoint(as, 'device_authorization_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(parameters);\n body.set('client_id', client.client_id);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n}\nexport async function processDeviceAuthorizationResponse(as, client, response) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Device Authorization Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.device_code, '\"response\" body \"device_code\" property', INVALID_RESPONSE, {\n body: json,\n });\n assertString(json.user_code, '\"response\" body \"user_code\" property', INVALID_RESPONSE, {\n body: json,\n });\n assertString(json.verification_uri, '\"response\" body \"verification_uri\" property', INVALID_RESPONSE, { body: json });\n let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;\n assertNumber(expiresIn, true, '\"response\" body \"expires_in\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.expires_in = expiresIn;\n if (json.verification_uri_complete !== undefined) {\n assertString(json.verification_uri_complete, '\"response\" body \"verification_uri_complete\" property', INVALID_RESPONSE, { body: json });\n }\n if (json.interval !== undefined) {\n assertNumber(json.interval, false, '\"response\" body \"interval\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n return json;\n}\nexport async function deviceCodeGrantRequest(as, client, clientAuthentication, deviceCode, options) {\n assertAs(as);\n assertClient(client);\n assertString(deviceCode, '\"deviceCode\"');\n const parameters = new URLSearchParams(options?.additionalParameters);\n parameters.set('device_code', deviceCode);\n return tokenEndpointRequest(as, client, clientAuthentication, 'urn:ietf:params:oauth:grant-type:device_code', parameters, options);\n}\nexport async function processDeviceCodeResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nexport async function generateKeyPair(alg, options) {\n assertString(alg, '\"alg\"');\n const algorithm = algToSubtle(alg);\n if (alg.startsWith('PS') || alg.startsWith('RS')) {\n Object.assign(algorithm, {\n modulusLength: options?.modulusLength ?? 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n });\n }\n return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, [\n 'sign',\n 'verify',\n ]);\n}\nfunction normalizeHtu(htu) {\n const url = new URL(htu);\n url.search = '';\n url.hash = '';\n return url.href;\n}\nasync function validateDPoP(request, accessToken, accessTokenClaims, options) {\n const headerValue = request.headers.get('dpop');\n if (headerValue === null) {\n throw OPE('operation indicated DPoP use but the request has no DPoP HTTP Header', INVALID_REQUEST, { headers: request.headers });\n }\n if (request.headers.get('authorization')?.toLowerCase().startsWith('dpop ') === false) {\n throw OPE(`operation indicated DPoP use but the request's Authorization HTTP Header scheme is not DPoP`, INVALID_REQUEST, { headers: request.headers });\n }\n if (typeof accessTokenClaims.cnf?.jkt !== 'string') {\n throw OPE('operation indicated DPoP use but the JWT Access Token has no jkt confirmation claim', INVALID_REQUEST, { claims: accessTokenClaims });\n }\n const clockSkew = getClockSkew(options);\n const proof = await validateJwt(headerValue, checkSigningAlgorithm.bind(undefined, options?.signingAlgorithms, undefined, supported), clockSkew, getClockTolerance(options), undefined)\n .then(checkJwtType.bind(undefined, 'dpop+jwt'))\n .then(validatePresence.bind(undefined, ['iat', 'jti', 'ath', 'htm', 'htu']))\n .then(validateStringClaim.bind(undefined, 'jti'));\n const now = epochTime() + clockSkew;\n const diff = Math.abs(now - proof.claims.iat);\n if (diff > 300) {\n throw OPE('DPoP Proof iat is not recent enough', JWT_TIMESTAMP_CHECK, {\n now,\n claims: proof.claims,\n claim: 'iat',\n });\n }\n if (proof.claims.htm !== request.method) {\n throw OPE('DPoP Proof htm mismatch', JWT_CLAIM_COMPARISON, {\n expected: request.method,\n claims: proof.claims,\n claim: 'htm',\n });\n }\n if (typeof proof.claims.htu !== 'string' ||\n normalizeHtu(proof.claims.htu) !== normalizeHtu(request.url)) {\n throw OPE('DPoP Proof htu mismatch', JWT_CLAIM_COMPARISON, {\n expected: normalizeHtu(request.url),\n claims: proof.claims,\n claim: 'htu',\n });\n }\n {\n const expected = b64u(await crypto.subtle.digest('SHA-256', buf(accessToken)));\n if (proof.claims.ath !== expected) {\n throw OPE('DPoP Proof ath mismatch', JWT_CLAIM_COMPARISON, {\n expected,\n claims: proof.claims,\n claim: 'ath',\n });\n }\n }\n const { jwk, alg } = proof.header;\n if (!isJsonObject(jwk)) {\n throw OPE('DPoP Proof jwk header parameter must be a JSON object', INVALID_REQUEST, {\n header: proof.header,\n });\n }\n {\n const expected = await calculateJwkThumbprint(jwk);\n if (accessTokenClaims.cnf.jkt !== expected) {\n throw OPE('JWT Access Token confirmation mismatch', JWT_CLAIM_COMPARISON, {\n expected,\n claims: accessTokenClaims,\n claim: 'cnf.jkt',\n });\n }\n }\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = headerValue.split('.');\n const signature = b64u(encodedSignature);\n const key = await importJwk(alg, jwk);\n if (key.type !== 'public') {\n throw OPE('DPoP Proof jwk header parameter must contain a public key', INVALID_REQUEST, {\n header: proof.header,\n });\n }\n await validateJwsSignature(protectedHeader, payload, key, signature);\n}\nexport async function validateJwtAccessToken(as, request, expectedAudience, options) {\n assertAs(as);\n if (!looseInstanceOf(request, Request)) {\n throw CodedTypeError('\"request\" must be an instance of Request', ERR_INVALID_ARG_TYPE);\n }\n assertString(expectedAudience, '\"expectedAudience\"');\n const authorization = request.headers.get('authorization');\n if (authorization === null) {\n throw OPE('\"request\" is missing an Authorization HTTP Header', INVALID_REQUEST, {\n headers: request.headers,\n });\n }\n let { 0: scheme, 1: accessToken, length } = authorization.split(/ +/);\n scheme = scheme.toLowerCase();\n switch (scheme) {\n case 'dpop':\n case 'bearer':\n break;\n default:\n throw new UnsupportedOperationError('unsupported Authorization HTTP Header scheme', {\n cause: { headers: request.headers },\n });\n }\n if (length !== 2) {\n throw OPE('invalid Authorization HTTP Header format', INVALID_REQUEST, {\n headers: request.headers,\n });\n }\n const requiredClaims = [\n 'iss',\n 'exp',\n 'aud',\n 'sub',\n 'iat',\n 'jti',\n 'client_id',\n ];\n if (options?.requireDPoP || scheme === 'dpop' || request.headers.has('dpop')) {\n requiredClaims.push('cnf');\n }\n const { claims, header } = await validateJwt(accessToken, checkSigningAlgorithm.bind(undefined, options?.signingAlgorithms, undefined, supported), getClockSkew(options), getClockTolerance(options), undefined)\n .then(checkJwtType.bind(undefined, 'at+jwt'))\n .then(validatePresence.bind(undefined, requiredClaims))\n .then(validateIssuer.bind(undefined, as))\n .then(validateAudience.bind(undefined, expectedAudience))\n .catch(reassignRSCode);\n for (const claim of ['client_id', 'jti', 'sub']) {\n if (typeof claims[claim] !== 'string') {\n throw OPE(`unexpected JWT \"${claim}\" claim type`, INVALID_REQUEST, { claims });\n }\n }\n if ('cnf' in claims) {\n if (!isJsonObject(claims.cnf)) {\n throw OPE('unexpected JWT \"cnf\" (confirmation) claim value', INVALID_REQUEST, { claims });\n }\n const { 0: cnf, length } = Object.keys(claims.cnf);\n if (length) {\n if (length !== 1) {\n throw new UnsupportedOperationError('multiple confirmation claims are not supported', {\n cause: { claims },\n });\n }\n if (cnf !== 'jkt') {\n throw new UnsupportedOperationError('unsupported JWT Confirmation method', {\n cause: { claims },\n });\n }\n }\n }\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = accessToken.split('.');\n const signature = b64u(encodedSignature);\n const key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);\n await validateJwsSignature(protectedHeader, payload, key, signature);\n if (options?.requireDPoP ||\n scheme === 'dpop' ||\n claims.cnf?.jkt !== undefined ||\n request.headers.has('dpop')) {\n await validateDPoP(request, accessToken, claims, options).catch(reassignRSCode);\n }\n return claims;\n}\nfunction reassignRSCode(err) {\n if (err instanceof OperationProcessingError && err?.code === INVALID_REQUEST) {\n err.code = INVALID_RESPONSE;\n }\n throw err;\n}\nexport async function backchannelAuthenticationRequest(as, client, clientAuthentication, parameters, options) {\n assertAs(as);\n assertClient(client);\n const url = resolveEndpoint(as, 'backchannel_authentication_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(parameters);\n body.set('client_id', client.client_id);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n}\nexport async function processBackchannelAuthenticationResponse(as, client, response) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Backchannel Authentication Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.auth_req_id, '\"response\" body \"auth_req_id\" property', INVALID_RESPONSE, {\n body: json,\n });\n let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;\n assertNumber(expiresIn, true, '\"response\" body \"expires_in\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.expires_in = expiresIn;\n if (json.interval !== undefined) {\n assertNumber(json.interval, false, '\"response\" body \"interval\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n return json;\n}\nexport async function backchannelAuthenticationGrantRequest(as, client, clientAuthentication, authReqId, options) {\n assertAs(as);\n assertClient(client);\n assertString(authReqId, '\"authReqId\"');\n const parameters = new URLSearchParams(options?.additionalParameters);\n parameters.set('auth_req_id', authReqId);\n return tokenEndpointRequest(as, client, clientAuthentication, 'urn:openid:params:grant-type:ciba', parameters, options);\n}\nexport async function processBackchannelAuthenticationGrantResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nexport async function dynamicClientRegistrationRequest(as, metadata, options) {\n assertAs(as);\n const url = resolveEndpoint(as, 'registration_endpoint', metadata.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n headers.set('content-type', 'application/json');\n const method = 'POST';\n if (options?.DPoP) {\n assertDPoP(options.DPoP);\n await options.DPoP.addProof(url, headers, method, options.initialAccessToken);\n }\n if (options?.initialAccessToken) {\n headers.set('authorization', `${headers.has('dpop') ? 'DPoP' : 'Bearer'} ${options.initialAccessToken}`);\n }\n const response = await (options?.[customFetch] || fetch)(url.href, {\n body: JSON.stringify(metadata),\n headers: Object.fromEntries(headers.entries()),\n method,\n redirect: 'manual',\n signal: signal(url, options?.signal),\n });\n options?.DPoP?.cacheNonce(response, url);\n return response;\n}\nexport async function processDynamicClientRegistrationResponse(response) {\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 201, 'Dynamic Client Registration Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.client_id, '\"response\" body \"client_id\" property', INVALID_RESPONSE, {\n body: json,\n });\n if (json.client_secret !== undefined) {\n assertString(json.client_secret, '\"response\" body \"client_secret\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n if (json.client_secret) {\n assertNumber(json.client_secret_expires_at, true, '\"response\" body \"client_secret_expires_at\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n return json;\n}\nexport async function resourceDiscoveryRequest(resourceIdentifier, options) {\n return performDiscovery(resourceIdentifier, 'resourceIdentifier', (url) => {\n prependWellKnown(url, '.well-known/oauth-protected-resource', true);\n return url;\n }, options);\n}\nexport async function processResourceDiscoveryResponse(expectedResourceIdentifier, response) {\n const expected = expectedResourceIdentifier;\n if (!(expected instanceof URL) && expected !== _nodiscoverycheck) {\n throw CodedTypeError('\"expectedResourceIdentifier\" must be an instance of URL', ERR_INVALID_ARG_TYPE);\n }\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n if (response.status !== 200) {\n throw OPE('\"response\" is not a conform Resource Server Metadata response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);\n }\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.resource, '\"response\" body \"resource\" property', INVALID_RESPONSE, {\n body: json,\n });\n if (expected !== _nodiscoverycheck && new URL(json.resource).href !== expected.href) {\n throw OPE('\"response\" body \"resource\" property does not match the expected value', JSON_ATTRIBUTE_COMPARISON, { expected: expected.href, body: json, attribute: 'resource' });\n }\n return json;\n}\nasync function getResponseJsonBody(response, check = assertApplicationJson) {\n let json;\n try {\n json = await response.json();\n }\n catch (cause) {\n check(response);\n throw OPE('failed to parse \"response\" body as JSON', PARSE_ERROR, cause);\n }\n if (!isJsonObject(json)) {\n throw OPE('\"response\" body must be a top level object', INVALID_RESPONSE, { body: json });\n }\n return json;\n}\nexport const _nopkce = nopkce;\nexport const _nodiscoverycheck = Symbol();\nexport const _expectedIssuer = Symbol();\n//# sourceMappingURL=index.js.map","import * as oauth from 'oauth4webapi';\nimport { compactDecrypt } from 'jose/jwe/compact/decrypt';\nimport { JOSEError } from 'jose/errors';\nlet headers;\nlet USER_AGENT;\nif (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {\n const NAME = 'openid-client';\n const VERSION = 'v6.8.8';\n USER_AGENT = `${NAME}/${VERSION}`;\n headers = { 'user-agent': USER_AGENT };\n}\nconst int = (config) => {\n return props.get(config);\n};\nlet props;\nexport { AuthorizationResponseError, ResponseBodyError, WWWAuthenticateChallengeError, } from 'oauth4webapi';\nexport function ClientSecretPost(clientSecret) {\n if (clientSecret !== undefined) {\n return oauth.ClientSecretPost(clientSecret);\n }\n const cache = new WeakMap();\n return (as, client, body, headers) => {\n let auth;\n if (!(auth = cache.get(client))) {\n assertString(client.client_secret, '\"metadata.client_secret\"');\n auth = oauth.ClientSecretPost(client.client_secret);\n cache.set(client, auth);\n }\n return auth(as, client, body, headers);\n };\n}\nfunction assertString(input, it) {\n if (typeof input !== 'string') {\n throw CodedTypeError(`${it} must be a string`, ERR_INVALID_ARG_TYPE);\n }\n if (input.length === 0) {\n throw CodedTypeError(`${it} must not be empty`, ERR_INVALID_ARG_VALUE);\n }\n}\nexport function ClientSecretBasic(clientSecret) {\n if (clientSecret !== undefined) {\n return oauth.ClientSecretBasic(clientSecret);\n }\n const cache = new WeakMap();\n return (as, client, body, headers) => {\n let auth;\n if (!(auth = cache.get(client))) {\n assertString(client.client_secret, '\"metadata.client_secret\"');\n auth = oauth.ClientSecretBasic(client.client_secret);\n cache.set(client, auth);\n }\n return auth(as, client, body, headers);\n };\n}\nexport function ClientSecretJwt(clientSecret, options) {\n if (clientSecret !== undefined) {\n return oauth.ClientSecretJwt(clientSecret, options);\n }\n const cache = new WeakMap();\n return (as, client, body, headers) => {\n let auth;\n if (!(auth = cache.get(client))) {\n assertString(client.client_secret, '\"metadata.client_secret\"');\n auth = oauth.ClientSecretJwt(client.client_secret, options);\n cache.set(client, auth);\n }\n return auth(as, client, body, headers);\n };\n}\nexport function None() {\n return oauth.None();\n}\nexport function PrivateKeyJwt(clientPrivateKey, options) {\n return oauth.PrivateKeyJwt(clientPrivateKey, options);\n}\nexport function TlsClientAuth() {\n return oauth.TlsClientAuth();\n}\nexport const skipStateCheck = oauth.skipStateCheck;\nexport const skipSubjectCheck = oauth.skipSubjectCheck;\nexport const customFetch = oauth.customFetch;\nexport const modifyAssertion = oauth.modifyAssertion;\nexport const clockSkew = oauth.clockSkew;\nexport const clockTolerance = oauth.clockTolerance;\nconst ERR_INVALID_ARG_VALUE = 'ERR_INVALID_ARG_VALUE';\nconst ERR_INVALID_ARG_TYPE = 'ERR_INVALID_ARG_TYPE';\nfunction CodedTypeError(message, code, cause) {\n const err = new TypeError(message, { cause });\n Object.assign(err, { code });\n return err;\n}\nexport function calculatePKCECodeChallenge(codeVerifier) {\n return oauth.calculatePKCECodeChallenge(codeVerifier);\n}\nexport function randomPKCECodeVerifier() {\n return oauth.generateRandomCodeVerifier();\n}\nexport function randomNonce() {\n return oauth.generateRandomNonce();\n}\nexport function randomState() {\n return oauth.generateRandomState();\n}\nexport class ClientError extends Error {\n code;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = options?.code;\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nconst decoder = new TextDecoder();\nfunction e(msg, cause, code) {\n return new ClientError(msg, { cause, code });\n}\nfunction errorHandler(err) {\n if (err instanceof TypeError ||\n err instanceof ClientError ||\n err instanceof oauth.ResponseBodyError ||\n err instanceof oauth.AuthorizationResponseError ||\n err instanceof oauth.WWWAuthenticateChallengeError) {\n throw err;\n }\n if (err instanceof oauth.OperationProcessingError) {\n switch (err.code) {\n case oauth.HTTP_REQUEST_FORBIDDEN:\n throw e('only requests to HTTPS are allowed', err, err.code);\n case oauth.REQUEST_PROTOCOL_FORBIDDEN:\n throw e('only requests to HTTP or HTTPS are allowed', err, err.code);\n case oauth.RESPONSE_IS_NOT_CONFORM:\n throw e('unexpected HTTP response status code', err.cause, err.code);\n case oauth.RESPONSE_IS_NOT_JSON:\n throw e('unexpected response content-type', err.cause, err.code);\n case oauth.PARSE_ERROR:\n throw e('parsing error occured', err, err.code);\n case oauth.INVALID_RESPONSE:\n throw e('invalid response encountered', err, err.code);\n case oauth.JWT_CLAIM_COMPARISON:\n throw e('unexpected JWT claim value encountered', err, err.code);\n case oauth.JSON_ATTRIBUTE_COMPARISON:\n throw e('unexpected JSON attribute value encountered', err, err.code);\n case oauth.JWT_TIMESTAMP_CHECK:\n throw e('JWT timestamp claim value failed validation', err, err.code);\n default:\n throw e(err.message, err, err.code);\n }\n }\n if (err instanceof oauth.UnsupportedOperationError) {\n throw e('unsupported operation', err, err.code);\n }\n if (err instanceof DOMException) {\n switch (err.name) {\n case 'OperationError':\n throw e('runtime operation error', err, oauth.UNSUPPORTED_OPERATION);\n case 'NotSupportedError':\n throw e('runtime unsupported operation', err, oauth.UNSUPPORTED_OPERATION);\n case 'TimeoutError':\n throw e('operation timed out', err, 'OAUTH_TIMEOUT');\n case 'AbortError':\n throw e('operation aborted', err, 'OAUTH_ABORT');\n }\n }\n throw new ClientError('something went wrong', { cause: err });\n}\nexport function randomDPoPKeyPair(alg, options) {\n return oauth\n .generateKeyPair(alg ?? 'ES256', {\n extractable: options?.extractable,\n })\n .catch(errorHandler);\n}\nfunction handleEntraId(server, as, options) {\n if (server.origin === 'https://login.microsoftonline.com' &&\n (!options?.algorithm || options.algorithm === 'oidc')) {\n as[kEntraId] = true;\n return true;\n }\n return false;\n}\nfunction handleB2Clogin(server, options) {\n if (server.hostname.endsWith('.b2clogin.com') &&\n (!options?.algorithm || options.algorithm === 'oidc')) {\n return true;\n }\n return false;\n}\nexport async function dynamicClientRegistration(server, metadata, clientAuthentication, options) {\n let as;\n if (options?.flag === retry) {\n as = options.as;\n }\n else {\n as = await performDiscovery(server, options);\n }\n const clockSkew = metadata[oauth.clockSkew] ?? 0;\n const clockTolerance = metadata[oauth.clockTolerance] ?? 30;\n metadata = structuredClone(metadata);\n metadata[oauth.clockSkew] = clockSkew;\n metadata[oauth.clockTolerance] = clockTolerance;\n const timeout = options?.timeout ?? 30;\n const signal = AbortSignal.timeout(timeout * 1000);\n let registered;\n try {\n registered = await oauth\n .dynamicClientRegistrationRequest(as, metadata, {\n initialAccessToken: options?.initialAccessToken,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n [oauth.customFetch]: options?.[customFetch],\n [oauth.allowInsecureRequests]: options?.execute?.includes(allowInsecureRequests),\n signal,\n })\n .then(oauth.processDynamicClientRegistrationResponse);\n }\n catch (err) {\n if (retryable(err, options)) {\n return dynamicClientRegistration(server, metadata, clientAuthentication, {\n ...options,\n flag: retry,\n as,\n });\n }\n errorHandler(err);\n }\n registered[oauth.clockSkew] = clockSkew;\n registered[oauth.clockTolerance] = clockTolerance;\n const instance = new Configuration(as, registered.client_id, registered, clientAuthentication);\n let internals = int(instance);\n if (options?.[customFetch]) {\n internals.fetch = options[customFetch];\n }\n if (options?.timeout !== undefined) {\n internals.timeout = options.timeout;\n }\n if (options?.execute) {\n for (const extension of options.execute) {\n extension(instance);\n }\n }\n return instance;\n}\nexport async function discovery(server, clientId, metadata, clientAuthentication, options) {\n const as = await performDiscovery(server, options);\n const instance = new Configuration(as, clientId, metadata, clientAuthentication);\n let internals = int(instance);\n if (options?.[customFetch]) {\n internals.fetch = options[customFetch];\n }\n if (options?.timeout !== undefined) {\n internals.timeout = options.timeout;\n }\n if (options?.execute) {\n for (const extension of options.execute) {\n extension(instance);\n }\n }\n return instance;\n}\nasync function performDiscovery(server, options) {\n if (!(server instanceof URL)) {\n throw CodedTypeError('\"server\" must be an instance of URL', ERR_INVALID_ARG_TYPE);\n }\n const resolve = !server.href.includes('/.well-known/');\n const timeout = options?.timeout ?? 30;\n const signal = AbortSignal.timeout(timeout * 1000);\n const as = await (resolve\n ? oauth.discoveryRequest(server, {\n algorithm: options?.algorithm,\n [oauth.customFetch]: options?.[customFetch],\n [oauth.allowInsecureRequests]: options?.execute?.includes(allowInsecureRequests),\n signal,\n headers: new Headers(headers),\n })\n : (options?.[customFetch] || fetch)((() => {\n oauth.checkProtocol(server, options?.execute?.includes(allowInsecureRequests) ? false : true);\n return server.href;\n })(), {\n headers: Object.fromEntries(new Headers({ accept: 'application/json', ...headers }).entries()),\n body: undefined,\n method: 'GET',\n redirect: 'manual',\n signal,\n }))\n .then((response) => oauth.processDiscoveryResponse(oauth._nodiscoverycheck, response))\n .catch(errorHandler);\n if (resolve && new URL(as.issuer).href !== server.href) {\n handleEntraId(server, as, options) ||\n handleB2Clogin(server, options) ||\n (() => {\n throw new ClientError('discovered metadata issuer does not match the expected issuer', {\n code: oauth.JSON_ATTRIBUTE_COMPARISON,\n cause: {\n expected: server.href,\n body: as,\n attribute: 'issuer',\n },\n });\n })();\n }\n return as;\n}\nfunction isRsaOaep(input) {\n return input.name === 'RSA-OAEP';\n}\nfunction isEcdh(input) {\n return input.name === 'ECDH';\n}\nconst ecdhEs = 'ECDH-ES';\nconst ecdhEsA128Kw = 'ECDH-ES+A128KW';\nconst ecdhEsA192Kw = 'ECDH-ES+A192KW';\nconst ecdhEsA256Kw = 'ECDH-ES+A256KW';\nfunction checkEcdhAlg(algs, alg, pk) {\n switch (alg) {\n case undefined:\n algs.add(ecdhEs);\n algs.add(ecdhEsA128Kw);\n algs.add(ecdhEsA192Kw);\n algs.add(ecdhEsA256Kw);\n break;\n case ecdhEs:\n case ecdhEsA128Kw:\n case ecdhEsA192Kw:\n case ecdhEsA256Kw:\n algs.add(alg);\n break;\n default:\n throw CodedTypeError('invalid key alg', ERR_INVALID_ARG_VALUE, { pk });\n }\n}\nexport function enableDecryptingResponses(config, contentEncryptionAlgorithms = [\n 'A128GCM',\n 'A192GCM',\n 'A256GCM',\n 'A128CBC-HS256',\n 'A192CBC-HS384',\n 'A256CBC-HS512',\n], ...keys) {\n if (int(config).decrypt !== undefined) {\n throw new TypeError('enableDecryptingResponses can only be called on a given Configuration instance once');\n }\n if (keys.length === 0) {\n throw CodedTypeError('no keys were provided', ERR_INVALID_ARG_VALUE);\n }\n const algs = new Set();\n const normalized = [];\n for (const pk of keys) {\n let key;\n if ('key' in pk) {\n key = { key: pk.key };\n if (typeof pk.alg === 'string')\n key.alg = pk.alg;\n if (typeof pk.kid === 'string')\n key.kid = pk.kid;\n }\n else {\n key = { key: pk };\n }\n if (key.key.type !== 'private') {\n throw CodedTypeError('only private keys must be provided', ERR_INVALID_ARG_VALUE);\n }\n if (isRsaOaep(key.key.algorithm)) {\n switch (key.key.algorithm.hash.name) {\n case 'SHA-1':\n case 'SHA-256':\n case 'SHA-384':\n case 'SHA-512': {\n let alg = 'RSA-OAEP';\n let sha;\n if ((sha = parseInt(key.key.algorithm.hash.name.slice(-3), 10))) {\n alg = `${alg}-${sha}`;\n }\n key.alg ||= alg;\n if (alg !== key.alg)\n throw CodedTypeError('invalid key alg', ERR_INVALID_ARG_VALUE, {\n pk,\n });\n algs.add(key.alg);\n break;\n }\n default:\n throw CodedTypeError('only SHA-512, SHA-384, SHA-256, and SHA-1 RSA-OAEP keys are supported', ERR_INVALID_ARG_VALUE);\n }\n }\n else if (isEcdh(key.key.algorithm)) {\n if (key.key.algorithm.namedCurve !== 'P-256') {\n throw CodedTypeError('Only P-256 ECDH keys are supported', ERR_INVALID_ARG_VALUE);\n }\n checkEcdhAlg(algs, key.alg, pk);\n }\n else if (key.key.algorithm.name === 'X25519') {\n checkEcdhAlg(algs, key.alg, pk);\n }\n else {\n throw CodedTypeError('only RSA-OAEP, ECDH, or X25519 keys are supported', ERR_INVALID_ARG_VALUE);\n }\n normalized.push(key);\n }\n int(config).decrypt = async (jwe) => decrypt(normalized, jwe, contentEncryptionAlgorithms, [...algs]).catch(errorHandler);\n}\nfunction checkCryptoKey(key, alg, epk) {\n if (alg.startsWith('RSA-OAEP')) {\n return key.algorithm.name === 'RSA-OAEP';\n }\n if (alg.startsWith('ECDH-ES')) {\n if (key.algorithm.name !== 'ECDH' && key.algorithm.name !== 'X25519') {\n return false;\n }\n if (key.algorithm.name === 'ECDH') {\n return epk?.crv === key.algorithm.namedCurve;\n }\n if (key.algorithm.name === 'X25519') {\n return epk?.crv === 'X25519';\n }\n }\n return false;\n}\nfunction selectCryptoKeyForDecryption(keys, alg, kid, epk) {\n const { 0: key, length } = keys.filter((key) => {\n if (kid !== undefined && kid !== key.kid) {\n return false;\n }\n if (key.alg && alg !== key.alg) {\n return false;\n }\n return checkCryptoKey(key.key, alg, epk);\n });\n if (!key) {\n throw e('no applicable decryption key selected', undefined, 'OAUTH_DECRYPTION_FAILED');\n }\n if (length !== 1) {\n throw e('multiple applicable decryption keys selected', undefined, 'OAUTH_DECRYPTION_FAILED');\n }\n return key.key;\n}\nasync function decrypt(keys, jwe, contentEncryptionAlgorithms, keyManagementAlgorithms) {\n return decoder.decode((await compactDecrypt(jwe, (header) => {\n const { kid, alg, epk } = header;\n return selectCryptoKeyForDecryption(keys, alg, kid, epk);\n }, { keyManagementAlgorithms, contentEncryptionAlgorithms }).catch((err) => {\n if (err instanceof JOSEError) {\n throw e('decryption failed', err, 'OAUTH_DECRYPTION_FAILED');\n }\n errorHandler(err);\n })).plaintext);\n}\nfunction getServerHelpers(metadata) {\n return {\n supportsPKCE: {\n __proto__: null,\n value(method = 'S256') {\n return (metadata.code_challenge_methods_supported?.includes(method) === true);\n },\n },\n };\n}\nfunction addServerHelpers(metadata) {\n Object.defineProperties(metadata, getServerHelpers(metadata));\n}\nconst kEntraId = Symbol();\nexport class Configuration {\n constructor(server, clientId, metadata, clientAuthentication) {\n if (typeof clientId !== 'string' || !clientId.length) {\n throw CodedTypeError('\"clientId\" must be a non-empty string', ERR_INVALID_ARG_TYPE);\n }\n if (typeof metadata === 'string') {\n metadata = { client_secret: metadata };\n }\n if (metadata?.client_id !== undefined && clientId !== metadata.client_id) {\n throw CodedTypeError('\"clientId\" and \"metadata.client_id\" must be the same', ERR_INVALID_ARG_VALUE);\n }\n const client = {\n ...structuredClone(metadata),\n client_id: clientId,\n };\n client[oauth.clockSkew] = metadata?.[oauth.clockSkew] ?? 0;\n client[oauth.clockTolerance] = metadata?.[oauth.clockTolerance] ?? 30;\n let auth;\n if (clientAuthentication) {\n auth = clientAuthentication;\n }\n else {\n if (typeof client.client_secret === 'string' &&\n client.client_secret.length) {\n auth = ClientSecretPost(client.client_secret);\n }\n else {\n auth = None();\n }\n }\n let c = Object.freeze(client);\n const clone = structuredClone(server);\n if (kEntraId in server) {\n clone[oauth._expectedIssuer] = ({ claims: { tid } }) => server.issuer.replace('{tenantid}', tid);\n }\n let as = Object.freeze(clone);\n props ||= new WeakMap();\n props.set(this, {\n __proto__: null,\n as,\n c,\n auth,\n tlsOnly: true,\n timeout: 30,\n jwksCache: {},\n });\n }\n serverMetadata() {\n const metadata = structuredClone(int(this).as);\n addServerHelpers(metadata);\n return metadata;\n }\n clientMetadata() {\n const metadata = structuredClone(int(this).c);\n return metadata;\n }\n get timeout() {\n return int(this).timeout;\n }\n set timeout(value) {\n int(this).timeout = value;\n }\n get [customFetch]() {\n return int(this).fetch;\n }\n set [customFetch](value) {\n int(this).fetch = value;\n }\n}\nObject.freeze(Configuration.prototype);\nfunction getHelpers(response) {\n let exp = undefined;\n if (response.expires_in !== undefined) {\n exp = Date.now() + response.expires_in * 1000;\n }\n return {\n expiresIn: {\n __proto__: null,\n value() {\n if (exp) {\n const now = Date.now();\n if (exp > now) {\n return Math.floor((exp - now) / 1000);\n }\n return 0;\n }\n return undefined;\n },\n },\n claims: {\n __proto__: null,\n value() {\n return oauth.getValidatedIdTokenClaims(response);\n },\n },\n };\n}\nfunction addHelpers(response) {\n Object.defineProperties(response, getHelpers(response));\n}\nexport function getDPoPHandle(config, keyPair, options) {\n checkConfig(config);\n return oauth.DPoP(int(config).c, keyPair, options);\n}\nasync function handleRetryAfter(response, currentInterval, signal, throwIfInvalid = false) {\n const retryAfter = response.headers.get('retry-after')?.trim();\n if (retryAfter === undefined)\n return;\n let delaySeconds;\n if (/^\\d+$/.test(retryAfter)) {\n delaySeconds = parseInt(retryAfter, 10);\n }\n else {\n const retryDate = new Date(retryAfter);\n if (Number.isFinite(retryDate.getTime())) {\n const now = new Date();\n const delayMs = retryDate.getTime() - now.getTime();\n if (delayMs > 0) {\n delaySeconds = Math.ceil(delayMs / 1000);\n }\n }\n }\n if (throwIfInvalid && !Number.isFinite(delaySeconds)) {\n throw new oauth.OperationProcessingError('invalid Retry-After header value', { cause: response });\n }\n if (delaySeconds > currentInterval) {\n await wait(delaySeconds - currentInterval, signal);\n }\n}\nfunction wait(duration, signal) {\n return new Promise((resolve, reject) => {\n const waitStep = (remaining) => {\n try {\n signal.throwIfAborted();\n }\n catch (err) {\n reject(err);\n return;\n }\n if (remaining <= 0) {\n resolve();\n return;\n }\n const currentWait = Math.min(remaining, 5);\n setTimeout(() => waitStep(remaining - currentWait), currentWait * 1000);\n };\n waitStep(duration);\n });\n}\nfunction pollRequestSignal(pollingSignal, timeout) {\n const timeoutSignal = signal(timeout);\n if (!timeoutSignal) {\n return {\n signal: pollingSignal,\n cleanup() { },\n };\n }\n const controller = new AbortController();\n const abort = (event) => {\n const source = event.target;\n controller.abort(source.reason);\n };\n if (pollingSignal.aborted) {\n controller.abort(pollingSignal.reason);\n }\n else if (timeoutSignal.aborted) {\n controller.abort(timeoutSignal.reason);\n }\n else {\n pollingSignal.addEventListener('abort', abort, { once: true });\n timeoutSignal.addEventListener('abort', abort, { once: true });\n }\n return {\n signal: controller.signal,\n cleanup() {\n pollingSignal.removeEventListener('abort', abort);\n timeoutSignal.removeEventListener('abort', abort);\n },\n };\n}\nasync function pollGrant(config, authorizationResponse, grantCode, request, processResponse, parameters, options) {\n const requestParameters = new URLSearchParams(parameters);\n let interval = authorizationResponse.interval ?? 5;\n const pollingSignal = options?.signal ??\n AbortSignal.timeout(authorizationResponse.expires_in * 1000);\n for (;;) {\n try {\n await wait(interval, pollingSignal);\n }\n catch (error) {\n errorHandler(error);\n }\n const { as, c, auth, fetch, tlsOnly, nonRepudiation, timeout, decrypt } = int(config);\n const requestSignal = pollRequestSignal(pollingSignal, timeout);\n try {\n const response = await request(as, c, auth, grantCode, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n additionalParameters: requestParameters,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: requestSignal.signal,\n }).catch(errorHandler);\n if (response.status === 503 && response.headers.has('retry-after')) {\n await response.body?.cancel();\n await handleRetryAfter(response, interval, pollingSignal, true);\n options = { ...options, flag: undefined };\n continue;\n }\n let result;\n try {\n result = await processResponse(as, c, response, {\n [oauth.jweDecrypt]: decrypt,\n });\n }\n catch (error) {\n if (retryable(error, options)) {\n options = { ...options, flag: retry };\n continue;\n }\n if (error instanceof oauth.ResponseBodyError &&\n (error.error === 'slow_down' ||\n error.error === 'authorization_pending')) {\n if (error.error === 'slow_down')\n interval += 5;\n await handleRetryAfter(error.response, interval, pollingSignal);\n options = { ...options, flag: undefined };\n continue;\n }\n errorHandler(error);\n }\n result.id_token && (await nonRepudiation?.(response));\n addHelpers(result);\n return result;\n }\n finally {\n requestSignal.cleanup();\n }\n }\n}\nexport async function pollDeviceAuthorizationGrant(config, deviceAuthorizationResponse, parameters, options) {\n checkConfig(config);\n return pollGrant(config, deviceAuthorizationResponse, deviceAuthorizationResponse.device_code, oauth.deviceCodeGrantRequest, oauth.processDeviceCodeResponse, parameters, options);\n}\nexport async function initiateDeviceAuthorization(config, parameters) {\n checkConfig(config);\n const { as, c, auth, fetch, tlsOnly, timeout } = int(config);\n return oauth\n .deviceAuthorizationRequest(as, c, auth, parameters, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .then((response) => oauth.processDeviceAuthorizationResponse(as, c, response))\n .catch(errorHandler);\n}\nexport async function initiateBackchannelAuthentication(config, parameters) {\n checkConfig(config);\n const { as, c, auth, fetch, tlsOnly, timeout } = int(config);\n return oauth\n .backchannelAuthenticationRequest(as, c, auth, parameters, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .then((response) => oauth.processBackchannelAuthenticationResponse(as, c, response))\n .catch(errorHandler);\n}\nexport async function pollBackchannelAuthenticationGrant(config, backchannelAuthenticationResponse, parameters, options) {\n checkConfig(config);\n return pollGrant(config, backchannelAuthenticationResponse, backchannelAuthenticationResponse.auth_req_id, oauth.backchannelAuthenticationGrantRequest, oauth.processBackchannelAuthenticationGrantResponse, parameters, options);\n}\nexport function allowInsecureRequests(config) {\n int(config).tlsOnly = false;\n}\nexport function setJwksCache(config, jwksCache) {\n int(config).jwksCache = structuredClone(jwksCache);\n}\nexport function getJwksCache(config) {\n const cache = int(config).jwksCache;\n if (cache.uat) {\n return cache;\n }\n return undefined;\n}\nexport function enableNonRepudiationChecks(config) {\n checkConfig(config);\n int(config).nonRepudiation = (response) => {\n const { as, fetch, tlsOnly, timeout, jwksCache } = int(config);\n return oauth\n .validateApplicationLevelSignature(as, response, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n [oauth.jwksCache]: jwksCache,\n })\n .catch(errorHandler);\n };\n}\nexport function useJwtResponseMode(config) {\n checkConfig(config);\n const { hybrid, implicit } = int(config);\n if (hybrid || implicit) {\n throw e('JARM cannot be combined with a hybrid or implicit response types', undefined, oauth.UNSUPPORTED_OPERATION);\n }\n int(config).jarm = (authorizationResponse, expectedState) => validateJARMResponse(config, authorizationResponse, expectedState);\n}\nexport function enableDetachedSignatureResponseChecks(config) {\n if (!int(config).hybrid) {\n throw e('\"code id_token\" response type must be configured to be used first', undefined, oauth.UNSUPPORTED_OPERATION);\n }\n int(config).hybrid = (authorizationResponse, expectedNonce, expectedState, maxAge) => validateCodeIdTokenResponse(config, authorizationResponse, expectedNonce, expectedState, maxAge, true);\n}\nexport async function implicitAuthentication(config, currentUrl, expectedNonce, checks) {\n checkConfig(config);\n if (!(currentUrl instanceof URL) &&\n !webInstanceOf(currentUrl, 'Request')) {\n throw CodedTypeError('\"currentUrl\" must be an instance of URL, or Request', ERR_INVALID_ARG_TYPE);\n }\n if (typeof expectedNonce !== 'string') {\n throw CodedTypeError('\"expectedNonce\" must be a string', ERR_INVALID_ARG_TYPE);\n }\n const { as, c, fetch, tlsOnly, timeout, decrypt, implicit, jwksCache } = int(config);\n if (!implicit) {\n throw new TypeError('implicitAuthentication() cannot be used by clients using flows other than response_type=id_token');\n }\n let params;\n if (!(currentUrl instanceof URL)) {\n const request = currentUrl;\n switch (request.method) {\n case 'GET':\n params = new URLSearchParams(new URL(request.url).hash.slice(1));\n break;\n case 'POST':\n params = new URLSearchParams(await oauth.formPostResponse(request));\n break;\n default:\n throw CodedTypeError('unexpected Request HTTP method', ERR_INVALID_ARG_VALUE);\n }\n }\n else {\n params = new URLSearchParams(currentUrl.hash.slice(1));\n }\n try {\n {\n const decoy = new URLSearchParams(params);\n decoy.delete('id_token');\n oauth.validateAuthResponse({\n ...as,\n authorization_response_iss_parameter_supported: undefined,\n }, c, decoy, checks?.expectedState);\n }\n {\n const decoy = new Response(JSON.stringify({\n access_token: 'decoy',\n token_type: 'bearer',\n id_token: params.get('id_token'),\n }), {\n headers: new Headers({ 'content-type': 'application/json' }),\n });\n const ref = await oauth.processAuthorizationCodeResponse(as, c, decoy, {\n expectedNonce,\n maxAge: checks?.maxAge,\n [oauth.jweDecrypt]: decrypt,\n });\n await oauth.validateApplicationLevelSignature(as, decoy, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n [oauth.jwksCache]: jwksCache,\n });\n return oauth.getValidatedIdTokenClaims(ref);\n }\n }\n catch (err) {\n errorHandler(err);\n }\n}\nexport function useCodeIdTokenResponseType(config) {\n checkConfig(config);\n const { jarm, implicit } = int(config);\n if (jarm || implicit) {\n throw e('\"code id_token\" response type cannot be combined with JARM or implicit response type', undefined, oauth.UNSUPPORTED_OPERATION);\n }\n int(config).hybrid = (authorizationResponse, expectedNonce, expectedState, maxAge) => validateCodeIdTokenResponse(config, authorizationResponse, expectedNonce, expectedState, maxAge, false);\n}\nexport function useIdTokenResponseType(config) {\n checkConfig(config);\n const { jarm, hybrid } = int(config);\n if (jarm || hybrid) {\n throw e('\"id_token\" response type cannot be combined with JARM or hybrid response type', undefined, oauth.UNSUPPORTED_OPERATION);\n }\n int(config).implicit = true;\n}\nfunction stripParams(url) {\n url = new URL(url);\n url.search = '';\n url.hash = '';\n return url.href;\n}\nfunction webInstanceOf(input, toStringTag) {\n try {\n return Object.getPrototypeOf(input)[Symbol.toStringTag] === toStringTag;\n }\n catch {\n return false;\n }\n}\nexport async function authorizationCodeGrant(config, currentUrl, checks, tokenEndpointParameters, options) {\n checkConfig(config);\n if (options?.flag !== retry &&\n !(currentUrl instanceof URL) &&\n !webInstanceOf(currentUrl, 'Request')) {\n throw CodedTypeError('\"currentUrl\" must be an instance of URL, or Request', ERR_INVALID_ARG_TYPE);\n }\n let authResponse;\n let redirectUri;\n const { as, c, auth, fetch, tlsOnly, jarm, hybrid, nonRepudiation, timeout, decrypt, implicit } = int(config);\n if (options?.flag === retry) {\n authResponse = options.authResponse;\n redirectUri = options.redirectUri;\n }\n else {\n if (!(currentUrl instanceof URL)) {\n const request = currentUrl;\n currentUrl = new URL(currentUrl.url);\n switch (request.method) {\n case 'GET':\n break;\n case 'POST':\n const params = new URLSearchParams(await oauth.formPostResponse(request));\n if (hybrid) {\n currentUrl.hash = params.toString();\n }\n else {\n for (const [k, v] of params.entries()) {\n currentUrl.searchParams.append(k, v);\n }\n }\n break;\n default:\n throw CodedTypeError('unexpected Request HTTP method', ERR_INVALID_ARG_VALUE);\n }\n }\n redirectUri = stripParams(currentUrl);\n switch (true) {\n case !!jarm:\n authResponse = await jarm(currentUrl, checks?.expectedState);\n break;\n case !!hybrid:\n authResponse = await hybrid(currentUrl, checks?.expectedNonce, checks?.expectedState, checks?.maxAge);\n break;\n case !!implicit:\n throw new TypeError('authorizationCodeGrant() cannot be used by response_type=id_token clients');\n default:\n try {\n authResponse = oauth.validateAuthResponse(as, c, currentUrl.searchParams, checks?.expectedState);\n }\n catch (err) {\n errorHandler(err);\n }\n }\n }\n const response = await oauth\n .authorizationCodeGrantRequest(as, c, auth, authResponse, redirectUri, checks?.pkceCodeVerifier || oauth.nopkce, {\n additionalParameters: tokenEndpointParameters,\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n if (typeof checks?.expectedNonce === 'string' ||\n typeof checks?.maxAge === 'number') {\n checks.idTokenExpected = true;\n }\n const p = oauth.processAuthorizationCodeResponse(as, c, response, {\n expectedNonce: checks?.expectedNonce,\n maxAge: checks?.maxAge,\n requireIdToken: checks?.idTokenExpected,\n [oauth.jweDecrypt]: decrypt,\n });\n let result;\n try {\n result = await p;\n }\n catch (err) {\n if (retryable(err, options)) {\n return authorizationCodeGrant(config, undefined, checks, tokenEndpointParameters, {\n ...options,\n flag: retry,\n authResponse: authResponse,\n redirectUri: redirectUri,\n });\n }\n errorHandler(err);\n }\n result.id_token && (await nonRepudiation?.(response));\n addHelpers(result);\n return result;\n}\nasync function validateJARMResponse(config, authorizationResponse, expectedState) {\n const { as, c, fetch, tlsOnly, timeout, decrypt, jwksCache } = int(config);\n return oauth\n .validateJwtAuthResponse(as, c, authorizationResponse, expectedState, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n [oauth.jweDecrypt]: decrypt,\n [oauth.jwksCache]: jwksCache,\n })\n .catch(errorHandler);\n}\nasync function validateCodeIdTokenResponse(config, authorizationResponse, expectedNonce, expectedState, maxAge, fapi) {\n if (typeof expectedNonce !== 'string') {\n throw CodedTypeError('\"expectedNonce\" must be a string', ERR_INVALID_ARG_TYPE);\n }\n if (expectedState !== undefined && typeof expectedState !== 'string') {\n throw CodedTypeError('\"expectedState\" must be a string', ERR_INVALID_ARG_TYPE);\n }\n const { as, c, fetch, tlsOnly, timeout, decrypt, jwksCache } = int(config);\n return (fapi\n ? oauth.validateDetachedSignatureResponse\n : oauth.validateCodeIdTokenResponse)(as, c, authorizationResponse, expectedNonce, expectedState, maxAge, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n [oauth.jweDecrypt]: decrypt,\n [oauth.jwksCache]: jwksCache,\n }).catch(errorHandler);\n}\nexport async function refreshTokenGrant(config, refreshToken, parameters, options) {\n checkConfig(config);\n parameters = new URLSearchParams(parameters);\n const { as, c, auth, fetch, tlsOnly, nonRepudiation, timeout, decrypt } = int(config);\n const response = await oauth\n .refreshTokenGrantRequest(as, c, auth, refreshToken, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n additionalParameters: parameters,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n const p = oauth.processRefreshTokenResponse(as, c, response, {\n [oauth.jweDecrypt]: decrypt,\n });\n let result;\n try {\n result = await p;\n }\n catch (err) {\n if (retryable(err, options)) {\n return refreshTokenGrant(config, refreshToken, parameters, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n result.id_token && (await nonRepudiation?.(response));\n addHelpers(result);\n return result;\n}\nexport async function clientCredentialsGrant(config, parameters, options) {\n checkConfig(config);\n parameters = new URLSearchParams(parameters);\n const { as, c, auth, fetch, tlsOnly, timeout } = int(config);\n const response = await oauth\n .clientCredentialsGrantRequest(as, c, auth, parameters, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n const p = oauth.processClientCredentialsResponse(as, c, response);\n let result;\n try {\n result = await p;\n }\n catch (err) {\n if (retryable(err, options)) {\n return clientCredentialsGrant(config, parameters, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n addHelpers(result);\n return result;\n}\nexport function buildAuthorizationUrl(config, parameters) {\n checkConfig(config);\n const { as, c, tlsOnly, hybrid, jarm, implicit } = int(config);\n const authorizationEndpoint = oauth.resolveEndpoint(as, 'authorization_endpoint', false, tlsOnly);\n parameters = new URLSearchParams(parameters);\n if (!parameters.has('client_id')) {\n parameters.set('client_id', c.client_id);\n }\n if (!parameters.has('request_uri') && !parameters.has('request')) {\n if (!parameters.has('response_type')) {\n parameters.set('response_type', hybrid ? 'code id_token' : implicit ? 'id_token' : 'code');\n }\n if (implicit && !parameters.has('nonce')) {\n throw CodedTypeError('response_type=id_token clients must provide a nonce parameter in their authorization request parameters', ERR_INVALID_ARG_VALUE);\n }\n if (jarm) {\n parameters.set('response_mode', 'jwt');\n }\n }\n for (const [k, v] of parameters.entries()) {\n authorizationEndpoint.searchParams.append(k, v);\n }\n return authorizationEndpoint;\n}\nexport async function buildAuthorizationUrlWithJAR(config, parameters, signingKey, options) {\n checkConfig(config);\n const authorizationEndpoint = buildAuthorizationUrl(config, parameters);\n parameters = authorizationEndpoint.searchParams;\n if (!signingKey) {\n throw CodedTypeError('\"signingKey\" must be provided', ERR_INVALID_ARG_VALUE);\n }\n const { as, c } = int(config);\n const request = await oauth\n .issueRequestObject(as, c, parameters, signingKey, options)\n .catch(errorHandler);\n return buildAuthorizationUrl(config, { request });\n}\nexport async function buildAuthorizationUrlWithPAR(config, parameters, options) {\n checkConfig(config);\n const authorizationEndpoint = buildAuthorizationUrl(config, parameters);\n const { as, c, auth, fetch, tlsOnly, timeout } = int(config);\n const response = await oauth\n .pushedAuthorizationRequest(as, c, auth, authorizationEndpoint.searchParams, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n const p = oauth.processPushedAuthorizationResponse(as, c, response);\n let result;\n try {\n result = await p;\n }\n catch (err) {\n if (retryable(err, options)) {\n return buildAuthorizationUrlWithPAR(config, parameters, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n return buildAuthorizationUrl(config, { request_uri: result.request_uri });\n}\nexport function buildEndSessionUrl(config, parameters) {\n checkConfig(config);\n const { as, c, tlsOnly } = int(config);\n const endSessionEndpoint = oauth.resolveEndpoint(as, 'end_session_endpoint', false, tlsOnly);\n parameters = new URLSearchParams(parameters);\n if (!parameters.has('client_id')) {\n parameters.set('client_id', c.client_id);\n }\n for (const [k, v] of parameters.entries()) {\n endSessionEndpoint.searchParams.append(k, v);\n }\n return endSessionEndpoint;\n}\nfunction checkConfig(input) {\n if (!(input instanceof Configuration)) {\n throw CodedTypeError('\"config\" must be an instance of Configuration', ERR_INVALID_ARG_TYPE);\n }\n if (Object.getPrototypeOf(input) !== Configuration.prototype) {\n throw CodedTypeError('subclassing Configuration is not allowed', ERR_INVALID_ARG_VALUE);\n }\n}\nfunction signal(timeout) {\n return timeout ? AbortSignal.timeout(timeout * 1000) : undefined;\n}\nexport async function fetchUserInfo(config, accessToken, expectedSubject, options) {\n checkConfig(config);\n const { as, c, fetch, tlsOnly, nonRepudiation, timeout, decrypt } = int(config);\n const response = await oauth\n .userInfoRequest(as, c, accessToken, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n let exec = oauth.processUserInfoResponse(as, c, expectedSubject, response, {\n [oauth.jweDecrypt]: decrypt,\n });\n let result;\n try {\n result = await exec;\n }\n catch (err) {\n if (retryable(err, options)) {\n return fetchUserInfo(config, accessToken, expectedSubject, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n oauth.getContentType(response) === 'application/jwt' &&\n (await nonRepudiation?.(response));\n return result;\n}\nfunction retryable(err, options) {\n if (options?.DPoP && options.flag !== retry) {\n return oauth.isDPoPNonceError(err);\n }\n return false;\n}\nexport async function tokenIntrospection(config, token, parameters) {\n checkConfig(config);\n const { as, c, auth, fetch, tlsOnly, nonRepudiation, timeout, decrypt } = int(config);\n const response = await oauth\n .introspectionRequest(as, c, auth, token, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n additionalParameters: new URLSearchParams(parameters),\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n const result = await oauth\n .processIntrospectionResponse(as, c, response, {\n [oauth.jweDecrypt]: decrypt,\n })\n .catch(errorHandler);\n oauth.getContentType(response) === 'application/token-introspection+jwt' &&\n (await nonRepudiation?.(response));\n return result;\n}\nconst retry = Symbol();\nexport async function genericGrantRequest(config, grantType, parameters, options) {\n checkConfig(config);\n const { as, c, auth, fetch, tlsOnly, timeout, decrypt, nonRepudiation } = int(config);\n const response = await oauth\n .genericTokenEndpointRequest(as, c, auth, grantType, new URLSearchParams(parameters), {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n let recognizedTokenTypes;\n if (grantType === 'urn:ietf:params:oauth:grant-type:token-exchange') {\n recognizedTokenTypes = { n_a: () => { } };\n }\n const p = oauth.processGenericTokenEndpointResponse(as, c, response, {\n [oauth.jweDecrypt]: decrypt,\n recognizedTokenTypes,\n });\n let result;\n try {\n result = await p;\n }\n catch (err) {\n if (retryable(err, options)) {\n return genericGrantRequest(config, grantType, parameters, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n result.id_token && (await nonRepudiation?.(response));\n addHelpers(result);\n return result;\n}\nexport async function tokenRevocation(config, token, parameters) {\n checkConfig(config);\n const { as, c, auth, fetch, tlsOnly, timeout } = int(config);\n return oauth\n .revocationRequest(as, c, auth, token, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n additionalParameters: new URLSearchParams(parameters),\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .then(oauth.processRevocationResponse)\n .catch(errorHandler);\n}\nexport async function fetchProtectedResource(config, accessToken, url, method, body, headers, options) {\n checkConfig(config);\n headers ||= new Headers();\n if (USER_AGENT && !headers.has('user-agent')) {\n headers.set('user-agent', USER_AGENT);\n }\n const { fetch, tlsOnly, timeout } = int(config);\n const exec = oauth.protectedResourceRequest(accessToken, method, url, headers, body, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n signal: signal(timeout),\n });\n let result;\n try {\n result = await exec;\n }\n catch (err) {\n if (retryable(err, options)) {\n return fetchProtectedResource(config, accessToken, url, method, body, headers, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n return result;\n}\n//# sourceMappingURL=index.js.map","import { mkdir, readFile, writeFile } from \"node:fs/promises\"\nimport { join } from \"node:path\"\nimport * as oauth from \"openid-client\"\nimport { z } from \"zod\"\nimport type { env } from \"@/env\"\n\nexport type AuthEnv = Pick<\n\ttypeof env,\n\t\"CTX_AUTH_ISSUER\" | \"CTX_AUTH_CLIENT_ID\" | \"CTX_CONFIG_DIR\"\n>\nconst credentialSchema = z.object({\n\taccessToken: z.string(),\n\tclientId: z.string(),\n\texpiresAt: z.number(),\n\tissuer: z.url(),\n\trefreshToken: z.string().optional(),\n})\n\nexport class LoginRequiredError extends Error {\n\treadonly mismatch?: {\n\t\tsaved: Pick<z.infer<typeof credentialSchema>, \"issuer\" | \"clientId\">\n\t\texpected: Pick<z.infer<typeof credentialSchema>, \"issuer\" | \"clientId\">\n\t}\n\n\tconstructor(\n\t\treason: string,\n\t\toptions?: ErrorOptions & { mismatch?: LoginRequiredError[\"mismatch\"] },\n\t) {\n\t\tsuper(reason, options)\n\t\tthis.mismatch = options?.mismatch\n\t}\n}\n\nasync function configuration(env: AuthEnv) {\n\tconst issuer = new URL(env.CTX_AUTH_ISSUER)\n\treturn oauth.discovery(issuer, env.CTX_AUTH_CLIENT_ID, undefined, oauth.None(), {\n\t\talgorithm: \"oauth2\",\n\t\texecute:\n\t\t\tissuer.protocol === \"http:\" && [\"localhost\", \"127.0.0.1\"].includes(issuer.hostname)\n\t\t\t\t? [oauth.allowInsecureRequests]\n\t\t\t\t: [],\n\t})\n}\n\nasync function save(\n\tenv: AuthEnv,\n\ttokens: oauth.TokenEndpointResponse,\n\tpreviousRefreshToken?: string,\n) {\n\tconst credentials = credentialSchema.parse({\n\t\taccessToken: tokens.access_token,\n\t\tclientId: env.CTX_AUTH_CLIENT_ID,\n\t\texpiresAt: Date.now() + z.number().parse(tokens.expires_in) * 1000,\n\t\tissuer: env.CTX_AUTH_ISSUER,\n\t\trefreshToken: tokens.refresh_token ?? previousRefreshToken,\n\t})\n\tawait mkdir(env.CTX_CONFIG_DIR, { mode: 0o700, recursive: true })\n\tawait writeFile(join(env.CTX_CONFIG_DIR, \"auth.json\"), JSON.stringify(credentials), {\n\t\tmode: 0o600,\n\t})\n\treturn credentials\n}\n\nexport async function login(env: AuthEnv) {\n\tconst config = await configuration(env)\n\tconst authorization = await oauth.initiateDeviceAuthorization(config, {\n\t\tresource: \"https://platform.usecontextlayer.com\",\n\t\tscope: \"offline_access platform:access\",\n\t})\n\tconsole.log(\n\t\t`Open ${authorization.verification_uri_complete ?? authorization.verification_uri}`,\n\t)\n\tconsole.log(`Confirm this code: ${authorization.user_code}`)\n\tconsole.log(\"Waiting for approval…\")\n\tconst tokens = await oauth.pollDeviceAuthorizationGrant(config, authorization)\n\tawait save(env, tokens)\n\tconsole.log(\"Signed in to ContextLayer.\")\n}\n\nexport async function getAccessToken(env: AuthEnv) {\n\tconst contents = await readFile(join(env.CTX_CONFIG_DIR, \"auth.json\"), \"utf8\").catch(\n\t\t(error: unknown) => {\n\t\t\tif (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n\t\t\t\tthrow new LoginRequiredError(\"Not signed in.\", { cause: error })\n\t\t\t}\n\t\t\tthrow error\n\t\t},\n\t)\n\tlet credentials = credentialSchema.parse(JSON.parse(contents))\n\tif (\n\t\tcredentials.issuer !== env.CTX_AUTH_ISSUER ||\n\t\tcredentials.clientId !== env.CTX_AUTH_CLIENT_ID\n\t) {\n\t\tthrow new LoginRequiredError(\n\t\t\t\"Saved login belongs to a different auth server or client.\",\n\t\t\t{\n\t\t\t\tmismatch: {\n\t\t\t\t\texpected: {\n\t\t\t\t\t\tclientId: env.CTX_AUTH_CLIENT_ID,\n\t\t\t\t\t\tissuer: env.CTX_AUTH_ISSUER,\n\t\t\t\t\t},\n\t\t\t\t\tsaved: { clientId: credentials.clientId, issuer: credentials.issuer },\n\t\t\t\t},\n\t\t\t},\n\t\t)\n\t}\n\tif (credentials.expiresAt <= Date.now()) {\n\t\tif (!credentials.refreshToken) throw new LoginRequiredError(\"Login expired.\")\n\t\tcredentials = await save(\n\t\t\tenv,\n\t\t\tawait oauth\n\t\t\t\t.refreshTokenGrant(await configuration(env), credentials.refreshToken)\n\t\t\t\t.catch((error: unknown) => {\n\t\t\t\t\tif (\n\t\t\t\t\t\terror instanceof oauth.ResponseBodyError &&\n\t\t\t\t\t\terror.error === \"invalid_grant\"\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow new LoginRequiredError(\"Login expired.\", { cause: error })\n\t\t\t\t\t}\n\t\t\t\t\tthrow error\n\t\t\t\t}),\n\t\t\tcredentials.refreshToken,\n\t\t)\n\t}\n\treturn credentials.accessToken\n}\n\nexport async function getCurrentUser(env: AuthEnv, headers: HeadersInit) {\n\tconst response = await fetch(new URL(\"/api/me\", env.CTX_AUTH_ISSUER), { headers })\n\tif (response.status === 401) throw new LoginRequiredError(\"Saved login was rejected.\")\n\tif (!response.ok) throw new Error(`Identity request failed: HTTP ${response.status}`)\n\treturn z.object({ id: z.string().min(1) }).parse(await response.json())\n}\n\nexport async function listOrganizations(env: AuthEnv, headers: HeadersInit) {\n\tconst response = await fetch(\n\t\tnew URL(\"/api/platform/organizations\", env.CTX_AUTH_ISSUER),\n\t\t{\n\t\t\theaders,\n\t\t},\n\t)\n\tif (!response.ok) throw new Error(`Organization lookup failed: HTTP ${response.status}`)\n\tconst { organizations } = z\n\t\t.object({\n\t\t\torganizations: z.array(z.object({ id: z.string().min(1), slug: z.string() })),\n\t\t})\n\t\t.parse(await response.json())\n\treturn organizations\n}\n"],"ignoreList":[0,1],"mappings":";;;;AAAA,IAAIA;AACJ,IAAI,OAAO,cAAc,eAAe,CAAC,UAAU,WAAW,aAAa,cAAc,GAGrF,eAAa;AAEjB,SAAS,gBAAgB,OAAO,UAAU;CACtC,IAAI,S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EACxC,IAAI,CAAC,YAAY,cAAc,MAAM,IAAI,mBAAmB,gBAAgB;EAC5E,cAAc,MAAM,KACnB,KACA,MAAMC,kBACc,MAAM,cAAc,GAAG,GAAG,YAAY,YAAY,CAAC,CACrE,OAAO,UAAmB;GAC1B,IACC,iBAAiBC,qBACjB,MAAM,UAAU,iBAEhB,MAAM,IAAI,mBAAmB,kBAAkB,EAAE,OAAO,MAAM,CAAC;GAEhE,MAAM;EACP,CAAC,GACF,YAAY,YACb;CACD;CACA,OAAO,YAAY;AACpB;AAEA,eAAsB,eAAe,KAAc,SAAsB;CACxE,MAAM,WAAW,MAAM,MAAM,IAAI,IAAI,WAAW,IAAI,eAAe,GAAG,EAAE,QAAQ,CAAC;CACjF,IAAI,SAAS,WAAW,KAAK,MAAM,IAAI,mBAAmB,2BAA2B;CACrF,IAAI,CAAC,SAAS,IAAI,MAAM,IAAI,MAAM,iCAAiC,SAAS,QAAQ;CACpF,OAAOV,OAAS,EAAE,IAAIC,OAAS,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,MAAM,SAAS,KAAK,CAAC;AACvE;AAEA,eAAsB,kBAAkB,KAAc,SAAsB;CAC3E,MAAM,WAAW,MAAM,MACtB,IAAI,IAAI,+BAA+B,IAAI,eAAe,GAC1D,EACC,QACD,CACD;CACA,IAAI,CAAC,SAAS,IAAI,MAAM,IAAI,MAAM,oCAAoC,SAAS,QAAQ;CACvF,MAAM,EAAE,kBAAkBU,OACjB,EACP,eAAeC,MAAQZ,OAAS;EAAE,IAAIC,OAAS,CAAC,CAAC,IAAI,CAAC;EAAG,MAAMA,OAAS;CAAE,CAAC,CAAC,EAC7E,CAAC,CAAC,CACD,MAAM,MAAM,SAAS,KAAK,CAAC;CAC7B,OAAO;AACR"}
package/dist/auth.d.mts CHANGED
@@ -1,14 +1,29 @@
1
+ import { c as ZodObject, d as ZodString, f as ZodURL, g as $strip, l as ZodOptional, m as output, s as ZodNumber } from "./schemas-DeaNWrS-.mjs";
1
2
  //#region env.d.ts
2
3
  declare const env: {
3
4
  CTX_AUTH_CLIENT_ID: string;
4
5
  CTX_AUTH_ISSUER: string;
6
+ CTX_CONFIG_DIR: string;
5
7
  CTX_PLATFORM_URL: string;
6
8
  };
7
9
  //#endregion
8
10
  //#region auth.d.ts
9
- type AuthEnv = Pick<typeof env, "CTX_AUTH_ISSUER" | "CTX_AUTH_CLIENT_ID">;
11
+ type AuthEnv = Pick<typeof env, "CTX_AUTH_ISSUER" | "CTX_AUTH_CLIENT_ID" | "CTX_CONFIG_DIR">;
12
+ declare const credentialSchema: ZodObject<{
13
+ accessToken: ZodString;
14
+ clientId: ZodString;
15
+ expiresAt: ZodNumber;
16
+ issuer: ZodURL;
17
+ refreshToken: ZodOptional<ZodString>;
18
+ }, $strip>;
10
19
  export declare class LoginRequiredError extends Error {
11
- constructor(reason: string, options?: ErrorOptions);
20
+ readonly mismatch?: {
21
+ saved: Pick<output<typeof credentialSchema>, "issuer" | "clientId">;
22
+ expected: Pick<output<typeof credentialSchema>, "issuer" | "clientId">;
23
+ };
24
+ constructor(reason: string, options?: ErrorOptions & {
25
+ mismatch?: LoginRequiredError["mismatch"];
26
+ });
12
27
  }
13
28
  export declare function getAccessToken(env: AuthEnv): Promise<string>;
14
29
  export declare function getCurrentUser(env: AuthEnv, headers: HeadersInit): Promise<{
@@ -1 +1 @@
1
- {"version":3,"file":"auth.d.mts","names":[],"sources":["../env.ts","../auth.ts"],"mappings":";cAMa;;;;;;;KCCD,UAAU,YAAY;qBAYrB,2BAA2B;EACvC,YAAY,gBAAgB,UAAU;;wBAiDjB,eAAe,KAAK,UAAO;wBAqC3B,eAAe,KAAK,SAAS,SAAS,cAAW;;;wBAOjD,kBAAkB,KAAK,SAAS,SAAS,cAAW"}
1
+ {"version":3,"file":"auth.d.mts","names":["z.ZodString","z.ZodNumber","z.ZodURL","z.ZodOptional","z.core.$strip","z.ZodObject","z.infer"],"sources":["../env.ts","../auth.ts"],"mappings":";;cAYa;;;;;;;;KCND,UAAU,YACd;cAGF,kBAAgBK;;;;;;GAMpBD;qBAEW,2BAA2B;WAC9B;IACR,OAAO,KAAKE,cAAe;IAC3B,UAAU,KAAKA,cAAe;;EAG/B,YACC,gBACA,UAAU;IAAiB,WAAW;;;wBAqDlB,eAAe,KAAK,UAAO;wBAgD3B,eAAe,KAAK,SAAS,SAAS,cAAW;;;wBAOjD,kBAAkB,KAAK,SAAS,SAAS,cAAW"}
package/dist/auth.mjs CHANGED
@@ -1,2 +1 @@
1
- import { i as listOrganizations, n as getAccessToken, r as getCurrentUser, t as LoginRequiredError } from "./auth-DOsE8GwJ.mjs";
2
- export { LoginRequiredError, getAccessToken, getCurrentUser, listOrganizations };
1
+ export { t as LoginRequiredError, n as getAccessToken, r as getCurrentUser, i as listOrganizations } from "./auth-BL9AxZGb.mjs";