@softistx/alxia-clavix 0.3.2 → 0.4.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.
@@ -52,8 +52,8 @@ extensions. Scopes are non-empty strings without spaces or quotes; give at least
52
52
  ## 401 reasons
53
53
 
54
54
  `missing` (no token), `malformed`, `issuer`, `audience`, `type`, `signature`, `algorithm`, `expired`,
55
- `not_yet_valid`, `key`, `keys_unavailable`, `claims`, and with DPoP (RFC 9449): `dpop_required`,
55
+ `not_yet_valid`, `key`, `claims`, and with DPoP (RFC 9449): `dpop_required`,
56
56
  `dpop_unsupported`, `dpop_malformed`, `dpop_unbound`, `dpop_proof_*` (the check of the proof that failed) and `dpop_nonce`.
57
57
  The challenge follows the scheme: `Bearer error="invalid_token"` for a bearer token, `DPoP
58
58
  error="invalid_token"`, `invalid_dpop_proof` or `use_dpop_nonce` (with `algs` and a `DPoP-Nonce`
59
- header) for the DPoP ones. See [Troubleshooting](../troubleshooting.md).
59
+ header) for the DPoP ones. `keys_unavailable` (the issuer's keys cannot be fetched) is a `503`, not a 401. See [Troubleshooting](../troubleshooting.md).
@@ -0,0 +1,140 @@
1
+ # Wiring an API to Clavix
2
+
3
+ An API that moves to Clavix as its identity provider writes three things: its environment, a resource,
4
+ and a mapping from the verified token to its own viewer. The package does the rest.
5
+
6
+ ## 1. The environment
7
+
8
+ `@softistx/alxia-clavix/env` reads the `CLAVIX_*` variables once, at start-up. A wrong or partial set
9
+ stops the process with one `ClavixEnvError` that names every refused variable (never a value or a path).
10
+ It needs `zod`, an optional peer of the package.
11
+
12
+ ```ts
13
+ import { clavixEnv } from '@softistx/alxia-clavix/env';
14
+
15
+ // the API verifies Clavix access tokens: issuer, audience and origin are required
16
+ export const clavixSettings = clavixEnv({ resource: true });
17
+ ```
18
+
19
+ | Variable | Field | Meaning |
20
+ | --- | --- | --- |
21
+ | `CLAVIX_ISSUER` | `issuer` | the tenant's issuer, `https` (`http` on localhost outside production) |
22
+ | `CLAVIX_AUDIENCE` | `audience` | the API's identifier at Clavix: a token's `aud` must contain it |
23
+ | `CLAVIX_API_ORIGIN` | `origin` | the public origin of the API (scheme and host, no path), what a DPoP proof's `htu` starts with; `https` in production |
24
+ | `CLAVIX_SCOPE` | `scope` | the scope every token must carry (optional) |
25
+ | `CLAVIX_CLIENT_ID`, `CLAVIX_CLIENT_SECRET_FILE` | `clientId`, `clientSecretFile` | the client registered with Clavix, for "Sign in with Clavix": both or neither |
26
+ | `CLAVIX_WEBHOOK_SECRET_FILE` | `webhookSecretFile` | the webhook signing secret (optional) |
27
+ | `CLAVIX_MACHINE_CLIENT_ID`, `CLAVIX_MACHINE_SECRET_FILE` | `machineClientId`, `machineSecretFile` | the machine client that calls Clavix's management API: both or neither |
28
+
29
+ - A `*_FILE` variable holds the **path** of a file, never the secret. It is refused, by name, when it
30
+ points at a directory, a missing or unreadable file, an empty one, or one readable by group or others (use `chmod 600`, see below). The content is read only to check
31
+ it is not blank; `clavixEnv()` returns the paths.
32
+ - **Mounting the secret**: the mode must be owner-only. The error is
33
+ `CLAVIX_CLIENT_SECRET_FILE is readable by group or others (mode 644); restrict it to its owner, such as chmod 600`.
34
+ On Kubernetes set `defaultMode: 0400` on the secret volume; on Docker Compose or Swarm set `mode: 0400`
35
+ on the secret (the file must also belong to the user the API runs as).
36
+ - An empty variable counts as unset.
37
+ - `production` (default: `NODE_ENV === 'production'` of the source) requires an `https` origin.
38
+ - `source` replaces `process.env`, for a spec.
39
+
40
+ To keep one `z.object` for the whole app, compose the shape instead; the cross-variable rules stay
41
+ `clavixEnv()`'s:
42
+
43
+ ```ts
44
+ import { clavixEnvShape } from '@softistx/alxia-clavix/env';
45
+ import { z } from 'zod';
46
+
47
+ const env = z.object({ PORT: z.coerce.number(), ...clavixEnvShape() }).parse(process.env);
48
+ ```
49
+
50
+ ## 2. The resource
51
+
52
+ ```ts
53
+ import { alxia } from '@softistx/alxia';
54
+ import { clavixResource } from '@softistx/alxia-clavix';
55
+ import { redisDpopReplayStore } from '@softistx/alxia-redis';
56
+ import { connectRedis } from '@softistx/redis';
57
+
58
+ const redis = await connectRedis(Bun.env['REDIS_URL']!);
59
+ // `accounts` stands for the app's own store of accounts
60
+ const resource = clavixResource({
61
+ issuer: clavixSettings.issuer,
62
+ audience: clavixSettings.audience,
63
+ origin: clavixSettings.origin,
64
+ scope: clavixSettings.scope,
65
+ replay: redisDpopReplayStore(redis.client, { name: 'myapp:dpop' }), // shared by every instance
66
+ viewerOf: async (principal) => {
67
+ const account = await accounts.find(principal.subject);
68
+ return account?.active === false ? null : { id: principal.subject, name: account?.name ?? '' };
69
+ },
70
+ });
71
+
72
+ alxia()
73
+ .use(resource.viewer)
74
+ .get('/me', ({ viewer, reply }) => reply(200, { viewer }))
75
+ .listen(3000);
76
+ ```
77
+
78
+ `viewerOf(principal)` is all the app writes. It gets the verified `ClavixPrincipal` (`subject`, `tenant`,
79
+ `issuer`, `scopes`, `claims`, …) and returns the app's viewer, or `null` for an account that is inactive
80
+ (disabled, erased).
81
+
82
+ `resource.viewer` is a middleware that adds `viewer` (typed `Viewer | null`) to every route after it:
83
+
84
+ | Request | Answer |
85
+ | --- | --- |
86
+ | no `Authorization` header (or a route `carries` excludes) | goes on, `viewer: null`; a route that needs one refuses |
87
+ | a token or proof the guard refuses | 401 with the guard's `reason` (`signature`, `expired`, `dpop_proof_replay`, …), its `WWW-Authenticate` and `DPoP-Nonce` |
88
+ | a valid token without `scope` (one token, no spaces) | 403 `insufficient_scope`, with its `WWW-Authenticate` challenge |
89
+ | `viewerOf` returns `null` | 401 `inactive`, no challenge: refreshing the token would not help |
90
+ | the issuer's keys cannot be fetched | 503 `keys_unavailable` |
91
+ | the replay store or `viewerOf` throws | 503 `unavailable`, after `onError(error)` |
92
+ | a route or resolver throws after the viewer is known | not caught here: it is the route's error, never an outage |
93
+
94
+ A 503 is never a 401: a BFF reads a 401 as an expired session and signs everyone out.
95
+
96
+ Options beyond the four above:
97
+
98
+ - `carries(request)`: the routes that carry a viewer; the others (probes, webhooks) go on anonymous and
99
+ their `Authorization` header is not read. Every route by default.
100
+ - `body({ status, reason })`: the JSON body of every refusal, in the API's own error shape, also under `alxia({ errors: 'problem' })`. Left out, the
101
+ guard's `{ error, reason }` is kept, and RFC 9457 problems under `alxia({ errors: 'problem' })`.
102
+ - `onError(error)`: log what a store or `viewerOf` threw.
103
+ - `nonce`: a `hmacDpopNonce(...)` server nonce for the proofs.
104
+ - `tenant`: the tenant name of the issuer (the first label of its host by default).
105
+
106
+ ## 3. Streams and readiness
107
+
108
+ ```ts
109
+ import { health } from '@softistx/alxia';
110
+
111
+ alxia().plugin(health({ checks: { clavix: resource.ready } }));
112
+
113
+ // a subscription or a WebSocket upgrade, from its own request
114
+ const viewer = await resource.streamViewer(request);
115
+ ```
116
+
117
+ `streamViewer(request)` judges the token as a route does (signature, `iss`, `aud`, `exp`, scope) and calls
118
+ `viewerOf`. A token bound to a key (`cnf.jkt`) needs the `DPoP` scheme and a proof for that request, whose
119
+ `jti` is spent once; an unbound token needs the `Bearer` scheme. It answers `null` for any refusal (a
120
+ bound token without its proof included), and a `viewerOf` that throws propagates. A client that sends the
121
+ token in a connection message, not in the upgrade request's headers, is
122
+ [#999](https://github.com/softistx/alxia/issues/999).
123
+
124
+ ## Types
125
+
126
+ `ClavixResource<Viewer>`, `ClavixResourceOptions<Viewer>`, `ClavixViewerContext<Viewer>` (what a route
127
+ reads: `{ viewer: Viewer | null }`), `ClavixViewerMiddleware<Viewer>`, `ClavixRefusal`, `ViewerOf<Viewer>`;
128
+ from `/env`: `ClavixEnv`, `ClavixResourceEnv`, `ClavixEnvOptions`, `ClavixEnvIssue`, `ClavixEnvSource`, `ClavixEnvError`.
129
+
130
+ ## Development without Redis
131
+
132
+ `memoryDpopReplayStore()` (exported by this package) keeps replayed proofs in the process. It is for
133
+ development and tests only: with two instances, or after a restart, a proof can be replayed. Use it when
134
+ Redis is absent instead of writing a fallback of your own; production keeps `redisDpopReplayStore`.
135
+
136
+ ## Behind a proxy
137
+
138
+ `origin` is configuration, never read from `Host` or `X-Forwarded-*`. A proxy that strips a path prefix
139
+ is [#993](https://github.com/softistx/alxia/issues/993); `clavixResource` passes `origin` to `dpop` and gets that
140
+ fix when it ships.
package/docs/roadmap.md CHANGED
@@ -26,6 +26,8 @@ Nothing scheduled yet.
26
26
 
27
27
  ### Unreleased
28
28
 
29
+ - **An API on Clavix in a few lines.** `clavixResource({ viewerOf })` gives the verifier, the DPoP replay store, a `viewer` middleware (401, 403 and 503 told apart) and a stream viewer, and `clavixEnv()` from `@softistx/alxia-clavix/env` reads the `CLAVIX_*` variables eagerly, refusing each wrong one by name. The app writes only `viewerOf`.
30
+
29
31
  - **DPoP proofs checked.** `clavix({ dpop })` accepts the `DPoP` scheme and verifies each proof
30
32
  (`typ`, ES256 or EdDSA, `htm`, `htu` from the public origin, fresh `iat`, single-use `jti`, `ath`,
31
33
  key thumbprint equal to `cnf.jkt`), with an optional `DPoP-Nonce` and `WWW-Authenticate: DPoP`
@@ -21,6 +21,7 @@ startup (`verify` never throws), or the body of a 401 or 403.
21
21
  - [`TypeError: clavix: dpop.clockSkewSec must be a finite number, 0 or more`](#typeerror-clavix-dpopclockskewsec-must-be-a-finite-number-0-or-more)
22
22
  - [`TypeError: clavix: the dpop nonce secret needs 16 characters`](#typeerror-clavix-the-dpop-nonce-secret-needs-16-characters)
23
23
  - [`TypeError: clavix: the dpop nonce ttlMs must be a finite number above 0`](#typeerror-clavix-the-dpop-nonce-ttlms-must-be-a-finite-number-above-0)
24
+ - [`Invalid CLAVIX_* environment`](#invalid-clavix_-environment)
24
25
  - [`TypeError: requireScope: give scopes, each a non-empty token without spaces or quotes`](#typeerror-requirescope-give-scopes-each-a-non-empty-token-without-spaces-or-quotes)
25
26
 
26
27
  **Responses**
@@ -33,11 +34,13 @@ startup (`verify` never throws), or the body of a 401 or 403.
33
34
  - [`401 … "reason": "malformed"`](#401-reason-malformed)
34
35
  - [`401 … "reason": "claims"`](#401-reason-claims)
35
36
  - [`401 … "reason": "expired"` or `"not_yet_valid"`](#401-reason-expired-or-not_yet_valid)
36
- - [`401 … "reason": "key"` or `"keys_unavailable"`](#401-reason-key-or-keys_unavailable)
37
+ - [`401 … "reason": "key"`, and the 503 `keys_unavailable`](#401-reason-key-and-503-keys_unavailable)
37
38
  - [`401 … "reason": "dpop_required"`, `"dpop_unsupported"`, `"dpop_malformed"` or `"dpop_unbound"`](#401-reason-dpop_required-dpop_unsupported-dpop_malformed-or-dpop_unbound)
38
39
  - [`401 … "reason": "dpop_proof_*"`](#401-reason-dpop_proof_)
39
40
  - [`401 … "reason": "dpop_nonce"`](#401-reason-dpop_nonce)
40
41
  - [`500` on a request with a DPoP proof](#500-on-a-request-with-a-dpop-proof)
42
+ - [`503 { "error": "unavailable", "reason": "unavailable" }` from `clavixResource().viewer`](#503-unavailable-from-clavixresourceviewer)
43
+ - [`401 … "reason": "inactive"` from `clavixResource().viewer`](#401-inactive-from-clavixresourceviewer)
41
44
  - [`403 { "error": "forbidden", "reason": "insufficient_scope" }`](#403-insufficient_scope)
42
45
 
43
46
  **Traps**
@@ -148,6 +151,23 @@ Give `dpop.replay`: `redisDpopReplayStore(connection.client, { name: 'dpop' })`
148
151
 
149
152
  `hmacDpopNonce({ ttlMs })` takes a finite number of milliseconds above 0 (default 300000, 5 minutes).
150
153
 
154
+ ### `Invalid CLAVIX_* environment`
155
+
156
+ `clavixEnv()` (from `@softistx/alxia-clavix/env`) throws a `ClavixEnvError` at start-up, one line per
157
+ refused variable, never a value or a path:
158
+
159
+ | Line | Fix |
160
+ | --- | --- |
161
+ | `CLAVIX_ISSUER: …` | an `https` URL (`http` on localhost outside production) |
162
+ | `CLAVIX_API_ORIGIN: …` | scheme and host only, no path or trailing slash; `https` in production |
163
+ | `CLAVIX_ISSUER`, `CLAVIX_AUDIENCE` or `CLAVIX_API_ORIGIN`: `required` | set it: the API verifies Clavix tokens (`resource: true`) |
164
+ | `CLAVIX_*_SECRET_FILE points at a directory, not a file` | the variable holds the path of the secret file; mount the file, not its folder |
165
+ | `… is readable by group or others (mode 644); restrict it to its owner, such as chmod 600` | `chmod 600` the file; Kubernetes: `defaultMode: 0400` on the secret volume; Compose or Swarm: `mode: 0400` on the secret |
166
+ | `… points at an empty file` | the secret file has no content: write the secret to it |
167
+ | `… points at a file that does not exist or cannot be reached` or `cannot be read` | check the path and the file's owner and mode |
168
+ | `CLAVIX_ISSUER: required when … are set` | a client id or machine client needs the issuer it registered with |
169
+ | `… unset while … is set` | the client id and its secret file go together, as do the machine client's |
170
+
151
171
  ### `TypeError: requireScope: give scopes, each a non-empty token without spaces or quotes`
152
172
 
153
173
  `requireScope()` got no scope, or one with a space, a quote or a backslash. One argument per scope:
@@ -200,10 +220,11 @@ are `malformed`, not `claims`.
200
220
  The token's `exp` has passed, or its `nbf` is in the future. Refresh the token, or check the
201
221
  clocks; `clockTolerance` (seconds) allows for small skew.
202
222
 
203
- ### 401 reason `key` or `keys_unavailable`
223
+ ### 401 reason `key`, and 503 `keys_unavailable`
204
224
 
205
225
  `key`: no published key matches the token's `kid` (after one refetch). `keys_unavailable`: the issuer's
206
- keys could not be fetched and none is cached. Check that the issuer's discovery document is reachable
226
+ keys could not be fetched and none is cached; the guard answers `503 {"error":"unavailable","reason":"keys_unavailable"}` with no
227
+ `WWW-Authenticate` (never a 401, so a BFF does not read it as an expired session). Check that the issuer's discovery document is reachable
207
228
  from the API (egress, DNS, `timeoutMs`). See
208
229
  [`@softistx/alxia-jwt`'s JWKS guide](https://github.com/softistx/alxia/blob/develop/packages/jwt/docs/guide/jwks.md).
209
230
 
@@ -252,6 +273,21 @@ Check the Redis connection (`/ready`, the `connectRedis` handle); `Bearer` token
252
273
  are not affected. `memoryDpopReplayStore` throws `memoryDpopReplayStore: full (use a shared store)`
253
274
  past `maxEntries` live proofs: use a shared store.
254
275
 
276
+ ### 503 `unavailable` from `clavixResource().viewer`
277
+
278
+ ```json
279
+ { "error": "unavailable", "reason": "unavailable" }
280
+ ```
281
+
282
+ The replay store (Redis) or the app's `viewerOf` threw, so the request was not judged. It is an
283
+ outage, not a refusal: check the store, and the `onError` log. With the bare `bearer()` guard the same
284
+ failure is a 500; `clavixResource` answers a 503. A 503 `keys_unavailable` is the issuer's keys.
285
+
286
+ ### 401 `inactive` from `clavixResource().viewer`
287
+
288
+ `viewerOf` returned `null`: the token is valid but the app's account is disabled or erased. There is
289
+ no `WWW-Authenticate`, since a new token would not help.
290
+
255
291
  ### 403 `insufficient_scope`
256
292
 
257
293
  ```json
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@softistx/alxia-clavix",
3
- "version": "0.3.2",
3
+ "version": "0.4.0",
4
4
  "description": "Verify the access tokens an OpenID Connect identity provider issues in an alxia API: a multi-tenant issuer allow-list on the RFC 9068 profile of @softistx/alxia-jwt",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -19,6 +19,11 @@
19
19
  "import": "./dist/index.js",
20
20
  "default": "./dist/index.js"
21
21
  },
22
+ "./env": {
23
+ "types": "./dist/env/index.d.ts",
24
+ "import": "./dist/env/index.js",
25
+ "default": "./dist/env/index.js"
26
+ },
22
27
  "./package.json": "./package.json"
23
28
  },
24
29
  "repository": {
@@ -37,17 +42,25 @@
37
42
  },
38
43
  "alxia": {
39
44
  "entrypoints": [
40
- "src/index.ts"
45
+ "src/index.ts",
46
+ "src/env/index.ts"
41
47
  ]
42
48
  },
43
49
  "devDependencies": {
44
50
  "@softistx/alxia": "^0.29.1",
45
- "@softistx/alxia-jwt": "^0.10.2",
46
- "@types/bun": "^1.4.5"
51
+ "@softistx/alxia-jwt": "^0.11.0",
52
+ "@types/bun": "^1.4.5",
53
+ "zod": "^4.2.0"
47
54
  },
48
55
  "peerDependencies": {
49
56
  "@softistx/alxia": "^0.29.1",
50
- "@softistx/alxia-jwt": "^0.10.2",
51
- "typescript": "^6.0.3 || ^7.0.0"
57
+ "@softistx/alxia-jwt": "^0.11.0",
58
+ "typescript": "^6.0.3 || ^7.0.0",
59
+ "zod": "^4.2.0"
60
+ },
61
+ "peerDependenciesMeta": {
62
+ "zod": {
63
+ "optional": true
64
+ }
52
65
  }
53
66
  }