@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
package/README.md CHANGED
@@ -1,3 +1,656 @@
1
- # Temporary Holding Version
1
+ # elysia-oauth-provider
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Turn an Elysia app that already has ordinary login into a **standards-compliant
4
+ OAuth 2.1 authorization server**, so MCP clients (Claude, Cursor, MCP Inspector,
5
+ …) can authenticate against it. A Bun + Elysia port of the ideas in
6
+ [`@cloudflare/workers-oauth-provider`](https://github.com/cloudflare/workers-oauth-provider)
7
+ with **pluggable storage** instead of Workers KV.
8
+
9
+ You keep owning the login UI and the user database. The plugin owns the
10
+ protocol:
11
+
12
+ - `GET /.well-known/oauth-authorization-server` (RFC 8414)
13
+ - `GET /.well-known/oauth-protected-resource[/path]` (RFC 9728, what MCP clients look for)
14
+ - `POST /register` – Dynamic Client Registration (RFC 7591), optional / gated
15
+ - `GET /authorize` – validated, then delegated to **your** login page
16
+ - `POST /token` – `authorization_code` + `refresh_token`
17
+ - `POST /revoke` (RFC 7009)
18
+ - Bearer validation on your routes with a typed `ctx.oauth`, and a correct
19
+ `WWW-Authenticate: Bearer resource_metadata="…"` challenge on 401
20
+
21
+ Security posture: PKCE **S256 mandatory**, exact redirect-URI matching (RFC 8252
22
+ loopback port exception), one-time codes with short TTL (replay revokes the
23
+ whole grant; consumed atomically, and revocation cannot be undone by a racing exchange), refresh-token
24
+ rotation with reuse detection, RFC 8707
25
+ `resource`/audience binding, RFC 9207 `iss`, secrets/codes/tokens stored only
26
+ as SHA-256, props encrypted at rest with per-grant keys, constant-time compares,
27
+ `no-store` everywhere, no implicit flow, no plain PKCE.
28
+
29
+ ---
30
+
31
+ ## Quickstart
32
+
33
+ ```sh
34
+ bun add @20baht/elysia-oauth-provider
35
+ ```
36
+
37
+ ```ts
38
+ import { Elysia, t } from 'elysia'
39
+ import { oauthProvider, MemoryStorage } from '@20baht/elysia-oauth-provider'
40
+
41
+ // Whatever your protected handlers need to know about the user.
42
+ type Props = { userId: number; username: string }
43
+
44
+ const app = new Elysia()
45
+ .use(
46
+ oauthProvider<Props>({
47
+ issuer: 'https://api.example.com', // public URL of this server
48
+ storage: new MemoryStorage(), // dev only – see Storage
49
+ resource: 'https://api.example.com/mcp', // bind tokens to your MCP endpoint
50
+ scopesSupported: ['expenses:read', 'profile'], // required; enforced everywhere
51
+ clientRegistration: true, // off by default; MCP clients register themselves
52
+
53
+ // GET /authorize was validated. Show YOUR login page.
54
+ handleAuthorize: ({ authRequestId }) =>
55
+ Response.redirect(`https://api.example.com/login?auth=${authRequestId}`),
56
+ }),
57
+ )
58
+
59
+ // Your login page's form handler. You verify the password.
60
+ .post(
61
+ '/login',
62
+ async ({ body, oauthProvider, redirect }) => {
63
+ const user = await myUsers.verify(body.username, body.password)
64
+ if (!user) return new Response('nope', { status: 401 })
65
+
66
+ const { redirectTo } = await oauthProvider.completeAuthorization({
67
+ authRequestId: body.auth,
68
+ userId: String(user.id),
69
+ scopes: ['expenses:read', 'profile'],
70
+ props: { userId: user.id, username: user.username },
71
+ })
72
+ return redirect(redirectTo, 302)
73
+ },
74
+ { body: t.Object({ auth: t.String(), username: t.String(), password: t.String() }) },
75
+ )
76
+
77
+ // Protected route: `oauth: true` requires a valid bearer token.
78
+ .post('/mcp', ({ oauth }) => handleMcp(oauth.props.userId), { oauth: true })
79
+
80
+ // …with a scope requirement (403 insufficient_scope otherwise).
81
+ .get('/mcp/me', ({ oauth }) => oauth.props, { oauth: { scopes: ['profile'] } })
82
+
83
+ .listen(3000)
84
+ ```
85
+
86
+ `ctx.oauth` is fully typed from the `Props` generic:
87
+
88
+ ```ts
89
+ interface OAuthContext<Props> {
90
+ userId: string
91
+ clientId: string
92
+ grantId: string
93
+ scopes: string[]
94
+ props: Props
95
+ expiresAt: number // epoch seconds
96
+ audience?: string // RFC 8707 resource the token is bound to
97
+ token: string
98
+ }
99
+ ```
100
+
101
+ A complete runnable app with a login page and an MCP endpoint lives in
102
+ [`examples/oauth-provider-basic`](../../../examples/oauth-provider-basic).
103
+
104
+ ---
105
+
106
+ ## The authorization flow
107
+
108
+ ```
109
+ MCP client elysia-oauth-provider your app
110
+ │ GET /authorize?… │ │
111
+ │──────────────────────────────▶│ validate client, redirect_uri, │
112
+ │ │ PKCE, scope, resource │
113
+ │ │ stash as authreq:{id} (10 min) │
114
+ │ │────── handleAuthorize({id}) ─────▶│ render / redirect to login
115
+ │◀──────────────────────────────┼───────────────────────────────────┤
116
+ │ user logs in on your page │ │
117
+ │──────────────────────────────────────────────────────────────────▶│ POST /login
118
+ │ │◀── completeAuthorization({id, │
119
+ │ │ userId, scopes, props }) ────┤
120
+ │◀── 302 redirect_uri?code&state&iss ───────────────────────────────┤
121
+ │ POST /token (code, verifier) │ │
122
+ │──────────────────────────────▶│ → access + refresh token │
123
+ │ POST /mcp Bearer … │ │
124
+ │──────────────────────────────▶│ macro `oauth` → ctx.oauth ───────▶│ handler
125
+ ```
126
+
127
+ `completeAuthorization` can also be called with a parsed `authRequest` instead
128
+ of an id if you prefer to run the workers-oauth-provider style
129
+ (`oauthProvider.parseAuthRequest(request)` → stash it yourself → complete).
130
+
131
+ Use `rejectAuthorization({ authRequestId })` when the user cancels; the client
132
+ receives `error=access_denied`.
133
+
134
+ ---
135
+
136
+ ## Config reference
137
+
138
+ ```ts
139
+ oauthProvider<Props>(config: OAuthProviderConfig<Props>)
140
+ ```
141
+
142
+ | Option | Type | Default | Notes |
143
+ | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
144
+ | `issuer` **(required)** | `string` | – | Absolute http(s) URL, optional base path (`https://x.com/auth`). Used for all advertised URLs; never the Host header. |
145
+ | `storage` **(required)** | `OAuthStorage` | – | See [Storage](#storage). |
146
+ | `handleAuthorize` **(required)** | `(input) => Response \| Promise<Response>` | – | `input = { authRequest, authRequestId, client, request }`. |
147
+ | `paths` | `Partial<{ authorize, token, register, revoke, jwks }>` | `/authorize`, `/token`, `/register`, `/revoke`, `/.well-known/jwks.json` | Relative to the issuer's base path. |
148
+ | `resource` | `string` | – | Canonical RFC 8707 resource. When set, every token is bound to it and other `resource` values → `invalid_target`. |
149
+ | `publicOrigin` | `string` | – (request URL as received) | Origin clients use when a proxy rewrites URLs. Protected routes check token audience and advertise `resource_metadata` against it. |
150
+ | `resourceMetadata` | `{ resource?, authorizationServers?, scopesSupported?, resourceName?, resourceDocumentation? }` | derived | Extra fields for the RFC 9728 document. |
151
+ | `scopesSupported` **(required)** | `string[]` | – | At least one scope. Advertised and enforced at `/authorize`, `/register`, `completeAuthorization`. |
152
+ | `accessTokenTTL` | seconds | `3600` | |
153
+ | `refreshTokenTTL` | seconds | `2592000` (30 d) | `0` disables refresh tokens. |
154
+ | `refreshTokenReuseGraceSeconds` | integer >= 0 (seconds) | `30` |
155
+ | `authCodeTTL` | seconds | `600` | |
156
+ | `authRequestTTL` | seconds | `600` | How long the user has to finish logging in. |
157
+ | `clientRegistrationTTL` | seconds \| `undefined` | `7776000` (90 d) | For dynamically registered clients only. Pass `undefined` explicitly for no expiry. |
158
+ | `clientRegistration` | `boolean \| { allowPublicClients?, maxBodyBytes? }` | `false` | Off: no `/register`, no `registration_endpoint`. `true` or options enable RFC 7591. Public clients allowed by default (MCP needs them). |
159
+ | `allowInsecureRedirectUris` | `boolean` | `false` | Accept redirect URIs outside the [redirect URI policy](#redirect-uri-policy). `javascript:` and friends stay rejected. |
160
+ | `tokenFormat` | `'opaque' \| { type:'jwt', alg, privateKey, publicKey?, kid?, additionalPublicKeys? } \| { type:'jwt', alg:'HS256', secret }` | `'opaque'` |
161
+ | `accessTokenClaims` | `(input) => Record<string, unknown> \| Promise<…>` | | JWT only. Extra claims merged into each access token; see [Custom access token claims](#custom-access-token-claims). |
162
+ | `encryptProps` | `boolean` | `true` | Encrypt `props` at rest with a per-grant AES-GCM key wrapped by the token (server cannot read props without a live token). |
163
+ | `cors` | `boolean` | `true` | Reflects `Origin` on OAuth endpoints and protected routes; answers `OPTIONS` on OAuth endpoints. |
164
+ | `rateLimit` | `boolean \| RateLimitConfig` | `true` | `DEFAULT_RATE_LIMITS` (token 30/min, register 10/h, authorize 60/min) with an in-process counter; `false` disables. See [Rate limiting](#rate-limiting). |
165
+ | `hooks` | see below | `{}` | |
166
+
167
+ ### Hooks
168
+
169
+ ```ts
170
+ hooks: {
171
+ // Gate / annotate dynamic registration. Return { error, description, status } to reject,
172
+ // { metadata, scope } to attach data, or throw an OAuthError.
173
+ onClientRegister?: ({ metadata, request }) => ClientRegisterHookResult | void
174
+
175
+ // After a valid /authorize request is parsed, before handleAuthorize. Throw to deny.
176
+ onAuthorize?: ({ authRequest, client, request }) => void
177
+
178
+ // Every access-token issuance (code exchange or refresh). Errors it throws are
179
+ // reported through onError / console.error and do not fail the token request.
180
+ onTokenIssued?: ({ grantType, clientId, userId, grantId, scopes, props }) => void
181
+
182
+ // Every OAuth error response (already spec-shaped; internals never leak).
183
+ onError?: ({ code, description, status, request }) => void
184
+
185
+ // A request was rejected by the rate limiter (429 already sent).
186
+ onRateLimited?: ({ endpoint, key, retryAfterSeconds, request }) => void
187
+ }
188
+ ```
189
+
190
+ ### Helpers (`ctx.oauthProvider`, also `plugin.decorator.oauthProvider`)
191
+
192
+ | Method | Purpose |
193
+ | ----------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
194
+ | `getAuthRequest(id)` | Load a pending request stashed by `GET /authorize`. |
195
+ | `parseAuthRequest(url \| Request)` | Validate `/authorize` params yourself. |
196
+ | `completeAuthorization({ authRequestId \| authRequest, userId, scopes, props, metadata?, resource?, revokeExistingGrants? })` | Issue a code; returns `{ redirectTo }`. Older grants for the same user + client are revoked unless `revokeExistingGrants: false`. `resource` binds the grant (see [Resource binding](#resource-binding)). |
197
+ | `rejectAuthorization({ authRequestId \| authRequest, error?, description? })` | Returns `{ redirectTo }` carrying `access_denied` (or the given error). |
198
+ | `verifyAccessToken(token, requestUrl?)` | Manual bearer check (e.g. WebSockets). |
199
+ | `createClient / lookupClient / updateClient / deleteClient / listClients` | Client admin. `createClient` returns the plaintext secret once. `updateClient` validates like `createClient` (redirect URIs, grant/response types, scope, auth method) and cannot change `dynamicallyRegistered`; switching a public client to a confidential method issues a new secret (returned once), switching to `none` drops the secret. `deleteClient` revokes the client's grants. |
200
+ | `listUserGrants(userId)` / `listClientGrants(clientId)` / `listGrants()` | "Connected apps" UI and admin: grants of one user, one client, or all (`GrantSummary[]`). |
201
+ | `revokeGrant(grantId, userId)` | Delete a grant with its access and refresh tokens. |
202
+ | `core` | The framework-agnostic `OAuthProviderCore` engine. |
203
+
204
+ ### Protected routes (`oauth` macro)
205
+
206
+ ```ts
207
+ .get('/x', handler, { oauth: true }) // valid token required
208
+ .get('/x', handler, { oauth: { scopes: ['a', 'b'] } }) // …and all listed scopes
209
+ ```
210
+
211
+ Responses on failure (all with `Cache-Control: no-store` and CORS headers):
212
+
213
+ | Case | Status | `WWW-Authenticate` |
214
+ | ----------------------------- | ------ | ------------------------------------------------------------------------------------------------------------ |
215
+ | no `Authorization` header | 401 | `Bearer realm="OAuth", resource_metadata="<issuer>/.well-known/oauth-protected-resource<path>"[, scope="…"]` |
216
+ | invalid / expired / revoked | 401 | `… error="invalid_token"`, JSON body `{ error: "invalid_token" }` |
217
+ | token bound to other resource | 401 | `… error="invalid_token", error_description="Token audience does not cover this resource"` |
218
+ | missing scope | 403 | `… error="insufficient_scope", scope="<required>"` |
219
+
220
+ `<path>` is the configured `resource`'s path, or the request path when no
221
+ resource is configured. The plugin serves
222
+ `/.well-known/oauth-protected-resource/*` for any suffix, so the pointer always
223
+ resolves.
224
+
225
+ Preflight `OPTIONS` for **your** protected routes is your responsibility
226
+ (e.g. `@elysiajs/cors`); the macro only adds CORS headers to its responses.
227
+
228
+ ### Scopes as capabilities (a layout that works)
229
+
230
+ Name scopes after API areas rather than tools — `profile`, `tasks:read`,
231
+ `requests:read`, `requests:write` — and list them all in `scopesSupported` so
232
+ the consent page can describe each one. Two things the plugin leaves to you
233
+ that are worth deciding up front:
234
+
235
+ - **Granted ⊆ requested.** `completeAuthorization` rejects a grant wider than the
236
+ request (`invalid_scope`); a consent page that lets people untick scopes should
237
+ check the same thing first so it can answer in its own error shape.
238
+ - **Your own sessions are not scope-limited.** If the same routes also serve a
239
+ first-party web app (JWT / cookie session), resolve _both_ token kinds in one
240
+ place and carry `oauthScopes: string[] | null` on the user — `null` for a
241
+ first-party session — so a per-route scope check can skip it. Then a single
242
+ route implementation serves the browser and an MCP client identically.
243
+
244
+ ### Resource binding
245
+
246
+ A grant is bound to one resource (RFC 8707). The binding comes from, in order:
247
+ `config.resource`, the `resource` option of `completeAuthorization`, then the
248
+ `resource` the client sent to `/authorize`. `completeAuthorization({ resource })`
249
+ is validated as an absolute http(s) URI without fragment, must equal
250
+ `config.resource` when that is set (`invalid_target` otherwise), and wins over
251
+ the client's request.
252
+
253
+ At `/token` a requested `resource` must match the grant's. If the grant has no
254
+ resource and `config.resource` is unset, any `resource` parameter is rejected
255
+ with `invalid_target`: a client cannot choose an audience the user never
256
+ authorized. `normalizeResource`, `resourcesEqual` and `audienceCoversUrl` are
257
+ exported; note that a resource without a path normalises to the trailing-slash
258
+ form (`https://host` becomes `https://host/`), which is also the form in the
259
+ JWT `aud`.
260
+
261
+ ### User ids
262
+
263
+ `userId` must be a non-empty string without `:`. With `tokenFormat: 'opaque'`
264
+ the id is embedded in the access token (`userId:grantId:secret`) and sent as a
265
+ bearer token, so it must also match `[A-Za-z0-9\-._~+/]+`; `completeAuthorization`
266
+ throws a `TypeError` otherwise (an email address such as `a@b.com` would produce
267
+ tokens that always get 401). Use a numeric/UUID id, or JWT mode, where any
268
+ non-colon id works.
269
+
270
+ ### Refresh token rotation and reuse detection
271
+
272
+ Every refresh issues a new refresh token and demotes the one just presented to
273
+ "previous". For `refreshTokenReuseGraceSeconds` (default `30`, `0` disables)
274
+ the previous token is still accepted, and it returns the same response its
275
+ rotation produced: the same access token and the same new refresh token. A
276
+ client that lost the response, or two browser tabs that refresh at the same
277
+ moment, end up holding the same tokens and nobody is logged out. The response
278
+ is stored sealed under the previous token, so a storage dump does not reveal
279
+ it. Retrying does not extend the window, and `expires_in` is recomputed from the
280
+ cached expiry. Presenting the previous token after the window, or any older
281
+ token, is treated as theft: the whole grant (its access and refresh tokens) is
282
+ revoked and the request fails with `invalid_grant`.
283
+
284
+ Rotation and revocation are linearizable. The grant record carries a `version`
285
+ and every write goes through the storage's `compareAndSet` or
286
+ `compareAndDelete` (see [Storage](#storage)). A refresh that loses the race
287
+ re-reads the grant and takes the "previous token" path above. A refresh that
288
+ races a revocation either commits first (and the revocation then re-reads and
289
+ removes what it minted) or fails its commit and deletes its own tokens. A
290
+ revoked grant cannot come back.
291
+
292
+ ### Authorization codes
293
+
294
+ Codes are single use. Besides the grant, `completeAuthorization` writes a
295
+ marker key (`authcode:{sha256(code)}`, TTL `authCodeTTL`) that `/token` consumes
296
+ just before minting tokens (after client, PKCE, scope and resource validation, so
297
+ a failed attempt does not burn the code). A second use, including a concurrent
298
+ one, finds the marker gone, revokes the grant and returns `invalid_grant`.
299
+ The consume is atomic (`consume(key)` is a required storage primitive), and the
300
+ winner's tokens are committed with `compareAndSet`, so when the loser revokes
301
+ the grant the winner's commit fails and the winner deletes what it minted. A
302
+ replayed code never leaves a working token behind (RFC 6749 §10.5).
303
+
304
+ ### JWT key rotation
305
+
306
+ ```ts
307
+ tokenFormat: {
308
+ type: 'jwt',
309
+ alg: 'ES256',
310
+ privateKey: newPrivateKey,
311
+ kid: 'key-2', // required when additionalPublicKeys is used
312
+ additionalPublicKeys: [{ publicKey: oldPublicKey, kid: 'key-1' }],
313
+ }
314
+ ```
315
+
316
+ New tokens are signed with the primary key. Verification selects the key by
317
+ the token's `kid` header among the primary and additional keys (a token with an
318
+ unknown or missing `kid` is rejected), and `/.well-known/jwks.json` lists all of
319
+ them. Drop an additional key once the tokens it signed have expired.
320
+
321
+ ### Custom access token claims
322
+
323
+ ```ts
324
+ tokenFormat: { type: 'jwt', alg: 'ES256', privateKey },
325
+ accessTokenClaims: ({ userId, clientId, grantId, scopes, resource, props }) => ({
326
+ email: props.email,
327
+ }),
328
+ ```
329
+
330
+ Called on code exchange and on every refresh, after validation and before
331
+ signing. The result is merged into the payload. Returning a registered claim
332
+ (`iss`, `sub`, `aud`, `exp`, `iat`, `jti`, `client_id`, `scope`, `grant_id`,
333
+ exported as `ACCESS_TOKEN_REGISTERED_CLAIMS`) fails the request with
334
+ `server_error` instead of being dropped: `sub` and `grant_id` locate the stored
335
+ token record, so overriding them would mint a token that never verifies, and
336
+ silently ignoring the claim would hide the bug until a resource server misses
337
+ it. The claims are not stored; `verifyAccessToken` and `ctx.oauth` return the
338
+ stored record as before. Setting it with opaque tokens throws at startup.
339
+
340
+ ### Elysia and runtime notes
341
+
342
+ - `POST /token`, `/revoke` and `/register` read the raw body themselves. They
343
+ work with `new Elysia({ aot: false })` (Cloudflare Workers) and next to an
344
+ app-level `onParse` hook with no workaround: the routes install a route-level
345
+ `parse` hook that claims the body so Elysia leaves the stream untouched.
346
+ - Every route the plugin registers has `detail: { hide: true }`, so it stays out
347
+ of `@elysiajs/openapi` documents.
348
+ - `maxBodyBytes` for `/register` is enforced on bytes while the body streams
349
+ (and via `Content-Length` up front), not on characters after buffering.
350
+ - The build targets `browser` (runtime neutral): the bundle uses web-standard
351
+ APIs only and runs on Bun, Node and Cloudflare Workers.
352
+
353
+ ### Rate limiting
354
+
355
+ Covers `/token`, `/register`, `/authorize` and `/revoke`. On by default with
356
+ the rules below, per client IP, in an in-process counter. Behind a proxy set
357
+ `trustProxy`, and across several instances plug a shared limiter; `rateLimit: false`
358
+ turns it off.
359
+
360
+ ```ts
361
+ rateLimit: {
362
+ token: { max: 30, windowSeconds: 60 },
363
+ register: { max: 10, windowSeconds: 3600 },
364
+ revoke: { max: 30, windowSeconds: 60 },
365
+ authorize: false, // disable for one endpoint
366
+ trustProxy: true, // read the first X-Forwarded-For entry (only behind your own proxy)
367
+ // trustProxy: 'cf-connecting-ip', // or name the header to read the IP from, verbatim
368
+ keyFor: ({ endpoint, ip, request }) => (ip === '10.0.0.1' ? null : `${endpoint}:${ip}`), // null = exempt
369
+ limiter: new RedisRateLimiter(redisClient), // shared across instances (INCR + EXPIRE)
370
+ }
371
+ ```
372
+
373
+ Blocked requests get `429` with `{ "error": "temporarily_unavailable" }`,
374
+ `Retry-After` and `Cache-Control: no-store`. `trustProxy: true` uses the first
375
+ `X-Forwarded-For` entry; a string names a header whose value is the client IP
376
+ (e.g. `'cf-connecting-ip'` on Cloudflare, where `X-Forwarded-For` is not
377
+ reliable). If that header is absent the socket address is used. Implement `RateLimiter`
378
+ (`hit(key, rule) → { allowed, retryAfterSeconds, remaining }`) to plug any
379
+ other backend.
380
+
381
+ Granted scopes are also checked against the request: `completeAuthorization`
382
+ throws `invalid_scope` if the app tries to grant a scope the client did not
383
+ ask for (a request with no `scope` leaves the choice to the app, bounded by
384
+ `scopesSupported`).
385
+
386
+ ### Redirect URI policy
387
+
388
+ Registered and requested redirect URIs must be one of (OAuth 2.1 §1.5, RFC 8252 §7):
389
+
390
+ - `https://…`
391
+ - `http://` to a loopback host only: `localhost`, `127.0.0.0/8`, `[::1]`. The
392
+ port may differ between registration and `/authorize` (RFC 8252 §7.3).
393
+ - A private-use scheme in reverse-DNS form, e.g. `com.example.app:/callback`.
394
+
395
+ Anything else (`http://app.example/cb`, `myapp://cb`) is `invalid_redirect_uri`
396
+ at `/register`, `createClient` and `updateClient`, and `invalid_request` at
397
+ `/authorize`. `allowInsecureRedirectUris: true` lifts the policy for legacy
398
+ clients; `javascript:`, `data:`, `file:` and similar schemes are rejected
399
+ regardless.
400
+
401
+ ### Behind a proxy (`publicOrigin`)
402
+
403
+ Protected routes compare a token's audience with the request URL and point
404
+ clients at `/.well-known/oauth-protected-resource` in `WWW-Authenticate`. When a
405
+ proxy rewrites the URL (`https://api.example.com/mcp` arrives as
406
+ `http://10.0.0.5:3000/mcp`), set `publicOrigin: 'https://api.example.com'` so
407
+ both use the origin the client sees. Only the origin is replaced; path and
408
+ query come from the request.
409
+
410
+ ### Errors
411
+
412
+ `OAuthError(code, description, { status?, headers? })` renders as
413
+ `{ "error": code, "error_description": description }` with RFC-correct status
414
+ codes (`invalid_client` → 401 + `WWW-Authenticate: Basic`, `insufficient_scope`
415
+ → 403, …). Unexpected exceptions become `server_error` with no details leaked.
416
+ `AuthorizationError` is redirected to the client only after the client and
417
+ redirect URI were validated; before that it is rendered locally as JSON 400.
418
+
419
+ ---
420
+
421
+ ## Storage
422
+
423
+ ```ts
424
+ interface OAuthStorage {
425
+ get<T>(key: string): Promise<T | null>
426
+ set<T>(key: string, value: T, opts?: { ttlSeconds?: number }): Promise<void>
427
+ delete(key: string): Promise<void>
428
+ list(prefix: string): Promise<string[]> // all live keys starting with prefix
429
+ consume<T>(key: string): Promise<T | null> // atomic get + delete
430
+ compareAndSet<T extends { version: number }>(
431
+ key: string,
432
+ expectedVersion: number,
433
+ value: T,
434
+ opts?: { ttlSeconds?: number },
435
+ ): Promise<boolean>
436
+ compareAndDelete(key: string, expectedVersion: number): Promise<boolean>
437
+ close?(): Promise<void> | void
438
+ }
439
+ ```
440
+
441
+ The three atomic primitives are required. The plugin throws a `TypeError` at
442
+ startup when any is missing, because refresh-token rotation and revocation are
443
+ only correct when the grant record is written through them. Their contract:
444
+
445
+ - `consume(key)`: read and delete in one step. Of concurrent callers exactly
446
+ one receives the value, the rest get `null`. Missing or expired keys return
447
+ `null`.
448
+ - `compareAndSet(key, expectedVersion, value, opts)`: write `value` (and apply
449
+ or replace the TTL) only if the key holds a live value whose top-level
450
+ `version` field equals `expectedVersion`. Return whether the write happened.
451
+ A missing, expired, or unversioned value never matches. The provider always
452
+ writes `value.version === expectedVersion + 1`; the adapter does not check that.
453
+ - `compareAndDelete(key, expectedVersion)`: delete only under the same
454
+ condition, and return whether the delete happened.
455
+ - Of concurrent `compareAndSet` and `compareAndDelete` calls for one key at one
456
+ version, exactly one succeeds. They must also be atomic with respect to `set`
457
+ and `delete` on that key.
458
+
459
+ Only `grant:*` records are versioned. Every other key is written with `set` and,
460
+ for `authcode:*`, read with `consume`.
461
+
462
+ ### Bundled adapters
463
+
464
+ **`MemoryStorage`** – `Map` + expiry timestamps. Lost on restart, **not shared
465
+ across processes/instances**. Dev, tests, single-process only.
466
+
467
+ ```ts
468
+ new MemoryStorage({ sweepIntervalMs: 60_000 })
469
+ ```
470
+
471
+ **`RedisStorage`** – native key TTLs, `SCAN MATCH` for `list`. Works with
472
+ `ioredis` **or Bun's built-in client**. The atomic primitives run as Lua
473
+ scripts through `EVAL` (the client needs `eval()` or `send()`), and compare
474
+ `cjson.decode(value).version`. Neither client is a hard dependency (`ioredis`
475
+ is an optional peer).
476
+
477
+ ```ts
478
+ import { RedisStorage } from '@20baht/elysia-oauth-provider' // or '@20baht/elysia-oauth-provider/storage/redis'
479
+
480
+ new RedisStorage(new Bun.RedisClient(process.env.REDIS_URL), { keyPrefix: 'oauth:' })
481
+ // or
482
+ import Redis from 'ioredis'
483
+ new RedisStorage(new Redis(process.env.REDIS_URL), { keyPrefix: 'oauth:' })
484
+ ```
485
+
486
+ Anything else (Postgres, SQLite, Deno KV, …) is a ~40-line adapter you own —
487
+ see [Writing your own adapter](#writing-your-own-adapter). The library deliberately
488
+ ships no SQL driver binding.
489
+
490
+ ### Key layout
491
+
492
+ | Key | Value | TTL / persistence |
493
+ | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------- |
494
+ | `client:{clientId}` | client record, `clientSecretHash` (SHA-256 hex) | `clientRegistrationTTL` for DCR clients; **persistent** for `createClient` |
495
+ | `authreq:{id}` | validated `/authorize` params waiting for login | `authRequestTTL` |
496
+ | `grant:{userId}:{grantId}` | `version`, scopes, encrypted props, code hash + PKCE (until exchanged), refresh hashes, sealed previous-refresh response | `authCodeTTL` until exchanged, then refresh lifetime (or access TTL if refresh disabled) |
497
+ | `token:{userId}:{grantId}:{sha256(token)}` | denormalised access-token record (one read per request) | `accessTokenTTL` |
498
+ | `refresh:{sha256(refreshToken)}` | `{ userId, grantId }` pointer | refresh lifetime |
499
+ | `authcode:{sha256(code)}` | one-time marker consumed by the code exchange | `authCodeTTL` |
500
+
501
+ Prefix scans used by the provider: `grant:{userId}:` (list/revoke a user's
502
+ grants), `token:{userId}:{grantId}:` (revoke a grant's tokens), `client:` and
503
+ `grant:` (admin only). `userId` must not contain `:` (and, in opaque mode, only token68 characters).
504
+
505
+ Opaque access tokens and authorization codes look like
506
+ `{userId}:{grantId}:{32 random chars}` so they can be located in one read;
507
+ only their SHA-256 is stored.
508
+
509
+ ### Writing your own adapter
510
+
511
+ Any store that can do get, set with TTL, delete, prefix list, and a conditional
512
+ single-row write works. Values are plain JSON. The conditional writes need one
513
+ atomic statement each, not a transaction. Example with `bun:sqlite`; the same
514
+ SQL runs on Cloudflare D1 (`.run()` returns `meta.changes`) and Postgres
515
+ (`value::jsonb->>'version'`):
516
+
517
+ ```ts
518
+ import { Database } from 'bun:sqlite'
519
+ import type { OAuthStorage, StorageSetOptions } from '@20baht/elysia-oauth-provider'
520
+
521
+ export class SqliteStorage implements OAuthStorage {
522
+ #db: Database
523
+ constructor(path = 'oauth.sqlite') {
524
+ this.#db = new Database(path)
525
+ this.#db.run(
526
+ `CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL, expires_at INTEGER)`,
527
+ )
528
+ }
529
+ async get<T>(key: string) {
530
+ const row = this.#db
531
+ .query<{ value: string; expires_at: number | null }, [string]>(
532
+ 'SELECT value, expires_at FROM kv WHERE key = ?',
533
+ )
534
+ .get(key)
535
+ if (!row) return null
536
+ if (row.expires_at !== null && row.expires_at <= Date.now()) {
537
+ await this.delete(key)
538
+ return null
539
+ }
540
+ return JSON.parse(row.value) as T
541
+ }
542
+ async set<T>(key: string, value: T, opts?: StorageSetOptions) {
543
+ this.#db.run('INSERT OR REPLACE INTO kv (key, value, expires_at) VALUES (?, ?, ?)', [
544
+ key,
545
+ JSON.stringify(value),
546
+ expiry(opts),
547
+ ])
548
+ }
549
+ async delete(key: string) {
550
+ this.#db.run('DELETE FROM kv WHERE key = ?', [key])
551
+ }
552
+ async list(prefix: string) {
553
+ const now = Date.now()
554
+ return this.#db
555
+ .query<{ key: string }, [string, string, number]>(
556
+ `SELECT key FROM kv WHERE key >= ? AND key < ? || X'FF' AND (expires_at IS NULL OR expires_at > ?)`,
557
+ )
558
+ .all(prefix, prefix, now)
559
+ .map((r) => r.key)
560
+ }
561
+ async consume<T>(key: string) {
562
+ const row = this.#db
563
+ .query<{ value: string; expires_at: number | null }, [string]>(
564
+ 'DELETE FROM kv WHERE key = ? RETURNING value, expires_at',
565
+ )
566
+ .get(key)
567
+ if (!row || (row.expires_at !== null && row.expires_at <= Date.now())) return null
568
+ return JSON.parse(row.value) as T
569
+ }
570
+ async compareAndSet<T extends { version: number }>(
571
+ key: string,
572
+ expectedVersion: number,
573
+ value: T,
574
+ opts?: StorageSetOptions,
575
+ ) {
576
+ const { changes } = this.#db.run(
577
+ `UPDATE kv SET value = ?, expires_at = ?
578
+ WHERE key = ? AND json_extract(value, '$.version') = ?
579
+ AND (expires_at IS NULL OR expires_at > ?)`,
580
+ [JSON.stringify(value), expiry(opts), key, expectedVersion, Date.now()],
581
+ )
582
+ return changes === 1
583
+ }
584
+ async compareAndDelete(key: string, expectedVersion: number) {
585
+ const { changes } = this.#db.run(
586
+ `DELETE FROM kv WHERE key = ? AND json_extract(value, '$.version') = ?
587
+ AND (expires_at IS NULL OR expires_at > ?)`,
588
+ [key, expectedVersion, Date.now()],
589
+ )
590
+ return changes === 1
591
+ }
592
+ }
593
+
594
+ const expiry = (opts?: StorageSetOptions) =>
595
+ opts?.ttlSeconds === undefined ? null : Date.now() + opts.ttlSeconds * 1000
596
+ ```
597
+
598
+ On Cloudflare D1, `consume` is `DELETE ... RETURNING` through `.first()`, and
599
+ the two conditional statements read `(await stmt.run()).meta.changes`. Each is
600
+ a single statement, so no `db.batch()` is needed. On Redis, use Lua scripts
601
+ (see `REDIS_SCRIPTS` in `storage/redis.ts`); a `GET` followed by a `SET` on the
602
+ client side is not atomic.
603
+
604
+ Run the **conformance suite** against it in `bun test`:
605
+
606
+ ```ts
607
+ import { runStorageConformance } from '@20baht/elysia-oauth-provider/storage/conformance'
608
+ runStorageConformance('SqliteStorage', { create: () => new SqliteStorage(':memory:') })
609
+ ```
610
+
611
+ It checks JSON round-trips, reference isolation, overwrite, delete, prefix
612
+ listing, TTL expiry (including TTL replacement), bulk writes, `consume`,
613
+ `compareAndSet` and `compareAndDelete`, including that of ten concurrent
614
+ conditional writes at one version exactly one wins.
615
+
616
+ ---
617
+
618
+ ## Migrating from `@cloudflare/workers-oauth-provider`
619
+
620
+ | workers-oauth-provider | elysia-oauth-provider |
621
+ | ---------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
622
+ | `new OAuthProvider({ apiRoute, apiHandler, defaultHandler, … })` as the Worker's `fetch` | `app.use(oauthProvider({ … }))`. There is no wrapper: your routes stay yours; mark protected ones with `{ oauth: true }`. |
623
+ | `env.OAUTH_KV` | `storage: new RedisStorage(...)` (or any `OAuthStorage`) |
624
+ | `authorizeEndpoint` handled by _your_ `defaultHandler` | Plugin serves `GET /authorize`, validates, then calls `handleAuthorize`. The request is stashed for you as `authRequestId`. |
625
+ | `env.OAUTH_PROVIDER.parseAuthRequest(request)` | `ctx.oauthProvider.parseAuthRequest(request)` (still available) or just `getAuthRequest(id)` |
626
+ | `completeAuthorization({ request, userId, scope, props, metadata })` | `completeAuthorization({ authRequestId, userId, scopes, props, metadata })` (`scope` → `scopes`) |
627
+ | `ctx.props` in the API handler | `ctx.oauth.props` (+ `userId`, `clientId`, `scopes`, …), typed via `oauthProvider<Props>()` |
628
+ | `tokenEndpoint` doubles as revocation endpoint | Separate `POST /revoke` (path configurable) |
629
+ | `clientRegistrationEndpoint: undefined` disables DCR | `clientRegistration: false` |
630
+ | `clientRegistrationCallback` | `hooks.onClientRegister` |
631
+ | `tokenExchangeCallback` | `hooks.onTokenIssued` (observe only; props are fixed at grant time in v1) |
632
+ | `resourceMetadata.resource` | `resource` (+ `resourceMetadata` for the other fields) |
633
+ | `allowImplicitFlow`, `allowPlainPKCE`, CIMD, token exchange, EMA | not supported (OAuth 2.1 only) |
634
+ | `accessTokenTTL` min 60 s (KV limit) | any positive integer |
635
+ | `purgeExpiredData()` cron | not needed: every key carries a TTL the storage enforces |
636
+ | Token format `userId:grantId:secret` | same for access tokens/codes; refresh tokens are plain random strings with a `refresh:{hash}` pointer |
637
+ | Props encryption (AES-GCM key wrapped by token) | same scheme (`encryptProps: true` by default) |
638
+
639
+ The storage layout is close enough that a migration script from KV is
640
+ mechanical (`client:*` → same shape minus `authMethodExplicit`; grants/tokens
641
+ are short-lived, let them expire).
642
+
643
+ ---
644
+
645
+ ## Development
646
+
647
+ ```sh
648
+ bun install
649
+ bun test packages # unit + flow tests (Redis live suite runs when REDIS_URL is set)
650
+ bun run --filter @20baht/elysia-oauth-provider build
651
+ bun run example # examples/basic-mcp on :3000
652
+ ```
653
+
654
+ ## License
655
+
656
+ MIT