@20baht/elysia-oauth-provider 0.0.0-stage → 0.2.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 (62) hide show
  1. package/README.md +655 -2
  2. package/dist/config.d.ts +37 -0
  3. package/dist/config.d.ts.map +1 -0
  4. package/dist/core/bearer.d.ts +11 -0
  5. package/dist/core/bearer.d.ts.map +1 -0
  6. package/dist/core/pkce.d.ts +6 -0
  7. package/dist/core/pkce.d.ts.map +1 -0
  8. package/dist/core/provider.d.ts +109 -0
  9. package/dist/core/provider.d.ts.map +1 -0
  10. package/dist/core/rate-limit.d.ts +61 -0
  11. package/dist/core/rate-limit.d.ts.map +1 -0
  12. package/dist/core/redirect-uri.d.ts +19 -0
  13. package/dist/core/redirect-uri.d.ts.map +1 -0
  14. package/dist/core/resource.d.ts +19 -0
  15. package/dist/core/resource.d.ts.map +1 -0
  16. package/dist/core/scope.d.ts +7 -0
  17. package/dist/core/scope.d.ts.map +1 -0
  18. package/dist/crypto/hash.d.ts +10 -0
  19. package/dist/crypto/hash.d.ts.map +1 -0
  20. package/dist/crypto/jwt.d.ts +51 -0
  21. package/dist/crypto/jwt.d.ts.map +1 -0
  22. package/dist/crypto/props-encryption.d.ts +14 -0
  23. package/dist/crypto/props-encryption.d.ts.map +1 -0
  24. package/dist/crypto/random.d.ts +8 -0
  25. package/dist/crypto/random.d.ts.map +1 -0
  26. package/dist/endpoints/authorize.d.ts +4 -0
  27. package/dist/endpoints/authorize.d.ts.map +1 -0
  28. package/dist/endpoints/http.d.ts +27 -0
  29. package/dist/endpoints/http.d.ts.map +1 -0
  30. package/dist/endpoints/metadata.d.ts +9 -0
  31. package/dist/endpoints/metadata.d.ts.map +1 -0
  32. package/dist/endpoints/register.d.ts +4 -0
  33. package/dist/endpoints/register.d.ts.map +1 -0
  34. package/dist/endpoints/revoke.d.ts +4 -0
  35. package/dist/endpoints/revoke.d.ts.map +1 -0
  36. package/dist/endpoints/token.d.ts +4 -0
  37. package/dist/endpoints/token.d.ts.map +1 -0
  38. package/dist/errors.d.ts +42 -0
  39. package/dist/errors.d.ts.map +1 -0
  40. package/dist/index.d.ts +28 -0
  41. package/dist/index.d.ts.map +1 -0
  42. package/dist/index.js +2376 -0
  43. package/dist/index.js.map +33 -0
  44. package/dist/plugin.d.ts +426 -0
  45. package/dist/plugin.d.ts.map +1 -0
  46. package/dist/storage/conformance.d.ts +36 -0
  47. package/dist/storage/conformance.d.ts.map +1 -0
  48. package/dist/storage/conformance.js +163 -0
  49. package/dist/storage/conformance.js.map +10 -0
  50. package/dist/storage/keys.d.ts +33 -0
  51. package/dist/storage/keys.d.ts.map +1 -0
  52. package/dist/storage/memory.d.ts +35 -0
  53. package/dist/storage/memory.d.ts.map +1 -0
  54. package/dist/storage/redis.d.ts +83 -0
  55. package/dist/storage/redis.d.ts.map +1 -0
  56. package/dist/storage/redis.js +135 -0
  57. package/dist/storage/redis.js.map +10 -0
  58. package/dist/storage/types.d.ts +61 -0
  59. package/dist/storage/types.d.ts.map +1 -0
  60. package/dist/types.d.ts +329 -0
  61. package/dist/types.d.ts.map +1 -0
  62. package/package.json +67 -4
@@ -0,0 +1,33 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/storage/redis.ts", "../src/plugin.ts", "../src/storage/types.ts", "../src/core/rate-limit.ts", "../src/config.ts", "../src/core/bearer.ts", "../src/crypto/hash.ts", "../src/crypto/jwt.ts", "../src/crypto/props-encryption.ts", "../src/crypto/random.ts", "../src/errors.ts", "../src/storage/keys.ts", "../src/core/pkce.ts", "../src/core/redirect-uri.ts", "../src/core/resource.ts", "../src/core/scope.ts", "../src/core/provider.ts", "../src/endpoints/authorize.ts", "../src/endpoints/http.ts", "../src/endpoints/metadata.ts", "../src/endpoints/register.ts", "../src/endpoints/revoke.ts", "../src/endpoints/token.ts", "../src/storage/memory.ts"],
4
+ "sourcesContent": [
5
+ "import type { OAuthStorage, StorageSetOptions, Versioned } from './types.ts';\n\n/**\n * Minimal command surface the adapter needs. Satisfied by both `ioredis`\n * (`new Redis(url)`) and Bun's built-in client (`new Bun.RedisClient(url)` /\n * `Bun.redis`) without wrappers.\n */\nexport interface RedisLikeClient {\n get(key: string): Promise<string | null>;\n set(key: string, value: string): Promise<unknown>;\n set(key: string, value: string, ex: 'EX', seconds: number): Promise<unknown>;\n del(key: string): Promise<unknown>;\n /** ioredis-style `EVAL`. One of `eval` or `send` is required for the atomic primitives. */\n eval?(script: string, numKeys: number, ...args: (string | number)[]): Promise<unknown>;\n /** Bun-style raw command (`client.send('EVAL', [...])`). */\n send?(command: string, args: string[]): Promise<unknown>;\n scan(\n cursor: string | number,\n match: 'MATCH',\n pattern: string,\n count: 'COUNT',\n countValue: number,\n ): Promise<[cursor: string, keys: string[]]>;\n quit?(): Promise<unknown> | unknown;\n close?(): Promise<unknown> | unknown;\n}\n\nexport interface RedisStorageOptions {\n /** Prepended to every key, e.g. `\"oauth:\"`. Default `\"\"`. */\n keyPrefix?: string;\n /** `COUNT` hint for SCAN. Default 500. */\n scanCount?: number;\n /** Call `quit()`/`close()` on the client when `close()` is invoked. Default false. */\n ownsClient?: boolean;\n}\n\n/**\n * Lua bodies behind the atomic primitives. Exported so a test double can\n * recognise them; the scripts are the contract, the adapter only ships them.\n */\nexport const REDIS_SCRIPTS = {\n /** KEYS[1] */\n consume: `local v = redis.call('GET', KEYS[1])\nif v then redis.call('DEL', KEYS[1]) end\nreturn v`,\n /** KEYS[1], ARGV[1] = expected version, ARGV[2] = JSON value, ARGV[3] = ttl seconds or '' */\n compareAndSet: `local cur = redis.call('GET', KEYS[1])\nif not cur then return 0 end\nlocal ok, doc = pcall(cjson.decode, cur)\nif not ok or type(doc) ~= 'table' or tostring(doc.version) ~= ARGV[1] then return 0 end\nif ARGV[3] == '' then redis.call('SET', KEYS[1], ARGV[2]) else redis.call('SET', KEYS[1], ARGV[2], 'EX', ARGV[3]) end\nreturn 1`,\n /** KEYS[1], ARGV[1] = expected version */\n compareAndDelete: `local cur = redis.call('GET', KEYS[1])\nif not cur then return 0 end\nlocal ok, doc = pcall(cjson.decode, cur)\nif not ok or type(doc) ~= 'table' or tostring(doc.version) ~= ARGV[1] then return 0 end\nredis.call('DEL', KEYS[1])\nreturn 1`,\n} as const;\n\n/**\n * Redis-backed storage using native key TTLs.\n *\n * ```ts\n * import Redis from 'ioredis'\n * new RedisStorage(new Redis(process.env.REDIS_URL))\n * // or, with zero extra dependencies on Bun:\n * new RedisStorage(new Bun.RedisClient(process.env.REDIS_URL))\n * ```\n *\n * `list(prefix)` uses SCAN + MATCH; keep prefixes selective (the provider does).\n */\nexport class RedisStorage implements OAuthStorage {\n readonly #client: RedisLikeClient;\n readonly #prefix: string;\n readonly #scanCount: number;\n readonly #ownsClient: boolean;\n\n constructor(client: RedisLikeClient, options: RedisStorageOptions = {}) {\n this.#client = client;\n this.#prefix = options.keyPrefix ?? '';\n this.#scanCount = options.scanCount ?? 500;\n this.#ownsClient = options.ownsClient ?? false;\n if (!client.eval && !client.send) {\n throw new TypeError('RedisStorage: client must expose eval() or send() for EVAL');\n }\n }\n\n #eval(script: string, key: string, args: string[]): Promise<unknown> {\n const c = this.#client;\n if (c.eval) return c.eval(script, 1, key, ...args);\n return c.send!('EVAL', [script, '1', key, ...args]);\n }\n\n async get<T>(key: string): Promise<T | null> {\n const raw = await this.#client.get(this.#prefix + key);\n if (raw === null || raw === undefined) return null;\n return JSON.parse(raw) as T;\n }\n\n async set<T>(key: string, value: T, opts?: StorageSetOptions): Promise<void> {\n const raw = JSON.stringify(value);\n const ttl = opts?.ttlSeconds;\n if (ttl === undefined) await this.#client.set(this.#prefix + key, raw);\n else await this.#client.set(this.#prefix + key, raw, 'EX', Math.max(1, Math.ceil(ttl)));\n }\n\n async delete(key: string): Promise<void> {\n await this.#client.del(this.#prefix + key);\n }\n\n async consume<T>(key: string): Promise<T | null> {\n const raw = await this.#eval(REDIS_SCRIPTS.consume, this.#prefix + key, []);\n if (typeof raw !== 'string') return null;\n return JSON.parse(raw) as T;\n }\n\n async compareAndSet<T extends Versioned>(\n key: string,\n expectedVersion: number,\n value: T,\n opts?: StorageSetOptions,\n ): Promise<boolean> {\n const ttl = opts?.ttlSeconds;\n const result = await this.#eval(REDIS_SCRIPTS.compareAndSet, this.#prefix + key, [\n String(expectedVersion),\n JSON.stringify(value),\n ttl === undefined ? '' : String(Math.max(1, Math.ceil(ttl))),\n ]);\n return Number(result) === 1;\n }\n\n async compareAndDelete(key: string, expectedVersion: number): Promise<boolean> {\n const result = await this.#eval(REDIS_SCRIPTS.compareAndDelete, this.#prefix + key, [\n String(expectedVersion),\n ]);\n return Number(result) === 1;\n }\n\n async list(prefix: string): Promise<string[]> {\n const pattern = escapeGlob(this.#prefix + prefix) + '*';\n const out: string[] = [];\n let cursor = '0';\n do {\n const [next, keys] = await this.#client.scan(\n cursor,\n 'MATCH',\n pattern,\n 'COUNT',\n this.#scanCount,\n );\n for (const k of keys) out.push(k.slice(this.#prefix.length));\n cursor = next;\n } while (cursor !== '0');\n return [...new Set(out)];\n }\n\n async close(): Promise<void> {\n if (!this.#ownsClient) return;\n if (this.#client.quit) await this.#client.quit();\n else if (this.#client.close) await this.#client.close();\n }\n}\n\n/** Escape Redis glob metacharacters so a literal prefix is matched. */\nexport function escapeGlob(s: string): string {\n return s.replace(/[\\\\*?[\\]]/g, (c) => `\\\\${c}`);\n}\n\n// -----------------------------------------------------------------------------\n// Rate limiting\n// -----------------------------------------------------------------------------\n\nimport type { RateLimitDecision, RateLimitRule, RateLimiter } from '../core/rate-limit.ts';\n\n/** Extra commands needed by `RedisRateLimiter`; both ioredis and Bun's client have them. */\nexport interface RedisRateLimitClient {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n ttl(key: string): Promise<number>;\n}\n\n/**\n * Fixed-window counter shared across instances: `INCR` + `EXPIRE` on first hit.\n */\nexport class RedisRateLimiter implements RateLimiter {\n readonly #client: RedisRateLimitClient;\n readonly #prefix: string;\n\n constructor(client: RedisRateLimitClient, options: { keyPrefix?: string } = {}) {\n this.#client = client;\n this.#prefix = options.keyPrefix ?? 'ratelimit:';\n }\n\n async hit(key: string, rule: RateLimitRule): Promise<RateLimitDecision> {\n const k = this.#prefix + key;\n const count = await this.#client.incr(k);\n if (count === 1) await this.#client.expire(k, rule.windowSeconds);\n let ttl = await this.#client.ttl(k);\n if (ttl < 0) {\n // Key lost its expiry (e.g. crash between INCR and EXPIRE): reset it.\n await this.#client.expire(k, rule.windowSeconds);\n ttl = rule.windowSeconds;\n }\n return {\n allowed: count <= rule.max,\n remaining: Math.max(0, rule.max - count),\n retryAfterSeconds: Math.max(1, ttl),\n };\n }\n}\n",
6
+ "import { Elysia } from 'elysia';\nimport { resolveConfig } from './config.ts';\nimport { bearerChallenge, extractBearer } from './core/bearer.ts';\nimport { OAuthProviderCore, type CreateClientInput } from './core/provider.ts';\nimport { isSubset } from './core/scope.ts';\nimport { clientIpFrom, type RateLimitedEndpoint } from './core/rate-limit.ts';\nimport { handleAuthorize } from './endpoints/authorize.ts';\nimport { corsHeaders, json, methodNotAllowed, NO_STORE } from './endpoints/http.ts';\nimport { authorizationServerMetadata, protectedResourceMetadata } from './endpoints/metadata.ts';\nimport { handleRegister } from './endpoints/register.ts';\nimport { handleRevoke } from './endpoints/revoke.ts';\nimport { handleToken } from './endpoints/token.ts';\nimport { AuthorizationError, OAuthError } from './errors.ts';\nimport type {\n AuthRequest,\n ClientInfo,\n CompleteAuthorizationOptions,\n GrantSummary,\n OAuthContext,\n OAuthProviderConfig,\n PendingAuthRequest,\n RejectAuthorizationOptions,\n TokenInfo,\n} from './types.ts';\n\n/** Helpers exposed as `ctx.oauthProvider` inside handlers (and as `plugin.decorator.oauthProvider`). */\nexport interface OAuthHelpers<Props> {\n /** Validate `/authorize` query params yourself (workers-oauth-provider style). */\n parseAuthRequest(\n url: URL | string | Request,\n ): Promise<{ authRequest: AuthRequest; client: ClientInfo }>;\n /** Load a pending request stashed by `GET /authorize`. */\n getAuthRequest(authRequestId: string): Promise<PendingAuthRequest | null>;\n /** Issue an authorization code and return where to redirect the user-agent. */\n completeAuthorization(\n options: CompleteAuthorizationOptions<Props>,\n ): Promise<{ redirectTo: string }>;\n /** Send the user-agent back to the client with an error (e.g. consent denied). */\n rejectAuthorization(options: RejectAuthorizationOptions): Promise<{ redirectTo: string }>;\n /** Verify a bearer token string. `null` when invalid / expired / revoked. */\n verifyAccessToken(token: string, requestUrl?: string): Promise<TokenInfo<Props> | null>;\n createClient(input: CreateClientInput): Promise<ClientInfo>;\n lookupClient(clientId: string): Promise<ClientInfo | null>;\n updateClient(\n clientId: string,\n updates: Partial<Omit<CreateClientInput, 'clientId' | 'dynamicallyRegistered'>>,\n ): Promise<ClientInfo | null>;\n deleteClient(clientId: string): Promise<void>;\n listClients(): Promise<ClientInfo[]>;\n listUserGrants(userId: string): Promise<GrantSummary[]>;\n /** Every live grant (all users and clients). */\n listGrants(): Promise<GrantSummary[]>;\n listClientGrants(clientId: string): Promise<GrantSummary[]>;\n revokeGrant(grantId: string, userId: string): Promise<void>;\n /** Escape hatch to the engine. */\n readonly core: OAuthProviderCore<Props>;\n}\n\nexport interface OAuthMacroOptions {\n /** Every listed scope must be present on the token (403 `insufficient_scope` otherwise). */\n scopes?: string[];\n}\n\nfunction createHelpers<Props>(core: OAuthProviderCore<Props>): OAuthHelpers<Props> {\n return {\n core,\n parseAuthRequest: (url) => core.parseAuthRequest(url instanceof Request ? url.url : url),\n getAuthRequest: (id) => core.getAuthRequest(id),\n completeAuthorization: (o) => core.completeAuthorization(o),\n rejectAuthorization: (o) => core.rejectAuthorization(o),\n verifyAccessToken: (t, u) => core.verifyAccessToken(t, u),\n createClient: (i) => core.createClient(i),\n lookupClient: (id) => core.lookupClient(id),\n updateClient: (id, u) => core.updateClient(id, u),\n deleteClient: (id) => core.deleteClient(id),\n listClients: () => core.listClients(),\n listUserGrants: (u) => core.listUserGrants(u),\n listGrants: () => core.listGrants(),\n listClientGrants: (id) => core.listClientGrants(id),\n revokeGrant: (g, u) => core.revokeGrant(g, u),\n };\n}\n\n/**\n * OAuth 2.1 authorization server as an Elysia plugin.\n *\n * ```ts\n * const app = new Elysia()\n * .use(oauthProvider<Props>({ issuer, storage, handleAuthorize }))\n * .post('/mcp', ({ oauth }) => oauth.props, { oauth: { scopes: ['mcp'] } })\n * ```\n */\nexport function oauthProvider<Props = Record<string, unknown>>(\n userConfig: OAuthProviderConfig<Props>,\n) {\n const config = resolveConfig(userConfig);\n const core = new OAuthProviderCore<Props>(config);\n const helpers = createHelpers(core);\n const basePath = config.issuerUrl.pathname.replace(/\\/+$/, '');\n const p = (path: string) => `${basePath}${path}`;\n const cors = (req: Request) => (config.cors ? corsHeaders(req) : {});\n\n const withHeaders = (res: Response, headers: Record<string, string>): Response => {\n for (const [k, v] of Object.entries(headers)) if (!res.headers.has(k)) res.headers.set(k, v);\n return res;\n };\n\n /** 429 when the request exceeds its endpoint's rate-limit rule; null otherwise. */\n const rateLimited = async (\n endpoint: RateLimitedEndpoint,\n request: Request,\n socketIp: string | null,\n ): Promise<Response | null> => {\n const rl = config.rateLimit;\n const rule = rl?.rules[endpoint];\n if (!rl || !rule) return null;\n const ip = clientIpFrom(request, socketIp, rl.trustProxy);\n const key = rl.keyFor\n ? await rl.keyFor({ endpoint, request, ip })\n : `${endpoint}:${ip ?? 'unknown'}`;\n if (key === null) return null;\n const decision = await rl.limiter.hit(key, rule);\n if (decision.allowed) return null;\n config.hooks.onRateLimited?.({\n endpoint,\n key,\n retryAfterSeconds: decision.retryAfterSeconds,\n request,\n });\n return new OAuthError('temporarily_unavailable', 'Too many requests', {\n status: 429,\n headers: { 'Retry-After': String(decision.retryAfterSeconds) },\n }).toResponse();\n };\n\n /** Run an endpoint, mapping OAuth errors to spec responses. Never leaks internals. */\n const run = async (\n request: Request,\n fn: () => Promise<Response>,\n limit?: { endpoint: RateLimitedEndpoint; ip: string | null },\n ): Promise<Response> => {\n const extra = cors(request);\n try {\n if (limit) {\n const blocked = await rateLimited(limit.endpoint, request, limit.ip);\n if (blocked) return withHeaders(blocked, extra);\n }\n return withHeaders(await fn(), extra);\n } catch (e) {\n if (e instanceof OAuthError) {\n config.hooks.onError?.({ code: e.code, description: e.message, status: e.status, request });\n return withHeaders(e.toResponse(), extra);\n }\n if (e instanceof AuthorizationError) {\n config.hooks.onError?.({\n code: e.code,\n description: e.message,\n status: e.redirectUri ? 302 : 400,\n request,\n });\n return withHeaders(e.toResponse(), extra);\n }\n config.hooks.onError?.({\n code: 'server_error',\n description: 'Unexpected error',\n status: 500,\n request,\n });\n console.error('[elysia-oauth-provider]', e);\n return withHeaders(\n new OAuthError('server_error', 'Internal server error').toResponse(),\n extra,\n );\n }\n };\n\n // Keep the plugin's routes out of generated API docs (@elysiajs/openapi).\n const hidden = { detail: { hide: true } };\n // Handlers read the raw body themselves. `parse: 'none'` is ignored when the\n // app has an onParse hook or runs with `aot: false`, so Elysia would consume\n // the body first; a hook that claims the body (any truthy return) leaves the\n // Request stream untouched in every mode.\n const rawBody = { ...hidden, parse: () => true };\n\n const preflight = (request: Request) =>\n new Response(null, { status: 204, headers: cors(request) });\n\n /** The request URL as a client saw it: `publicOrigin` replaces the origin a proxy rewrote. */\n const publicUrlOf = (request: Request): string => {\n if (!config.publicOrigin) return request.url;\n const u = new URL(request.url);\n return `${config.publicOrigin}${u.pathname}${u.search}`;\n };\n\n const resourceMetadataUrlFor = (requestUrl: string): string => {\n const path = config.resource\n ? new URL(config.resource).pathname.replace(/\\/$/, '')\n : new URL(requestUrl).pathname;\n const origin = config.publicOrigin ?? config.issuerUrl.origin;\n return `${origin}/.well-known/oauth-protected-resource${path === '/' ? '' : path}`;\n };\n\n const app = new Elysia({ name: '@20baht/elysia-oauth-provider', seed: config.issuer })\n .decorate('oauthProvider', helpers)\n\n // ---- discovery -----------------------------------------------------------\n .get(\n '/.well-known/oauth-authorization-server',\n ({ request }) => run(request, async () => json(authorizationServerMetadata(core))),\n hidden,\n )\n .options('/.well-known/oauth-authorization-server', ({ request }) => preflight(request), hidden)\n .get(\n '/.well-known/oauth-protected-resource',\n ({ request }) => run(request, async () => json(protectedResourceMetadata(core, ''))),\n hidden,\n )\n .options('/.well-known/oauth-protected-resource', ({ request }) => preflight(request), hidden)\n .get(\n '/.well-known/oauth-protected-resource/*',\n ({ request, params }) =>\n run(request, async () => json(protectedResourceMetadata(core, `/${params['*']}`))),\n hidden,\n )\n .options('/.well-known/oauth-protected-resource/*', ({ request }) => preflight(request), hidden)\n\n // ---- authorize ---------------------------------------------------------\n .get(\n p(config.paths.authorize),\n ({ request, server }) =>\n run(request, () => handleAuthorize(core, request), {\n endpoint: 'authorize',\n ip: server?.requestIP(request)?.address ?? null,\n }),\n hidden,\n )\n\n // ---- token -------------------------------------------------------------\n .post(\n p(config.paths.token),\n ({ request, server }) =>\n run(request, () => handleToken(core, request), {\n endpoint: 'token',\n ip: server?.requestIP(request)?.address ?? null,\n }),\n rawBody,\n )\n .get(p(config.paths.token), () => methodNotAllowed('POST'), hidden)\n .options(p(config.paths.token), ({ request }) => preflight(request), hidden)\n\n // ---- revoke ------------------------------------------------------------\n .post(\n p(config.paths.revoke),\n ({ request, server }) =>\n run(request, () => handleRevoke(core, request), {\n endpoint: 'revoke',\n ip: server?.requestIP(request)?.address ?? null,\n }),\n rawBody,\n )\n .get(p(config.paths.revoke), () => methodNotAllowed('POST'), hidden)\n .options(p(config.paths.revoke), ({ request }) => preflight(request), hidden);\n\n if (basePath !== '') {\n app.get(\n `/.well-known/oauth-authorization-server${basePath}`,\n ({ request }) => run(request, async () => json(authorizationServerMetadata(core))),\n hidden,\n );\n }\n\n // ---- register (optional) ---------------------------------------------------\n if (config.clientRegistration.enabled) {\n app\n .post(\n p(config.paths.register),\n ({ request, server }) =>\n run(request, () => handleRegister(core, request), {\n endpoint: 'register',\n ip: server?.requestIP(request)?.address ?? null,\n }),\n rawBody,\n )\n .get(p(config.paths.register), () => methodNotAllowed('POST'), hidden)\n .options(p(config.paths.register), ({ request }) => preflight(request), hidden);\n }\n\n // ---- jwks (JWT mode only) -------------------------------------------------\n if (core.jwtSigner) {\n app.get(\n p(config.paths.jwks),\n ({ request }) =>\n run(request, async () => {\n const jwks = await (await core.jwtSigner!).jwks();\n return json(jwks ?? { keys: [] }, {\n headers: { 'Cache-Control': 'public, max-age=300' },\n });\n }),\n hidden,\n );\n }\n\n // ---- protected routes ------------------------------------------------------\n return app.macro({\n oauth: (options: true | OAuthMacroOptions) => ({\n resolve: async ({ request, set, status }) => {\n const required = options === true ? [] : (options.scopes ?? []);\n Object.assign(set.headers, cors(request));\n const requestUrl = publicUrlOf(request);\n const resourceMetadataUrl = resourceMetadataUrlFor(requestUrl);\n const scopeHint = config.resourceMetadata.scopesSupported ?? config.scopesSupported;\n\n const fail = (code: 401 | 403, challenge: string, body?: Record<string, string>) => {\n set.headers['WWW-Authenticate'] = challenge;\n Object.assign(set.headers, NO_STORE);\n return status(code, body ?? '');\n };\n\n const token = extractBearer(request.headers.get('Authorization'));\n if (!token) return fail(401, bearerChallenge({ resourceMetadataUrl, scope: scopeHint }));\n\n let info: TokenInfo<Props> | null;\n try {\n info = await core.verifyAccessToken(token, requestUrl);\n } catch (e) {\n const description = e instanceof OAuthError ? e.message : 'Invalid token';\n return fail(\n 401,\n bearerChallenge({\n resourceMetadataUrl,\n error: 'invalid_token',\n errorDescription: description,\n scope: scopeHint,\n }),\n { error: 'invalid_token', error_description: description },\n );\n }\n if (!info) {\n return fail(\n 401,\n bearerChallenge({ resourceMetadataUrl, error: 'invalid_token', scope: scopeHint }),\n { error: 'invalid_token', error_description: 'The access token is invalid or expired' },\n );\n }\n if (!isSubset(required, info.scopes)) {\n return fail(\n 403,\n bearerChallenge({ resourceMetadataUrl, error: 'insufficient_scope', scope: required }),\n {\n error: 'insufficient_scope',\n error_description: `Requires scope: ${required.join(' ')}`,\n },\n );\n }\n const oauth: OAuthContext<Props> = {\n userId: info.userId,\n clientId: info.clientId,\n grantId: info.grantId,\n scopes: info.scopes,\n props: info.props,\n expiresAt: info.expiresAt,\n audience: info.audience,\n token,\n };\n return { oauth };\n },\n }),\n });\n}\n\nexport type OAuthProviderPlugin<Props> = ReturnType<typeof oauthProvider<Props>>;\n",
7
+ "/**\n * Minimal async key-value contract the provider needs.\n *\n * Implementations MUST:\n * - store JSON-serialisable values and return them structurally equal from `get`\n * - return `null` for missing or expired keys\n * - honour `ttlSeconds` (key disappears after that many seconds)\n * - overwrite on `set` for an existing key (and replace/clear its TTL)\n * - make `list(prefix)` return every live key starting with `prefix`\n * - implement `consume`, `compareAndSet` and `compareAndDelete` atomically with\n * respect to each other and to `set`/`delete` on the same key. Of several\n * concurrent callers exactly one wins. The provider refuses to start with a\n * storage that lacks them, because refresh-token rotation and revocation are\n * only correct when the grant record is updated through them.\n *\n * See `storage/keys.ts` for the key layout the provider uses and which\n * keys need TTL vs. persistence.\n */\nexport interface OAuthStorage {\n get<T>(key: string): Promise<T | null>;\n set<T>(key: string, value: T, opts?: StorageSetOptions): Promise<void>;\n delete(key: string): Promise<void>;\n /** Return all live keys beginning with `prefix`. Order is not significant. */\n list(prefix: string): Promise<string[]>;\n /**\n * Atomically read and delete a key (Redis `GETDEL`, SQL `DELETE ... RETURNING`).\n * Of several concurrent callers exactly one receives the value, the rest get `null`.\n */\n consume<T>(key: string): Promise<T | null>;\n /**\n * Write `value` only if the key currently holds a live value whose top-level\n * `version` field equals `expectedVersion`. Returns whether the write happened.\n * A missing or expired key never matches. The provider always writes\n * `value.version === expectedVersion + 1`; adapters need not check that.\n * SQL: `UPDATE kv SET value = ?, expires_at = ? WHERE key = ? AND json_extract(value, '$.version') = ?`.\n */\n compareAndSet<T extends Versioned>(\n key: string,\n expectedVersion: number,\n value: T,\n opts?: StorageSetOptions,\n ): Promise<boolean>;\n /**\n * Delete the key only if it currently holds a live value whose top-level\n * `version` field equals `expectedVersion`. Returns whether the delete happened.\n * SQL: `DELETE FROM kv WHERE key = ? AND json_extract(value, '$.version') = ?`.\n */\n compareAndDelete(key: string, expectedVersion: number): Promise<boolean>;\n /** Optional: release timers / connections. Called by nothing automatically. */\n close?(): Promise<void> | void;\n}\n\n/** A record whose writes are serialised through `compareAndSet` / `compareAndDelete`. */\nexport interface Versioned {\n /** Non-negative integer, incremented by the provider on every write. */\n version: number;\n}\n\nexport interface StorageSetOptions {\n /** Seconds until the key expires. Omit (or `undefined`) for no expiry. */\n ttlSeconds?: number;\n}\n\nconst ATOMIC_METHODS = ['consume', 'compareAndSet', 'compareAndDelete'] as const;\n\n/**\n * Throws when `storage` lacks any atomic primitive. Called at plugin startup so\n * a JS caller or an adapter written for 0.2 fails loudly instead of racing.\n */\nexport function assertStorageContract(storage: OAuthStorage): void {\n const candidate: Partial<Record<(typeof ATOMIC_METHODS)[number], unknown>> = storage;\n const missing = ATOMIC_METHODS.filter((m) => typeof candidate[m] !== 'function');\n if (missing.length > 0) {\n throw new TypeError(\n `oauthProvider: storage must implement ${missing.join(', ')} atomically (see the storage adapter docs)`,\n );\n }\n}\n",
8
+ "export interface RateLimitRule {\n /** Requests allowed per window. */\n max: number;\n windowSeconds: number;\n}\n\nexport interface RateLimitDecision {\n allowed: boolean;\n /** Seconds until the window resets (sent as `Retry-After` when blocked). */\n retryAfterSeconds: number;\n remaining: number;\n}\n\n/**\n * Pluggable counter. `hit` records one request for `key` and says whether it\n * is still within `rule`. Implementations: `MemoryRateLimiter` (single\n * process) and `RedisRateLimiter` (shared, in `storage/redis`).\n */\nexport interface RateLimiter {\n hit(key: string, rule: RateLimitRule): Promise<RateLimitDecision>;\n}\n\nexport type RateLimitedEndpoint = 'token' | 'register' | 'authorize' | 'revoke';\n\nexport interface RateLimitConfig {\n /** Counter backend. Default `new MemoryRateLimiter()`. */\n limiter?: RateLimiter;\n /** `false` disables limiting for that endpoint. */\n token?: RateLimitRule | false;\n register?: RateLimitRule | false;\n authorize?: RateLimitRule | false;\n revoke?: RateLimitRule | false;\n /**\n * Derive the bucket key. Return `null` to skip limiting for this request.\n * Default: `${endpoint}:${ip}` where `ip` is the socket address, or the\n * first `X-Forwarded-For` entry when `trustProxy` is `true`, or the verbatim\n * value of the named header when `trustProxy` is a string.\n */\n keyFor?: (input: {\n endpoint: RateLimitedEndpoint;\n request: Request;\n ip: string | null;\n }) => string | null | Promise<string | null>;\n /**\n * Read the client IP from a proxy header. `true` uses the first\n * `X-Forwarded-For` entry; a string names the header to read verbatim\n * (e.g. `'cf-connecting-ip'`). Only enable behind a proxy you control.\n */\n trustProxy?: boolean | string;\n}\n\nexport const DEFAULT_RATE_LIMITS: Record<RateLimitedEndpoint, RateLimitRule> = {\n token: { max: 30, windowSeconds: 60 },\n register: { max: 10, windowSeconds: 3600 },\n authorize: { max: 60, windowSeconds: 60 },\n revoke: { max: 30, windowSeconds: 60 },\n};\n\n/**\n * Fixed-window counter in a `Map`. Per process only — use `RedisRateLimiter`\n * (or your own) when running more than one instance.\n */\nexport class MemoryRateLimiter implements RateLimiter {\n readonly #buckets = new Map<string, { count: number; resetAt: number }>();\n readonly #now: () => number;\n #ops = 0;\n\n constructor(options: { now?: () => number } = {}) {\n this.#now = options.now ?? Date.now;\n }\n\n async hit(key: string, rule: RateLimitRule): Promise<RateLimitDecision> {\n const now = this.#now();\n let b = this.#buckets.get(key);\n if (!b || b.resetAt <= now) {\n b = { count: 0, resetAt: now + rule.windowSeconds * 1000 };\n this.#buckets.set(key, b);\n }\n b.count++;\n if (++this.#ops % 1000 === 0) this.sweep();\n const retryAfterSeconds = Math.max(1, Math.ceil((b.resetAt - now) / 1000));\n return {\n allowed: b.count <= rule.max,\n remaining: Math.max(0, rule.max - b.count),\n retryAfterSeconds,\n };\n }\n\n sweep(): void {\n const now = this.#now();\n for (const [k, b] of this.#buckets) if (b.resetAt <= now) this.#buckets.delete(k);\n }\n}\n\nexport function clientIpFrom(\n request: Request,\n socketIp: string | null,\n trustProxy: boolean | string,\n): string | null {\n if (typeof trustProxy === 'string') {\n const value = request.headers.get(trustProxy);\n if (value) return value;\n } else if (trustProxy) {\n const xff = request.headers.get('x-forwarded-for');\n const first = xff?.split(',')[0]?.trim();\n if (first) return first;\n }\n return socketIp;\n}\n",
9
+ "import type { EndpointPaths, OAuthProviderConfig } from './types.ts';\nimport { assertStorageContract } from './storage/types.ts';\nimport {\n DEFAULT_RATE_LIMITS,\n MemoryRateLimiter,\n type RateLimitConfig,\n type RateLimitRule,\n type RateLimitedEndpoint,\n type RateLimiter,\n} from './core/rate-limit.ts';\n\nexport interface ResolvedConfig<Props> extends Required<\n Pick<\n OAuthProviderConfig<Props>,\n | 'issuer'\n | 'storage'\n | 'handleAuthorize'\n | 'accessTokenTTL'\n | 'refreshTokenTTL'\n | 'refreshTokenReuseGraceSeconds'\n | 'authCodeTTL'\n | 'authRequestTTL'\n | 'encryptProps'\n | 'cors'\n | 'hooks'\n | 'tokenFormat'\n | 'scopesSupported'\n | 'allowInsecureRedirectUris'\n >\n> {\n issuerUrl: URL;\n paths: EndpointPaths;\n /** Absolute URLs for each endpoint. */\n urls: EndpointPaths & { metadata: string; protectedResource: string };\n resource: string | undefined;\n /** Origin clients reach this server at, when it differs from the one requests arrive on. */\n publicOrigin: string | undefined;\n resourceMetadata: NonNullable<OAuthProviderConfig<Props>['resourceMetadata']>;\n clientRegistrationTTL: number | undefined;\n clientRegistration: { enabled: boolean; allowPublicClients: boolean; maxBodyBytes: number };\n rateLimit: ResolvedRateLimit | null;\n accessTokenClaims: OAuthProviderConfig<Props>['accessTokenClaims'];\n}\n\ninterface ResolvedRateLimit {\n limiter: RateLimiter;\n rules: Record<RateLimitedEndpoint, RateLimitRule | null>;\n keyFor: NonNullable<RateLimitConfig['keyFor']> | null;\n trustProxy: boolean | string;\n}\n\nexport const DEFAULT_PATHS: EndpointPaths = {\n authorize: '/authorize',\n token: '/token',\n register: '/register',\n revoke: '/revoke',\n jwks: '/.well-known/jwks.json',\n};\n\nconst DAY = 24 * 60 * 60;\n\n// eslint-disable-next-line sonarjs/cognitive-complexity -- above the limit since before the move into this repo (NOTES 2026-11-20); split it when it is next changed\nexport function resolveConfig<Props>(config: OAuthProviderConfig<Props>): ResolvedConfig<Props> {\n if (!config.issuer) throw new TypeError('oauthProvider: `issuer` is required');\n let issuerUrl: URL;\n try {\n issuerUrl = new URL(config.issuer);\n } catch {\n throw new TypeError('oauthProvider: `issuer` must be an absolute URL');\n }\n if (issuerUrl.protocol !== 'https:' && issuerUrl.protocol !== 'http:') {\n throw new TypeError('oauthProvider: `issuer` must be http(s)');\n }\n if (issuerUrl.search || issuerUrl.hash) {\n throw new TypeError('oauthProvider: `issuer` must not contain a query or fragment');\n }\n const issuer = config.issuer.replace(/\\/+$/, '');\n if (!config.storage) throw new TypeError('oauthProvider: `storage` is required');\n assertStorageContract(config.storage);\n if (typeof config.handleAuthorize !== 'function') {\n throw new TypeError('oauthProvider: `handleAuthorize` is required');\n }\n if (config.accessTokenClaims && (config.tokenFormat ?? 'opaque') === 'opaque') {\n throw new TypeError('oauthProvider: `accessTokenClaims` requires a JWT `tokenFormat`');\n }\n\n const paths: EndpointPaths = { ...DEFAULT_PATHS, ...stripUndefined(config.paths ?? {}) };\n for (const [name, p] of Object.entries(paths) as [string, string][]) {\n if (!p.startsWith('/')) throw new TypeError(`oauthProvider: paths.${name} must start with '/'`);\n }\n const basePath = issuerUrl.pathname.replace(/\\/+$/, '');\n const abs = (p: string) => `${issuerUrl.origin}${basePath}${p}`;\n\n const ttl = (name: string, value: number | undefined, def: number, min = 1) => {\n const v = value ?? def;\n if (!Number.isInteger(v) || v < min) {\n throw new TypeError(`oauthProvider: ${name} must be an integer >= ${min}`);\n }\n return v;\n };\n\n const scopesSupported = config.scopesSupported;\n if (!Array.isArray(scopesSupported) || scopesSupported.length === 0) {\n throw new TypeError('oauthProvider: `scopesSupported` must list at least one scope');\n }\n for (const s of scopesSupported) {\n if (!isValidScopeToken(s)) throw new TypeError(`oauthProvider: invalid scope token \"${s}\"`);\n }\n if (new Set(scopesSupported).size !== scopesSupported.length) {\n throw new TypeError('oauthProvider: scopesSupported contains duplicates');\n }\n\n const resource = config.resource ?? config.resourceMetadata?.resource;\n if (resource !== undefined) validateResourceUri(resource);\n\n const publicOrigin =\n config.publicOrigin === undefined ? undefined : parsePublicOrigin(config.publicOrigin);\n\n const reg = config.clientRegistration ?? false;\n const clientRegistration =\n reg === false\n ? { enabled: false, allowPublicClients: true, maxBodyBytes: 1024 * 1024 }\n : {\n enabled: true,\n allowPublicClients: (reg === true ? undefined : reg.allowPublicClients) ?? true,\n maxBodyBytes: (reg === true ? undefined : reg.maxBodyBytes) ?? 1024 * 1024,\n };\n\n const rateLimit = resolveRateLimit(config.rateLimit ?? true);\n\n return {\n issuer,\n issuerUrl,\n storage: config.storage,\n handleAuthorize: config.handleAuthorize,\n paths,\n urls: {\n authorize: abs(paths.authorize),\n token: abs(paths.token),\n register: abs(paths.register),\n revoke: abs(paths.revoke),\n jwks: abs(paths.jwks),\n metadata: `${issuerUrl.origin}/.well-known/oauth-authorization-server${basePath}`,\n protectedResource: `${issuerUrl.origin}/.well-known/oauth-protected-resource${basePath}`,\n },\n resource,\n publicOrigin,\n resourceMetadata: config.resourceMetadata ?? {},\n scopesSupported,\n allowInsecureRedirectUris: config.allowInsecureRedirectUris ?? false,\n accessTokenTTL: ttl('accessTokenTTL', config.accessTokenTTL, 3600),\n refreshTokenTTL: ttl('refreshTokenTTL', config.refreshTokenTTL, 30 * DAY, 0),\n refreshTokenReuseGraceSeconds: ttl(\n 'refreshTokenReuseGraceSeconds',\n config.refreshTokenReuseGraceSeconds,\n 30,\n 0,\n ),\n authCodeTTL: ttl('authCodeTTL', config.authCodeTTL, 600),\n authRequestTTL: ttl('authRequestTTL', config.authRequestTTL, 600),\n clientRegistrationTTL:\n 'clientRegistrationTTL' in config\n ? config.clientRegistrationTTL === undefined\n ? undefined\n : ttl('clientRegistrationTTL', config.clientRegistrationTTL, 90 * DAY)\n : 90 * DAY,\n clientRegistration,\n tokenFormat: config.tokenFormat ?? 'opaque',\n encryptProps: config.encryptProps ?? true,\n cors: config.cors ?? true,\n hooks: config.hooks ?? {},\n rateLimit,\n accessTokenClaims: config.accessTokenClaims,\n };\n}\n\nfunction resolveRateLimit(input: boolean | RateLimitConfig): ResolvedRateLimit | null {\n if (!input) return null;\n const cfg: RateLimitConfig = input === true ? {} : input;\n const rule = (name: RateLimitedEndpoint): RateLimitRule | null => {\n const v = cfg[name];\n if (v === false) return null;\n const r = v ?? DEFAULT_RATE_LIMITS[name];\n if (!Number.isInteger(r.max) || r.max < 1 || !(r.windowSeconds > 0)) {\n throw new TypeError(\n `oauthProvider: rateLimit.${name} needs integer max >= 1 and windowSeconds > 0`,\n );\n }\n return r;\n };\n const trustProxy = cfg.trustProxy ?? false;\n if (typeof trustProxy === 'string' && trustProxy.trim() === '') {\n throw new TypeError('oauthProvider: rateLimit.trustProxy header name must not be empty');\n }\n return {\n limiter: cfg.limiter ?? new MemoryRateLimiter(),\n rules: {\n token: rule('token'),\n register: rule('register'),\n authorize: rule('authorize'),\n revoke: rule('revoke'),\n },\n keyFor: cfg.keyFor ?? null,\n trustProxy,\n };\n}\n\nfunction parsePublicOrigin(input: string): string {\n let url: URL;\n try {\n url = new URL(input);\n } catch {\n throw new TypeError('oauthProvider: `publicOrigin` must be an absolute URL');\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n throw new TypeError('oauthProvider: `publicOrigin` must be http(s)');\n }\n if (url.pathname !== '/' || url.search || url.hash) {\n throw new TypeError(\n 'oauthProvider: `publicOrigin` must be an origin without path, query or fragment',\n );\n }\n return url.origin;\n}\n\nfunction stripUndefined<T extends object>(o: T): Partial<T> {\n return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined)) as Partial<T>;\n}\n\n/** RFC 6749 §3.3: scope-token = 1*( %x21 / %x23-5B / %x5D-7E ) */\nexport function isValidScopeToken(s: string): boolean {\n return s.length > 0 && /^[\\x21\\x23-\\x5B\\x5D-\\x7E]+$/.test(s);\n}\n\n/** RFC 8707 §2: absolute URI, no fragment. We additionally require http(s). */\nexport function validateResourceUri(resource: string): URL {\n let url: URL;\n try {\n url = new URL(resource);\n } catch {\n throw new TypeError(`Invalid resource URI \"${resource}\": must be an absolute URI`);\n }\n if (url.hash)\n throw new TypeError(`Invalid resource URI \"${resource}\": must not contain a fragment`);\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n throw new TypeError(`Invalid resource URI \"${resource}\": must be http(s)`);\n }\n return url;\n}\n",
10
+ "/** Extract the bearer token from an Authorization header (RFC 6750 §2.1). */\nexport function extractBearer(header: string | null | undefined): string | null {\n if (!header) return null;\n const m = /^Bearer\\s+([A-Za-z0-9\\-._~+/:]+=*)\\s*$/i.exec(header);\n return m ? m[1]! : null;\n}\n\nexport interface ChallengeOptions {\n resourceMetadataUrl: string;\n error?: 'invalid_token' | 'insufficient_scope' | 'invalid_request';\n errorDescription?: string;\n scope?: string[];\n}\n\n/** Build a `WWW-Authenticate: Bearer …` value (RFC 6750 §3, RFC 9728 §5.1). */\nexport function bearerChallenge(o: ChallengeOptions): string {\n const parts = [`realm=\"OAuth\"`, `resource_metadata=\"${o.resourceMetadataUrl}\"`];\n if (o.error) parts.push(`error=\"${o.error}\"`);\n if (o.errorDescription) {\n parts.push(`error_description=\"${o.errorDescription.replace(/\"/g, \"'\")}\"`);\n }\n if (o.scope && o.scope.length > 0) parts.push(`scope=\"${o.scope.join(' ')}\"`);\n return `Bearer ${parts.join(', ')}`;\n}\n",
11
+ "const encoder = new TextEncoder();\n\nexport async function sha256Hex(input: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', encoder.encode(input));\n return bytesToHex(new Uint8Array(digest));\n}\n\nexport async function sha256Base64Url(input: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', encoder.encode(input));\n return bytesToBase64Url(new Uint8Array(digest));\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n let out = '';\n for (const b of bytes) out += b.toString(16).padStart(2, '0');\n return out;\n}\n\nexport function bytesToBase64Url(bytes: Uint8Array): string {\n let bin = '';\n for (const b of bytes) bin += String.fromCharCode(b);\n return btoa(bin).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nexport function base64UrlToBytes(str: string): Uint8Array<ArrayBuffer> {\n const padded = str\n .replace(/-/g, '+')\n .replace(/_/g, '/')\n .padEnd(Math.ceil(str.length / 4) * 4, '=');\n const bin = atob(padded);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\n/**\n * Constant-time string equality. Compares UTF-8 bytes; strings of different\n * length still run a full comparison against `a` before returning false.\n */\nexport function timingSafeEqual(a: string, b: string): boolean {\n const ab = encoder.encode(a);\n const bb = encoder.encode(b);\n let diff = ab.length ^ bb.length;\n for (let i = 0; i < ab.length; i++) diff |= ab[i]! ^ (bb[i % (bb.length || 1)] ?? 0);\n return diff === 0;\n}\n",
12
+ "import {\n SignJWT,\n exportJWK,\n importJWK,\n importPKCS8,\n importSPKI,\n decodeProtectedHeader,\n jwtVerify,\n type JWK,\n type JWTPayload,\n type CryptoKey as JoseCryptoKey,\n type KeyObject,\n} from 'jose';\n\n/**\n * Claims the provider sets on every access token. `sub` and `grant_id` locate\n * the stored token record, so `accessTokenClaims` may not replace any of them.\n */\nexport const ACCESS_TOKEN_REGISTERED_CLAIMS = [\n 'iss',\n 'sub',\n 'aud',\n 'exp',\n 'iat',\n 'jti',\n 'client_id',\n 'scope',\n 'grant_id',\n] as const;\n\ntype KeyInput = JoseCryptoKey | KeyObject | Uint8Array | JWK | string;\n\nexport type JwtTokenFormat =\n | {\n type: 'jwt';\n alg: 'ES256' | 'RS256' | 'EdDSA';\n /** PKCS#8 PEM string, JWK, or CryptoKey. */\n privateKey: KeyInput;\n /** SPKI PEM string, JWK, or CryptoKey. Derived from the JWK/CryptoKey when omitted. */\n publicKey?: KeyInput;\n /** Required when `additionalPublicKeys` is used. */\n kid?: string;\n /**\n * Keys that were rotated out but whose tokens must keep verifying. Tokens\n * are matched by their `kid` header against the primary key and these;\n * all are published in the JWKS. Signing always uses the primary key.\n */\n additionalPublicKeys?: { publicKey: KeyInput; kid: string }[];\n }\n | {\n type: 'jwt';\n alg: 'HS256';\n /** Raw secret (string is UTF-8 encoded). Minimum 32 bytes. */\n secret: string | Uint8Array;\n kid?: string;\n };\n\nexport interface JwtSigner {\n readonly alg: string;\n readonly kid: string | undefined;\n sign(\n payload: JWTPayload,\n opts: { expiresAt: number; issuedAt: number; jti: string },\n ): Promise<string>;\n verify(token: string, expected: { issuer: string }): Promise<JWTPayload | null>;\n /** Public JWKS document, or `null` for symmetric algorithms. */\n jwks(): Promise<{ keys: JWK[] } | null>;\n}\n\nconst encoder = new TextEncoder();\n\nasync function importPrivate(\n alg: string,\n input: KeyInput,\n): Promise<JoseCryptoKey | KeyObject | Uint8Array> {\n if (typeof input === 'string') return importPKCS8(input, alg);\n if (input instanceof Uint8Array) return input;\n if (isJwk(input)) return importJWK(input, alg);\n return input;\n}\n\nasync function importPublic(\n alg: string,\n input: KeyInput,\n): Promise<JoseCryptoKey | KeyObject | Uint8Array> {\n if (typeof input === 'string') return importSPKI(input, alg);\n if (input instanceof Uint8Array) return input;\n if (isJwk(input)) return importJWK(input, alg);\n return input;\n}\n\nfunction isJwk(v: unknown): v is JWK {\n return typeof v === 'object' && v !== null && 'kty' in v;\n}\n\n// eslint-disable-next-line sonarjs/cognitive-complexity -- above the limit when it came in from elysia-oauth-provider 0.3.0 (NOTES 2026-11-21); split it when it is next changed\nexport async function createJwtSigner(format: JwtTokenFormat): Promise<JwtSigner> {\n if (format.alg === 'HS256') {\n const secret =\n typeof format.secret === 'string' ? encoder.encode(format.secret) : format.secret;\n if (secret.byteLength < 32) {\n throw new TypeError('tokenFormat.secret must be at least 32 bytes for HS256');\n }\n return makeSigner('HS256', format.kid, secret, secret, null);\n }\n\n const privateKey = await importPrivate(format.alg, format.privateKey);\n let publicKey: JoseCryptoKey | KeyObject | Uint8Array;\n if (format.publicKey) publicKey = await importPublic(format.alg, format.publicKey);\n else if (isJwk(format.privateKey)) {\n const pub = { ...format.privateKey };\n delete pub.d;\n delete pub.p;\n delete pub.q;\n delete pub.dp;\n delete pub.dq;\n delete pub.qi;\n publicKey = await importJWK(pub, format.alg);\n } else if (typeof privateKey === 'object' && 'algorithm' in privateKey) {\n // CryptoKey: try to derive public key via JWK export.\n const jwk = await exportJWK(privateKey);\n delete jwk.d;\n delete jwk.p;\n delete jwk.q;\n delete jwk.dp;\n delete jwk.dq;\n delete jwk.qi;\n publicKey = await importJWK(jwk, format.alg);\n } else {\n throw new TypeError('tokenFormat.publicKey is required when privateKey is a PEM string');\n }\n const toJwk = async (key: JoseCryptoKey | KeyObject | Uint8Array, kid: string | undefined) => {\n const jwk = await exportJWK(key);\n jwk.alg = format.alg;\n jwk.use = 'sig';\n if (kid) jwk.kid = kid;\n return jwk;\n };\n const keys = [await toJwk(publicKey, format.kid)];\n\n const additional = format.additionalPublicKeys ?? [];\n if (additional.length === 0) {\n return makeSigner(format.alg, format.kid, privateKey, publicKey, { keys });\n }\n if (!format.kid) {\n throw new TypeError('tokenFormat.kid is required when additionalPublicKeys is used');\n }\n const byKid = new Map<string, JoseCryptoKey | KeyObject | Uint8Array>([[format.kid, publicKey]]);\n for (const extra of additional) {\n if (!extra.kid) throw new TypeError('tokenFormat.additionalPublicKeys[].kid is required');\n if (byKid.has(extra.kid)) {\n throw new TypeError(`tokenFormat: duplicate kid \"${extra.kid}\"`);\n }\n const key = await importPublic(format.alg, extra.publicKey);\n byKid.set(extra.kid, key);\n keys.push(await toJwk(key, extra.kid));\n }\n return makeSigner(format.alg, format.kid, privateKey, byKid, { keys });\n}\n\nfunction makeSigner(\n alg: string,\n kid: string | undefined,\n privateKey: JoseCryptoKey | KeyObject | Uint8Array,\n publicKey:\n JoseCryptoKey | KeyObject | Uint8Array | Map<string, JoseCryptoKey | KeyObject | Uint8Array>,\n jwks: { keys: JWK[] } | null,\n): JwtSigner {\n return {\n alg,\n kid,\n async sign(payload, { expiresAt, issuedAt, jti }) {\n const header: Record<string, string> = { alg, typ: 'at+jwt' };\n if (kid) header.kid = kid;\n return new SignJWT(payload)\n .setProtectedHeader(header as { alg: string; typ: string; kid?: string })\n .setIssuedAt(issuedAt)\n .setExpirationTime(expiresAt)\n .setJti(jti)\n .sign(privateKey);\n },\n async verify(token, { issuer }) {\n try {\n let key: JoseCryptoKey | KeyObject | Uint8Array | undefined;\n if (publicKey instanceof Map) {\n const tokenKid = decodeProtectedHeader(token).kid;\n key = tokenKid === undefined ? undefined : publicKey.get(tokenKid);\n if (!key) return null;\n } else key = publicKey;\n const { payload } = await jwtVerify(token, key, {\n issuer,\n algorithms: [alg],\n typ: 'at+jwt',\n });\n return payload;\n } catch {\n return null;\n }\n },\n async jwks() {\n return jwks;\n },\n };\n}\n",
13
+ "/**\n * Props encryption, ported from workers-oauth-provider.\n *\n * Each grant gets a fresh AES-GCM-256 key. Props are encrypted exactly once\n * per key, so a constant zero IV is safe (never reuse a key for a second\n * plaintext — always call `encryptProps` again to get a new key).\n *\n * The key is stored only in *wrapped* form. The wrapping key is derived from\n * the credential string (auth code, refresh token or access token) with\n * HMAC-SHA256 under a fixed, public domain-separation key, then used as an\n * AES-KW key. Because the credential itself is stored only as SHA-256 hash,\n * a leaked storage dump cannot recover the props.\n */\nimport { base64UrlToBytes, bytesToBase64Url } from './hash.ts';\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\nconst ZERO_IV = new Uint8Array(12);\n\n// Public constant. Purpose is domain separation from sha256(token) used as key\n// id, not secrecy. Changing it invalidates all wrapped keys.\nconst WRAPPING_KEY_HMAC_KEY = encoder.encode('elysia-oauth-provider:props-wrapping-key:v1');\n\nexport interface EncryptedProps {\n /** base64url ciphertext (AES-GCM, includes tag). */\n ciphertext: string;\n key: CryptoKey;\n}\n\nexport async function encryptProps(props: unknown): Promise<EncryptedProps> {\n const key = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, [\n 'encrypt',\n 'decrypt',\n ]);\n const data = encoder.encode(JSON.stringify(props ?? null));\n const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: ZERO_IV }, key, data);\n return { ciphertext: bytesToBase64Url(new Uint8Array(ct)), key };\n}\n\nexport async function decryptProps<T>(ciphertext: string, key: CryptoKey): Promise<T> {\n const pt = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: ZERO_IV },\n key,\n base64UrlToBytes(ciphertext),\n );\n return JSON.parse(decoder.decode(pt)) as T;\n}\n\nasync function deriveWrappingKey(credential: string): Promise<CryptoKey> {\n const hmacKey = await crypto.subtle.importKey(\n 'raw',\n WRAPPING_KEY_HMAC_KEY,\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n );\n const raw = await crypto.subtle.sign('HMAC', hmacKey, encoder.encode(credential));\n return crypto.subtle.importKey('raw', raw, { name: 'AES-KW' }, false, ['wrapKey', 'unwrapKey']);\n}\n\n/** Wrap `key` so that only the holder of `credential` can unwrap it. */\nexport async function wrapKeyWithCredential(key: CryptoKey, credential: string): Promise<string> {\n const wrappingKey = await deriveWrappingKey(credential);\n const wrapped = await crypto.subtle.wrapKey('raw', key, wrappingKey, { name: 'AES-KW' });\n return bytesToBase64Url(new Uint8Array(wrapped));\n}\n\nexport async function unwrapKeyWithCredential(\n wrapped: string,\n credential: string,\n): Promise<CryptoKey> {\n const wrappingKey = await deriveWrappingKey(credential);\n return crypto.subtle.unwrapKey(\n 'raw',\n base64UrlToBytes(wrapped),\n wrappingKey,\n { name: 'AES-KW' },\n { name: 'AES-GCM', length: 256 },\n true,\n ['encrypt', 'decrypt'],\n );\n}\n\n// Domain-separated from the wrapping key: the same credential must not yield\n// the same raw key for AES-KW and AES-GCM.\nconst SEAL_KEY_HMAC_KEY = encoder.encode('elysia-oauth-provider:credential-seal-key:v1');\n\nasync function deriveSealKey(credential: string): Promise<CryptoKey> {\n const hmacKey = await crypto.subtle.importKey(\n 'raw',\n SEAL_KEY_HMAC_KEY,\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n );\n const raw = await crypto.subtle.sign('HMAC', hmacKey, encoder.encode(credential));\n return crypto.subtle.importKey('raw', raw, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);\n}\n\n/** Encrypt `plaintext` so that only the holder of `credential` can read it back. */\nexport async function sealWithCredential(credential: string, plaintext: string): Promise<string> {\n const key = await deriveSealKey(credential);\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ct = new Uint8Array(\n await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, encoder.encode(plaintext)),\n );\n const out = new Uint8Array(iv.length + ct.length);\n out.set(iv);\n out.set(ct, iv.length);\n return bytesToBase64Url(out);\n}\n\nexport async function openWithCredential(credential: string, sealed: string): Promise<string> {\n const key = await deriveSealKey(credential);\n const bytes = base64UrlToBytes(sealed);\n const pt = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: bytes.slice(0, 12) },\n key,\n bytes.slice(12),\n );\n return decoder.decode(pt);\n}\n",
14
+ "const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';\n\n/**\n * URL-safe random string. Alphabet has exactly 64 symbols so `byte % 64`\n * introduces no modulo bias.\n */\nexport function randomString(length: number): string {\n const bytes = new Uint8Array(length);\n crypto.getRandomValues(bytes);\n let out = '';\n for (let i = 0; i < length; i++) out += ALPHABET.charAt(bytes[i]! % 64);\n return out;\n}\n\nexport const randomId = (): string => randomString(16);\nexport const randomSecret = (): string => randomString(32);\n",
15
+ "/** RFC 6749 / 7591 / 7009 / 8707 error codes plus a few used by the token endpoint. */\nexport type OAuthErrorCode =\n | 'invalid_request'\n | 'invalid_client'\n | 'invalid_grant'\n | 'unauthorized_client'\n | 'unsupported_grant_type'\n | 'unsupported_response_type'\n | 'invalid_scope'\n | 'invalid_target'\n | 'access_denied'\n | 'server_error'\n | 'temporarily_unavailable'\n | 'invalid_client_metadata'\n | 'invalid_redirect_uri'\n | 'invalid_token'\n | 'insufficient_scope'\n | 'unsupported_token_type';\n\n/**\n * Error returned as a JSON body `{ error, error_description }` with the given\n * HTTP status. Thrown inside endpoint handlers; never leaks internals.\n */\nexport class OAuthError extends Error {\n readonly code: OAuthErrorCode;\n readonly status: number;\n readonly headers: Record<string, string>;\n\n constructor(\n code: OAuthErrorCode,\n description: string,\n options: { status?: number; headers?: Record<string, string>; cause?: unknown } = {},\n ) {\n super(description, options.cause === undefined ? undefined : { cause: options.cause });\n this.name = 'OAuthError';\n this.code = code;\n this.status = options.status ?? defaultStatus(code);\n this.headers = options.headers ?? {};\n }\n\n toJSON(): { error: OAuthErrorCode; error_description: string } {\n return { error: this.code, error_description: this.message };\n }\n\n toResponse(extraHeaders: Record<string, string> = {}): Response {\n return Response.json(this.toJSON(), {\n status: this.status,\n headers: {\n 'Cache-Control': 'no-store',\n Pragma: 'no-cache',\n ...extraHeaders,\n ...this.headers,\n },\n });\n }\n}\n\nfunction defaultStatus(code: OAuthErrorCode): number {\n switch (code) {\n case 'invalid_client':\n case 'invalid_token':\n return 401;\n case 'insufficient_scope':\n return 403;\n case 'server_error':\n return 500;\n case 'temporarily_unavailable':\n return 503;\n default:\n return 400;\n }\n}\n\n/**\n * Error raised while validating an authorization request.\n * When `redirectUri` is set the client and redirect URI were already validated\n * and the error MUST be delivered by redirecting the user-agent (RFC 6749 §4.1.2.1).\n * Otherwise it must be rendered locally — never redirect to an unvalidated URI.\n */\nexport class AuthorizationError extends Error {\n readonly code: OAuthErrorCode;\n readonly redirectUri: string | undefined;\n readonly state: string | undefined;\n readonly issuer: string | undefined;\n\n constructor(\n code: OAuthErrorCode,\n description: string,\n options: { redirectUri?: string; state?: string; issuer?: string } = {},\n ) {\n super(description);\n this.name = 'AuthorizationError';\n this.code = code;\n this.redirectUri = options.redirectUri;\n this.state = options.state;\n this.issuer = options.issuer;\n }\n\n /** Redirect URL carrying the error, or `null` when it must be rendered locally. */\n toRedirectUrl(): string | null {\n if (!this.redirectUri) return null;\n const url = new URL(this.redirectUri);\n url.searchParams.set('error', this.code);\n url.searchParams.set('error_description', this.message);\n if (this.state !== undefined) url.searchParams.set('state', this.state);\n if (this.issuer) url.searchParams.set('iss', this.issuer);\n return url.toString();\n }\n\n toResponse(): Response {\n const redirectTo = this.toRedirectUrl();\n if (redirectTo) {\n return new Response(null, {\n status: 302,\n headers: { Location: redirectTo, 'Cache-Control': 'no-store' },\n });\n }\n return Response.json(\n { error: this.code, error_description: this.message },\n { status: 400, headers: { 'Cache-Control': 'no-store', Pragma: 'no-cache' } },\n );\n }\n}\n",
16
+ "/**\n * Key layout used by the provider.\n *\n * | Key | Value | TTL |\n * |--------------------------------------------|-----------------------------|--------------------------------------------------|\n * | `client:{clientId}` | StoredClient | `clientRegistrationTTL` for DCR clients, none for admin-created |\n * | `authreq:{authRequestId}` | PendingAuthRequest | `authRequestTTL` (default 600s) |\n * | `grant:{userId}:{grantId}` | Grant | `authCodeTTL` until the code is exchanged, then refresh lifetime (or none) |\n * | `token:{userId}:{grantId}:{sha256(token)}` | AccessTokenRecord | `accessTokenTTL` |\n * | `refresh:{sha256(refreshToken)}` | RefreshPointer | `refreshTokenTTL` |\n * | `authcode:{sha256(code)}` | one-time marker (consumed) | `authCodeTTL` |\n *\n * `userId` and `grantId` must not contain `:` — the provider rejects such userIds.\n */\nexport const KEY_PREFIX = {\n client: 'client:',\n authRequest: 'authreq:',\n grant: 'grant:',\n token: 'token:',\n refresh: 'refresh:',\n authCode: 'authcode:',\n} as const;\n\nexport const keys = {\n client: (clientId: string) => `${KEY_PREFIX.client}${clientId}`,\n authRequest: (id: string) => `${KEY_PREFIX.authRequest}${id}`,\n grant: (userId: string, grantId: string) => `${KEY_PREFIX.grant}${userId}:${grantId}`,\n grantPrefixForUser: (userId: string) => `${KEY_PREFIX.grant}${userId}:`,\n token: (userId: string, grantId: string, tokenHash: string) =>\n `${KEY_PREFIX.token}${userId}:${grantId}:${tokenHash}`,\n tokenPrefixForGrant: (userId: string, grantId: string) =>\n `${KEY_PREFIX.token}${userId}:${grantId}:`,\n refresh: (refreshHash: string) => `${KEY_PREFIX.refresh}${refreshHash}`,\n authCode: (codeHash: string) => `${KEY_PREFIX.authCode}${codeHash}`,\n} as const;\n",
17
+ "import { sha256Base64Url, timingSafeEqual } from '../crypto/hash.ts';\n\n/** RFC 7636 §4.1: 43–128 chars of [A-Za-z0-9-._~] */\nexport function isValidCodeVerifier(v: string): boolean {\n return /^[A-Za-z0-9\\-._~]{43,128}$/.test(v);\n}\n\n/** RFC 7636 §4.2: base64url(sha256) is always 43 chars. */\nexport function isValidCodeChallenge(c: string): boolean {\n return /^[A-Za-z0-9\\-_]{43}$/.test(c);\n}\n\nexport async function verifyPkce(verifier: string, challenge: string): Promise<boolean> {\n if (!isValidCodeVerifier(verifier)) return false;\n return timingSafeEqual(await sha256Base64Url(verifier), challenge);\n}\n",
18
+ "const DANGEROUS_SCHEMES = new Set([\n 'javascript:',\n 'data:',\n 'vbscript:',\n 'file:',\n 'blob:',\n 'mailto:',\n]);\n\nexport interface RedirectUriPolicy {\n /** Skip the OAuth 2.1 / RFC 8252 scheme and host policy; only `DANGEROUS_SCHEMES` stay rejected. */\n allowInsecure: boolean;\n}\n\n/**\n * Syntactic check for redirect URIs at registration and authorization time.\n * Returns an error message or `null` when acceptable.\n *\n * Default policy (OAuth 2.1 §1.5, RFC 8252 §7): `https:`; `http:` only to a\n * loopback host; private-use schemes in reverse-DNS form (`com.example.app:/cb`).\n */\nexport function validateRedirectUriSyntax(\n uri: string,\n policy: RedirectUriPolicy = { allowInsecure: false },\n): string | null {\n if (typeof uri !== 'string' || uri.length === 0) return 'redirect_uri must be a non-empty string';\n // eslint-disable-next-line no-control-regex\n if (/[\\x00-\\x1f\\x7f\\s]/.test(uri))\n return 'redirect_uri must not contain whitespace or control characters';\n if (uri.includes('#')) return 'redirect_uri must not contain a fragment';\n let url: URL;\n try {\n url = new URL(uri);\n } catch {\n return 'redirect_uri must be an absolute URI';\n }\n if (DANGEROUS_SCHEMES.has(url.protocol))\n return `redirect_uri scheme \"${url.protocol}\" is not allowed`;\n if (policy.allowInsecure) return null;\n if (url.protocol === 'https:') return null;\n if (url.protocol === 'http:') {\n return isLoopbackHost(url.hostname)\n ? null\n : 'redirect_uri with scheme \"http:\" must use a loopback host (localhost, 127.0.0.1, [::1])';\n }\n if (url.protocol.includes('.')) return null;\n return `redirect_uri scheme \"${url.protocol}\" is not allowed: use https:, a loopback http: URI, or a reverse-DNS private-use scheme`;\n}\n\n/** Strict IPv4 127.0.0.0/8 (a hostname like `127.evil.com` is not loopback). */\nfunction isLoopbackIPv4(host: string): boolean {\n const m = /^127\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(host);\n return m ? m.slice(1).every((octet) => Number(octet) <= 255) : false;\n}\n\nfunction isLoopbackHost(host: string): boolean {\n return host === 'localhost' || host === '[::1]' || isLoopbackIPv4(host);\n}\n\n/**\n * Exact string match (OAuth 2.1 §4.1.3), except for loopback redirect URIs\n * (RFC 8252 §7.3) where the port may vary.\n */\nexport function redirectUriMatches(registered: string, requested: string): boolean {\n if (registered === requested) return true;\n let a: URL;\n let b: URL;\n try {\n a = new URL(registered);\n b = new URL(requested);\n } catch {\n return false;\n }\n if (a.protocol !== 'http:' || b.protocol !== 'http:') return false;\n if (!isLoopbackHost(a.hostname) || !isLoopbackHost(b.hostname)) return false;\n return (\n a.hostname === b.hostname &&\n a.pathname === b.pathname &&\n a.search === b.search &&\n a.username === b.username &&\n a.password === b.password\n );\n}\n\nexport function isRegisteredRedirectUri(\n redirectUris: readonly string[],\n requested: string,\n): boolean {\n return redirectUris.some((r) => redirectUriMatches(r, requested));\n}\n",
19
+ "/**\n * RFC 8707 resource handling.\n *\n * - When the provider is configured with a canonical `resource`, every\n * grant/token is bound to it; requests naming a different resource are\n * rejected with `invalid_target`.\n * - Otherwise a token is bound to the resource the grant carries (from the\n * client's request or `completeAuthorization({ resource })`), if any, and\n * protected routes check that the request URL falls under it.\n */\nexport function normalizeResource(resource: string): string {\n const url = new URL(resource);\n url.hash = '';\n // `URL` serialises an empty path as \"/\", so `https://host` normalises to\n // `https://host/`. Consumers rely on that form in `aud`; the path is kept as-is.\n return url.toString();\n}\n\nexport function resourcesEqual(a: string, b: string): boolean {\n try {\n return normalizeResource(a) === normalizeResource(b);\n } catch {\n return false;\n }\n}\n\n/**\n * True when `requestUrl` is covered by the token's `audience`:\n * same origin, same query (if the audience has one), and the audience path is\n * a path-boundary prefix of the request path.\n */\nexport function audienceCoversUrl(audience: string, requestUrl: string): boolean {\n let a: URL;\n let r: URL;\n try {\n a = new URL(audience);\n r = new URL(requestUrl);\n } catch {\n return false;\n }\n if (a.origin !== r.origin) return false;\n if (a.search && a.search !== r.search) return false;\n const ap = a.pathname.replace(/\\/+$/, '');\n const rp = r.pathname.replace(/\\/+$/, '');\n return ap === '' || rp === ap || rp.startsWith(ap + '/');\n}\n",
20
+ "import { isValidScopeToken } from '../config.ts';\n\n/** Parse a space-delimited scope string, deduplicating and validating tokens. Returns null if any token is invalid. */\nexport function parseScope(scope: string | undefined | null): string[] | null {\n if (!scope) return [];\n const out: string[] = [];\n for (const s of scope.split(' ')) {\n if (s === '') continue;\n if (!isValidScopeToken(s)) return null;\n if (!out.includes(s)) out.push(s);\n }\n return out;\n}\n\nexport const formatScope = (scopes: readonly string[]): string => scopes.join(' ');\n\nexport function isSubset(subset: readonly string[], superset: readonly string[]): boolean {\n return subset.every((s) => superset.includes(s));\n}\n\n/** Requested ∩ granted, or `granted` when nothing requested. Returns null when requested ⊄ granted. */\nexport function downscope(\n requested: readonly string[] | undefined,\n granted: readonly string[],\n): string[] | null {\n if (!requested || requested.length === 0) return [...granted];\n if (!isSubset(requested, granted)) return null;\n return [...requested];\n}\n",
21
+ "import type { ResolvedConfig } from '../config.ts';\nimport { validateResourceUri } from '../config.ts';\nimport { sha256Hex, timingSafeEqual } from '../crypto/hash.ts';\nimport { ACCESS_TOKEN_REGISTERED_CLAIMS, createJwtSigner, type JwtSigner } from '../crypto/jwt.ts';\nimport {\n decryptProps,\n encryptProps,\n openWithCredential,\n sealWithCredential,\n unwrapKeyWithCredential,\n wrapKeyWithCredential,\n} from '../crypto/props-encryption.ts';\nimport { randomId, randomSecret, randomString } from '../crypto/random.ts';\nimport { AuthorizationError, OAuthError } from '../errors.ts';\nimport { keys, KEY_PREFIX } from '../storage/keys.ts';\nimport type {\n AccessTokenRecord,\n AuthRequest,\n CachedRefreshResponse,\n ClientInfo,\n CompleteAuthorizationOptions,\n Grant,\n GrantSummary,\n PendingAuthRequest,\n RefreshPointer,\n RejectAuthorizationOptions,\n StoredClient,\n TokenEndpointAuthMethod,\n TokenInfo,\n TokenResponse,\n} from '../types.ts';\nimport { verifyPkce, isValidCodeChallenge } from './pkce.ts';\nimport { isRegisteredRedirectUri, validateRedirectUriSyntax } from './redirect-uri.ts';\nimport { audienceCoversUrl, normalizeResource, resourcesEqual } from './resource.ts';\nimport { downscope, formatScope, isSubset, parseScope } from './scope.ts';\n\nconst OPAQUE_USER_ID = /^[A-Za-z0-9\\-._~+/]+$/;\n\nconst nowSeconds = () => Math.floor(Date.now() / 1000);\n\n/**\n * Upper bound on compare-and-set retries. Each retry means another writer\n * committed the grant in between; in practice that is one or two.\n */\nconst MAX_COMMIT_ATTEMPTS = 8;\n\nexport const AUTH_METHODS: TokenEndpointAuthMethod[] = [\n 'client_secret_basic',\n 'client_secret_post',\n 'none',\n];\n\nexport interface ClientCredentials {\n clientId: string;\n clientSecret?: string;\n method: TokenEndpointAuthMethod;\n}\n\nexport interface CreateClientInput {\n clientId?: string;\n redirectUris: string[];\n clientName?: string;\n clientUri?: string;\n logoUri?: string;\n policyUri?: string;\n tosUri?: string;\n jwksUri?: string;\n contacts?: string[];\n grantTypes?: string[];\n responseTypes?: string[];\n scope?: string;\n tokenEndpointAuthMethod?: TokenEndpointAuthMethod;\n metadata?: Record<string, unknown>;\n /** Internal: mark as dynamically registered (applies registration TTL). */\n dynamicallyRegistered?: boolean;\n}\n\n/**\n * Framework-agnostic OAuth engine. All state goes through `config.storage`.\n * The Elysia plugin is a thin HTTP layer on top of this class.\n */\nexport class OAuthProviderCore<Props> {\n readonly config: ResolvedConfig<Props>;\n readonly #signer: Promise<JwtSigner> | null = null;\n\n constructor(config: ResolvedConfig<Props>) {\n this.config = config;\n if (config.tokenFormat !== 'opaque') this.#signer = createJwtSigner(config.tokenFormat);\n }\n\n get storage() {\n return this.config.storage;\n }\n\n get jwtSigner(): Promise<JwtSigner> | null {\n return this.#signer;\n }\n\n // ---------------------------------------------------------------------------\n // Clients\n // ---------------------------------------------------------------------------\n\n async createClient(input: CreateClientInput): Promise<ClientInfo> {\n const method = input.tokenEndpointAuthMethod ?? 'client_secret_basic';\n const grantTypes = input.grantTypes ?? ['authorization_code', 'refresh_token'];\n const responseTypes = input.responseTypes ?? ['code'];\n this.#validateClientFields({\n redirectUris: input.redirectUris ?? [],\n grantTypes,\n responseTypes,\n scope: input.scope,\n tokenEndpointAuthMethod: method,\n dynamicallyRegistered: input.dynamicallyRegistered ?? false,\n });\n\n const clientId = input.clientId ?? randomId();\n if (await this.storage.get<StoredClient>(keys.client(clientId))) {\n throw new OAuthError('invalid_client_metadata', 'client_id already exists');\n }\n const secret = method === 'none' ? undefined : randomSecret();\n const stored: StoredClient = {\n clientId,\n clientSecretHash: secret ? await sha256Hex(secret) : undefined,\n redirectUris: [...input.redirectUris],\n clientName: input.clientName,\n clientUri: input.clientUri,\n logoUri: input.logoUri,\n policyUri: input.policyUri,\n tosUri: input.tosUri,\n jwksUri: input.jwksUri,\n contacts: input.contacts,\n grantTypes,\n responseTypes,\n scope: input.scope,\n tokenEndpointAuthMethod: method,\n registrationDate: nowSeconds(),\n dynamicallyRegistered: input.dynamicallyRegistered ?? false,\n metadata: input.metadata,\n };\n await this.storage.set(keys.client(clientId), stripUndefined(stored), {\n ttlSeconds: stored.dynamicallyRegistered ? this.config.clientRegistrationTTL : undefined,\n });\n const info = toPublicClient(stored);\n if (secret) info.clientSecret = secret;\n return info;\n }\n\n async getStoredClient(clientId: string): Promise<StoredClient | null> {\n if (!clientId) return null;\n return this.storage.get<StoredClient>(keys.client(clientId));\n }\n\n async lookupClient(clientId: string): Promise<ClientInfo | null> {\n const stored = await this.getStoredClient(clientId);\n return stored ? toPublicClient(stored) : null;\n }\n\n async updateClient(\n clientId: string,\n updates: Partial<Omit<CreateClientInput, 'clientId' | 'dynamicallyRegistered'>>,\n ): Promise<ClientInfo | null> {\n const stored = await this.getStoredClient(clientId);\n if (!stored) return null;\n // `dynamicallyRegistered` is not updatable (JS callers may still pass it).\n const { dynamicallyRegistered: _ignored, ...rest } = updates as typeof updates & {\n dynamicallyRegistered?: boolean;\n };\n const next: StoredClient = { ...stored, ...stripUndefined(rest) };\n this.#validateClientFields({\n redirectUris: rest.redirectUris,\n grantTypes: next.grantTypes,\n responseTypes: next.responseTypes,\n scope: rest.scope,\n tokenEndpointAuthMethod: rest.tokenEndpointAuthMethod,\n dynamicallyRegistered: stored.dynamicallyRegistered,\n });\n\n // The secret must follow the auth method: public clients hold none, and a\n // client switched to a confidential method gets a fresh one (shown once).\n let secret: string | undefined;\n if (next.tokenEndpointAuthMethod === 'none') delete next.clientSecretHash;\n else if (!next.clientSecretHash) {\n secret = randomSecret();\n next.clientSecretHash = await sha256Hex(secret);\n }\n await this.storage.set(keys.client(clientId), stripUndefined(next), {\n ttlSeconds: next.dynamicallyRegistered ? this.config.clientRegistrationTTL : undefined,\n });\n const info = toPublicClient(next);\n if (secret) info.clientSecret = secret;\n return info;\n }\n\n /** Shared by `createClient` and `updateClient`; checks only the fields given. */\n // eslint-disable-next-line sonarjs/cognitive-complexity -- above the limit when it came in from elysia-oauth-provider 0.3.0 (NOTES 2026-11-21); split it when it is next changed\n #validateClientFields(f: {\n redirectUris?: string[];\n grantTypes: string[];\n responseTypes: string[];\n scope?: string;\n tokenEndpointAuthMethod?: TokenEndpointAuthMethod;\n dynamicallyRegistered: boolean;\n }): void {\n if (f.redirectUris !== undefined) {\n if (!Array.isArray(f.redirectUris) || f.redirectUris.length === 0) {\n throw new OAuthError('invalid_redirect_uri', 'At least one redirect_uri is required');\n }\n for (const uri of f.redirectUris) {\n const err = validateRedirectUriSyntax(uri, {\n allowInsecure: this.config.allowInsecureRedirectUris,\n });\n if (err) throw new OAuthError('invalid_redirect_uri', err);\n }\n }\n const method = f.tokenEndpointAuthMethod;\n if (method !== undefined) {\n if (!AUTH_METHODS.includes(method)) {\n throw new OAuthError(\n 'invalid_client_metadata',\n `Unsupported token_endpoint_auth_method \"${method}\"`,\n );\n }\n if (\n method === 'none' &&\n f.dynamicallyRegistered &&\n !this.config.clientRegistration.allowPublicClients\n ) {\n throw new OAuthError(\n 'invalid_client_metadata',\n 'Public clients are not allowed to register',\n );\n }\n }\n for (const g of f.grantTypes) {\n if (g !== 'authorization_code' && g !== 'refresh_token') {\n throw new OAuthError('invalid_client_metadata', `Unsupported grant_type \"${g}\"`);\n }\n }\n for (const r of f.responseTypes) {\n if (r !== 'code') {\n throw new OAuthError('invalid_client_metadata', `Unsupported response_type \"${r}\"`);\n }\n }\n if (f.grantTypes.includes('authorization_code') && !f.responseTypes.includes('code')) {\n throw new OAuthError(\n 'invalid_client_metadata',\n 'grant_type authorization_code requires response_type code',\n );\n }\n if (f.scope !== undefined) {\n const scopes = parseScope(f.scope);\n if (!scopes) throw new OAuthError('invalid_client_metadata', 'Invalid scope');\n if (!isSubset(scopes, this.config.scopesSupported)) {\n throw new OAuthError('invalid_client_metadata', 'Requested scope is not supported');\n }\n }\n }\n\n /** Delete a client and revoke every grant issued to it. */\n async deleteClient(clientId: string): Promise<void> {\n for (const grant of await this.listClientGrants(clientId)) {\n await this.revokeGrant(grant.id, grant.userId);\n }\n await this.storage.delete(keys.client(clientId));\n }\n\n async listClients(): Promise<ClientInfo[]> {\n const out: ClientInfo[] = [];\n for (const key of await this.storage.list(KEY_PREFIX.client)) {\n const c = await this.storage.get<StoredClient>(key);\n if (c) out.push(toPublicClient(c));\n }\n return out;\n }\n\n /**\n * Authenticate a client at the token/revocation endpoint.\n * Throws `invalid_client` (401) on failure.\n */\n async authenticateClient(creds: ClientCredentials): Promise<StoredClient> {\n const stored = await this.getStoredClient(creds.clientId);\n // An unknown id answers exactly like a confidential client would, so callers\n // cannot probe which client ids exist.\n if (!stored) {\n if (creds.method === 'none' || creds.clientSecret === undefined) {\n throw invalidClient('Client authentication required', 'client_secret_basic');\n }\n throw invalidClient('Invalid client credentials', creds.method);\n }\n const registered = stored.tokenEndpointAuthMethod;\n if (registered === 'none') {\n if (creds.method !== 'none' || creds.clientSecret !== undefined) {\n throw invalidClient(\n 'Client is registered as a public client and must not send a secret',\n creds.method,\n );\n }\n return stored;\n }\n // Confidential client: accept either secret transport (basic or post).\n if (creds.method === 'none' || creds.clientSecret === undefined) {\n throw invalidClient('Client authentication required', 'client_secret_basic');\n }\n if (!stored.clientSecretHash) throw invalidClient('Client has no secret', creds.method);\n const presented = await sha256Hex(creds.clientSecret);\n if (!timingSafeEqual(presented, stored.clientSecretHash)) {\n throw invalidClient('Invalid client credentials', creds.method);\n }\n return stored;\n }\n\n // ---------------------------------------------------------------------------\n // Authorization request\n // ---------------------------------------------------------------------------\n\n /**\n * Validate `GET /authorize` query parameters. Errors before the client and\n * redirect URI are validated have no `redirectUri` (render locally).\n */\n // eslint-disable-next-line sonarjs/cognitive-complexity -- above the limit since before the move into this repo (NOTES 2026-11-20); split it when it is next changed\n async parseAuthRequest(\n url: URL | string,\n ): Promise<{ authRequest: AuthRequest; client: ClientInfo }> {\n const u = typeof url === 'string' ? new URL(url) : url;\n const q = u.searchParams;\n const single = (name: string): string | undefined => {\n const all = q.getAll(name);\n if (all.length > 1) {\n throw new AuthorizationError('invalid_request', `Parameter \"${name}\" must not be repeated`);\n }\n return all[0];\n };\n\n const clientId = single('client_id');\n if (!clientId) throw new AuthorizationError('invalid_request', 'Missing client_id');\n const stored = await this.getStoredClient(clientId);\n if (!stored) throw new AuthorizationError('invalid_request', 'Unknown client_id');\n\n const redirectUri = single('redirect_uri');\n if (!redirectUri) throw new AuthorizationError('invalid_request', 'Missing redirect_uri');\n const syntaxErr = validateRedirectUriSyntax(redirectUri, {\n allowInsecure: this.config.allowInsecureRedirectUris,\n });\n if (syntaxErr) throw new AuthorizationError('invalid_request', syntaxErr);\n if (!isRegisteredRedirectUri(stored.redirectUris, redirectUri)) {\n throw new AuthorizationError(\n 'invalid_request',\n 'redirect_uri does not match a registered redirect URI',\n );\n }\n\n // From here on, errors can be delivered via redirect.\n const state = single('state');\n const redir = { redirectUri, state, issuer: this.config.issuer };\n const fail = (code: ConstructorParameters<typeof AuthorizationError>[0], msg: string) =>\n new AuthorizationError(code, msg, redir);\n\n const responseType = single('response_type');\n if (!responseType) throw fail('invalid_request', 'Missing response_type');\n if (responseType !== 'code') {\n throw fail('unsupported_response_type', 'Only response_type=code is supported');\n }\n if (!stored.responseTypes.includes('code')) {\n throw fail('unauthorized_client', 'Client may not use response_type=code');\n }\n\n const scopes = parseScope(single('scope'));\n if (!scopes) throw fail('invalid_scope', 'Malformed scope');\n if (!isSubset(scopes, this.config.scopesSupported)) {\n throw fail('invalid_scope', 'Requested scope is not supported');\n }\n if (stored.scope !== undefined) {\n const allowed = parseScope(stored.scope) ?? [];\n if (!isSubset(scopes, allowed)) {\n throw fail('invalid_scope', 'Requested scope exceeds the client registration');\n }\n }\n\n const codeChallenge = single('code_challenge');\n const codeChallengeMethod = single('code_challenge_method');\n if (!codeChallenge) throw fail('invalid_request', 'code_challenge is required (PKCE)');\n if (codeChallengeMethod !== undefined && codeChallengeMethod !== 'S256') {\n throw fail('invalid_request', 'Only code_challenge_method=S256 is supported');\n }\n if (!isValidCodeChallenge(codeChallenge))\n throw fail('invalid_request', 'Malformed code_challenge');\n\n const resources: string[] = [];\n for (const r of q.getAll('resource')) {\n try {\n validateResourceUri(r);\n } catch (e) {\n throw fail('invalid_target', (e as Error).message);\n }\n resources.push(normalizeResource(r));\n }\n if (this.config.resource) {\n for (const r of resources) {\n if (!resourcesEqual(r, this.config.resource)) {\n throw fail(\n 'invalid_target',\n `This authorization server only issues tokens for ${this.config.resource}`,\n );\n }\n }\n } else if (resources.length > 1) {\n throw fail('invalid_target', 'Only a single resource parameter is supported');\n }\n\n return {\n authRequest: {\n responseType: 'code',\n clientId,\n redirectUri,\n scopes,\n state,\n codeChallenge,\n codeChallengeMethod: 'S256',\n resources,\n },\n client: toPublicClient(stored),\n };\n }\n\n /** Persist a validated request so the login flow only needs to carry an opaque id. */\n async stashAuthRequest(authRequest: AuthRequest): Promise<PendingAuthRequest> {\n const pending: PendingAuthRequest = {\n ...authRequest,\n id: randomString(32),\n createdAt: nowSeconds(),\n };\n await this.storage.set(keys.authRequest(pending.id), stripUndefined(pending), {\n ttlSeconds: this.config.authRequestTTL,\n });\n return pending;\n }\n\n async getAuthRequest(id: string): Promise<PendingAuthRequest | null> {\n if (!id) return null;\n return this.storage.get<PendingAuthRequest>(keys.authRequest(id));\n }\n\n async #resolveAuthRequest(o: {\n authRequestId?: string;\n authRequest?: AuthRequest;\n }): Promise<{ authRequest: AuthRequest; pendingId?: string }> {\n if (o.authRequestId) {\n const pending = await this.getAuthRequest(o.authRequestId);\n if (!pending) {\n throw new OAuthError('invalid_request', 'Unknown or expired authorization request');\n }\n return { authRequest: pending, pendingId: pending.id };\n }\n if (o.authRequest) return { authRequest: o.authRequest };\n throw new TypeError('authRequestId or authRequest is required');\n }\n\n // eslint-disable-next-line sonarjs/cognitive-complexity -- above the limit since before the move into this repo (NOTES 2026-11-20); split it when it is next changed\n async completeAuthorization(\n o: CompleteAuthorizationOptions<Props>,\n ): Promise<{ redirectTo: string }> {\n const { authRequest, pendingId } = await this.#resolveAuthRequest(o);\n if (typeof o.userId !== 'string' || o.userId.length === 0) {\n throw new TypeError('userId must be a non-empty string');\n }\n if (o.userId.includes(':')) throw new TypeError('userId must not contain \":\"');\n // Opaque tokens embed the userId, and bearer extraction only accepts token68\n // characters; any other userId would yield tokens that always 401.\n if (this.config.tokenFormat === 'opaque' && !OPAQUE_USER_ID.test(o.userId)) {\n throw new TypeError(\n 'userId may only contain letters, digits and \"-._~+/\" when tokenFormat is \"opaque\"',\n );\n }\n\n // Re-validate the client and redirect URI (they may have changed since parsing).\n const stored = await this.getStoredClient(authRequest.clientId);\n if (!stored) throw new OAuthError('invalid_request', 'Unknown client_id');\n if (!isRegisteredRedirectUri(stored.redirectUris, authRequest.redirectUri)) {\n throw new OAuthError(\n 'invalid_request',\n 'redirect_uri is no longer registered for this client',\n );\n }\n if (!isValidCodeChallenge(authRequest.codeChallenge)) {\n throw new OAuthError('invalid_request', 'Malformed code_challenge');\n }\n\n const scopes = [...new Set(o.scopes)];\n if (!isSubset(scopes, this.config.scopesSupported)) {\n throw new OAuthError('invalid_scope', 'Granted scope is not in scopesSupported');\n }\n // Never grant more than the client asked for. A request without `scope`\n // leaves the choice to the app (bounded by scopesSupported above).\n if (authRequest.scopes.length > 0 && !isSubset(scopes, authRequest.scopes)) {\n throw new OAuthError('invalid_scope', 'Granted scope exceeds the requested scope');\n }\n\n let resource = this.config.resource ?? authRequest.resources[0];\n if (o.resource !== undefined) {\n const requested = normalizeResource(validateResourceUri(o.resource).toString());\n if (this.config.resource && !resourcesEqual(requested, this.config.resource)) {\n throw new OAuthError(\n 'invalid_target',\n `This authorization server only issues tokens for ${this.config.resource}`,\n );\n }\n resource = requested;\n }\n const grantId = randomId();\n const now = nowSeconds();\n const code = `${o.userId}:${grantId}:${randomSecret()}`;\n const { props, propsEncrypted, key } = await this.#sealProps(o.props);\n\n const grant: Grant = {\n version: 0,\n id: grantId,\n clientId: authRequest.clientId,\n userId: o.userId,\n scopes,\n props,\n propsEncrypted,\n metadata: o.metadata,\n createdAt: now,\n resource: resource ? normalizeResource(resource) : undefined,\n redirectUri: authRequest.redirectUri,\n authCodeHash: await sha256Hex(code),\n authCodeWrappedKey: key ? await wrapKeyWithCredential(key, code) : undefined,\n codeChallenge: authRequest.codeChallenge,\n codeChallengeMethod: 'S256',\n };\n\n // Collect existing grants first, store the new one, then revoke the old ones.\n const existing: Grant[] = [];\n if (o.revokeExistingGrants !== false) {\n for (const k of await this.storage.list(keys.grantPrefixForUser(o.userId))) {\n const g = await this.storage.get<Grant>(k);\n if (g?.clientId === grant.clientId && g.id !== grantId) existing.push(g);\n }\n }\n await this.storage.set(keys.grant(o.userId, grantId), stripUndefined(grant), {\n ttlSeconds: this.config.authCodeTTL,\n });\n // One-time marker the token endpoint consumes atomically (see `consume`).\n await this.storage.set(\n keys.authCode(await sha256Hex(code)),\n { userId: o.userId, grantId },\n { ttlSeconds: this.config.authCodeTTL },\n );\n if (pendingId) await this.storage.delete(keys.authRequest(pendingId));\n await Promise.allSettled(existing.map((g) => this.revokeGrant(g.id, g.userId)));\n\n const url = new URL(authRequest.redirectUri);\n url.searchParams.set('code', code);\n if (authRequest.state !== undefined) url.searchParams.set('state', authRequest.state);\n url.searchParams.set('iss', this.config.issuer);\n return { redirectTo: url.toString() };\n }\n\n /** Send the user back to the client with an error (e.g. they declined consent). */\n async rejectAuthorization(o: RejectAuthorizationOptions): Promise<{ redirectTo: string }> {\n const { authRequest, pendingId } = await this.#resolveAuthRequest(o);\n if (pendingId) await this.storage.delete(keys.authRequest(pendingId));\n const err = new AuthorizationError(\n o.error ?? 'access_denied',\n o.description ?? 'The user denied the request',\n {\n redirectUri: authRequest.redirectUri,\n state: authRequest.state,\n issuer: this.config.issuer,\n },\n );\n return { redirectTo: err.toRedirectUrl()! };\n }\n\n // ---------------------------------------------------------------------------\n // Token endpoint grants\n // ---------------------------------------------------------------------------\n\n async exchangeAuthorizationCode(o: {\n client: StoredClient;\n code: string;\n codeVerifier: string | undefined;\n redirectUri: string | undefined;\n resource: string | undefined;\n requestedScope: string | undefined;\n }): Promise<TokenResponse> {\n const parts = o.code.split(':');\n if (parts.length !== 3) throw new OAuthError('invalid_grant', 'Invalid authorization code');\n const [userId, grantId] = parts as [string, string, string];\n const grant = await this.#getGrant(userId, grantId);\n if (!grant?.authCodeHash) {\n throw new OAuthError('invalid_grant', 'Invalid authorization code');\n }\n const codeHash = await sha256Hex(o.code);\n if (!timingSafeEqual(codeHash, grant.authCodeHash)) {\n throw new OAuthError('invalid_grant', 'Invalid authorization code');\n }\n if (grant.clientId !== o.client.clientId) {\n throw new OAuthError('invalid_grant', 'Authorization code was issued to another client');\n }\n\n // Replay detection (RFC 6749 §10.5): code already consumed → revoke everything.\n if (!grant.codeChallenge) {\n await this.revokeGrant(grantId, userId);\n throw new OAuthError('invalid_grant', 'Authorization code has already been used');\n }\n if (!o.client.grantTypes.includes('authorization_code')) {\n throw new OAuthError(\n 'unauthorized_client',\n 'Client may not use the authorization_code grant',\n );\n }\n if (o.redirectUri !== undefined && o.redirectUri !== grant.redirectUri) {\n throw new OAuthError(\n 'invalid_grant',\n 'redirect_uri does not match the authorization request',\n );\n }\n if (!o.codeVerifier) throw new OAuthError('invalid_request', 'code_verifier is required');\n if (!(await verifyPkce(o.codeVerifier, grant.codeChallenge))) {\n throw new OAuthError('invalid_grant', 'PKCE verification failed');\n }\n const resource = this.#resolveTokenResource(grant, o.resource);\n const requested = parseScope(o.requestedScope);\n if (requested === null) throw new OAuthError('invalid_scope', 'Malformed scope');\n const scopes = downscope(requested, grant.scopes);\n if (!scopes) throw new OAuthError('invalid_scope', 'Requested scope exceeds the granted scope');\n\n // Last gate before minting: of concurrent exchanges exactly one gets the\n // marker. Done after validation so a failed PKCE check does not burn the code.\n if ((await this.storage.consume(keys.authCode(codeHash))) === null) {\n await this.revokeGrant(grantId, userId);\n throw new OAuthError('invalid_grant', 'Authorization code has already been used');\n }\n\n const key = grant.authCodeWrappedKey\n ? await unwrapKeyWithCredential(grant.authCodeWrappedKey, o.code)\n : undefined;\n const props = await this.#openProps(grant.props, grant.propsEncrypted, key);\n\n const now = nowSeconds();\n const refresh = await this.#mintRefreshToken(grant, key, now);\n // Consume the code: keep the hash so a replay can be detected.\n delete grant.authCodeWrappedKey;\n delete grant.codeChallenge;\n delete grant.codeChallengeMethod;\n const access = await this.#issueAccessToken({ grant, key, scopes, resource, props, now });\n // The loser of the marker race revokes the grant; a commit that finds it\n // gone must not resurrect it. Nothing to retry: the code is spent.\n if (!(await this.#commitGrant(grant, now))) {\n await this.#discardMinted(grant, access.hash);\n throw new OAuthError('invalid_grant', 'Authorization code has already been used');\n }\n\n await this.#notifyTokenIssued({\n grantType: 'authorization_code',\n clientId: grant.clientId,\n userId: grant.userId,\n grantId: grant.id,\n scopes,\n props,\n });\n return this.#tokenResponse(access, refresh?.token, scopes, resource);\n }\n\n // eslint-disable-next-line sonarjs/cognitive-complexity -- above the limit since before the move into this repo (NOTES 2026-11-20); split it when it is next changed\n async refreshAccessToken(o: {\n client: StoredClient;\n refreshToken: string;\n requestedScope: string | undefined;\n resource: string | undefined;\n }): Promise<TokenResponse> {\n const presentedHash = await sha256Hex(o.refreshToken);\n const pointer = await this.storage.get<RefreshPointer>(keys.refresh(presentedHash));\n if (!pointer) throw new OAuthError('invalid_grant', 'Invalid refresh token');\n\n // Rotation is a compare-and-set on the grant. Losing it means another\n // request rotated first, so re-read and classify the presented token again:\n // it is now the previous token and, inside the grace window, gets the\n // winner's response.\n for (let attempt = 0; attempt < MAX_COMMIT_ATTEMPTS; attempt++) {\n const grant = await this.#getGrant(pointer.userId, pointer.grantId);\n if (!grant) throw new OAuthError('invalid_grant', 'Invalid refresh token');\n if (grant.clientId !== o.client.clientId) {\n throw new OAuthError('invalid_grant', 'Refresh token was issued to another client');\n }\n if (!o.client.grantTypes.includes('refresh_token')) {\n throw new OAuthError('unauthorized_client', 'Client may not use the refresh_token grant');\n }\n const now = nowSeconds();\n\n if (grant.refreshTokenHash && timingSafeEqual(presentedHash, grant.refreshTokenHash)) {\n const committed = await this.#rotateRefreshToken(grant, o, presentedHash, now);\n if (committed) return committed;\n continue;\n }\n\n if (\n grant.previousRefreshTokenHash &&\n timingSafeEqual(presentedHash, grant.previousRefreshTokenHash)\n ) {\n const rotatedAt = grant.previousRefreshTokenRotatedAt;\n const inGrace =\n rotatedAt !== undefined && now < rotatedAt + this.config.refreshTokenReuseGraceSeconds;\n if (!inGrace || !grant.previousRefreshResponse) {\n await this.revokeGrant(grant.id, grant.userId);\n throw new OAuthError('invalid_grant', 'Refresh token has already been used');\n }\n return this.#replayCachedResponse(grant.previousRefreshResponse, o.refreshToken, now);\n }\n\n // The pointer is still alive but the token is no longer part of the grant:\n // a long-rotated token is being replayed.\n await this.revokeGrant(grant.id, grant.userId);\n throw new OAuthError('invalid_grant', 'Refresh token has already been used');\n }\n throw new OAuthError('server_error', 'Refresh token rotation did not settle');\n }\n\n /**\n * Rotate the current refresh token. Returns `null` when the compare-and-set\n * lost (the caller re-reads); everything minted here is then discarded.\n */\n async #rotateRefreshToken(\n grant: Grant,\n o: { refreshToken: string; requestedScope: string | undefined; resource: string | undefined },\n presentedHash: string,\n now: number,\n ): Promise<TokenResponse | null> {\n if (grant.expiresAt !== undefined && grant.expiresAt <= now) {\n throw new OAuthError('invalid_grant', 'Refresh token has expired');\n }\n const requested = parseScope(o.requestedScope);\n if (requested === null) throw new OAuthError('invalid_scope', 'Malformed scope');\n const scopes = downscope(requested, grant.scopes);\n if (!scopes) throw new OAuthError('invalid_scope', 'Requested scope exceeds the granted scope');\n const resource = this.#resolveTokenResource(grant, o.resource);\n\n const wrappedKey = grant.refreshTokenWrappedKey;\n const key = wrappedKey ? await unwrapKeyWithCredential(wrappedKey, o.refreshToken) : undefined;\n const props = await this.#openProps(grant.props, grant.propsEncrypted, key);\n\n // The token just presented becomes \"previous\" for the grace window, and\n // the response it produced is sealed under it so a retry (a client that\n // lost the response, or a second tab) gets the same tokens back instead of\n // a second rotation. At most two refresh tokens are ever valid for a grant.\n // The previous token's pointer is left to expire by TTL so that replaying\n // it after the window is detected (and revokes the grant).\n grant.previousRefreshTokenHash = presentedHash;\n grant.previousRefreshTokenRotatedAt = now;\n const refresh = await this.#mintRefreshToken(grant, key, now, /* keepExpiry */ true);\n const access = await this.#issueAccessToken({ grant, key, scopes, resource, props, now });\n const response = this.#tokenResponse(access, refresh?.token, scopes, resource);\n const cached: CachedRefreshResponse = {\n response,\n accessTokenExpiresAt: now + access.expiresIn,\n };\n grant.previousRefreshResponse = await sealWithCredential(\n o.refreshToken,\n JSON.stringify(cached),\n );\n\n if (!(await this.#commitGrant(grant, now))) {\n await this.#discardMinted(grant, access.hash);\n return null;\n }\n await this.#notifyTokenIssued({\n grantType: 'refresh_token',\n clientId: grant.clientId,\n userId: grant.userId,\n grantId: grant.id,\n scopes,\n props,\n });\n return response;\n }\n\n async #replayCachedResponse(\n sealed: string,\n refreshToken: string,\n now: number,\n ): Promise<TokenResponse> {\n const cached = JSON.parse(\n await openWithCredential(refreshToken, sealed),\n ) as CachedRefreshResponse;\n if (cached.accessTokenExpiresAt <= now) {\n // Only reachable when accessTokenTTL is shorter than the grace window.\n throw new OAuthError('invalid_grant', 'Refresh token has already been used');\n }\n return { ...cached.response, expires_in: cached.accessTokenExpiresAt - now };\n }\n\n #resolveTokenResource(grant: Grant, requested: string | undefined): string | undefined {\n if (requested === undefined) return grant.resource;\n let normalized: string;\n try {\n normalized = normalizeResource(validateResourceUri(requested).toString());\n } catch (e) {\n throw new OAuthError('invalid_target', (e as Error).message);\n }\n if (this.config.resource && !resourcesEqual(normalized, this.config.resource)) {\n throw new OAuthError(\n 'invalid_target',\n `This authorization server only issues tokens for ${this.config.resource}`,\n );\n }\n if (grant.resource && !resourcesEqual(normalized, grant.resource)) {\n throw new OAuthError('invalid_target', 'resource does not match the authorized resource');\n }\n // An unbound grant must not be upgradable to an arbitrary audience.\n if (!grant.resource && !this.config.resource) {\n throw new OAuthError('invalid_target', 'The authorization was not bound to a resource');\n }\n return normalized;\n }\n\n async #mintRefreshToken(\n grant: Grant,\n key: CryptoKey | undefined,\n now: number,\n keepExpiry = false,\n ): Promise<{ token: string } | null> {\n if (this.config.refreshTokenTTL === 0) return null;\n const token = randomString(48);\n const hash = await sha256Hex(token);\n grant.refreshTokenHash = hash;\n grant.refreshTokenWrappedKey = key ? await wrapKeyWithCredential(key, token) : undefined;\n if (!keepExpiry || grant.expiresAt === undefined) {\n grant.expiresAt = now + this.config.refreshTokenTTL;\n }\n const ttl = Math.max(1, grant.expiresAt - now);\n await this.storage.set<RefreshPointer>(\n keys.refresh(hash),\n { userId: grant.userId, grantId: grant.id },\n { ttlSeconds: ttl },\n );\n return { token };\n }\n\n /** A failing hook must not turn an already-committed issuance into a 500. */\n async #notifyTokenIssued(\n input: Parameters<NonNullable<ResolvedConfig<Props>['hooks']['onTokenIssued']>>[0],\n ): Promise<void> {\n try {\n await this.config.hooks.onTokenIssued?.(input);\n } catch (e) {\n this.config.hooks.onError?.({\n code: 'server_error',\n description: 'onTokenIssued hook failed',\n status: 500,\n });\n console.error('[elysia-oauth-provider] onTokenIssued hook failed', e);\n }\n }\n\n /** Returns `null` for a missing grant or one written before grants were versioned. */\n async #getGrant(userId: string, grantId: string): Promise<Grant | null> {\n const grant = await this.storage.get<Partial<Grant>>(keys.grant(userId, grantId));\n if (!grant || !Number.isInteger(grant.version)) return null;\n return grant as Grant;\n }\n\n /**\n * Persist `grant` only if nobody else wrote it since it was read. On success\n * `grant.version` is advanced in place. A concurrent revoke deletes the key,\n * so a stale commit fails instead of resurrecting the grant.\n */\n async #commitGrant(grant: Grant, now: number): Promise<boolean> {\n const ttl =\n grant.expiresAt !== undefined\n ? Math.max(1, grant.expiresAt - now)\n : this.config.accessTokenTTL;\n const next = stripUndefined({ ...grant, version: grant.version + 1 });\n const ok = await this.storage.compareAndSet(\n keys.grant(grant.userId, grant.id),\n grant.version,\n next,\n { ttlSeconds: ttl },\n );\n if (ok) grant.version = next.version;\n return ok;\n }\n\n /** Undo the refresh pointer and access token written ahead of a failed commit. */\n async #discardMinted(grant: Grant, accessTokenHash: string): Promise<void> {\n await this.storage.delete(keys.token(grant.userId, grant.id, accessTokenHash));\n if (grant.refreshTokenHash) await this.storage.delete(keys.refresh(grant.refreshTokenHash));\n }\n\n async #issueAccessToken(o: {\n grant: Grant;\n key: CryptoKey | undefined;\n scopes: string[];\n resource: string | undefined;\n props: Props;\n now: number;\n }): Promise<{ token: string; hash: string; expiresIn: number }> {\n let ttl = this.config.accessTokenTTL;\n if (o.grant.expiresAt !== undefined) {\n ttl = Math.max(1, Math.min(ttl, o.grant.expiresAt - o.now));\n }\n const expiresAt = o.now + ttl;\n\n let token: string;\n if (this.#signer) {\n const signer = await this.#signer;\n const extra = await this.config.accessTokenClaims?.({\n userId: o.grant.userId,\n clientId: o.grant.clientId,\n grantId: o.grant.id,\n scopes: o.scopes,\n resource: o.resource,\n props: o.props,\n });\n const clash = Object.keys(extra ?? {}).filter((c) =>\n (ACCESS_TOKEN_REGISTERED_CLAIMS as readonly string[]).includes(c),\n );\n if (clash.length > 0) {\n throw new TypeError(`accessTokenClaims may not set registered claims: ${clash.join(', ')}`);\n }\n token = await signer.sign(\n {\n ...extra,\n iss: this.config.issuer,\n sub: o.grant.userId,\n aud: o.resource ?? this.config.issuer,\n client_id: o.grant.clientId,\n scope: formatScope(o.scopes),\n grant_id: o.grant.id,\n },\n { issuedAt: o.now, expiresAt, jti: randomId() },\n );\n } else {\n token = `${o.grant.userId}:${o.grant.id}:${randomSecret()}`;\n }\n const hash = await sha256Hex(token);\n const record: AccessTokenRecord = {\n id: hash,\n grantId: o.grant.id,\n userId: o.grant.userId,\n clientId: o.grant.clientId,\n scopes: o.scopes,\n createdAt: o.now,\n expiresAt,\n audience: o.resource,\n wrappedKey: o.key ? await wrapKeyWithCredential(o.key, token) : undefined,\n props: o.grant.props,\n propsEncrypted: o.grant.propsEncrypted,\n };\n await this.storage.set(keys.token(o.grant.userId, o.grant.id, hash), stripUndefined(record), {\n ttlSeconds: ttl,\n });\n return { token, hash, expiresIn: ttl };\n }\n\n #tokenResponse(\n access: { token: string; expiresIn: number },\n refreshToken: string | undefined,\n scopes: string[],\n resource: string | undefined,\n ): TokenResponse {\n const res: TokenResponse = {\n access_token: access.token,\n token_type: 'Bearer',\n expires_in: access.expiresIn,\n scope: formatScope(scopes),\n };\n if (refreshToken) res.refresh_token = refreshToken;\n if (resource) res.resource = resource;\n return res;\n }\n\n // ---------------------------------------------------------------------------\n // Bearer validation\n // ---------------------------------------------------------------------------\n\n /** Locate the stored record for an access token string (opaque or JWT). */\n async #locateAccessToken(token: string): Promise<AccessTokenRecord | null> {\n let userId: string;\n let grantId: string;\n if (this.#signer) {\n const payload = await (await this.#signer).verify(token, { issuer: this.config.issuer });\n if (!payload || typeof payload.sub !== 'string' || typeof payload.grant_id !== 'string') {\n return null;\n }\n userId = payload.sub;\n grantId = payload.grant_id;\n } else {\n const parts = token.split(':');\n if (parts.length !== 3) return null;\n [userId, grantId] = parts as [string, string, string];\n }\n const hash = await sha256Hex(token);\n const record = await this.storage.get<AccessTokenRecord>(keys.token(userId, grantId, hash));\n if (!record || !timingSafeEqual(record.id, hash)) return null;\n return record;\n }\n\n /**\n * Verify a bearer token. Returns `null` when invalid/expired/revoked.\n * Throws `OAuthError('invalid_token')` when the token is valid but its\n * audience does not cover `requestUrl`.\n */\n async verifyAccessToken(token: string, requestUrl?: string): Promise<TokenInfo<Props> | null> {\n const record = await this.#locateAccessToken(token);\n if (!record) return null;\n if (record.expiresAt <= nowSeconds()) return null;\n if (requestUrl && record.audience && !audienceCoversUrl(record.audience, requestUrl)) {\n throw new OAuthError('invalid_token', 'Token audience does not cover this resource');\n }\n const key = record.wrappedKey\n ? await unwrapKeyWithCredential(record.wrappedKey, token)\n : undefined;\n const props = await this.#openProps(record.props, record.propsEncrypted, key);\n return {\n userId: record.userId,\n clientId: record.clientId,\n grantId: record.grantId,\n scopes: record.scopes,\n props,\n expiresAt: record.expiresAt,\n createdAt: record.createdAt,\n audience: record.audience,\n token,\n };\n }\n\n // ---------------------------------------------------------------------------\n // Revocation & grant management\n // ---------------------------------------------------------------------------\n\n /**\n * RFC 7009 revocation. Never reveals whether the token existed. Only tokens\n * owned by `client` are affected.\n */\n async revokeToken(o: {\n client: StoredClient;\n token: string;\n tokenTypeHint?: string;\n }): Promise<void> {\n const tryAccess = async () => {\n const record = await this.#locateAccessToken(o.token);\n if (record?.clientId !== o.client.clientId) return false;\n await this.storage.delete(keys.token(record.userId, record.grantId, record.id));\n return true;\n };\n const tryRefresh = async () => {\n const hash = await sha256Hex(o.token);\n const pointer = await this.storage.get<RefreshPointer>(keys.refresh(hash));\n if (!pointer) return false;\n const grant = await this.storage.get<Grant>(keys.grant(pointer.userId, pointer.grantId));\n if (grant?.clientId !== o.client.clientId) return false;\n await this.revokeGrant(grant.id, grant.userId);\n return true;\n };\n if (o.tokenTypeHint === 'refresh_token') {\n if (!(await tryRefresh())) await tryAccess();\n } else if (!(await tryAccess())) await tryRefresh();\n }\n\n /**\n * Delete a grant, all its access tokens and refresh pointers. The grant\n * record is removed by compare-and-delete: a refresh or code exchange that\n * commits in between bumps the version, so the loop re-reads and also\n * removes what that commit minted.\n */\n async revokeGrant(grantId: string, userId: string): Promise<void> {\n const grantKey = keys.grant(userId, grantId);\n for (let attempt = 0; attempt < MAX_COMMIT_ATTEMPTS; attempt++) {\n const grant = await this.storage.get<Partial<Grant>>(grantKey);\n for (const k of await this.storage.list(keys.tokenPrefixForGrant(userId, grantId))) {\n await this.storage.delete(k);\n }\n if (!grant) return;\n if (grant.refreshTokenHash) await this.storage.delete(keys.refresh(grant.refreshTokenHash));\n if (grant.previousRefreshTokenHash) {\n await this.storage.delete(keys.refresh(grant.previousRefreshTokenHash));\n }\n if (!Number.isInteger(grant.version)) {\n // Written before grants were versioned; nothing can commit over it.\n await this.storage.delete(grantKey);\n return;\n }\n if (await this.storage.compareAndDelete(grantKey, grant.version!)) return;\n }\n throw new OAuthError('server_error', 'Grant revocation did not settle');\n }\n\n async listUserGrants(userId: string): Promise<GrantSummary[]> {\n return this.#summarizeGrants(await this.storage.list(keys.grantPrefixForUser(userId)));\n }\n\n /** Every live grant, across all users and clients. */\n async listGrants(): Promise<GrantSummary[]> {\n return this.#summarizeGrants(await this.storage.list(KEY_PREFIX.grant));\n }\n\n async listClientGrants(clientId: string): Promise<GrantSummary[]> {\n return (await this.listGrants()).filter((g) => g.clientId === clientId);\n }\n\n async #summarizeGrants(grantKeys: string[]): Promise<GrantSummary[]> {\n const out: GrantSummary[] = [];\n for (const k of grantKeys) {\n const g = await this.storage.get<Grant>(k);\n if (!g) continue;\n out.push({\n id: g.id,\n clientId: g.clientId,\n userId: g.userId,\n scopes: g.scopes,\n metadata: g.metadata,\n createdAt: g.createdAt,\n expiresAt: g.expiresAt,\n resource: g.resource,\n });\n }\n return out;\n }\n\n // ---------------------------------------------------------------------------\n // Props sealing\n // ---------------------------------------------------------------------------\n\n async #sealProps(\n props: Props,\n ): Promise<{ props: string; propsEncrypted: boolean; key: CryptoKey | undefined }> {\n if (!this.config.encryptProps) {\n return { props: JSON.stringify(props ?? null), propsEncrypted: false, key: undefined };\n }\n const { ciphertext, key } = await encryptProps(props);\n return { props: ciphertext, propsEncrypted: true, key };\n }\n\n async #openProps(sealed: string, encrypted: boolean, key: CryptoKey | undefined): Promise<Props> {\n if (!encrypted) return JSON.parse(sealed) as Props;\n if (!key) throw new OAuthError('server_error', 'Missing props key');\n return decryptProps<Props>(sealed, key);\n }\n}\n\n// -----------------------------------------------------------------------------\n\nfunction invalidClient(description: string, method: TokenEndpointAuthMethod): OAuthError {\n const headers: Record<string, string> = {};\n if (method === 'client_secret_basic') headers['WWW-Authenticate'] = 'Basic realm=\"OAuth\"';\n return new OAuthError('invalid_client', description, { status: 401, headers });\n}\n\nfunction toPublicClient(stored: StoredClient): ClientInfo {\n const { clientSecretHash: _hash, ...rest } = stored;\n return { ...rest };\n}\n\nfunction stripUndefined<T extends object>(o: T): T {\n return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined)) as T;\n}\n",
22
+ "import type { OAuthProviderCore } from '../core/provider.ts';\nimport { AuthorizationError } from '../errors.ts';\n\n/** `GET /authorize`: validate, stash, delegate to the app's login UI. */\nexport async function handleAuthorize<Props>(\n core: OAuthProviderCore<Props>,\n request: Request,\n): Promise<Response> {\n const url = new URL(request.url);\n const { authRequest, client } = await core.parseAuthRequest(url);\n const pending = await core.stashAuthRequest(authRequest);\n try {\n await core.config.hooks.onAuthorize?.({ authRequest: pending, client, request });\n } catch (e) {\n if (e instanceof AuthorizationError) throw e;\n console.error('[elysia-oauth-provider] onAuthorize hook failed', e);\n throw new AuthorizationError('access_denied', 'Authorization rejected', {\n redirectUri: authRequest.redirectUri,\n state: authRequest.state,\n issuer: core.config.issuer,\n });\n }\n return core.config.handleAuthorize({\n authRequest: pending,\n authRequestId: pending.id,\n client,\n request,\n });\n}\n",
23
+ "import { OAuthError } from '../errors.ts';\nimport type { ClientCredentials } from '../core/provider.ts';\n\nexport const NO_STORE: Record<string, string> = { 'Cache-Control': 'no-store', Pragma: 'no-cache' };\n\nexport function corsHeaders(request: Request): Record<string, string> {\n const origin = request.headers.get('Origin');\n if (!origin) return {};\n return {\n 'Access-Control-Allow-Origin': origin,\n 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',\n 'Access-Control-Allow-Headers': 'Authorization, Content-Type, Mcp-Protocol-Version, *',\n 'Access-Control-Expose-Headers': 'WWW-Authenticate, Retry-After',\n 'Access-Control-Max-Age': '86400',\n Vary: 'Origin',\n };\n}\n\nexport function json(\n body: unknown,\n init: { status?: number; headers?: Record<string, string> } = {},\n): Response {\n return Response.json(body, { status: init.status ?? 200, headers: init.headers });\n}\n\nexport function methodNotAllowed(allow: string): Response {\n return json(\n { error: 'invalid_request', error_description: `Method not allowed. Use ${allow}.` },\n { status: 405, headers: { Allow: allow, ...NO_STORE } },\n );\n}\n\n/**\n * Read the body as UTF-8 text, stopping once more than `maxBytes` bytes have\n * arrived (413) so an oversized or chunked body is never fully buffered.\n */\nexport async function readBodyText(request: Request, maxBytes: number): Promise<string> {\n const tooLarge = () =>\n new OAuthError('invalid_request', 'Request body too large', { status: 413 });\n if (!request.body) return '';\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel().catch(() => undefined); // already over the limit: nothing to do if it fails\n throw tooLarge();\n }\n chunks.push(value);\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const c of chunks) {\n bytes.set(c, offset);\n offset += c.byteLength;\n }\n return new TextDecoder().decode(bytes);\n}\n\nexport interface ParsedForm {\n /** Single-valued params (any repeated one already rejected). */\n get(name: string): string | undefined;\n /** `resource` may legally repeat. */\n getAll(name: string): string[];\n}\n\n/** Strict `application/x-www-form-urlencoded` parsing (RFC 6749 §4.1.3, §3.2). */\nexport async function parseFormBody(\n request: Request,\n repeatable: readonly string[] = ['resource'],\n): Promise<ParsedForm> {\n const ct = request.headers.get('Content-Type') ?? '';\n const mediaType = ct.split(';')[0]!.trim().toLowerCase();\n if (mediaType !== 'application/x-www-form-urlencoded') {\n throw new OAuthError(\n 'invalid_request',\n 'Content-Type must be application/x-www-form-urlencoded',\n );\n }\n let params: URLSearchParams;\n try {\n params = new URLSearchParams(await request.text());\n } catch {\n throw new OAuthError('invalid_request', 'Malformed request body');\n }\n const seen = new Set<string>();\n for (const key of params.keys()) {\n if (seen.has(key) && !repeatable.includes(key)) {\n throw new OAuthError('invalid_request', `Parameter \"${key}\" must not be repeated`);\n }\n seen.add(key);\n }\n return {\n get: (name) => params.get(name) ?? undefined,\n getAll: (name) => params.getAll(name),\n };\n}\n\n/**\n * Extract client credentials from Basic auth or the form body (RFC 6749 §2.3.1).\n * Mixing both is rejected.\n */\nexport function extractClientCredentials(request: Request, form: ParsedForm): ClientCredentials {\n const authz = request.headers.get('Authorization');\n const bodyId = form.get('client_id');\n const bodySecret = form.get('client_secret');\n\n if (authz && /^basic\\s/i.test(authz)) {\n if (bodySecret !== undefined) {\n throw new OAuthError('invalid_request', 'Multiple client authentication methods used');\n }\n let decoded: string;\n try {\n decoded = atob(authz.slice(6).trim());\n } catch {\n throw new OAuthError('invalid_client', 'Malformed Authorization header', {\n status: 401,\n headers: { 'WWW-Authenticate': 'Basic realm=\"OAuth\"' },\n });\n }\n const idx = decoded.indexOf(':');\n if (idx < 0) {\n throw new OAuthError('invalid_client', 'Malformed Authorization header', {\n status: 401,\n headers: { 'WWW-Authenticate': 'Basic realm=\"OAuth\"' },\n });\n }\n const clientId = safeDecode(decoded.slice(0, idx));\n const clientSecret = safeDecode(decoded.slice(idx + 1));\n if (bodyId !== undefined && bodyId !== clientId) {\n throw new OAuthError(\n 'invalid_request',\n 'client_id in body does not match Authorization header',\n );\n }\n return { clientId, clientSecret, method: 'client_secret_basic' };\n }\n if (!bodyId) throw new OAuthError('invalid_client', 'Missing client_id', { status: 401 });\n if (bodySecret !== undefined)\n return { clientId: bodyId, clientSecret: bodySecret, method: 'client_secret_post' };\n return { clientId: bodyId, method: 'none' };\n}\n\nfunction safeDecode(s: string): string {\n try {\n return decodeURIComponent(s);\n } catch {\n return s;\n }\n}\n",
24
+ "import type { OAuthProviderCore } from '../core/provider.ts';\n\n/** RFC 8414 Authorization Server Metadata. */\nexport function authorizationServerMetadata<Props>(\n core: OAuthProviderCore<Props>,\n): Record<string, unknown> {\n const { config } = core;\n const doc: Record<string, unknown> = {\n issuer: config.issuer,\n authorization_endpoint: config.urls.authorize,\n token_endpoint: config.urls.token,\n revocation_endpoint: config.urls.revoke,\n response_types_supported: ['code'],\n response_modes_supported: ['query'],\n grant_types_supported:\n config.refreshTokenTTL === 0\n ? ['authorization_code']\n : ['authorization_code', 'refresh_token'],\n token_endpoint_auth_methods_supported: ['client_secret_basic', 'client_secret_post', 'none'],\n revocation_endpoint_auth_methods_supported: [\n 'client_secret_basic',\n 'client_secret_post',\n 'none',\n ],\n code_challenge_methods_supported: ['S256'],\n authorization_response_iss_parameter_supported: true,\n };\n if (config.clientRegistration.enabled) doc.registration_endpoint = config.urls.register;\n if (config.scopesSupported) doc.scopes_supported = config.scopesSupported;\n if (config.tokenFormat !== 'opaque') doc.jwks_uri = config.urls.jwks;\n return doc;\n}\n\n/**\n * RFC 9728 Protected Resource Metadata.\n * `suffix` is whatever followed `/.well-known/oauth-protected-resource` in the request path.\n */\nexport function protectedResourceMetadata<Props>(\n core: OAuthProviderCore<Props>,\n suffix: string,\n): Record<string, unknown> {\n const { config } = core;\n const rm = config.resourceMetadata;\n const resource = config.resource ?? `${config.issuerUrl.origin}${suffix}`;\n const doc: Record<string, unknown> = {\n resource,\n authorization_servers: rm.authorizationServers ?? [config.issuer],\n bearer_methods_supported: ['header'],\n };\n const scopes = (rm.scopesSupported ?? config.scopesSupported)?.filter(\n (s) => s !== 'offline_access',\n );\n if (scopes && scopes.length > 0) doc.scopes_supported = [...new Set(scopes)];\n if (rm.resourceName) doc.resource_name = rm.resourceName;\n if (rm.resourceDocumentation) doc.resource_documentation = rm.resourceDocumentation;\n return doc;\n}\n",
25
+ "import { AUTH_METHODS, type CreateClientInput, type OAuthProviderCore } from '../core/provider.ts';\nimport { OAuthError } from '../errors.ts';\nimport type { ClientInfo, ClientRegisterHookResult, TokenEndpointAuthMethod } from '../types.ts';\nimport { json, NO_STORE, readBodyText } from './http.ts';\n\n/** RFC 7591 Dynamic Client Registration. */\n\nexport async function handleRegister<Props>(\n core: OAuthProviderCore<Props>,\n request: Request,\n): Promise<Response> {\n const { config } = core;\n const len = Number(request.headers.get('Content-Length') ?? '0');\n if (len > config.clientRegistration.maxBodyBytes) {\n throw new OAuthError('invalid_request', 'Request body too large', { status: 413 });\n }\n const text = await readBodyText(request, config.clientRegistration.maxBodyBytes);\n let raw: unknown;\n try {\n raw = JSON.parse(text);\n } catch {\n throw new OAuthError('invalid_request', 'Request body must be valid JSON');\n }\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n throw new OAuthError('invalid_client_metadata', 'Client metadata must be a JSON object');\n }\n const m = raw as Record<string, unknown>;\n\n const str = (k: string): string | undefined => {\n const v = m[k];\n if (v === undefined) return undefined;\n if (typeof v !== 'string')\n throw new OAuthError('invalid_client_metadata', `${k} must be a string`);\n return v;\n };\n const strArr = (k: string): string[] | undefined => {\n const v = m[k];\n if (v === undefined) return undefined;\n if (!Array.isArray(v) || !v.every((x) => typeof x === 'string')) {\n throw new OAuthError('invalid_client_metadata', `${k} must be an array of strings`);\n }\n return v;\n };\n const httpUrl = (k: string): string | undefined => {\n const v = str(k);\n if (v === undefined) return undefined;\n let u: URL;\n try {\n u = new URL(v);\n } catch {\n throw new OAuthError('invalid_client_metadata', `${k} must be an absolute URL`);\n }\n if (u.protocol !== 'https:' && u.protocol !== 'http:') {\n throw new OAuthError('invalid_client_metadata', `${k} must be an http(s) URL`);\n }\n return v;\n };\n\n const redirectUris = strArr('redirect_uris');\n if (!redirectUris || redirectUris.length === 0) {\n throw new OAuthError('invalid_redirect_uri', 'redirect_uris is required');\n }\n\n // Negotiate token_endpoint_auth_method (RFC 7591 + RP metadata choices).\n let method = str('token_endpoint_auth_method') as TokenEndpointAuthMethod | undefined;\n const methodChoices = strArr('token_endpoint_auth_methods_supported');\n if (method === undefined && methodChoices) {\n method = AUTH_METHODS.find((am) => methodChoices.includes(am));\n if (!method)\n throw new OAuthError('invalid_client_metadata', 'No supported token_endpoint_auth_method');\n }\n if (method !== undefined && !AUTH_METHODS.includes(method)) {\n throw new OAuthError(\n 'invalid_client_metadata',\n `Unsupported token_endpoint_auth_method \"${method}\"`,\n );\n }\n\n let hookResult: ClientRegisterHookResult | void;\n try {\n hookResult = await config.hooks.onClientRegister?.({ metadata: m, request });\n } catch (e) {\n if (e instanceof OAuthError) throw e;\n throw new OAuthError('server_error', 'Client registration failed', { cause: e });\n }\n if (hookResult && 'error' in hookResult) {\n throw new OAuthError(hookResult.error, hookResult.description ?? 'Registration rejected', {\n status: hookResult.status,\n });\n }\n\n const input: CreateClientInput = {\n redirectUris,\n clientName: str('client_name'),\n clientUri: httpUrl('client_uri'),\n logoUri: httpUrl('logo_uri'),\n policyUri: httpUrl('policy_uri'),\n tosUri: httpUrl('tos_uri'),\n jwksUri: httpUrl('jwks_uri'),\n contacts: strArr('contacts'),\n grantTypes: strArr('grant_types'),\n responseTypes: strArr('response_types'),\n scope: hookResult?.scope ?? str('scope'),\n tokenEndpointAuthMethod: method,\n metadata: hookResult?.metadata,\n dynamicallyRegistered: true,\n };\n const client = await core.createClient(input);\n return json(toRegistrationResponse(client, config.clientRegistrationTTL), {\n status: 201,\n headers: NO_STORE,\n });\n}\n\nfunction toRegistrationResponse(\n client: ClientInfo,\n ttl: number | undefined,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {\n client_id: client.clientId,\n client_id_issued_at: client.registrationDate,\n redirect_uris: client.redirectUris,\n grant_types: client.grantTypes,\n response_types: client.responseTypes,\n token_endpoint_auth_method: client.tokenEndpointAuthMethod,\n };\n if (client.clientSecret) {\n out.client_secret = client.clientSecret;\n out.client_secret_expires_at = ttl === undefined ? 0 : client.registrationDate + ttl;\n }\n if (client.clientName) out.client_name = client.clientName;\n if (client.clientUri) out.client_uri = client.clientUri;\n if (client.logoUri) out.logo_uri = client.logoUri;\n if (client.policyUri) out.policy_uri = client.policyUri;\n if (client.tosUri) out.tos_uri = client.tosUri;\n if (client.jwksUri) out.jwks_uri = client.jwksUri;\n if (client.contacts) out.contacts = client.contacts;\n if (client.scope !== undefined) out.scope = client.scope;\n return out;\n}\n",
26
+ "import type { OAuthProviderCore } from '../core/provider.ts';\nimport { OAuthError } from '../errors.ts';\nimport { extractClientCredentials, NO_STORE, parseFormBody } from './http.ts';\n\n/** `POST /revoke` (RFC 7009). Always 200 for well-formed authenticated requests. */\nexport async function handleRevoke<Props>(\n core: OAuthProviderCore<Props>,\n request: Request,\n): Promise<Response> {\n const form = await parseFormBody(request);\n const creds = extractClientCredentials(request, form);\n const client = await core.authenticateClient(creds);\n const token = form.get('token');\n if (!token) throw new OAuthError('invalid_request', 'Missing token');\n const hint = form.get('token_type_hint');\n if (hint !== undefined && hint !== 'access_token' && hint !== 'refresh_token') {\n throw new OAuthError('unsupported_token_type', `Unsupported token_type_hint \"${hint}\"`);\n }\n await core.revokeToken({ client, token, tokenTypeHint: hint });\n return new Response(null, { status: 200, headers: NO_STORE });\n}\n",
27
+ "import type { OAuthProviderCore } from '../core/provider.ts';\nimport { OAuthError } from '../errors.ts';\nimport { extractClientCredentials, json, NO_STORE, parseFormBody } from './http.ts';\n\n/** `POST /token` — authorization_code and refresh_token grants. */\nexport async function handleToken<Props>(\n core: OAuthProviderCore<Props>,\n request: Request,\n): Promise<Response> {\n const form = await parseFormBody(request);\n const grantType = form.get('grant_type');\n const creds = extractClientCredentials(request, form);\n const client = await core.authenticateClient(creds);\n\n const resources = form.getAll('resource');\n if (resources.length > 1)\n throw new OAuthError('invalid_target', 'Only a single resource parameter is supported');\n const resource = resources[0];\n\n switch (grantType) {\n case 'authorization_code': {\n const code = form.get('code');\n if (!code) throw new OAuthError('invalid_request', 'Missing code');\n const res = await core.exchangeAuthorizationCode({\n client,\n code,\n codeVerifier: form.get('code_verifier'),\n redirectUri: form.get('redirect_uri'),\n resource,\n requestedScope: form.get('scope'),\n });\n return json(res, { headers: NO_STORE });\n }\n case 'refresh_token': {\n const refreshToken = form.get('refresh_token');\n if (!refreshToken) throw new OAuthError('invalid_request', 'Missing refresh_token');\n const res = await core.refreshAccessToken({\n client,\n refreshToken,\n requestedScope: form.get('scope'),\n resource,\n });\n return json(res, { headers: NO_STORE });\n }\n case undefined:\n throw new OAuthError('invalid_request', 'Missing grant_type');\n default:\n throw new OAuthError('unsupported_grant_type', `Unsupported grant_type \"${grantType}\"`);\n }\n}\n",
28
+ "import type { OAuthStorage, StorageSetOptions, Versioned } from './types.ts';\n\ninterface Entry {\n value: unknown;\n /** Epoch ms; `undefined` = never expires. */\n expiresAt?: number;\n}\n\nexport interface MemoryStorageOptions {\n /**\n * How often (ms) to sweep expired entries. Defaults to 60_000.\n * Set to `0` to disable the timer (expired keys are still filtered lazily).\n */\n sweepIntervalMs?: number;\n /** Injectable clock for tests. */\n now?: () => number;\n}\n\n/**\n * In-process storage backed by a `Map`.\n *\n * ⚠️ Data is lost when the process exits and is NOT shared between\n * multiple instances/workers. Use it for development, tests and\n * single-process deployments only.\n */\nexport class MemoryStorage implements OAuthStorage {\n readonly #map = new Map<string, Entry>();\n readonly #now: () => number;\n #timer: ReturnType<typeof setInterval> | undefined;\n\n constructor(options: MemoryStorageOptions = {}) {\n this.#now = options.now ?? Date.now;\n const interval = options.sweepIntervalMs ?? 60_000;\n if (interval > 0) {\n this.#timer = setInterval(() => {\n this.sweep();\n }, interval);\n // Don't keep the event loop alive just for the sweeper.\n if (typeof this.#timer === 'object' && 'unref' in this.#timer) this.#timer.unref();\n }\n }\n\n async get<T>(key: string): Promise<T | null> {\n const entry = this.#map.get(key);\n if (!entry) return null;\n if (this.#isExpired(entry)) {\n this.#map.delete(key);\n return null;\n }\n // Structured clone so callers can't mutate stored state by reference.\n return structuredClone(entry.value) as T;\n }\n\n async set<T>(key: string, value: T, opts?: StorageSetOptions): Promise<void> {\n const ttl = opts?.ttlSeconds;\n const expiresAt = ttl === undefined ? undefined : this.#now() + ttl * 1000;\n this.#map.set(key, { value: structuredClone(value), expiresAt });\n }\n\n /** Read and delete in one synchronous step, so concurrent callers cannot both win. */\n async consume<T>(key: string): Promise<T | null> {\n const entry = this.#map.get(key);\n this.#map.delete(key);\n if (!entry || this.#isExpired(entry)) return null;\n return entry.value as T;\n }\n\n async compareAndSet<T extends Versioned>(\n key: string,\n expectedVersion: number,\n value: T,\n opts?: StorageSetOptions,\n ): Promise<boolean> {\n if (!this.#holdsVersion(key, expectedVersion)) return false;\n await this.set(key, value, opts);\n return true;\n }\n\n async compareAndDelete(key: string, expectedVersion: number): Promise<boolean> {\n if (!this.#holdsVersion(key, expectedVersion)) return false;\n this.#map.delete(key);\n return true;\n }\n\n /** Synchronous, so a check-then-write pair in the same method cannot interleave. */\n #holdsVersion(key: string, expectedVersion: number): boolean {\n const entry = this.#map.get(key);\n if (!entry || this.#isExpired(entry)) return false;\n return (entry.value as Partial<Versioned>).version === expectedVersion;\n }\n\n async delete(key: string): Promise<void> {\n this.#map.delete(key);\n }\n\n async list(prefix: string): Promise<string[]> {\n const out: string[] = [];\n for (const [key, entry] of this.#map) {\n if (!key.startsWith(prefix)) continue;\n if (this.#isExpired(entry)) {\n this.#map.delete(key);\n continue;\n }\n out.push(key);\n }\n return out;\n }\n\n /** Remove every expired entry now. */\n sweep(): void {\n for (const [key, entry] of this.#map) if (this.#isExpired(entry)) this.#map.delete(key);\n }\n\n /** Number of live + not-yet-swept entries. Mostly for tests. */\n get size(): number {\n return this.#map.size;\n }\n\n close(): void {\n if (this.#timer) clearInterval(this.#timer);\n this.#timer = undefined;\n }\n\n #isExpired(entry: Entry): boolean {\n return entry.expiresAt !== undefined && entry.expiresAt <= this.#now();\n }\n}\n"
29
+ ],
30
+ "mappings": ";AAwCO,IAAM,gBAAgB;AAAA,EAE3B,SAAS;AAAA;AAAA;AAAA,EAIT,eAAe;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOf,kBAAkB;AAAA;AAAA;AAAA;AAAA;AAAA;AAMpB;AAAA;AAcO,MAAM,aAAqC;AAAA,EACvC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,WAAW,CAAC,QAAyB,UAA+B,CAAC,GAAG;AAAA,IACtE,KAAK,UAAU;AAAA,IACf,KAAK,UAAU,QAAQ,aAAa;AAAA,IACpC,KAAK,aAAa,QAAQ,aAAa;AAAA,IACvC,KAAK,cAAc,QAAQ,cAAc;AAAA,IACzC,IAAI,CAAC,OAAO,QAAQ,CAAC,OAAO,MAAM;AAAA,MAChC,MAAM,IAAI,UAAU,4DAA4D;AAAA,IAClF;AAAA;AAAA,EAGF,KAAK,CAAC,QAAgB,KAAa,MAAkC;AAAA,IACnE,MAAM,IAAI,KAAK;AAAA,IACf,IAAI,EAAE;AAAA,MAAM,OAAO,EAAE,KAAK,QAAQ,GAAG,KAAK,GAAG,IAAI;AAAA,IACjD,OAAO,EAAE,KAAM,QAAQ,CAAC,QAAQ,KAAK,KAAK,GAAG,IAAI,CAAC;AAAA;AAAA,OAG9C,IAAM,CAAC,KA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