@dokebi/oauth 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AI.md +469 -0
- package/LICENSE +21 -0
- package/README.md +41 -2
- package/dist/bounded.d.ts +9 -0
- package/dist/bounded.js +36 -0
- package/dist/cimd.d.ts +97 -0
- package/dist/cimd.js +384 -0
- package/dist/clients.d.ts +85 -0
- package/dist/clients.js +303 -0
- package/dist/dependency.d.ts +4 -0
- package/dist/dependency.js +14 -0
- package/dist/errors.d.ts +87 -0
- package/dist/errors.js +34 -0
- package/dist/extension.d.ts +161 -0
- package/dist/extension.js +108 -0
- package/dist/grants.d.ts +126 -0
- package/dist/grants.js +280 -0
- package/dist/index.d.ts +48 -0
- package/dist/index.js +28 -0
- package/dist/install.d.ts +33 -0
- package/dist/install.js +112 -0
- package/dist/live.d.ts +47 -0
- package/dist/live.js +105 -0
- package/dist/options.d.ts +173 -0
- package/dist/options.js +521 -0
- package/dist/plugin.d.ts +113 -0
- package/dist/plugin.js +766 -0
- package/dist/protocol.d.ts +81 -0
- package/dist/protocol.js +249 -0
- package/dist/server.d.ts +148 -0
- package/dist/server.js +1516 -0
- package/dist/signin.d.ts +40 -0
- package/dist/signin.js +86 -0
- package/dist/store-redis.d.ts +38 -0
- package/dist/store-redis.js +173 -0
- package/dist/store-sql.d.ts +46 -0
- package/dist/store-sql.js +363 -0
- package/dist/store.d.ts +126 -0
- package/dist/store.js +266 -0
- package/options.schema.json +633 -0
- package/package.json +143 -4
- package/templates/extension.ts +45 -0
- package/templates/migrations/dokebi_oauth.ts +117 -0
package/AI.md
ADDED
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
# AI guide — @dokebi/oauth
|
|
2
|
+
|
|
3
|
+
An **OAuth 2.1 authorization server** for @dokebi/web apps, on @dokebi/auth's opaque tokens (`dkb_…`, stored as sha256, revocable at once — no JWT): authorization code with **PKCE S256** (required), refresh tokens with rotation and reuse detection, revocation (RFC 7009), authorization server metadata (RFC 8414, derived from the options), protected resource metadata (RFC 9728), resource indicators (RFC 8707, **required**), the callback `iss` (RFC 9207), client ID metadata documents (CIMD, on by default), pre-registered clients and optional dynamic registration (RFC 7591, closed by default). Routes of the same app become protected resources with `config: { oauth: { resource, scopes? } }`. The consent page is the application's (`renderConsent` in `src/infra/oauth/extension.ts`). Node >=24.0.0, core ^0.4.2, @dokebi/web ^0.4.3, @dokebi/auth ^0.4.1 and @dokebi/session ^0.4.4 (required), @dokebi/csrf (recommended), @dokebi/db or @dokebi/redis (stores), @dokebi/rate-limit (optional). The design is [D-0091](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0091-oauth-authorization-server.md); the human-oriented description is the [README](README.md).
|
|
4
|
+
|
|
5
|
+
Not provided: OpenID Connect (no `id_token`, userinfo or `/.well-known/openid-configuration` — offering it makes clients expect an id_token), the implicit, password, client_credentials and device grants, token introspection, JWT access tokens, `private_key_jwt`.
|
|
6
|
+
|
|
7
|
+
## 1. Install
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npx dokebi add @dokebi/oauth # also @dokebi/auth and @dokebi/session when missing
|
|
11
|
+
npx dokebi add @dokebi/csrf # the consent form is a POST of your app
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
> `npx dokebi` is the @dokebi/cli installed in the project (`dokebi init` adds it to devDependencies). The npm package `dokebi` is not this CLI, so never use `npx -y dokebi`. Without an installed CLI use `npx -y @dokebi/cli …`.
|
|
15
|
+
|
|
16
|
+
- `dokebi add` creates the user-owned entry `src/infra/oauth/extension.ts` (an `OAuthExtension` subclass without `renderConsent`): **the app does not start until you implement `renderConsent`** (`EXTENSION_REQUIRED`).
|
|
17
|
+
- With `store: { driver: sql, connection: main }` it also writes the migration `src/infra/db/migrations/main/<time>_dokebi_oauth.ts` (three tables, §9); run `npx dokebi-migrate up`. The app never creates tables at start.
|
|
18
|
+
- Without @dokebi/csrf the start warns `OAUTH_CSRF_MISSING`.
|
|
19
|
+
- Register it after @dokebi/auth (it depends on it); routes with `config.oauth` may be added by any plugin or app, before or after it.
|
|
20
|
+
|
|
21
|
+
```yaml
|
|
22
|
+
# dokebi.yaml
|
|
23
|
+
options:
|
|
24
|
+
dokebi-oauth:
|
|
25
|
+
issuer: https://example.com
|
|
26
|
+
resources:
|
|
27
|
+
mcp:
|
|
28
|
+
uri: https://example.com/mcp
|
|
29
|
+
name: Notes
|
|
30
|
+
scopes: { 'notes:read': Read your notes, 'notes:write': Change your notes }
|
|
31
|
+
defaultScopes: ['notes:read']
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## 2. Options `options.dokebi-oauth`
|
|
35
|
+
|
|
36
|
+
| Key | Type | Default | Description |
|
|
37
|
+
|---|---|---|---|
|
|
38
|
+
| `issuer` | string | **required** | the authorization server identifier: an origin without a path (`https://example.com`). `http` only on `localhost` and `*.localhost`. It is the `issuer` of the metadata and the `iss` of every authorization answer |
|
|
39
|
+
| `app` | string or string[] | — (every host) | the app or apps of @dokebi/app whose hosts answer the authorization server ([D-0132](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0132-plugin-routes-bound-to-apps.md), §3): its metadata, `/oauth/authorize` (the consent page and its decision), token, revoke and register, for example `studio`. Other hosts get the 404 of an unknown route. Needs @dokebi/app |
|
|
40
|
+
| `realm` | string | `default` | the dokebi-auth realm whose users grant access (`INVALID_OPTIONS` when auth has no such realm) |
|
|
41
|
+
| `resources` | object | **required** (1 to 32) | protected resources by id. The id (1-64 letters, digits, `.`, `_`, `-`) is the audience of their tokens and the `resource` of `config.oauth` |
|
|
42
|
+
| `resources.<id>.uri` | string | **required** | the resource URI exactly as clients send it and as its metadata says (`https://example.com/mcp`). https (http only on localhost). Two resources may not name the same resource or have the same metadata path |
|
|
43
|
+
| `resources.<id>.name` | string | the id | human name (`resource_name`, the consent data) |
|
|
44
|
+
| `resources.<id>.scopes` | object | `{}` | scope names and their labels: `{ 'notes:read': Read your notes }`. Requests may ask only for these. A name is 1-128 letters, digits, `_`, `:`, `-` in dot-separated parts (an RFC 6749 scope token that is also a dokebi-auth token ability: tokens carry their scopes as abilities); names under `dokebi-oauth:` are reserved (`dokebi-oauth:none`, `dokebi-oauth:auth_time:…`, §7; `dokebi-oauth:pending`, §9) |
|
|
45
|
+
| `resources.<id>.app` | string or string[] | `app` | the apps whose hosts serve this resource's protected resource metadata (D-0132, §3): the app of the `uri` host, for example `mcp`. Neither set: every host |
|
|
46
|
+
| `resources.<id>.defaultScopes` | string[] | `[]` | what a request without `scope` gets, and the `scope` of the 401 challenge; each must be in `scopes`. A resource with scopes but no defaults refuses requests without `scope` (`invalid_scope`) |
|
|
47
|
+
| `clients` | object | `{}` | pre-registered clients by client_id (not a URL, not `dcr_…`) |
|
|
48
|
+
| `clients.<id>.name` | string | **required** | the name the consent data shows (trusted: you configured it) |
|
|
49
|
+
| `clients.<id>.redirectUris` | string[] | **required** | exact redirect URIs (https, or http on `127.0.0.1`, `[::1]` or `localhost`) |
|
|
50
|
+
| `clients.<id>.secretSha256` | string | — | sha256 of the client secret in lower-case hex (the secret itself is never stored): a confidential client (`client_secret_basic` or `client_secret_post`). Absent: a public client (`none`) |
|
|
51
|
+
| `clients.<id>.grant.maxDays` | integer | `grant.maxDays` | this client's own absolute grant lifetime in days (1..3650, at most `grant.clientMaxDays`; [D-0122](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0122-studio-terminal-needs.md)): a native app that signs in once a year sets 365 while AI connections keep 90. Only pre-registered clients; document and registered clients get `grant.maxDays` |
|
|
52
|
+
| `cimd.enabled` | boolean | `true` | accept client ID metadata documents (an https `client_id` URL whose JSON this server fetches; §8) |
|
|
53
|
+
| `cimd.allowHosts` | string[] | `[]` | hosts whose documents are accepted (lower case); empty: every public https host |
|
|
54
|
+
| `cimd.timeoutMs` | integer | `3000` | the whole fetch of one document (500..10000) |
|
|
55
|
+
| `cimd.maxFetches` | integer | `16` | document fetches running at once per process (1..1024); each is an outbound request to a host the client named, so beyond it the authorize request answers busy ([D-0113](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0113-overload-log-and-storage-wait.md) §5) |
|
|
56
|
+
| `cimd.maxFetchesPerAddress` | integer | `2` | document fetches one client address (IPv6 by /64) may start at once (1..1024) |
|
|
57
|
+
| `cimd.refusalCacheMs` | integer | `300000` | a refused document URL is not fetched again for this long (0..86400000; 0: every request fetches again) |
|
|
58
|
+
| `cimd.maxRefused` | integer | `1000` | refused document URLs remembered at once; beyond it the oldest go (1..1000000) |
|
|
59
|
+
| `cimd.maxBytes` | integer | `16384` | largest document body in bytes (1024..1048576); a larger one is refused (`too-large`) |
|
|
60
|
+
| `cimd.maxHeaderBytes` | integer | `8192` | largest response head of a document fetch in bytes (1024..65536; the built-in fetch) |
|
|
61
|
+
| `cimd.minCacheMs` · `cimd.maxCacheMs` · `cimd.defaultCacheMs` | integers | `300000` · `86400000` · `3600000` | how long a fetched document is kept: its `max-age` within min and max, `defaultCacheMs` without one, `minCacheMs` for no-store (0..604800000, max at least 60000; min ≤ default ≤ max) |
|
|
62
|
+
| `cimd.maxCached` | integer | `1000` | fetched documents kept at once; beyond it the oldest go (1..1000000) |
|
|
63
|
+
| `registrationLimit` | integer | `20` | registrations one client address (IPv6 by /64) may make per `registrationWindowMs`; beyond it 429 with Retry-After (1..1000000, [D-0113](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0113-overload-log-and-storage-wait.md) §5) |
|
|
64
|
+
| `registrationWindowMs` | integer | `3600000` | the window of `registrationLimit` (1000..86400000) |
|
|
65
|
+
| `clientUnusedMs` | integer | `2592000000` | a registered client unused this long is removed by `grants.purge()` (sql, memory) or expires (redis); 30 days (86400000..315360000000). Never less than `refreshMs`: the time used is the larger of the two, so a client stays while a refresh token it was given may still run (a client's use is a call of the token endpoint) |
|
|
66
|
+
| `maxTrackedAddresses` | integer | `10000` | client addresses whose registrations and document fetches this process counts; beyond it the least recently seen are forgotten (1..10000000) |
|
|
67
|
+
| `registration` | `closed` · `open` | `closed` | dynamic client registration: closed (POST /oauth/register answers 404, the metadata has no `registration_endpoint`) or open (public clients only, `registrationLimit` per address and `registrationWindowMs` (20 per hour), removed after `clientUnusedMs` unused (30 days)) |
|
|
68
|
+
| `accessMs` | integer | `900000` | access token lifetime (15 minutes). More than 5 minutes (minimum 360000): Claude Code refreshes before every call below that |
|
|
69
|
+
| `refreshMs` | integer | `2592000000` | refresh token lifetime (30 days; one use each); also the shortest time a registered client is kept after its last use (`clientUnusedMs`) |
|
|
70
|
+
| `grant.maxDays` | integer | `90` | absolute lifetime of a grant from the consent (1..3650). **Refreshes never extend it**; after it the user consents again and gets a new grant |
|
|
71
|
+
| `grant.clientMaxDays` | integer | `365` | the longest `clients.<id>.grant.maxDays` (1..3650); a longer one fails the options check at start (path `clients`) |
|
|
72
|
+
| `grant.maxPerClient` | integer | `20` | live grants (connected devices) one user may hold for one client, all resources together (1..1000, [D-0124](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0124-auth-time-bearer-live-grant-per-device.md)). A new authorization beyond it **revokes the least recently used** grant of that user and client (those that never got a live token first) and logs warn `OAUTH_GRANT_EVICTED`; it never refuses the new device. With the memory store at most `store.maxGrantsPerUser` (an options check at start, path `grant`) |
|
|
73
|
+
| `live.maxAgeMs` | integer | `5000` | `api.live()` (§7): a Bearer SSE stream or WebSocket ends at most this long after its token or grant was revoked where this process does not see it (another process), its account changed (a new stamp: a password change, `logoutOtherDevices`; `active: false`; deleted) or `canDelegate` turned false (100..60000). Expiry ends it at that instant; a revocation through this process at once. Each open connection reads its token, grant and user again about every `maxAgeMs - renewBeforeMs`, in one check (10,000 connections at the defaults: about 2,500 checks per second, three reads each; the user read is shared by a user's connections) |
|
|
74
|
+
| `live.renewBeforeMs` | integer | `1000` | how long before its deadline a connection is checked again (10..30000, smaller than `maxAgeMs`, at most half of it); keep it above the slowest token, grant and user read |
|
|
75
|
+
| `codeMs` | integer | `60000` | authorization code lifetime (one use) |
|
|
76
|
+
| `grantCacheMs` | integer | `5000` | protected routes keep a looked-up grant this long in process memory (0: one store lookup per request). A revocation through this process applies at once, through another one within this time |
|
|
77
|
+
| `maxCachedGrants` | integer | `10000` | grants the `grantCacheMs` cache, the delegation check and the last-use memo keep at once; beyond it the oldest go (1..10000000) |
|
|
78
|
+
| `grantTouchMs` | integer | `60000` | a grant's `lastUsedAt` is written at most this often (1000..86400000) |
|
|
79
|
+
| `codeGraceMs` | integer | `600000` | an expired code is kept this long before `grants.purge()` removes it, so a replay is still recognized and revokes its grant (0..86400000) |
|
|
80
|
+
| `pendingMs` | integer | `600000` | how long an authorization request waits in the session for login and consent (10000..3600000) |
|
|
81
|
+
| `maxPending` | integer | `5` | authorization requests one session keeps waiting at once (tabs); beyond it the oldest is dropped (1..100). Requests opened at the same moment do not see each other and may pass it by their number; the next request opened trims the session to it. Each shown one holds a decision ticket of @dokebi/session (`maxOnce`, 16 by default): keep it at or below that (§5) |
|
|
82
|
+
| `maxBodyBytes` | integer | `65536` | largest body of POST /oauth/token, /oauth/revoke and /oauth/register in bytes (1024..1048576; more is 413) |
|
|
83
|
+
| `storeRetryAfterMs` · `storeFullRetryAfterMs` | integers | `1000` · `5000` | the `data.retryAfterMs` (Retry-After) of 503 `STORE_FAILED` (1..60000) and of 503 `STORE_FULL` (1..600000) |
|
|
84
|
+
| `logRepeatWindowMs` | integer | `10000` | window of the repeated OAuth logs (`OAUTH_STORE_FAILED`, `OAUTH_STORE_FULL`, `OAUTH_TOUCH_FAILED`, `OAUTH_HOOK_FAILED`): the first of each hook or operation and code in full, the rest of the window counted into one summary line with `repeated` at its end or at close (1000..3600000) |
|
|
85
|
+
| `store.driver` | `memory` · `sql` · `redis` | `memory` | where grants, codes and registered clients live (§9) |
|
|
86
|
+
| `store.maxGrants` | integer | `100000` | memory: grants kept at once. Expired and revoked grants make room; **live grants are never dropped** — a new grant that does not fit is refused (503 `STORE_FULL`, warn `OAUTH_STORE_FULL`) |
|
|
87
|
+
| `store.maxGrantsPerUser` | integer | `100` | memory: live grants one user may hold over every client; beyond it a new grant is refused (`STORE_FULL`). `grant.maxPerClient` must not be above it |
|
|
88
|
+
| `store.maxCodes` | integer | `100000` | memory: authorization codes kept at once (each lives `codeMs`); beyond it the oldest go first (1..10000000) |
|
|
89
|
+
| `store.maxClients` | integer | `100000` | memory: dynamically registered clients kept at once; beyond it a registration is refused with 503 `STORE_FULL` (1..10000000) |
|
|
90
|
+
| `store.connection` | string | **required** for sql/redis | the dokebi-db connection (a pg, mysql2 or mariadb pool) or the dokebi-redis connection |
|
|
91
|
+
| `store.tablePrefix` | string | `dokebi_oauth` | sql: the tables `<prefix>_grants`, `<prefix>_codes`, `<prefix>_clients` |
|
|
92
|
+
| `store.namespace` | string | `dokebi` | redis: the key prefix (`<namespace>:oauth:…`) |
|
|
93
|
+
| `paths: { authorize, token, revoke, register }` | strings | `/oauth/authorize`, `/oauth/token`, `/oauth/revoke`, `/oauth/register` | endpoint paths (the metadata follows them) |
|
|
94
|
+
| `routeIds: { serverMetadata?, resourceMetadata?, authorize?, token?, revoke?, register? }` | strings | `oauth.<key>` | the route ids of the routes this plugin adds ([D-0142](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0142-plugin-route-ids.md)): `serverMetadata` GET `/.well-known/oauth-authorization-server`, `resourceMetadata` both protected resource metadata routes (one pair per app), `authorize` its GET and POST, `token`, `revoke`, `register`. `request.routeOptions.config.id`, `dokebi describe` `routes[].id` and the `routeId` of the refusal logs (`OAuth token refused`, …) show them. Set one when an app route has the id; an id taken by another route of the same app fails the start (`DUPLICATE_ROUTE_ID`, naming both) |
|
|
95
|
+
| `rateLimit.policy` | string | — | a @dokebi/rate-limit policy for POST /oauth/token, keyed by client and credential (claude.ai calls from a fixed address range: an address key would throttle everyone). Absent: no limit. Set without the plugin or with an unknown policy: `RATE_LIMIT_REQUIRED` at start |
|
|
96
|
+
|
|
97
|
+
The `defineOptions` declaration in `src/options.ts` is the parser; the build writes `options.schema.json` from it.
|
|
98
|
+
|
|
99
|
+
## 3. Endpoints
|
|
100
|
+
|
|
101
|
+
| Path | Meaning |
|
|
102
|
+
|---|---|
|
|
103
|
+
| `GET /.well-known/oauth-authorization-server` | RFC 8414 metadata, **derived from the options only**: `issuer`, the endpoints (`registration_endpoint` only when open), `response_types_supported: ["code"]`, `grant_types_supported: ["authorization_code", "refresh_token"]`, `code_challenge_methods_supported: ["S256"]`, `token_endpoint_auth_methods_supported: ["none", "client_secret_basic", "client_secret_post"]`, `scopes_supported` (all resources), `client_id_metadata_document_supported: true` (when CIMD is on), `authorization_response_iss_parameter_supported: true` |
|
|
104
|
+
| `GET /.well-known/oauth-protected-resource<path>` | RFC 9728 metadata of the resource whose URI has `<path>` (`https://h/mcp` → `/.well-known/oauth-protected-resource/mcp`): `resource` **exactly as configured** (never re-serialized: `new URL().href` adds a trailing `/` and breaks Claude's comparison), `authorization_servers: [issuer]`, `scopes_supported`, `bearer_methods_supported: ["header"]`, `resource_name`. Any other path under it: 404 `{ error: "not_found", error_description, resource_metadata: [every resource's metadata URL] }` (no log) |
|
|
105
|
+
| `GET /oauth/authorize` | the authorization request (§4) |
|
|
106
|
+
| `POST /oauth/authorize` | the consent decision of the app's page (§5); checked by @dokebi/csrf |
|
|
107
|
+
| `POST /oauth/token` | `authorization_code` and `refresh_token` (§6). `Cache-Control: no-store`. Errors are RFC 6749 bodies `{ error, error_description }` |
|
|
108
|
+
| `POST /oauth/revoke` | RFC 7009: a token of this server and this client revokes its whole grant; an unknown token or another client's token answers the same 200 and revokes nothing |
|
|
109
|
+
| `POST /oauth/register` | RFC 7591 when `registration: open` (public clients only); closed: 404 `{ error: "invalid_request", … }` |
|
|
110
|
+
|
|
111
|
+
**Hosts (D-0132).** Without `app` every endpoint answers on every host the server receives. In a project split into apps by host, `app` binds the authorization server (metadata, authorize with the consent page and its decision, token, revoke, register) to the issuer's app, and `resources.<id>.app` binds each resource's protected resource metadata to the app of its URI (RFC 9728 §3: the metadata lives at the origin of the resource identifier; RFC 8414 §3: the server metadata at the issuer's). Other hosts get the 404 of an unknown route. A resource without its own `app` follows `app`; resources on several apps get one pair of metadata routes per app, each serving only that app's resources (and those bound nowhere). The metadata itself never depends on the request host: `issuer`, the endpoints (`issuer` + path) and `authorization_servers` come from `issuer`, `resource` and the `resource_metadata` of the 401 challenge from the resource `uri`, so split hosts stay correct. At boot each published URL is checked against its apps: the issuer or a resource URI on a domain of another app fails the start (`INVALID_OPTIONS` naming the option to set), a host no domain names is warned (`OAUTH_HOST_UNMAPPED`, `where`, `host`, `apps`: a proxy may send another Host). The sign-in page is the app's own route (put it on the issuer's app). Example:
|
|
112
|
+
|
|
113
|
+
```yaml
|
|
114
|
+
dokebi-oauth:
|
|
115
|
+
issuer: https://studio.example.com
|
|
116
|
+
app: studio
|
|
117
|
+
resources:
|
|
118
|
+
mcp: { uri: https://mcp.example.com/mcp, app: mcp, scopes: { notes:read: Read your notes } }
|
|
119
|
+
dokebi-mcp: { app: mcp }
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
The metadata documents answer `Access-Control-Allow-Origin: *`. `/oauth/token`, `/oauth/revoke` and `/oauth/register` have `config: { csrf: false, auth: false }` and are never sealed (`seal: false`). The consent decision (`POST /oauth/authorize`) is a form of your app: on a seal host (`dokebi-app.domains.<host>.seal`) it is sealed like every form (a plain post gets 415 `SEAL_REQUIRED`), so the consent page writes `data.seal.head` (§5: `seal(request)` of @dokebi/app), never a copied seal `<script>` or import map (`dokebi check` warns `seal-head-copied`). An **Inertia consent page** posts the decision with Inertia's `router.post` instead (sealed by `sealInertia`; the answer is 409 `X-Inertia-Location`, an error such as `CONSENT_EXPIRED` renders the app's error page in place), not with `@dokebi/seal/forms`, whose HTML error answer would be the app's own shell (plugins/dokebi-seal AI.md §5.2). The plugin parses `application/x-www-form-urlencoded` bodies of its own routes itself (dokebi-web's `formBody` is not needed for them), so a **repeated parameter** is seen and refused (a framework parser keeps the last of `resource=A&resource=B` silently: the value checked and the value used could differ). Empty values count as omitted (RFC 6749 §3.1) but still count as a repeat.
|
|
123
|
+
|
|
124
|
+
**One resource comparison** decides everywhere (authorize, token, refresh, registration): scheme and host in lower case, the default port dropped, an empty path equal to `/` (RFC 3986 §6.2.3). The path, the query and their case are compared as they are. `resourceKey(uri)` and `sameResource(a, b)` are exported.
|
|
125
|
+
|
|
126
|
+
**Redirect URIs** are compared as exact strings — never by prefix, host or a normalized form. The one exception (RFC 8252 §7.3): on `127.0.0.1`, `[::1]` and `localhost` only the port may differ (native apps open a new port per login). `localhost` and `127.0.0.1` are different hosts. `redirectMatches(registered, presented)` is exported.
|
|
127
|
+
|
|
128
|
+
## 4. GET /oauth/authorize — the order of the checks is the contract
|
|
129
|
+
|
|
130
|
+
1. **client_id**: a pre-registered client, a registered (`dcr_…`) client, or a document URL (fetched and checked, §8). Unknown or refused: **400 page, no redirect** (`AUTHORIZE_REFUSED`).
|
|
131
|
+
2. **redirect_uri** must match a registered one exactly (§3). Otherwise: **400 page, no redirect** — a redirect to an unverified address is an open redirect.
|
|
132
|
+
3. The rest of the checks: `response_type` must be `code` (`unsupported_response_type`); `code_challenge` present (`invalid_request`), `code_challenge_method=S256` (plain or missing: `invalid_request`), 43 base64url characters. **Where the errors of steps 3-5 go depends on the client**: a **pre-registered** client gets them on its verified `redirect_uri` with `error`, `error_description`, `state` and `iss` (302, RFC 6749 §4.1.2.1). A **document or dynamically registered client** gets the **400 page** instead (`AUTHORIZE_REFUSED`, no redirect): anybody can publish a document or register a client, and redirecting their errors before the user decided would make this server an open redirector. Error descriptions are fixed sentences; nothing of the request (a scope, a parameter name that is not an OAuth parameter) is echoed.
|
|
133
|
+
4. **resource** required and one of `resources` by the comparison of §3 (`invalid_target`). Everything stored afterwards uses the configured resource, never the client's spelling.
|
|
134
|
+
5. **scope**: declared ones only (`invalid_scope`); none asked: the resource's `defaultScopes`.
|
|
135
|
+
6. **prompt** and **max_age** ([D-0122](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0122-studio-terminal-needs.md), OIDC Core §3.1.2.1, RFC 9470 §4): `prompt` may be `login` and/or `consent` (the consent page is always shown); `none`, `select_account` or anything else is `invalid_request`. `max_age` is whole seconds (`invalid_request` otherwise). They are checked here, before anything else happens.
|
|
136
|
+
7. **A fresh authentication** ([D-0124](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0124-auth-time-bearer-live-grant-per-device.md)) when `prompt=login`, or when `max_age` is given and the user's last authentication (dokebi-auth `request.auth.authenticatedAt()`: the sign-in, the sign-in behind a remember-me cookie, or a later confirmation) is older or unknown. The request waits in the session and remembers when it asked:
|
|
137
|
+
- **with dokebi-auth `reauthenticatePath`** (your re-authentication page) and a signed-in browser: 303 there through `request.auth.reauthenticate('/oauth/authorize?request=<id>')`. The user types the password (`confirmPassword`) or signs in again with their provider (`confirmSocial`), and your page sends them back with `takeReturnPath()`. **The session stays signed in** (other tabs, streams and the remember-me cookie too);
|
|
138
|
+
- **without that page** (or signed out): the D-0122 way — the browser session is signed out of the realm (`request.auth.logout()`: the remember-me cookie goes too, other tabs are signed out until the user signs in) and 303 to the login page as in step 8.
|
|
139
|
+
|
|
140
|
+
Back at the request, only an authentication newer than the moment it asked counts (to the second, the precision of a provider's `auth_time`); anything older — a session restored from a remember-me cookie, a page that came back without confirming — goes round once more. The **authentication time** (`auth_time`) of the tokens this request leads to is then `authenticatedAt()`, **exactly** (whole seconds). Without `max_age` and `prompt` the tokens carry `authenticatedAt()` as it is, or none when it is unknown (a remember-me cookie issued before D-0124).
|
|
141
|
+
8. **Login**: not signed in to the realm → the request waits in the session, `request.auth.rememberReturnPath('/oauth/authorize?request=<id>')` and 303 to the route's `loginPath`. After your login handler's `takeReturnPath()` the browser comes back to that short URL (the way back is in the session, never in a query).
|
|
142
|
+
9. **canDelegate(user, client)**: false → `access_denied` on the redirect for a pre-registered client, a 403 page (`FORBIDDEN`) for the others (the user has not decided yet).
|
|
143
|
+
10. The pending request is bound to the user (`pendingMs`, 10 minutes; at most `maxPending`, 5, per session; each request is its own session value `oauth:pending:<id>`, so requests opened at once in several tabs or by several clients all stay — a session's merged save keeps different keys; such requests may pass `maxPending` by their number until the next request opened trims the session) and **your consent page** renders (`renderConsent`), with `Cache-Control: no-store`, `X-Frame-Options: DENY`, `Content-Security-Policy: frame-ancestors 'none'` and `Referrer-Policy: no-referrer`.
|
|
144
|
+
|
|
145
|
+
`GET /oauth/authorize?request=<id>` alone resumes a pending request of this session (unknown or older than `pendingMs`: 400 `CONSENT_EXPIRED`).
|
|
146
|
+
|
|
147
|
+
## 5. The consent page and the decision
|
|
148
|
+
|
|
149
|
+
`renderConsent(request, reply, consent, context)` receives `OAuthConsent`:
|
|
150
|
+
|
|
151
|
+
| Field | Meaning |
|
|
152
|
+
|---|---|
|
|
153
|
+
| `id` | the consent request: post it back as `request` |
|
|
154
|
+
| `action` | where to post the decision (the authorize path) |
|
|
155
|
+
| `client` | `{ id, name, host, declaredName, kind }` (`OAuthClientInfo`). **Show `name` and `host`.** `name` is `clientName()` if it gave one, the configured name of a pre-registered client, else the host first with the self-declared name after it (`claude.ai (Claude)`): a self-declared name is never shown alone. `kind`: `document`, `registered` or `dynamic` |
|
|
156
|
+
| `redirectHost` | **show it**: where the code goes (MCP requires it). `redirectUri` is the full URI |
|
|
157
|
+
| `loopback` · `warning` | the redirect URI of **this request** is a loopback address (the answer goes to this computer); **show `warning`** when set (an English sentence) |
|
|
158
|
+
| `resource` | `{ id, uri, name }` |
|
|
159
|
+
| `scopes` | the requested scopes `{ name, label }` (`scopeLabel()` or the option label) |
|
|
160
|
+
| `userId` | the signed-in user's id |
|
|
161
|
+
| `grant` | what this user allowed this client for this resource before: the newest live grant of them (`{ id, scopes, kind, binding, expiresAt }`) to prefill the page, or undefined. Allowing makes a **new** grant (one per authorization, §9); that one stays |
|
|
162
|
+
| `expiresAt` | the request is gone after this |
|
|
163
|
+
| `fields` | the field names below |
|
|
164
|
+
|
|
165
|
+
The decision is a POST to `consent.action` with `request` (the id), `decision` (`allow` or `deny`), optionally `scope` (allowed names, repeated or space-separated; default all requested), `kind` (1-64 printable characters, your word for the connection) and `binding` (JSON text up to 4 KB, a hint of what the connection reaches), plus the CSRF field. An Inertia `router.post` sends the same names as JSON (`scope` a list, `binding` any JSON value).
|
|
166
|
+
|
|
167
|
+
- **`kind` and `binding` are user-submitted.** They are stored only through the `checkDecision(user, client, decision, context)` hook (§10), which validates them against what this user may reach and returns the accepted `{ kind, binding }` (or `false` to refuse). **Without the hook, a decision that carries a kind or a binding is refused** (400 `INVALID_CONSENT`). A stored binding is still a hint, not a permission: authorize it again on every use (`request.oauth.grant.binding` names a project → check that the user may open that project).
|
|
168
|
+
|
|
169
|
+
- `scope` must be a subset of the requested scopes: widening is 400 `INVALID_CONSENT`; allowing none of requested scopes is refused too. The pending request stays, so the page can be posted again correctly.
|
|
170
|
+
- Only the user the page was shown to decides (another sign-in: 403 `FORBIDDEN`; another session: 400 `CONSENT_EXPIRED`). A request is decided once, **on every worker**: the consent page sets a one-use decision ticket in the session (@dokebi/session `setOnce`, key `oauth:decide:<id>`, until the request expires) and the decision takes it (`takeOnce`, one store step), so a decision posted twice at once — to two workers or two servers on one session store — makes one grant and one code; the other answers 400 `CONSENT_EXPIRED`. A refused decision (`INVALID_CONSENT`) keeps the ticket. The tickets count against the session's `maxOnce` (16): keep `maxPending` at or below it. A session store without one-use values (an app store without `setOnce`/`takeOnce`) logs warn `OAUTH_DECIDE_NOT_ATOMIC` once and decides once per process only.
|
|
171
|
+
- `allow`: `checkDecision` (when it is there) judges kind and binding, `canDelegate` is asked again; a new grant is made (D-0124: one per authorization, an earlier grant is never changed; `grant.maxDays` from now, or the client's own `clients.<id>.grant.maxDays`; beyond `grant.maxPerClient` the least recently used one is revoked first, §9). A one-use code (32 random bytes, stored as sha256, `codeMs`) bound to the grant, client, redirect URI, PKCE challenge, resource and scopes goes back as `code`, `state`, `iss` (302).
|
|
172
|
+
- `deny`: `error=access_denied` (302). No grant.
|
|
173
|
+
- A request with `X-Inertia` gets **409 with `X-Inertia-Location`** instead of the 302: Inertia's XHR would follow a cross-origin 302 and stop silently.
|
|
174
|
+
|
|
175
|
+
```ts snippet
|
|
176
|
+
// src/infra/oauth/extension.ts — an EJS consent page with @dokebi/template-ejs and @dokebi/csrf
|
|
177
|
+
import type { AppGroupApi } from '@dokebi/app';
|
|
178
|
+
import type { PluginDependency } from '@dokebi/core';
|
|
179
|
+
import { dependency as csrf } from '@dokebi/csrf';
|
|
180
|
+
import {
|
|
181
|
+
type OAuthAcceptedDecision,
|
|
182
|
+
type OAuthClientInfo,
|
|
183
|
+
type OAuthConsent,
|
|
184
|
+
type OAuthDecision,
|
|
185
|
+
OAuthExtension,
|
|
186
|
+
type OAuthHookContext,
|
|
187
|
+
} from '@dokebi/oauth';
|
|
188
|
+
import type { FastifyReply, FastifyRequest } from 'fastify';
|
|
189
|
+
|
|
190
|
+
const views: PluginDependency<{ render(name: string, data: object): Promise<string> }> = {
|
|
191
|
+
name: 'dokebi-template-ejs',
|
|
192
|
+
version: '^0.4.0',
|
|
193
|
+
};
|
|
194
|
+
// data.seal of the app's pages: on a seal host the consent form is sealed like every form.
|
|
195
|
+
const apps: PluginDependency<AppGroupApi> = { name: 'dokebi-app', version: '^0.4.5' };
|
|
196
|
+
|
|
197
|
+
export default class AppOAuth extends OAuthExtension {
|
|
198
|
+
protected override dependencies(): readonly PluginDependency[] {
|
|
199
|
+
return [views, csrf, apps];
|
|
200
|
+
}
|
|
201
|
+
protected override async renderConsent(
|
|
202
|
+
request: FastifyRequest,
|
|
203
|
+
reply: FastifyReply,
|
|
204
|
+
consent: OAuthConsent,
|
|
205
|
+
context: OAuthHookContext,
|
|
206
|
+
) {
|
|
207
|
+
const token = await context.getDependency(csrf).token(request);
|
|
208
|
+
const seal = context.getDependency(apps).seal(request);
|
|
209
|
+
const html = await context
|
|
210
|
+
.getDependency(views)
|
|
211
|
+
.render('oauth/consent', { consent, csrf: token, seal });
|
|
212
|
+
return reply.type('text/html; charset=utf-8').send(html);
|
|
213
|
+
}
|
|
214
|
+
// The page may post binding = {"project": <id>}: accept it only for a project this user owns.
|
|
215
|
+
protected override async checkDecision(
|
|
216
|
+
user: { id: number },
|
|
217
|
+
client: OAuthClientInfo,
|
|
218
|
+
decision: OAuthDecision,
|
|
219
|
+
): Promise<OAuthAcceptedDecision | false> {
|
|
220
|
+
const project = (decision.binding as { project?: unknown } | null)?.project;
|
|
221
|
+
if (project === undefined) return { kind: null, binding: null };
|
|
222
|
+
if (typeof project !== 'number' || !(await projects.ownedBy(user.id, project))) return false;
|
|
223
|
+
return { kind: 'project', binding: { project } };
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
```ejs
|
|
229
|
+
<%# In the <head> of the page's layout: the seal forms module on a seal host, nothing elsewhere %>
|
|
230
|
+
<%- data.seal.head %>
|
|
231
|
+
<h1><%= data.consent.client.name %> wants to use <%= data.consent.resource.name %></h1>
|
|
232
|
+
<p>It sends the answer to <strong><%= data.consent.redirectHost %></strong>.</p>
|
|
233
|
+
<% if (data.consent.warning) { %><p class="warning"><%= data.consent.warning %></p><% } %>
|
|
234
|
+
<form method="post" action="<%= data.consent.action %>">
|
|
235
|
+
<input type="hidden" name="_csrf" value="<%= data.csrf %>">
|
|
236
|
+
<input type="hidden" name="request" value="<%= data.consent.id %>">
|
|
237
|
+
<% for (const scope of data.consent.scopes) { %>
|
|
238
|
+
<label><input type="checkbox" name="scope" value="<%= scope.name %>" checked> <%= scope.label %></label>
|
|
239
|
+
<% } %>
|
|
240
|
+
<button name="decision" value="allow">Allow</button>
|
|
241
|
+
<button name="decision" value="deny">Deny</button>
|
|
242
|
+
</form>
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
## 6. POST /oauth/token
|
|
246
|
+
|
|
247
|
+
Client authentication (RFC 6749 §2.3): a confidential client with `client_secret_basic` (Basic, the values form-urlencoded) or `client_secret_post`; a public client (`none`: a pre-registered client without a secret, a document client, a registered client) sends `client_id` only and no secret. Two methods at once is `invalid_request`; an unknown client, a wrong or missing secret, or a public client sending a secret is 401 `invalid_client` (with `WWW-Authenticate: Basic` after a Basic attempt).
|
|
248
|
+
|
|
249
|
+
- `grant_type=authorization_code`: `code`, `code_verifier`, `redirect_uri` (all required), `resource` (optional; must name the same resource). The code is read first: it must be of this client, `redirect_uri` the same string, the verifier must match (S256, constant time) and `resource` the same — **an attempt that does not match is refused without using the code** (a stranger cannot burn it). Then it is used **atomically, once**, must be unexpired, and the grant live. **The user is read again** (`findById`, then `canDelegate`), and the grant's **pending pair** must still be live for that user: an account suspended (`active: false`) or invalidated account-wide (a new stamp: password change, "log out other devices"; `tokens.revokeAll`) since the consent, or a grant revoked meanwhile, gets no token (`invalid_grant`). The pair is dokebi-auth's `tokens.pair(user, { family: grant.id, audience: <resource id>, accessMs, refreshMs, notAfter: grant end })`. **A matching second use of a code revokes its grant and every token it issued** (warn `OAUTH_CODE_REUSED`) — also when it races the first exchange. The tokens carry the code's scopes as dokebi-auth abilities (`dokebi-oauth:none` for a resource without scopes).
|
|
250
|
+
- `grant_type=refresh_token`: `refresh_token`, optional `resource` and `scope`. The token is looked at **before** it is used (`tokens.peek`): one of another client is `invalid_grant` and **its grant stays** (it was not consumed); a revoked or expired grant is `invalid_grant`. **The user is read again** and `canDelegate` asked: an account that is gone or may not delegate any more loses the grant (`invalid_grant`, info `OAUTH_GRANT_REVOKED` with `reason: cannot-delegate` or `user-gone`). **Narrowing** (RFC 6749 §6): `scope` may ask for a subset of the grant's scopes the refresh token holds — the new access token carries exactly that subset and the answer's `scope` says so; without `scope` the access token gets the grant's scopes the refresh token holds; the new refresh token keeps the refresh token's scopes. Asking for more is `invalid_scope`. Then dokebi-auth rotates it: a refresh token used before revokes the family, and this plugin revokes the grant (warn `OAUTH_REFRESH_REUSED`). The new tokens never outlive the grant (`notAfter`).
|
|
251
|
+
- Answer: `{ access_token, token_type: "Bearer", expires_in, refresh_token, scope? }`, `Cache-Control: no-store`, `Pragma: no-cache`.
|
|
252
|
+
- With `rateLimit`, each client and credential (code or refresh token) has a bucket; beyond it 429 `invalid_request` with `Retry-After`.
|
|
253
|
+
|
|
254
|
+
## 7. Protected routes and `request.oauth`
|
|
255
|
+
|
|
256
|
+
```ts snippet
|
|
257
|
+
// A resource of this app: a Bearer token issued for `mcp`, of a live grant that holds tools:write.
|
|
258
|
+
route.post('/mcp', handler, { config: { oauth: { resource: 'mcp', scopes: ['tools:write'] } } });
|
|
259
|
+
// In the handler:
|
|
260
|
+
const grant = request.oauth.grant; // OAuthGrant: id, userId, clientId, scopes, kind, binding, …
|
|
261
|
+
const user = await request.auth.user(); // the grant's user (dokebi-auth)
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
- `config.oauth` is `{ resource, scopes?, maxAge? }`: `resource` a key of `resources`, `scopes` declared by it, `maxAge` whole seconds (0..999999999). A wrong value fails the start (`INVALID_ROUTE_CONFIG` of dokebi-web, `details.problems`).
|
|
265
|
+
- Per request, before the route's own hooks: `api.of(request, { audience: resource, realm })` of dokebi-auth makes `request.auth` read `Authorization: Bearer` only (never the session) and accept **only tokens issued for that resource**; ordinary tokens (personal tokens, plain pairs) are refused there, and these tokens are refused on every other route (auth's two-way audience isolation). Then the user (stamp, `active`), then the grant (not revoked, not expired, the same resource; read per request with the `grantCacheMs` cache), then `canDelegate(user, client)` (when the hook is there; its yes is kept for `grantCacheMs` per grant, so it is no extra lookup per request), then `scopes` ⊆ the grant's scopes **and** the access token's (a refresh may have narrowed it). `lastUsedAt` of the grant is written at most once a minute, off the request path.
|
|
266
|
+
- No token or a bad one: 401 `UNAUTHENTICATED` with `WWW-Authenticate: Bearer resource_metadata="<metadata URL>", scope="<route scopes, else the resource's defaultScopes>"` (`error="invalid_token"` when a token was presented). Missing scopes: 403 `INSUFFICIENT_SCOPE` with `WWW-Authenticate: Bearer error="insufficient_scope", resource_metadata="…", scope="<needed>"`. The header travels with the error (an onError hook writes it), so no error responder loses it.
|
|
267
|
+
- `request.oauth` is `{ grant, resource, scopes, has(scope), authTime }` (`RequestOAuth`): `scopes` are the grant's that this access token holds; `authTime` when the user last authenticated before the consent of this token chain (a `Date`, exact to the second, see §4 step 7) or null when that was unknown; off protected routes `grant` and `resource` are undefined, `scopes` empty and `authTime` null.
|
|
268
|
+
- **The authentication time travels with each token chain**: as a reserved ability `dokebi-oauth:auth_time:<epoch seconds>` of its tokens, kept by every refresh, never shown as a scope (a grant is one authorization since D-0124, so its chain and it have one time; the mark stays on the tokens so that no table changed). There is no JWT or ID token: the routes of this app read it from `request.oauth.authTime`.
|
|
269
|
+
- **`maxAge` (RFC 9470)**: a route that needs a recent sign-in (a key export, a vault reset) declares `config: { oauth: { resource, maxAge: 300 } }`. A token whose sign-in is unknown or older is 401 `INSUFFICIENT_USER_AUTHENTICATION` with `WWW-Authenticate: Bearer error="insufficient_user_authentication", error_description="…", resource_metadata="…", max_age="300"`; the client opens the browser for `/oauth/authorize?…&max_age=300` (or `prompt=login`) and retries with the new token.
|
|
270
|
+
- `api.authenticate(request, { resource, scopes?, maxAge? })` runs the same check from your own hook (a WebSocket upgrade, an SSE `authenticate`, a route of an older scope); call it before anything reads `request.auth`.
|
|
271
|
+
- **Bearer streams: `api.live(request)`** (D-0122, [D-0124](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0124-auth-time-bearer-live-grant-per-device.md)). After `authenticate`, `await oauth.live(request)` returns an `OAuthLiveAuthorization` (`valid()`, `subscribe()`, `expiresAt`) to return as `identity.authorization`. It is dokebi-auth's Bearer lease (`request.auth.live({ check })`) with the grant (not revoked, not expired) and `canDelegate` in **the same check**: one read of the token row, the user and the grant per check. @dokebi/sse and @dokebi/websocket end the connection when it ends: **at the token's expiry instant** (or the grant's end), **at once** on a revocation through this process (`grants.revoke`, `revokeAll`, the client's `/oauth/revoke`, a code or refresh reuse, an eviction by `grant.maxPerClient`; dokebi-auth's `tokens.revokeFamily`, `revoke` and `logoutOtherDevices()` re-check at once too), and **within `live.maxAgeMs`** (5 s) on what this process does not see: a revocation in another process, an **account change** (a new stamp: a password change or "log out other devices" elsewhere; `active: false`; a deleted account) or a `canDelegate` that turned false. A check that fails or throws ends it (error `OAUTH_LIVE_CHECK_FAILED` for the grant read or the hook, `AUTH_LIVE_CHECK_FAILED` for the token or user read); one that hangs never extends it. A token that stopped being valid between the route check and `live()` is 401 `UNAUTHENTICATED`. `expiresAt` lets the app send its own "refresh now" event shortly before.
|
|
272
|
+
|
|
273
|
+
```ts snippet
|
|
274
|
+
// src/modules/term/events.ts — a Bearer event stream that ends with its token
|
|
275
|
+
sse.route({
|
|
276
|
+
path: '/term/events',
|
|
277
|
+
async authenticate(request) {
|
|
278
|
+
const grant = await oauth.authenticate(request, { resource: 'term' });
|
|
279
|
+
return { tenant: grant.userId, member: grant.id, authorization: await oauth.live(request) };
|
|
280
|
+
},
|
|
281
|
+
});
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
## 8. Clients
|
|
285
|
+
|
|
286
|
+
- **Client ID metadata documents** (`cimd.enabled`, default on): a `client_id` like `https://claude.ai/oauth/mcp-oauth-client-metadata` names a JSON document this server fetches at authorize time and caches (`max-age` within 5 minutes and 24 hours; 1 hour without; `no-store`/`no-cache`: 5 minutes).
|
|
287
|
+
- The URL: https, a path, no user information, no fragment, a host in `cimd.allowHosts` when set.
|
|
288
|
+
- **SSRF**: the address is checked in node:https's `lookup` hook, where the socket gets it (`agent: false`): every resolved address must be public — not loopback, private, link-local (169.254.169.254), CGNAT, documentation, benchmarking, multicast, reserved or an IPv6 special range (IPv4-compatible `::a.b.c.d` included); an IPv4-mapped IPv6 address is judged by its IPv4 address. Resolving first and fetching later was broken by DNS rebinding (XF S7). IP literals are checked on their own. `isPublicAddress(address)` is exported.
|
|
289
|
+
- No redirect is followed; 16 KB (the declared `Content-Length` and the bytes read); the whole fetch within `cimd.timeoutMs`; a JSON content type.
|
|
290
|
+
- The document: `client_id` equal to the URL, `redirect_uris` (1-32; https or loopback http), `grant_types` (when present) **containing** `authorization_code` — other values such as `urn:ietf:params:oauth:grant-type:jwt-bearer` (claude.ai) are fine —, `response_types` containing `code`, and the authentication methods intersected with this server's for documents (`none`): the plural `token_endpoint_auth_methods_supported` decides when present (ChatGPT's singular `private_key_jwt` next to `["none", "private_key_jwt"]` is accepted), else the singular one must be absent or `none`. `client_name` (at most 255) is shown after the host.
|
|
291
|
+
- A document client is public: at the token endpoint it is not fetched again (the code and the grant bind it).
|
|
292
|
+
- Limits: concurrent requests for one document share one fetch; at most 16 fetches run at once in a process and 2 per requesting address (IPv6 by /64); beyond that the page says the server is busy (warn `OAUTH_CIMD_BUSY`). A refused document is not fetched again for 5 minutes. The page only says that the client's document cannot be used; the reason and its cause (an errno, a parse error) go to the log (warn `OAUTH_CIMD_REFUSED` with the full `error`).
|
|
293
|
+
- `defineOAuthPlugin({ cimdFetch })` replaces the fetch (tests, an egress proxy): every response and document check still runs; the address checks are then the replacement's job.
|
|
294
|
+
- **Pre-registered** (`clients`): name, exact redirect URIs, optional `secretSha256`.
|
|
295
|
+
- **Dynamic registration** (`registration: open`): `POST /oauth/register` with JSON `{ redirect_uris, client_name?, grant_types?, response_types?, token_endpoint_auth_method? }` → 201 `{ client_id: "dcr_…", client_id_issued_at, client_name?, redirect_uris, grant_types, response_types, token_endpoint_auth_method: "none" }`. Only public clients; 20 per client address and hour (IPv6 by /64; per process, the buckets of at most 10,000 addresses, least recently used out first; 429 with `Retry-After`); a client unused for `clientUnusedMs` (30 days), and never before `refreshMs` after its last token request, is removed (`grants.purge()`, Redis by expiry). The memory store keeps at most 100,000 registered clients; to make room for a new registration it never drops one that holds a live grant (a registration that does not fit is 503 `temporarily_unavailable` with `Retry-After: 5`, the store's `STORE_FULL`). RFC 7591 errors: `invalid_redirect_uri`, `invalid_client_metadata`.
|
|
296
|
+
|
|
297
|
+
## 9. Grants and stores
|
|
298
|
+
|
|
299
|
+
A grant is `{ id, realm, userId, clientId, clientName, resource, scopes, kind, binding, createdAt, expiresAt, lastUsedAt, revokedAt }` (`OAuthGrant`; `binding` parsed JSON). `kind` and `binding` are the app's: the plugin only stores and hands them back. **The grant id is the dokebi-auth token family** of its tokens.
|
|
300
|
+
|
|
301
|
+
**One grant per authorization ([D-0124](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0124-auth-time-bearer-live-grant-per-device.md)).** Every allowed consent makes a new grant, and its code exchange starts that grant's own token family. Two devices that connect the same client hold two grants: `request.oauth.grant.id` tells them apart, `grants.revoke(id)` signs out one and leaves the other working, and `grants.list(user)` lists each device. What the user allowed before is offered again per user, client and resource (`consent.grant`, §5); allowing never changes an earlier grant. A grant's lifetime (`grant.maxDays`) starts at its own consent.
|
|
302
|
+
|
|
303
|
+
- **Bound**: at most `grant.maxPerClient` (20) live grants per user and client. A new authorization beyond it revokes, before its grant is stored, first the grants that never got a live token (a consent whose code was not exchanged within `codeMs`, or whose tokens all ended), oldest first, then the least recently used (`lastUsedAt`, written at most every `grantTouchMs`, else `createdAt`); the revoked grant's tokens and live streams end at once (info `OAUTH_GRANT_REVOKED` with `reason: evicted` or `unused`, warn `OAUTH_GRANT_EVICTED` for one that had a live token, once per client and `logRepeatWindowMs`). Evicting rather than refusing: the new device is the one the user is holding, and a refusal would leave it nothing to do but send the user to a page to sign another device out; the bound exists to stop a client that makes grants without end, and it only costs that client its own oldest connections of that user. Concurrent consents may pass the bound by their number.
|
|
304
|
+
- **Grants written before D-0124** need no migration (memory, sql and redis alike: the rows, tables and keys did not change). Each one is read as one authorization. Devices that already shared one (the old model: one per user, client and resource) keep sharing its token family: their tokens keep working, revoking that grant still ends all of them, and each of them gets its own grant the next time it authorizes. Nothing is split after the fact (the tokens do not say which device holds them).
|
|
305
|
+
- The store contract lost `updateGrant` (a consent no longer changes a grant).
|
|
306
|
+
|
|
307
|
+
| `api.grants` | Meaning |
|
|
308
|
+
|---|---|
|
|
309
|
+
| `list(user)` | the user's live grants: not revoked, not expired, **and with a live token** — after an account-wide invalidation (a new stamp: password change, "log out other devices"; `tokens.revokeAll`) a grant is neither usable nor listed. A grant whose code is not exchanged yet is listed too, until that code expires (`codeMs`): its token family holds the **pending pair**, a dokebi-auth pair issued at the consent (abilities `dokebi-oauth:pending`, `notAfter` = the code's end, its values never leave the plugin). Revoking it (or an account-wide invalidation) ends the code: the exchange answers `invalid_grant` |
|
|
310
|
+
| `revoke(id, user?)` | revokes a grant and its tokens (with `user`: only that user's); true when it was live |
|
|
311
|
+
| `revokeAll(user)` | every grant of the user; the number of those that were live (an expired grant is marked too, not counted) |
|
|
312
|
+
| `purge()` | deletes expired and revoked grants, codes `codeGraceMs` (10 minutes) past their end, registered clients unused for `clientUnusedMs` (30 days; at least `refreshMs`) (memory and sql; schedule it with @dokebi/scheduler); `{ grants, codes, clients }` |
|
|
313
|
+
|
|
314
|
+
| Store | Where | Notes |
|
|
315
|
+
|---|---|---|
|
|
316
|
+
| `memory` (default) | process memory | lost on restart; a cluster worker and production refuse it at start (`INVALID_OPTIONS`, ([D-0161](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0161-shared-state-redis.md))). Development, tests and `dokebi start`/`verify` on this machine (`DOKEBI_LOCAL_RUN=1`) |
|
|
317
|
+
| `sql` | `store.connection` of @dokebi/db: a pg, mysql2/promise or mariadb pool | PostgreSQL, MySQL, MariaDB; code use is one conditional `UPDATE … WHERE used_at IS NULL`. **Never DDL at start**: missing tables refuse the start (`TABLE_MISSING`). Not MongoDB (`UNSUPPORTED_RESOURCE`). The table check needs the database at start: name a `startup: required` dokebi-db connection (the default); an optional one that is down ([D-0127](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0127-optional-db-startup.md)) fails the start with the driver error. In describe mode (`dokebi describe`, D-0133) neither the pool probe nor the table check runs (a connection without `query` is still `UNSUPPORTED_RESOURCE`); a store call there rejects with `DESCRIBING` |
|
|
318
|
+
| `redis` | `store.connection` of @dokebi/redis | one JSON value per grant, code (sha256 key) and client, expiring with it; every write one Lua script |
|
|
319
|
+
|
|
320
|
+
### SQL tables
|
|
321
|
+
|
|
322
|
+
`oauthTableStatements(dialect, prefix?)` returns the statements (`'postgres'` or `'mysql'`, which MariaDB uses too); `dropOAuthTableStatements(prefix?)` the `down`. The migration `dokebi add` writes runs exactly these:
|
|
323
|
+
|
|
324
|
+
```sql
|
|
325
|
+
CREATE TABLE IF NOT EXISTS dokebi_oauth_grants (
|
|
326
|
+
id varchar(22) NOT NULL PRIMARY KEY, realm varchar(32) NOT NULL, user_id varchar(255) NOT NULL,
|
|
327
|
+
client_id text NOT NULL, client_name text NOT NULL, resource varchar(64) NOT NULL, scopes text NOT NULL,
|
|
328
|
+
kind varchar(64), binding text, created_at bigint NOT NULL, expires_at bigint NOT NULL,
|
|
329
|
+
last_used_at bigint, revoked_at bigint
|
|
330
|
+
);
|
|
331
|
+
CREATE INDEX IF NOT EXISTS dokebi_oauth_grants_user ON dokebi_oauth_grants (realm, user_id);
|
|
332
|
+
CREATE INDEX IF NOT EXISTS dokebi_oauth_grants_expires ON dokebi_oauth_grants (expires_at);
|
|
333
|
+
CREATE TABLE IF NOT EXISTS dokebi_oauth_codes (
|
|
334
|
+
code_hash varchar(43) NOT NULL PRIMARY KEY, grant_id varchar(22) NOT NULL, realm varchar(32) NOT NULL,
|
|
335
|
+
user_id varchar(255) NOT NULL, client_id text NOT NULL, redirect_uri text NOT NULL,
|
|
336
|
+
challenge varchar(43) NOT NULL, resource varchar(64) NOT NULL, scopes text NOT NULL,
|
|
337
|
+
created_at bigint NOT NULL, expires_at bigint NOT NULL, used_at bigint
|
|
338
|
+
);
|
|
339
|
+
CREATE INDEX IF NOT EXISTS dokebi_oauth_codes_expires ON dokebi_oauth_codes (expires_at);
|
|
340
|
+
CREATE TABLE IF NOT EXISTS dokebi_oauth_clients (
|
|
341
|
+
client_id varchar(64) NOT NULL PRIMARY KEY, name text NOT NULL, redirect_uris text NOT NULL,
|
|
342
|
+
created_at bigint NOT NULL, last_used_at bigint NOT NULL
|
|
343
|
+
);
|
|
344
|
+
CREATE INDEX IF NOT EXISTS dokebi_oauth_clients_used ON dokebi_oauth_clients (last_used_at);
|
|
345
|
+
-- MySQL and MariaDB: the same columns, ids and hashes CHARACTER SET ascii COLLATE ascii_bin,
|
|
346
|
+
-- text columns utf8mb4_bin, the indexes as KEY clauses, ENGINE=InnoDB (oauthTableStatements('mysql')).
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
## 10. Extension (D-0064): entry file `src/infra/oauth/extension.ts`
|
|
350
|
+
|
|
351
|
+
The entry's `default` is an `OAuthExtension` subclass (by hand: `createPlugin({ app, entry: { default: AppOAuth } })`). Hooks, all `protected`:
|
|
352
|
+
|
|
353
|
+
| Hook | Called | Default |
|
|
354
|
+
|---|---|---|
|
|
355
|
+
| `dependencies()` | once, when the plugin is created | `[]`: providers the hooks read through `context.getDependency` (the template engine, @dokebi/csrf) |
|
|
356
|
+
| `renderConsent(request, reply, consent, context)` | **required**; the consent page (§5) | none: `EXTENSION_REQUIRED` at start. It sends the page (or returns what the route answers); returning nothing without sending is a 500 `INVALID_HOOK_RESULT` |
|
|
357
|
+
| `canDelegate(user, client, context)` | before the consent, at the decision, at the code exchange, at every refresh (false revokes the grant) and on protected requests (once per `grantCacheMs` per grant); must return a boolean | `true` |
|
|
358
|
+
| `checkDecision(user, client, decision, context)` | at an `allow` decision: `decision` is `{ scopes, kind, binding }` (`OAuthDecision`, kind and binding as the browser posted them); return the accepted `{ kind?, binding? }` (`OAuthAcceptedDecision`, null or absent for none, checked again: kind 1-64 printable characters, binding JSON up to 4 KB) or `false` to refuse (400 `INVALID_CONSENT`); throwing an `OAuthError` answers it | refuses a decision that carries a kind or binding, accepts one without |
|
|
359
|
+
| `clientName(clientId, context)` | when the consent data is built; a name of 1-200 characters or undefined | undefined (host first, §5) |
|
|
360
|
+
| `scopeLabel(scope, request, context)` | per scope of the consent page (a translation); a string or undefined | undefined (the option label) |
|
|
361
|
+
|
|
362
|
+
`context` is `OAuthHookContext`: `{ realm, app, getDependency, logger, signal }`. No hook sees a code, a token, a secret, a PKCE verifier or the state, and no hook can widen what the user allowed. A hook that throws is logged (`OAUTH_HOOK_FAILED`) and answered 500 `HOOK_FAILED`.
|
|
363
|
+
|
|
364
|
+
## 11. API and exports
|
|
365
|
+
|
|
366
|
+
`createPlugin({ app, options?, entry })` and `defineOAuthPlugin({ cimdFetch? })`. The API (`app.get(plugin)`, or `context.getDependency(dependency)` with `dependency` from `@dokebi/oauth/dependency`, `OAuthApi`):
|
|
367
|
+
|
|
368
|
+
| Member | Meaning |
|
|
369
|
+
|---|---|
|
|
370
|
+
| `issuer` · `realm` · `resources` | the options (`resources`: the ids) |
|
|
371
|
+
| `grants` | §9 |
|
|
372
|
+
| `authenticate(request, { resource, scopes?, maxAge? })` | the protected-route check (§7); resolves to the `OAuthGrant` and sets `request.oauth` |
|
|
373
|
+
| `live(request)` | after `authenticate`: the `OAuthLiveAuthorization` of a Bearer SSE stream or WebSocket (§7, D-0122); `INVALID_ARGUMENT` on a request without such a token |
|
|
374
|
+
| `of(request)` | `request.oauth` |
|
|
375
|
+
| `metadataUrl(resource)` | the protected resource metadata URL of a resource (for a `WWW-Authenticate` of your own) |
|
|
376
|
+
| `resourceInfo(resource)` | the resource as configured, for a plugin that serves it (@dokebi/mcp): `{ id, uri, name, scopes, defaultScopes, metadataUrl }` (`OAuthResourceInfo`; `uri` verbatim, `scopes` the declared names with their labels) |
|
|
377
|
+
|
|
378
|
+
Other exports: `OAuthExtension` and `OAuthClientInfo`, `OAuthClientKind`, `OAuthConsent`, `OAuthDecision`, `OAuthAcceptedDecision`, `OAuthHookContext`; `OAuthError` (`OAuthErrorCode`), `OAuthProtocolErrorCode`; `options` and the option types; `OAuthApi`, `OAuthEntry`, `OAuthPluginSettings`, `OAuthResourceInfo`, `OAuthRouteSetting`, `RequestOAuth`, `OAuthGrant`, `OAuthGrants`, `OAuthLiveAuthorization`; `resourceKey`, `sameResource`, `redirectMatches`, `isPublicAddress`, `CimdFetch`, `CimdResponse`; the store contract (`OAuthStore`, `GrantRow`, `CodeRow`, `ClientRow`, `ConsumedCode`, `PurgeSettings`, `PurgeCounts`, `MemoryOAuthStore`) and `oauthTableStatements`, `dropOAuthTableStatements`, `SqlDialect`. `request.oauth` and `config.oauth` are typed through module augmentation of `fastify`.
|
|
379
|
+
|
|
380
|
+
## 12. Errors
|
|
381
|
+
|
|
382
|
+
`OAuthError` is a `DokebiError` (`plugin: 'dokebi-oauth'`): branch on `code`. No message, `data` or `details` carries a token, a code, a secret, a verifier or a state.
|
|
383
|
+
|
|
384
|
+
<!-- docs-check: complete-error-codes OAuthErrorCode -->
|
|
385
|
+
| Code | When |
|
|
386
|
+
|---|---|
|
|
387
|
+
| `INVALID_OPTIONS` | start: an http issuer or resource URI off localhost, a resource URI that is not absolute, two resources naming one resource or one metadata path, `defaultScopes` outside `scopes`, a client redirect URI that cannot be registered, a `dcr_` client id, a realm auth does not have, an unknown sql or redis connection; at boot (D-0132) the issuer or a resource URI on a domain of another app than the `app` that serves it (the message names the option to set) |
|
|
388
|
+
| `INVALID_ENTRY` | the entry module's shape (the extension class not `default`, a non-object) |
|
|
389
|
+
| `EXTENSION_REQUIRED` | creation: no extension or no `renderConsent` (`data.hooks`) |
|
|
390
|
+
| `INVALID_HOOK_RESULT` | a hook returned something unusable (`data.hook`): `dependencies`, `canDelegate` not a boolean, `checkDecision` not `{ kind?, binding? }` or `false` (or a bad kind or binding), `clientName`, `scopeLabel`, `renderConsent` sent nothing |
|
|
391
|
+
| `HOOK_FAILED` | a hook threw (`cause`; error log `OAUTH_HOOK_FAILED`) — 500 |
|
|
392
|
+
| `TABLE_MISSING` | start: `store.driver: sql` and a table does not exist (run the migration) |
|
|
393
|
+
| `UNSUPPORTED_RESOURCE` | start: `store.connection` is not a pg, mysql2/promise or mariadb pool (MongoDB) |
|
|
394
|
+
| `DESCRIBING` | a call of the sql store in a describing app (`dokebi describe` runs no query, D-0133) |
|
|
395
|
+
| `STORE_FAILED` | 503 with `Retry-After: 1` (`data.retryAfterMs`): the store did not answer (`cause`; error log `OAUTH_STORE_FAILED`). At `/oauth/token`, `/oauth/revoke` and `/oauth/register` the answer is RFC-shaped: 503 `temporarily_unavailable` with the same `Retry-After` |
|
|
396
|
+
| `STORE_INVALID` | the store returned a row of the wrong shape |
|
|
397
|
+
| `STORE_FULL` | 503: the memory store cannot take a new grant (`maxGrantsPerUser` of this user, or `maxGrants` live grants) or registered client (every one holds a live grant); `data.limit`; `Retry-After: 5` (`data.retryAfterMs`; at `/oauth/token`, `/oauth/revoke` and `/oauth/register` 503 `temporarily_unavailable`); warn `OAUTH_STORE_FULL` |
|
|
398
|
+
| `INVALID_ROUTE_CONFIG` | a request to a route whose `config.oauth` is wrong (the start fails before: web's `INVALID_ROUTE_CONFIG`) |
|
|
399
|
+
| `RATE_LIMIT_REQUIRED` | start: `rateLimit` without @dokebi/rate-limit, or with a policy it does not have |
|
|
400
|
+
| `AUTHORIZE_REFUSED` | 400 page of GET /oauth/authorize, never redirected: an unknown client, a refused document or too many document fetches at once, an unregistered redirect URI, a repeated parameter or a broken escape; and every error of a document or dynamically registered client before the user decided (§4) |
|
|
401
|
+
| `CONSENT_EXPIRED` | 400: the consent request is unknown in this session, older than `pendingMs` (10 minutes), or decided already |
|
|
402
|
+
| `INVALID_CONSENT` | 400: the decision widens the scopes, allows none, repeats a field, has a bad `decision`, `kind` or `binding`, carries a kind or binding without `checkDecision`, or `checkDecision` returned false |
|
|
403
|
+
| `FORBIDDEN` | 403: the consent is decided (or resumed) by another user than the one it was shown to; `canDelegate` said no before the decision for a client that is not pre-registered |
|
|
404
|
+
| `UNAUTHENTICATED` | 401 on a protected route: no token, or a token not valid for this resource (any reason; the reason is in the debug log). `WWW-Authenticate: Bearer resource_metadata=…` |
|
|
405
|
+
| `INSUFFICIENT_SCOPE` | 403 on a protected route: the grant lacks a route scope (`details.scopes` outside production) |
|
|
406
|
+
| `INSUFFICIENT_USER_AUTHENTICATION` | 401 on a route with `maxAge` (RFC 9470): the token's sign-in time is unknown or older (`details.maxAge`). `WWW-Authenticate: Bearer error="insufficient_user_authentication", …, max_age="<maxAge>"` |
|
|
407
|
+
| `INVALID_ARGUMENT` | an API call with a wrong argument: a grant call without a user object, `authenticate`, `metadataUrl` or `resourceInfo` with an unknown resource, a `maxAge` that is not whole seconds, `live()` on a request without an OAuth access token |
|
|
408
|
+
|
|
409
|
+
### Protocol error codes
|
|
410
|
+
|
|
411
|
+
RFC bodies `{ error, error_description }` of `/oauth/token`, `/oauth/revoke`, `/oauth/register`, and the `error` parameter of authorization redirects (`OAuthProtocolErrorCode`):
|
|
412
|
+
|
|
413
|
+
| `error` | Where and when |
|
|
414
|
+
|---|---|
|
|
415
|
+
| `invalid_request` | a missing or repeated parameter, a `prompt` other than `login` and `consent`, a `max_age` that is not whole seconds, a body that is not form-urlencoded, two client authentication methods, a missing PKCE challenge or plain PKCE; 429 of the rate limit or of registrations |
|
|
416
|
+
| `invalid_client` | 401: an unknown client, a wrong or missing secret, a public client sending one |
|
|
417
|
+
| `invalid_grant` | an unknown, used, expired or foreign code; a wrong verifier or redirect URI; a refresh token that is unknown, of another client, reused or of a revoked or expired grant; an account that is gone or cannot delegate any more (at a refresh this revokes the grant) |
|
|
418
|
+
| `unsupported_grant_type` | `grant_type` other than `authorization_code` and `refresh_token` |
|
|
419
|
+
| `unsupported_response_type` | authorize: `response_type` other than `code` |
|
|
420
|
+
| `invalid_scope` | an undeclared scope, no scope where the resource has no defaults, a refresh asking for more than was granted |
|
|
421
|
+
| `invalid_target` | `resource` missing, unknown, or different from the one of the code or token |
|
|
422
|
+
| `access_denied` | the user denied, or `canDelegate` said no (before the decision: pre-registered clients only) |
|
|
423
|
+
| `temporarily_unavailable` | 503 at `/oauth/token`, `/oauth/revoke` (RFC 7009 §2.2.1) and `/oauth/register` with `Retry-After`: the store did not answer (1 s) or is full for now (5 s); dokebi-auth's token store that did not answer (its `STORE_FAILED`, its `storeRetryAfterMs`) and the `rateLimit` policy's store that is down, full or closing (@dokebi/rate-limit `UNAVAILABLE`, `CAPACITY`, `CLOSED`: Redis stopped) are answered the same way, with their own Retry-After |
|
|
424
|
+
| `invalid_redirect_uri` · `invalid_client_metadata` | registration: a redirect URI that cannot be registered; a non-public method, missing `authorization_code` or `code`, a bad name or a body that is not JSON |
|
|
425
|
+
|
|
426
|
+
`unauthorized_client` and `server_error` are part of the type for completeness and not written by this version.
|
|
427
|
+
|
|
428
|
+
Related codes of other packages: `INVALID_ROUTE_CONFIG` (dokebi-web) for a wrong `config.oauth`; `UNAUTHENTICATED`, `LOGIN_THROTTLED` (dokebi-auth) — wrong Bearer tokens on protected routes count in auth's address bucket.
|
|
429
|
+
|
|
430
|
+
## 13. Logs
|
|
431
|
+
|
|
432
|
+
Never in a log line: tokens, codes, verifiers, states, secrets, cookies (tests search the captured logs for them).
|
|
433
|
+
|
|
434
|
+
| Level | Code or message | Fields |
|
|
435
|
+
|---|---|---|
|
|
436
|
+
| info | `OAUTH_GRANTED` | `realm`, `userId`, `clientId`, `grant`, `resource`, `scopes` |
|
|
437
|
+
| info | `OAUTH_DENIED` | `realm`, `userId`, `clientId`, `resource` |
|
|
438
|
+
| info | `OAUTH_GRANT_REVOKED` | `realm`, `userId`, `clientId`, `grant`, `reason` (`api`, `client`, `code-reused`, `refresh-reused`, `cannot-delegate`, `user-gone`, `evicted`, `unused`), `tokens`, `connections` (live Bearer connections it ended, when any) |
|
|
439
|
+
| warn | `OAUTH_GRANT_EVICTED` | `realm`, `userId`, `clientId`, `grant`, `max`: a new authorization of this user and client passed `grant.maxPerClient` and signed out the least recently used device (repeats counted per client) |
|
|
440
|
+
| info | `OAUTH_CLIENT_REGISTERED` | `clientId`, `redirectHosts` |
|
|
441
|
+
| warn | `OAUTH_CODE_REUSED` · `OAUTH_REFRESH_REUSED` | `realm`, `userId`, `clientId`, `grant` (repeats counted per grant) |
|
|
442
|
+
| warn | `OAUTH_CIMD_REFUSED` | `host`, `problem`, the full `error` with its cause (repeats counted per host and problem; a cached refusal is not logged again) |
|
|
443
|
+
| warn | `OAUTH_CIMD_BUSY` | `host` (document fetches at their limit; repeats counted) |
|
|
444
|
+
| warn | `OAUTH_STORE_FULL` | `store`, `operation`, `limit`, `max` (repeats counted) |
|
|
445
|
+
| warn | `OAUTH_CSRF_MISSING` | `fix` (once at start, without @dokebi/csrf) |
|
|
446
|
+
| warn | `OAUTH_DECIDE_NOT_ATOMIC` | `fix`, `error` (once: the session store has no one-use values, §5) |
|
|
447
|
+
| warn | `OAUTH_HOST_UNMAPPED` | `where` (`dokebi-oauth.issuer` or `dokebi-oauth.resources.<id>.uri`), `url`, `host`, `apps`, `unknownDomain`, `fix` (at boot, when bound: no domain of dokebi-app names that host, D-0132) |
|
|
448
|
+
| error | `OAUTH_STORE_FAILED` · `OAUTH_HOOK_FAILED` · `OAUTH_TOUCH_FAILED` · `OAUTH_STORE_CLOSE_FAILED` · `OAUTH_LIVE_CHECK_FAILED` | the full `error`; `store`, `operation`, `hook` or `resource` (a live check whose grant read or hook threw: the connection ends; repeats counted) |
|
|
449
|
+
| debug | `OAuth authorize refused` | `reason` (`repeated`, `encoding`, `unknown`, `document`, `redirect_uri`, an RFC code, `canDelegate`), `client` |
|
|
450
|
+
| debug | `OAuth authorize: re-authentication first` · `OAuth authorize: fresh sign-in first` · `OAuth authorize: fresh authentication seen` | `client`, `reason` (`prompt`, `max_age`, `again`) |
|
|
451
|
+
| debug | `OAuth grants made room` · `OAuth live authorization refused` | `clientId`, `live`, `max`, `evicted`; `resource`, `grant` |
|
|
452
|
+
| debug | `OAuth live authorization opened` · `OAuth live authorization ended` | `resource`, `grant`, `endsInMs`; `reason` (`expired`, `revoked`, `unconfirmed`), `listeners` |
|
|
453
|
+
| debug | `OAuth authorize: sign-in first` · `OAuth consent shown` · `OAuth client document fetched` | `client`, `resource`, `scopes`, `grant`; `host`, `bytes` |
|
|
454
|
+
| debug | `OAuth token refused` · `OAuth tokens issued` · `OAuth revocation` · `OAuth revocation refused` · `OAuth registration refused` | `grantType`, `error`, `reason`, `grant`, `clientId`, `revoked` |
|
|
455
|
+
| debug | `OAuth protected route refused` | `resource`, `reason` (`missing`, `token`, `grant-missing`, `grant-resource`, `grant-revoked`, `grant-expired`, `cannot-delegate`, `scope`, `auth-time-unknown`, `auth-time-old`), `maxAge` |
|
|
456
|
+
| debug | `OAuth setup finished` · `OAuth routes checked` · `OAuth SQL store ready` · `OAuth Redis store ready` · `OAuth store purged` | the resolved settings (no secret), `protected` routes, the dialect, the counts |
|
|
457
|
+
|
|
458
|
+
dokebi-auth logs its own lines too (`AUTH_TOKEN_ISSUED` with `audience`, `TOKEN_REUSED`, `Auth bearer token refused` with `reason: audience`).
|
|
459
|
+
|
|
460
|
+
## 14. Cautions
|
|
461
|
+
|
|
462
|
+
- Set `issuer` to the public https origin; behind a TLS-terminating proxy the app may see http, but the metadata always says `issuer`.
|
|
463
|
+
- The consent page decides what the user sees: show the client host, the redirect host and the warning. Never auto-allow from the page's script.
|
|
464
|
+
- Scopes are opaque to this plugin, and the tokens carry them as dokebi-auth abilities: `request.auth.can(ability)` on an OAuth request needs the ability among the token's scopes **and** your `authorize` hook (an OAuth token is never a `'*'` token). Routes check scopes through `config.oauth.scopes`.
|
|
465
|
+
- Revoking a grant, `revokeAll` or a new stamp ends its tokens at once in this process; other processes see a revoked grant within `grantCacheMs` and a revoked token within dokebi-auth's `cacheMs`. Open Bearer streams end only when they carry `api.live(request)` (§7).
|
|
466
|
+
- One grant per authorization (D-0124): `request.oauth.grant.id` is the device's connection; bind a device to it. Devices that shared a grant before D-0124 keep sharing it until they authorize again (§9).
|
|
467
|
+
- Set dokebi-auth `reauthenticatePath` when you use `prompt=login` or `max_age`: without it, `prompt=login` signs the browser out of the realm before the login page (D-0122), and a link with `prompt=login` that a stranger sends signs the user out — nothing else. With it the browser stays signed in and is only asked for the password (or the provider) again.
|
|
468
|
+
- With the memory store grants vanish on restart; use sql or redis with more than one process.
|
|
469
|
+
- Not supported yet: ChatGPT's `_meta["mcp/www_authenticate"]` scope step-up, a grace window for refresh reuse.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dokebi contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,42 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @dokebi/oauth
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An OAuth 2.1 authorization server for Dokebi web apps, so that AI clients such as Claude, ChatGPT, Claude Code or an MCP inspector can connect to a resource of your app on behalf of a signed-in user. It is built on [@dokebi/auth](https://git.nyx-zone.com/dokebi/framework/-/blob/main/plugins/dokebi-auth/README.md): the tokens are auth's opaque tokens (stored as hashes, revocable at once), one token family per grant, isolated by audience. Node >=24.0.0, @dokebi/core ^0.4.2. The design is [D-0091](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0091-oauth-authorization-server.md); the full contract is [AI.md](AI.md).
|
|
4
|
+
|
|
5
|
+
- Authorization code with PKCE S256 (required), refresh tokens with rotation and reuse detection, revocation (RFC 7009).
|
|
6
|
+
- Metadata derived from the options: authorization server (RFC 8414) and one protected resource document per resource (RFC 9728), the `iss` of every answer (RFC 9207), required resource indicators (RFC 8707) compared by one function.
|
|
7
|
+
- Clients: client ID metadata documents (fetched with an SSRF guard in the socket's lookup hook), pre-registered clients (public or with a hashed secret), and dynamic registration when you open it.
|
|
8
|
+
- Your consent page (EJS or Inertia) in `src/infra/oauth/extension.ts`; the plugin hands it the checked data (client host, redirect host, warning, scopes) and takes the decision.
|
|
9
|
+
- Protected routes: `config: { oauth: { resource: 'mcp', scopes: ['notes:write'] } }`, with `request.oauth.grant` in the handler and the `WWW-Authenticate: Bearer resource_metadata=…` challenge MCP clients follow.
|
|
10
|
+
- One grant per authorization (D-0124): every device that connects a client gets its own grant and token family (revoking one leaves the others), at most `grant.maxPerClient` (20) per user and client, the least recently used signed out beyond it. `prompt=login` and `max_age` use dokebi-auth's re-authentication page (`reauthenticatePath`) when the app has one, and `auth_time` is the exact authentication time; `api.live(request)` ends Bearer streams on account changes too.
|
|
11
|
+
- Grants per user: `api.grants.list(user)`, `revoke(id, user)`, `revokeAll(user)`; an account-wide invalidation (a new stamp) ends them, and a just-allowed grant whose code is not exchanged yet is listed and revocable.
|
|
12
|
+
- Stores: memory, sql (PostgreSQL, MySQL, MariaDB through @dokebi/db) and redis.
|
|
13
|
+
- Split hosts (D-0132): `app: studio` puts the authorization server on the issuer's app and `resources.<id>.app: mcp` each resource's metadata on its own app; every other host answers 404 like an unknown route, and the metadata names the right hosts ([examples/53-app-hosts](https://git.nyx-zone.com/dokebi/framework/-/blob/main/examples/53-app-hosts/README.md)).
|
|
14
|
+
|
|
15
|
+
Not provided: OpenID Connect, the implicit, password, client_credentials and device grants, introspection, JWT access tokens, `private_key_jwt`.
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
npx dokebi add @dokebi/oauth
|
|
19
|
+
npx dokebi add @dokebi/csrf
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
```yaml
|
|
23
|
+
options:
|
|
24
|
+
dokebi-oauth:
|
|
25
|
+
issuer: https://example.com
|
|
26
|
+
resources:
|
|
27
|
+
mcp:
|
|
28
|
+
uri: https://example.com/mcp
|
|
29
|
+
scopes: { 'notes:read': Read your notes }
|
|
30
|
+
defaultScopes: ['notes:read']
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
```ts snippet
|
|
34
|
+
// A protected resource route; the token must be issued for `mcp`.
|
|
35
|
+
route.post('/mcp', async (request) => ({ user: request.auth.id, grant: request.oauth.grant?.id }), {
|
|
36
|
+
config: { oauth: { resource: 'mcp' } },
|
|
37
|
+
});
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Every count, limit and time (document fetches and caches, registrations per address and window, pending requests, code grace, unused clients, body size, memory store sizes, Retry-After values, the repeat window of the logs) is an option with a minimum, a maximum and a default (D-0113 §5); the [AI guide](AI.md) has the table.
|
|
41
|
+
|
|
42
|
+
A runnable example of the whole flow over real HTTP is [examples/44-oauth](https://git.nyx-zone.com/dokebi/framework/-/blob/main/examples/44-oauth/README.md).
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** A Map that keeps at most `max` entries, dropping the least recently used one. */
|
|
2
|
+
export declare class LruMap<K, V> {
|
|
3
|
+
#private;
|
|
4
|
+
constructor(max: number);
|
|
5
|
+
get(key: K): V | undefined;
|
|
6
|
+
set(key: K, value: V): void;
|
|
7
|
+
delete(key: K): void;
|
|
8
|
+
get size(): number;
|
|
9
|
+
}
|