@softistx/alxia-clavix 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +85 -2
- package/dist/clavix.d.ts +79 -0
- package/dist/clavix.d.ts.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +283 -0
- package/dist/index.js.map +15 -0
- package/dist/issuers.d.ts +19 -0
- package/dist/issuers.d.ts.map +1 -0
- package/dist/lru.d.ts +10 -0
- package/dist/lru.d.ts.map +1 -0
- package/dist/principal.d.ts +25 -0
- package/dist/principal.d.ts.map +1 -0
- package/dist/scope.d.ts +30 -0
- package/dist/scope.d.ts.map +1 -0
- package/dist/unverified-issuer.d.ts +3 -0
- package/dist/unverified-issuer.d.ts.map +1 -0
- package/docs/README.md +14 -0
- package/docs/guide/issuers-and-tenants.md +70 -0
- package/docs/guide/principal-and-scopes.md +55 -0
- package/docs/guide/readiness.md +31 -0
- package/docs/guide/security.md +42 -0
- package/docs/roadmap.md +31 -0
- package/docs/troubleshooting.md +182 -0
- package/package.json +52 -5
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Steve Tsala
|
|
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,86 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @softistx/alxia-clavix
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> Moved from `@alxia/clavix`: see the [migration guide](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/migrating-from-alxia-scope.md).
|
|
4
|
+
|
|
5
|
+
Verify the access tokens Clavix (an OpenID Connect identity provider) issues in an
|
|
6
|
+
[alxia](https://www.npmjs.com/package/@softistx/alxia) API: a multi-tenant issuer allow-list on the
|
|
7
|
+
RFC 9068 profile of `@softistx/alxia-jwt`. A token is checked with the keys of its own issuer, but only an
|
|
8
|
+
issuer you allow is ever fetched from. Routes read a typed principal (`subject`, `tenant`, `scopes`, …)
|
|
9
|
+
and guard themselves with `requireScope`.
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
bun add @softistx/alxia-clavix @softistx/alxia-jwt @softistx/alxia
|
|
13
|
+
bun add -d typescript
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Example
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { alxia, health } from '@softistx/alxia';
|
|
20
|
+
import { clavix, requireScope } from '@softistx/alxia-clavix';
|
|
21
|
+
|
|
22
|
+
const auth = clavix({
|
|
23
|
+
domain: 'clavix.example.com', // https://<tenant>.clavix.example.com is allowed
|
|
24
|
+
audience: 'https://api.example.com',
|
|
25
|
+
warm: ['https://acme.clavix.example.com'], // /ready waits for these issuers' keys
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
alxia()
|
|
29
|
+
.plugin(health({ checks: { clavix: auth.ready } }))
|
|
30
|
+
.use(auth.bearer())
|
|
31
|
+
.get('/invoices', requireScope('invoices:read'), ({ user, reply }) =>
|
|
32
|
+
reply(200, { tenant: user.tenant, subject: user.subject }),
|
|
33
|
+
)
|
|
34
|
+
.listen(3000);
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
A request without a valid token is a 401 `{ error: 'unauthorized', reason }`; a token without the
|
|
38
|
+
scope is a 403 `{ error: 'forbidden', reason: 'insufficient_scope', scope }` with a
|
|
39
|
+
`WWW-Authenticate` challenge.
|
|
40
|
+
|
|
41
|
+
## Issuers and tenants
|
|
42
|
+
|
|
43
|
+
An issuer is allowed when it is listed (byte for byte) or is exactly `https://<one label>.<domain>`
|
|
44
|
+
(lowercase ASCII, no port, path, trailing slash or dot). The label is the tenant. Keep `domain` dedicated to Clavix tenants (no other host under it: it would be trusted). A custom domain
|
|
45
|
+
goes in `issuers`, as a list or as `{ issuer: tenant }` to name its tenant.
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
import { clavix } from '@softistx/alxia-clavix';
|
|
49
|
+
|
|
50
|
+
clavix({
|
|
51
|
+
domain: 'clavix.example.com',
|
|
52
|
+
issuers: { 'https://login.customer.example.org': 'customer' },
|
|
53
|
+
audience: 'https://api.example.com',
|
|
54
|
+
});
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## API
|
|
58
|
+
|
|
59
|
+
| Export | What it is |
|
|
60
|
+
| --- | --- |
|
|
61
|
+
| `clavix(options)` | a `ClavixVerifier`: a `Verifier` (`verify(token)`) with `bearer`, `ready` and `tenantOf` |
|
|
62
|
+
| `options.domain` | the deployment's domain; `https://<tenant>.<domain>` is allowed. Give `domain`, `issuers`, or both |
|
|
63
|
+
| `options.issuers` | `string[]` or `Record<issuer, tenant>`: issuers allowed beside the pattern, compared byte for byte. `https`, or `http` on localhost |
|
|
64
|
+
| `options.audience` | required: the API's identifier, which a token's `aud` must contain |
|
|
65
|
+
| `options.maxIssuers` | verified issuers whose keys are kept at once, the least recently used dropped past it (default 100) |
|
|
66
|
+
| `options.probation` | issuers not yet verified, kept in a cache of their own and promoted after one verified token (default `min(maxIssuers, 16)`) |
|
|
67
|
+
| `options.warm` | issuers whose keys `ready` waits for; each must be allowed; pinned, never evicted, not counted in `maxIssuers` |
|
|
68
|
+
| `cacheMs`, `staleMs`, `refetchMs`, `timeoutMs`, `clockTolerance`, `algorithms` | passed to `createJwt`; defaults as in [`@softistx/alxia-jwt`](https://github.com/softistx/alxia/blob/develop/packages/jwt/docs/guide/jwks.md); nothing else reaches it |
|
|
69
|
+
| `auth.bearer({ cookie? })` | the guard: routes after it read a `ClavixPrincipal` as `user`; a malformed token is a 401 `malformed`, and `claims` only means the issuer has no tenant |
|
|
70
|
+
| `auth.ready()` | `Promise<boolean>`, never throws: `true` once every `warm` issuer's keys are loaded (always `true` with none) |
|
|
71
|
+
| `auth.tenantOf(issuer)` | the tenant of an allowed issuer; `undefined` if refused or listed without a tenant |
|
|
72
|
+
| `requireScope(...scopes)` | a guard after `bearer()`: every scope required, else a 403 `insufficient_scope` |
|
|
73
|
+
| `ClavixPrincipal` | `subject`, `tenant`, `issuer`, `clientId`, `scopes`, `roles`, `claims` |
|
|
74
|
+
| `ClavixOptions`, `ClavixVerifier`, `RequireScope`, `InsufficientScopeBody`, `InsufficientScopeProblem` | the types |
|
|
75
|
+
|
|
76
|
+
Why a token is refused (`verify` result or the 401 `reason`): `malformed` (not a JWT, no readable
|
|
77
|
+
`iss`, a required RFC 9068 claim missing or empty, or a `scope`, `roles`, `permissions` or `cnf` of the wrong shape), `issuer` (not allowed; nothing is fetched),
|
|
78
|
+
`audience`, `type` (header `typ` is not `at+jwt`), `signature`, `algorithm`, `expired`,
|
|
79
|
+
`not_yet_valid`, `key`, `keys_unavailable`, and from the guard `missing` and `claims`.
|
|
80
|
+
|
|
81
|
+
## Documentation
|
|
82
|
+
|
|
83
|
+
- [Guide](https://github.com/softistx/alxia/blob/develop/packages/clavix/docs/README.md): issuers and tenants, the principal and scopes, readiness and warm-up, security notes.
|
|
84
|
+
- [Troubleshooting](https://github.com/softistx/alxia/blob/develop/packages/clavix/docs/troubleshooting.md): an error message, and what to do about it.
|
|
85
|
+
- [Roadmap](https://github.com/softistx/alxia/blob/develop/packages/clavix/docs/roadmap.md): what is coming, and what is not planned.
|
|
86
|
+
- [Authenticate requests](https://github.com/softistx/alxia/blob/develop/docs/recipes/authentication.md): the recipe for bearer tokens in general.
|
package/dist/clavix.d.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import type { StandardSchemaV1 } from '@softistx/alxia';
|
|
2
|
+
import { type Bearer, type JwksOptions, type Verifier } from '@softistx/alxia-jwt';
|
|
3
|
+
import { type ClavixPrincipal } from './principal';
|
|
4
|
+
export interface ClavixOptions extends Pick<JwksOptions, 'audience' | 'cacheMs' | 'staleMs' | 'refetchMs' | 'timeoutMs' | 'clockTolerance' | 'algorithms'> {
|
|
5
|
+
/**
|
|
6
|
+
* The deployment's domain: an issuer `https://<tenant>.<domain>` is
|
|
7
|
+
* allowed, with exactly one DNS label in front of it.
|
|
8
|
+
*/
|
|
9
|
+
readonly domain?: string;
|
|
10
|
+
/**
|
|
11
|
+
* Issuers allowed beside the pattern (custom domains, a test issuer): a
|
|
12
|
+
* list, or `{ issuer: tenant }` to name the tenant each one stands for.
|
|
13
|
+
* Compared byte for byte.
|
|
14
|
+
*/
|
|
15
|
+
readonly issuers?: readonly string[] | Readonly<Record<string, string>>;
|
|
16
|
+
/** The API's identifier, which a token's `aud` must contain. */
|
|
17
|
+
readonly audience: string;
|
|
18
|
+
/**
|
|
19
|
+
* Issuers whose keys are kept at once, once a token from them has
|
|
20
|
+
* verified; the least recently used is dropped past it. 100 by default.
|
|
21
|
+
* `warm` issuers are not counted.
|
|
22
|
+
*/
|
|
23
|
+
readonly maxIssuers?: number;
|
|
24
|
+
/**
|
|
25
|
+
* Issuers met but not yet proven, kept in a small cache of their own: one
|
|
26
|
+
* moves to the `maxIssuers` cache only when a token from it verifies, so
|
|
27
|
+
* forged issuers can only push each other out. `min(maxIssuers, 16)` by
|
|
28
|
+
* default.
|
|
29
|
+
*/
|
|
30
|
+
readonly probation?: number;
|
|
31
|
+
/**
|
|
32
|
+
* Issuers whose keys `ready` waits for, each allowed by the same rules as
|
|
33
|
+
* a token's issuer (a TypeError otherwise). They are pinned: never
|
|
34
|
+
* evicted, and not counted against `maxIssuers`. Left out, `ready` is
|
|
35
|
+
* always ready.
|
|
36
|
+
*/
|
|
37
|
+
readonly warm?: readonly string[];
|
|
38
|
+
}
|
|
39
|
+
export interface ClavixVerifier extends Verifier {
|
|
40
|
+
/**
|
|
41
|
+
* The tenant of an issuer the options allow: the slug of a pattern issuer,
|
|
42
|
+
* the mapped name of a listed one. `undefined` for a refused issuer, and
|
|
43
|
+
* for a listed issuer given without a tenant.
|
|
44
|
+
*/
|
|
45
|
+
tenantOf(issuer: string): string | undefined;
|
|
46
|
+
/**
|
|
47
|
+
* A readiness check for `health({ checks: { clavix: auth.ready } })`:
|
|
48
|
+
* resolves `true` once the keys of every `warm` issuer are loaded (a set
|
|
49
|
+
* within `cacheMs`, or stale within `staleMs`), `false` otherwise, and
|
|
50
|
+
* never throws. With no `warm` issuer it is always `true`: keys are then
|
|
51
|
+
* fetched on a tenant's first token, and a probe cannot wait for tenants
|
|
52
|
+
* it does not know.
|
|
53
|
+
*/
|
|
54
|
+
ready(): Promise<boolean>;
|
|
55
|
+
/**
|
|
56
|
+
* A guard, as `@softistx/alxia-jwt`'s `bearer()` (same 401s and cookie mode): the
|
|
57
|
+
* routes after it read a `ClavixPrincipal` as `user`. A token whose claims
|
|
58
|
+
* are malformed (no `sub`, `iss` or `client_id`, a bad `scope`, `roles`,
|
|
59
|
+
* `permissions` or `cnf`) is a 401 `malformed`, refused by the RFC 9068
|
|
60
|
+
* profile before the principal is built; reason `claims` is only for a
|
|
61
|
+
* listed issuer with no tenant (give `{ issuer: tenant }`).
|
|
62
|
+
*/
|
|
63
|
+
bearer(options?: {
|
|
64
|
+
/** Reads the token from this cookie when no `Authorization` header carries one. */
|
|
65
|
+
readonly cookie?: string;
|
|
66
|
+
}): Bearer<StandardSchemaV1<unknown, ClavixPrincipal>>;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* A verifier of the access tokens Clavix issues, for any tenant: a token is
|
|
70
|
+
* checked with the keys of its own issuer, but only an issuer the options
|
|
71
|
+
* allow is ever fetched from.
|
|
72
|
+
*
|
|
73
|
+
* ```ts
|
|
74
|
+
* const verifier = clavix({ domain: 'clavix.example', audience: 'https://api.example' });
|
|
75
|
+
* const result = await verifier.verify(token);
|
|
76
|
+
* ```
|
|
77
|
+
*/
|
|
78
|
+
export declare function clavix(options: ClavixOptions): ClavixVerifier;
|
|
79
|
+
//# sourceMappingURL=clavix.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"clavix.d.ts","sourceRoot":"","sources":["../src/clavix.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACxD,OAAO,EACN,KAAK,MAAM,EAIX,KAAK,WAAW,EAChB,KAAK,QAAQ,EACb,MAAM,qBAAqB,CAAC;AAQ7B,OAAO,EAAE,KAAK,eAAe,EAAmB,MAAM,aAAa,CAAC;AAGpE,MAAM,WAAW,aAChB,SAAQ,IAAI,CACX,WAAW,EACT,UAAU,GACV,SAAS,GACT,SAAS,GACT,WAAW,GACX,WAAW,GACX,gBAAgB,GAChB,YAAY,CACd;IACD;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB;;;;OAIG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACxE,gEAAgE;IAChE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B;;;;OAIG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B;;;;;OAKG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B;;;;;OAKG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAClC;AAED,MAAM,WAAW,cAAe,SAAQ,QAAQ;IAC/C;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;IAC7C;;;;;;;OAOG;IACH,KAAK,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;IAC1B;;;;;;;OAOG;IACH,MAAM,CAAC,OAAO,CAAC,EAAE;QAChB,mFAAmF;QACnF,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;KACzB,GAAG,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC,CAAC;CACvD;AAyBD;;;;;;;;;GASG;AACH,wBAAgB,MAAM,CAAC,OAAO,EAAE,aAAa,GAAG,cAAc,CAoF7D"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { type ClavixOptions, type ClavixVerifier, clavix } from './clavix';
|
|
2
|
+
export type { ClavixPrincipal } from './principal';
|
|
3
|
+
export { type InsufficientScopeBody, type InsufficientScopeProblem, type RequireScope, requireScope, } from './scope';
|
|
4
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,aAAa,EAAE,KAAK,cAAc,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAC3E,YAAY,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EACN,KAAK,qBAAqB,EAC1B,KAAK,wBAAwB,EAC7B,KAAK,YAAY,EACjB,YAAY,GACZ,MAAM,SAAS,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
// src/clavix.ts
|
|
2
|
+
import {
|
|
3
|
+
bearer,
|
|
4
|
+
createJwt
|
|
5
|
+
} from "@softistx/alxia-jwt";
|
|
6
|
+
|
|
7
|
+
// src/issuers.ts
|
|
8
|
+
var LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
9
|
+
var LOCAL = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
10
|
+
function normaliseDomain(domain) {
|
|
11
|
+
const name = domain.trim().toLowerCase().replace(/^\./, "").replace(/\.$/, "");
|
|
12
|
+
const labels = name.split(".");
|
|
13
|
+
if (labels.length < 2 || name.length > 253 || !labels.every((label) => LABEL.test(label) && !label.startsWith("xn--"))) {
|
|
14
|
+
throw new TypeError(`clavix: domain must be an ASCII DNS name such as "clavix.example", got ${JSON.stringify(domain)}`);
|
|
15
|
+
}
|
|
16
|
+
return name;
|
|
17
|
+
}
|
|
18
|
+
function listIssuers(issuers) {
|
|
19
|
+
const map = new Map;
|
|
20
|
+
const entries = Array.isArray(issuers) ? issuers.map((issuer) => [issuer, undefined]) : Object.entries(issuers);
|
|
21
|
+
for (const [issuer, tenant] of entries) {
|
|
22
|
+
let url;
|
|
23
|
+
try {
|
|
24
|
+
url = new URL(issuer);
|
|
25
|
+
} catch {
|
|
26
|
+
throw new TypeError(`clavix: issuer is not a URL: ${issuer}`);
|
|
27
|
+
}
|
|
28
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && LOCAL.has(url.hostname))) {
|
|
29
|
+
throw new TypeError(`clavix: issuer must be an https URL: ${issuer}`);
|
|
30
|
+
}
|
|
31
|
+
if (tenant === "") {
|
|
32
|
+
throw new TypeError(`clavix: the tenant of ${issuer} is empty`);
|
|
33
|
+
}
|
|
34
|
+
map.set(issuer, tenant);
|
|
35
|
+
}
|
|
36
|
+
return map;
|
|
37
|
+
}
|
|
38
|
+
function slugOf(issuer, domain) {
|
|
39
|
+
const prefix = "https://";
|
|
40
|
+
const suffix = `.${domain}`;
|
|
41
|
+
if (!issuer.startsWith(prefix) || !issuer.endsWith(suffix))
|
|
42
|
+
return;
|
|
43
|
+
const label = issuer.slice(prefix.length, issuer.length - suffix.length);
|
|
44
|
+
return LABEL.test(label) && !label.startsWith("xn--") ? label : undefined;
|
|
45
|
+
}
|
|
46
|
+
function resolveIssuer(rules, issuer) {
|
|
47
|
+
if (rules.listed.has(issuer))
|
|
48
|
+
return { tenant: rules.listed.get(issuer) };
|
|
49
|
+
if (rules.domain === undefined)
|
|
50
|
+
return;
|
|
51
|
+
const slug = slugOf(issuer, rules.domain);
|
|
52
|
+
return slug === undefined ? undefined : { tenant: slug };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// src/lru.ts
|
|
56
|
+
class Lru {
|
|
57
|
+
#entries = new Map;
|
|
58
|
+
#max;
|
|
59
|
+
constructor(max) {
|
|
60
|
+
this.#max = max;
|
|
61
|
+
}
|
|
62
|
+
get size() {
|
|
63
|
+
return this.#entries.size;
|
|
64
|
+
}
|
|
65
|
+
get(key) {
|
|
66
|
+
const value = this.#entries.get(key);
|
|
67
|
+
if (value === undefined)
|
|
68
|
+
return;
|
|
69
|
+
this.#entries.delete(key);
|
|
70
|
+
this.#entries.set(key, value);
|
|
71
|
+
return value;
|
|
72
|
+
}
|
|
73
|
+
delete(key) {
|
|
74
|
+
this.#entries.delete(key);
|
|
75
|
+
}
|
|
76
|
+
set(key, value) {
|
|
77
|
+
this.#entries.delete(key);
|
|
78
|
+
this.#entries.set(key, value);
|
|
79
|
+
if (this.#entries.size > this.#max) {
|
|
80
|
+
const oldest = this.#entries.keys().next();
|
|
81
|
+
if (!oldest.done)
|
|
82
|
+
this.#entries.delete(oldest.value);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// src/principal.ts
|
|
88
|
+
var isString = (value) => typeof value === "string" && value !== "";
|
|
89
|
+
function principalSchema(tenantOf) {
|
|
90
|
+
return {
|
|
91
|
+
"~standard": {
|
|
92
|
+
version: 1,
|
|
93
|
+
vendor: "@softistx/alxia-clavix",
|
|
94
|
+
validate(value) {
|
|
95
|
+
const claims = value;
|
|
96
|
+
const issues = [];
|
|
97
|
+
const need = (name) => issues.push({ message: `${name} is required`, path: [name] });
|
|
98
|
+
const { iss, sub, client_id: clientId, scope, roles } = claims;
|
|
99
|
+
if (!isString(iss))
|
|
100
|
+
need("iss");
|
|
101
|
+
if (!isString(sub))
|
|
102
|
+
need("sub");
|
|
103
|
+
if (!isString(clientId))
|
|
104
|
+
need("client_id");
|
|
105
|
+
if (scope !== undefined && typeof scope !== "string") {
|
|
106
|
+
issues.push({ message: "scope must be a string", path: ["scope"] });
|
|
107
|
+
}
|
|
108
|
+
if (roles !== undefined && !(Array.isArray(roles) && roles.every((r) => typeof r === "string"))) {
|
|
109
|
+
issues.push({
|
|
110
|
+
message: "roles must be an array of strings",
|
|
111
|
+
path: ["roles"]
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
const tenant = isString(iss) ? tenantOf(iss) : undefined;
|
|
115
|
+
if (isString(iss) && tenant === undefined) {
|
|
116
|
+
issues.push({ message: "the issuer has no tenant", path: ["iss"] });
|
|
117
|
+
}
|
|
118
|
+
if (issues.length > 0)
|
|
119
|
+
return { issues };
|
|
120
|
+
return {
|
|
121
|
+
value: {
|
|
122
|
+
subject: sub,
|
|
123
|
+
tenant,
|
|
124
|
+
issuer: iss,
|
|
125
|
+
clientId,
|
|
126
|
+
scopes: typeof scope === "string" ? scope.split(" ").filter(Boolean) : [],
|
|
127
|
+
roles: roles ?? [],
|
|
128
|
+
claims
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// src/unverified-issuer.ts
|
|
137
|
+
var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
138
|
+
function unverifiedIssuer(token) {
|
|
139
|
+
const parts = token.split(".");
|
|
140
|
+
const payload = parts[1];
|
|
141
|
+
if (parts.length !== 3 || payload === undefined)
|
|
142
|
+
return;
|
|
143
|
+
if (!/^[A-Za-z0-9_-]+$/.test(payload))
|
|
144
|
+
return;
|
|
145
|
+
try {
|
|
146
|
+
const claims = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(payload, "base64url")));
|
|
147
|
+
return isObject(claims) && typeof claims["iss"] === "string" ? claims["iss"] : undefined;
|
|
148
|
+
} catch {
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// src/clavix.ts
|
|
154
|
+
var PASSTHROUGH = [
|
|
155
|
+
"audience",
|
|
156
|
+
"cacheMs",
|
|
157
|
+
"staleMs",
|
|
158
|
+
"refetchMs",
|
|
159
|
+
"timeoutMs",
|
|
160
|
+
"clockTolerance",
|
|
161
|
+
"algorithms"
|
|
162
|
+
];
|
|
163
|
+
function pick(source, keys) {
|
|
164
|
+
const picked = {};
|
|
165
|
+
for (const key of keys) {
|
|
166
|
+
if (source[key] !== undefined)
|
|
167
|
+
picked[key] = source[key];
|
|
168
|
+
}
|
|
169
|
+
return picked;
|
|
170
|
+
}
|
|
171
|
+
function clavix(options) {
|
|
172
|
+
if (options.domain === undefined && options.issuers === undefined) {
|
|
173
|
+
throw new TypeError("clavix: give domain, issuers, or both");
|
|
174
|
+
}
|
|
175
|
+
if (typeof options.audience !== "string" || options.audience === "") {
|
|
176
|
+
throw new TypeError("clavix: audience is required");
|
|
177
|
+
}
|
|
178
|
+
const max = options.maxIssuers ?? 100;
|
|
179
|
+
if (!Number.isInteger(max) || max < 1) {
|
|
180
|
+
throw new TypeError("clavix: maxIssuers must be a positive integer");
|
|
181
|
+
}
|
|
182
|
+
const listed = listIssuers(options.issuers ?? []);
|
|
183
|
+
if (options.domain === undefined && listed.size === 0) {
|
|
184
|
+
throw new TypeError("clavix: give domain, issuers, or both");
|
|
185
|
+
}
|
|
186
|
+
const rules = {
|
|
187
|
+
domain: options.domain === undefined ? undefined : normaliseDomain(options.domain),
|
|
188
|
+
listed
|
|
189
|
+
};
|
|
190
|
+
const probationSize = options.probation ?? Math.min(max, 16);
|
|
191
|
+
if (!Number.isInteger(probationSize) || probationSize < 1) {
|
|
192
|
+
throw new TypeError("clavix: probation must be a positive integer");
|
|
193
|
+
}
|
|
194
|
+
const passthrough = pick(options, PASSTHROUGH);
|
|
195
|
+
const create = (issuer) => createJwt({ ...passthrough, discovery: issuer, profile: "rfc9068" });
|
|
196
|
+
const pinned = new Map;
|
|
197
|
+
for (const issuer of options.warm ?? []) {
|
|
198
|
+
if (resolveIssuer(rules, issuer) === undefined) {
|
|
199
|
+
throw new TypeError(`clavix: warm issuer ${issuer} is not allowed`);
|
|
200
|
+
}
|
|
201
|
+
pinned.set(issuer, create(issuer));
|
|
202
|
+
}
|
|
203
|
+
const proven = new Lru(max);
|
|
204
|
+
const probation = new Lru(probationSize);
|
|
205
|
+
const verifierOf = (issuer) => {
|
|
206
|
+
const known = pinned.get(issuer) ?? proven.get(issuer);
|
|
207
|
+
if (known !== undefined)
|
|
208
|
+
return known;
|
|
209
|
+
let verifier = probation.get(issuer);
|
|
210
|
+
if (verifier === undefined) {
|
|
211
|
+
verifier = create(issuer);
|
|
212
|
+
probation.set(issuer, verifier);
|
|
213
|
+
}
|
|
214
|
+
return verifier;
|
|
215
|
+
};
|
|
216
|
+
const tenantOf = (issuer) => resolveIssuer(rules, issuer)?.tenant;
|
|
217
|
+
const schema = principalSchema(tenantOf);
|
|
218
|
+
const self = {
|
|
219
|
+
tenantOf,
|
|
220
|
+
ready: async () => (await Promise.all([...pinned.values()].map((v) => v.ready()))).every(Boolean),
|
|
221
|
+
bearer: (guard) => bearer({
|
|
222
|
+
jwt: self,
|
|
223
|
+
schema,
|
|
224
|
+
...guard?.cookie === undefined ? {} : { cookie: guard.cookie }
|
|
225
|
+
}),
|
|
226
|
+
async verify(token) {
|
|
227
|
+
const issuer = unverifiedIssuer(token);
|
|
228
|
+
if (issuer === undefined)
|
|
229
|
+
return { ok: false, reason: "malformed" };
|
|
230
|
+
if (resolveIssuer(rules, issuer) === undefined) {
|
|
231
|
+
return { ok: false, reason: "issuer" };
|
|
232
|
+
}
|
|
233
|
+
const verifier = verifierOf(issuer);
|
|
234
|
+
const result = await verifier.verify(token);
|
|
235
|
+
if (result.ok && probation.get(issuer) === verifier) {
|
|
236
|
+
probation.delete(issuer);
|
|
237
|
+
proven.set(issuer, verifier);
|
|
238
|
+
}
|
|
239
|
+
return result;
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
return self;
|
|
243
|
+
}
|
|
244
|
+
// src/scope.ts
|
|
245
|
+
import {
|
|
246
|
+
defineMiddleware,
|
|
247
|
+
errorFormat,
|
|
248
|
+
markFactory,
|
|
249
|
+
problem,
|
|
250
|
+
problemOf
|
|
251
|
+
} from "@softistx/alxia";
|
|
252
|
+
function requireScope(...scopes) {
|
|
253
|
+
if (scopes.length === 0 || scopes.some((s) => !/^[\x21\x23-\x5B\x5D-\x7E]+$/.test(s))) {
|
|
254
|
+
throw new TypeError("requireScope: give scopes, each a non-empty token without spaces or quotes");
|
|
255
|
+
}
|
|
256
|
+
const scope = scopes.join(" ");
|
|
257
|
+
const challenge = {
|
|
258
|
+
headers: {
|
|
259
|
+
"www-authenticate": `Bearer error="insufficient_scope", scope="${scope}"`
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
return defineMiddleware()(async function requireScope(ctx, next) {
|
|
263
|
+
if (scopes.every((s) => ctx.user.scopes.includes(s)))
|
|
264
|
+
return next();
|
|
265
|
+
const why = { reason: "insufficient_scope", scope };
|
|
266
|
+
if (errorFormat(ctx) === "problem") {
|
|
267
|
+
return problem(problemOf(ctx, {
|
|
268
|
+
status: 403,
|
|
269
|
+
detail: `The access token lacks the scope: ${scope}`,
|
|
270
|
+
...why
|
|
271
|
+
}), challenge);
|
|
272
|
+
}
|
|
273
|
+
return ctx.reply(403, { error: "forbidden", ...why }, challenge);
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
markFactory(requireScope);
|
|
277
|
+
export {
|
|
278
|
+
clavix,
|
|
279
|
+
requireScope
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
//# debugId=3B825E64FC0F2E6764756E2164756E21
|
|
283
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/clavix.ts", "../src/issuers.ts", "../src/lru.ts", "../src/principal.ts", "../src/unverified-issuer.ts", "../src/scope.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import type { StandardSchemaV1 } from '@softistx/alxia';\nimport {\n\ttype Bearer,\n\tbearer,\n\tcreateJwt,\n\ttype JwksJwt,\n\ttype JwksOptions,\n\ttype Verifier,\n} from '@softistx/alxia-jwt';\nimport {\n\ttype IssuerRules,\n\tlistIssuers,\n\tnormaliseDomain,\n\tresolveIssuer,\n} from './issuers';\nimport { Lru } from './lru';\nimport { type ClavixPrincipal, principalSchema } from './principal';\nimport { unverifiedIssuer } from './unverified-issuer';\n\nexport interface ClavixOptions\n\textends Pick<\n\t\tJwksOptions,\n\t\t| 'audience'\n\t\t| 'cacheMs'\n\t\t| 'staleMs'\n\t\t| 'refetchMs'\n\t\t| 'timeoutMs'\n\t\t| 'clockTolerance'\n\t\t| 'algorithms'\n\t> {\n\t/**\n\t * The deployment's domain: an issuer `https://<tenant>.<domain>` is\n\t * allowed, with exactly one DNS label in front of it.\n\t */\n\treadonly domain?: string;\n\t/**\n\t * Issuers allowed beside the pattern (custom domains, a test issuer): a\n\t * list, or `{ issuer: tenant }` to name the tenant each one stands for.\n\t * Compared byte for byte.\n\t */\n\treadonly issuers?: readonly string[] | Readonly<Record<string, string>>;\n\t/** The API's identifier, which a token's `aud` must contain. */\n\treadonly audience: string;\n\t/**\n\t * Issuers whose keys are kept at once, once a token from them has\n\t * verified; the least recently used is dropped past it. 100 by default.\n\t * `warm` issuers are not counted.\n\t */\n\treadonly maxIssuers?: number;\n\t/**\n\t * Issuers met but not yet proven, kept in a small cache of their own: one\n\t * moves to the `maxIssuers` cache only when a token from it verifies, so\n\t * forged issuers can only push each other out. `min(maxIssuers, 16)` by\n\t * default.\n\t */\n\treadonly probation?: number;\n\t/**\n\t * Issuers whose keys `ready` waits for, each allowed by the same rules as\n\t * a token's issuer (a TypeError otherwise). They are pinned: never\n\t * evicted, and not counted against `maxIssuers`. Left out, `ready` is\n\t * always ready.\n\t */\n\treadonly warm?: readonly string[];\n}\n\nexport interface ClavixVerifier extends Verifier {\n\t/**\n\t * The tenant of an issuer the options allow: the slug of a pattern issuer,\n\t * the mapped name of a listed one. `undefined` for a refused issuer, and\n\t * for a listed issuer given without a tenant.\n\t */\n\ttenantOf(issuer: string): string | undefined;\n\t/**\n\t * A readiness check for `health({ checks: { clavix: auth.ready } })`:\n\t * resolves `true` once the keys of every `warm` issuer are loaded (a set\n\t * within `cacheMs`, or stale within `staleMs`), `false` otherwise, and\n\t * never throws. With no `warm` issuer it is always `true`: keys are then\n\t * fetched on a tenant's first token, and a probe cannot wait for tenants\n\t * it does not know.\n\t */\n\tready(): Promise<boolean>;\n\t/**\n\t * A guard, as `@softistx/alxia-jwt`'s `bearer()` (same 401s and cookie mode): the\n\t * routes after it read a `ClavixPrincipal` as `user`. A token whose claims\n\t * are malformed (no `sub`, `iss` or `client_id`, a bad `scope`, `roles`,\n\t * `permissions` or `cnf`) is a 401 `malformed`, refused by the RFC 9068\n\t * profile before the principal is built; reason `claims` is only for a\n\t * listed issuer with no tenant (give `{ issuer: tenant }`).\n\t */\n\tbearer(options?: {\n\t\t/** Reads the token from this cookie when no `Authorization` header carries one. */\n\t\treadonly cookie?: string;\n\t}): Bearer<StandardSchemaV1<unknown, ClavixPrincipal>>;\n}\n\n/** The options handed on to `createJwt`: nothing else of `options` reaches it. */\nconst PASSTHROUGH = [\n\t'audience',\n\t'cacheMs',\n\t'staleMs',\n\t'refetchMs',\n\t'timeoutMs',\n\t'clockTolerance',\n\t'algorithms',\n] as const;\n\n/** The defined `keys` of `source`, typed as such. */\nfunction pick<T extends object, K extends keyof T>(\n\tsource: T,\n\tkeys: readonly K[],\n): Pick<T, K> {\n\tconst picked: Partial<Pick<T, K>> = {};\n\tfor (const key of keys) {\n\t\tif (source[key] !== undefined) picked[key] = source[key];\n\t}\n\treturn picked as Pick<T, K>;\n}\n\n/**\n * A verifier of the access tokens Clavix issues, for any tenant: a token is\n * checked with the keys of its own issuer, but only an issuer the options\n * allow is ever fetched from.\n *\n * ```ts\n * const verifier = clavix({ domain: 'clavix.example', audience: 'https://api.example' });\n * const result = await verifier.verify(token);\n * ```\n */\nexport function clavix(options: ClavixOptions): ClavixVerifier {\n\tif (options.domain === undefined && options.issuers === undefined) {\n\t\tthrow new TypeError('clavix: give domain, issuers, or both');\n\t}\n\tif (typeof options.audience !== 'string' || options.audience === '') {\n\t\tthrow new TypeError('clavix: audience is required');\n\t}\n\tconst max = options.maxIssuers ?? 100;\n\tif (!Number.isInteger(max) || max < 1) {\n\t\tthrow new TypeError('clavix: maxIssuers must be a positive integer');\n\t}\n\tconst listed = listIssuers(options.issuers ?? []);\n\tif (options.domain === undefined && listed.size === 0) {\n\t\tthrow new TypeError('clavix: give domain, issuers, or both');\n\t}\n\tconst rules: IssuerRules = {\n\t\tdomain:\n\t\t\toptions.domain === undefined\n\t\t\t\t? undefined\n\t\t\t\t: normaliseDomain(options.domain),\n\t\tlisted,\n\t};\n\tconst probationSize = options.probation ?? Math.min(max, 16);\n\tif (!Number.isInteger(probationSize) || probationSize < 1) {\n\t\tthrow new TypeError('clavix: probation must be a positive integer');\n\t}\n\tconst passthrough = pick(options, PASSTHROUGH);\n\tconst create = (issuer: string): JwksJwt =>\n\t\tcreateJwt({ ...passthrough, discovery: issuer, profile: 'rfc9068' });\n\n\t// Pinned: never evicted, not counted in `max`.\n\tconst pinned = new Map<string, JwksJwt>();\n\tfor (const issuer of options.warm ?? []) {\n\t\tif (resolveIssuer(rules, issuer) === undefined) {\n\t\t\tthrow new TypeError(`clavix: warm issuer ${issuer} is not allowed`);\n\t\t}\n\t\tpinned.set(issuer, create(issuer));\n\t}\n\t// Proven issuers, then issuers met but not yet proven by a verified token.\n\tconst proven = new Lru<JwksJwt>(max);\n\tconst probation = new Lru<JwksJwt>(probationSize);\n\tconst verifierOf = (issuer: string): JwksJwt => {\n\t\tconst known = pinned.get(issuer) ?? proven.get(issuer);\n\t\tif (known !== undefined) return known;\n\t\tlet verifier = probation.get(issuer);\n\t\tif (verifier === undefined) {\n\t\t\tverifier = create(issuer);\n\t\t\tprobation.set(issuer, verifier);\n\t\t}\n\t\treturn verifier;\n\t};\n\n\tconst tenantOf = (issuer: string) => resolveIssuer(rules, issuer)?.tenant;\n\tconst schema = principalSchema(tenantOf);\n\n\tconst self: ClavixVerifier = {\n\t\ttenantOf,\n\t\tready: async () =>\n\t\t\t(await Promise.all([...pinned.values()].map((v) => v.ready()))).every(\n\t\t\t\tBoolean,\n\t\t\t),\n\t\tbearer: (guard) =>\n\t\t\tbearer({\n\t\t\t\tjwt: self,\n\t\t\t\tschema,\n\t\t\t\t...(guard?.cookie === undefined ? {} : { cookie: guard.cookie }),\n\t\t\t}),\n\t\tasync verify(token) {\n\t\t\tconst issuer = unverifiedIssuer(token);\n\t\t\tif (issuer === undefined) return { ok: false, reason: 'malformed' };\n\t\t\tif (resolveIssuer(rules, issuer) === undefined) {\n\t\t\t\treturn { ok: false, reason: 'issuer' };\n\t\t\t}\n\t\t\tconst verifier = verifierOf(issuer);\n\t\t\tconst result = await verifier.verify(token);\n\t\t\t// one verified token proves the issuer: it leaves probation\n\t\t\tif (result.ok && probation.get(issuer) === verifier) {\n\t\t\t\tprobation.delete(issuer);\n\t\t\t\tproven.set(issuer, verifier);\n\t\t\t}\n\t\t\treturn result;\n\t\t},\n\t};\n\treturn self;\n}\n",
|
|
6
|
+
"/** The allowed issuers of a Clavix deployment, and the tenant each one stands for. */\nexport interface IssuerRules {\n\t/** A lowercase DNS name without a dot at either end. */\n\treadonly domain: string | undefined;\n\t/** Issuer to tenant (`undefined` when the list gives none). */\n\treadonly listed: ReadonlyMap<string, string | undefined>;\n}\n\nconst LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\nconst LOCAL = new Set(['localhost', '127.0.0.1', '[::1]']);\n\n/** `domain` as a lowercase ASCII DNS name, or a `TypeError`. */\nexport function normaliseDomain(domain: string): string {\n\tconst name = domain\n\t\t.trim()\n\t\t.toLowerCase()\n\t\t.replace(/^\\./, '')\n\t\t.replace(/\\.$/, '');\n\tconst labels = name.split('.');\n\tif (\n\t\tlabels.length < 2 ||\n\t\tname.length > 253 ||\n\t\t!labels.every((label) => LABEL.test(label) && !label.startsWith('xn--'))\n\t) {\n\t\tthrow new TypeError(\n\t\t\t`clavix: domain must be an ASCII DNS name such as \"clavix.example\", got ${JSON.stringify(domain)}`,\n\t\t);\n\t}\n\treturn name;\n}\n\n/** The listed issuers as a map; an issuer must be an `https` URL, or `http` on this machine. */\nexport function listIssuers(\n\tissuers: readonly string[] | Readonly<Record<string, string>>,\n): Map<string, string | undefined> {\n\tconst map = new Map<string, string | undefined>();\n\tconst entries: [string, string | undefined][] = Array.isArray(issuers)\n\t\t? issuers.map((issuer) => [issuer, undefined])\n\t\t: Object.entries(issuers);\n\tfor (const [issuer, tenant] of entries) {\n\t\tlet url: URL;\n\t\ttry {\n\t\t\turl = new URL(issuer);\n\t\t} catch {\n\t\t\tthrow new TypeError(`clavix: issuer is not a URL: ${issuer}`);\n\t\t}\n\t\tif (\n\t\t\turl.protocol !== 'https:' &&\n\t\t\t!(url.protocol === 'http:' && LOCAL.has(url.hostname))\n\t\t) {\n\t\t\tthrow new TypeError(`clavix: issuer must be an https URL: ${issuer}`);\n\t\t}\n\t\tif (tenant === '') {\n\t\t\tthrow new TypeError(`clavix: the tenant of ${issuer} is empty`);\n\t\t}\n\t\tmap.set(issuer, tenant);\n\t}\n\treturn map;\n}\n\n/**\n * The slug of `https://<slug>.<domain>`, exactly: one DNS label in front of\n * the domain, lowercase ASCII (so no IDN, no `xn--` look-alike), and no port,\n * userinfo, path, query, fragment, trailing slash or trailing dot.\n */\nfunction slugOf(issuer: string, domain: string): string | undefined {\n\tconst prefix = 'https://';\n\tconst suffix = `.${domain}`;\n\tif (!issuer.startsWith(prefix) || !issuer.endsWith(suffix)) return undefined;\n\tconst label = issuer.slice(prefix.length, issuer.length - suffix.length);\n\treturn LABEL.test(label) && !label.startsWith('xn--') ? label : undefined;\n}\n\n/**\n * Whether `issuer` is allowed, and for which tenant: a listed issuer (byte\n * for byte) first, then the domain pattern. `undefined` when refused.\n */\nexport function resolveIssuer(\n\trules: IssuerRules,\n\tissuer: string,\n): { readonly tenant: string | undefined } | undefined {\n\tif (rules.listed.has(issuer)) return { tenant: rules.listed.get(issuer) };\n\tif (rules.domain === undefined) return undefined;\n\tconst slug = slugOf(issuer, rules.domain);\n\treturn slug === undefined ? undefined : { tenant: slug };\n}\n",
|
|
7
|
+
"/** A map that keeps at most `max` entries, dropping the least recently used. */\nexport class Lru<V> {\n\treadonly #entries = new Map<string, V>();\n\treadonly #max: number;\n\n\tconstructor(max: number) {\n\t\tthis.#max = max;\n\t}\n\n\tget size(): number {\n\t\treturn this.#entries.size;\n\t}\n\n\tget(key: string): V | undefined {\n\t\tconst value = this.#entries.get(key);\n\t\tif (value === undefined) return undefined;\n\t\tthis.#entries.delete(key);\n\t\tthis.#entries.set(key, value);\n\t\treturn value;\n\t}\n\n\tdelete(key: string): void {\n\t\tthis.#entries.delete(key);\n\t}\n\n\tset(key: string, value: V): void {\n\t\tthis.#entries.delete(key);\n\t\tthis.#entries.set(key, value);\n\t\tif (this.#entries.size > this.#max) {\n\t\t\tconst oldest = this.#entries.keys().next();\n\t\t\tif (!oldest.done) this.#entries.delete(oldest.value);\n\t\t}\n\t}\n}\n",
|
|
8
|
+
"import type { StandardSchemaV1 } from '@softistx/alxia';\nimport type { JwtClaims } from '@softistx/alxia-jwt';\n\n/** Who a verified Clavix access token stands for: what routes behind `bearer()` read as `user`. */\nexport interface ClavixPrincipal {\n\t/** The token's `sub`. */\n\treadonly subject: string;\n\t/** The tenant of the issuer: the slug of a pattern issuer, or the mapped name of a listed one. */\n\treadonly tenant: string;\n\t/** The token's `iss`. */\n\treadonly issuer: string;\n\t/** The client the token was issued to (`client_id`). */\n\treadonly clientId: string;\n\t/** The granted scopes: `scope` split on spaces, `[]` when absent. */\n\treadonly scopes: readonly string[];\n\t/** The subject's roles, `[]` when absent. */\n\treadonly roles: readonly string[];\n\t/** The verified claims, untouched (`permissions`, `cnf`, …). */\n\treadonly claims: JwtClaims;\n}\n\nconst isString = (value: unknown): value is string =>\n\ttypeof value === 'string' && value !== '';\n\n/**\n * The Standard Schema that maps verified claims to a principal. A claim an\n * RFC 9068 token must carry but does not is an issue, so a 401 `claims`.\n */\nexport function principalSchema(\n\ttenantOf: (issuer: string) => string | undefined,\n): StandardSchemaV1<unknown, ClavixPrincipal> {\n\treturn {\n\t\t'~standard': {\n\t\t\tversion: 1,\n\t\t\tvendor: '@softistx/alxia-clavix',\n\t\t\tvalidate(value) {\n\t\t\t\tconst claims = value as JwtClaims;\n\t\t\t\tconst issues: { message: string; path: string[] }[] = [];\n\t\t\t\tconst need = (name: string) =>\n\t\t\t\t\tissues.push({ message: `${name} is required`, path: [name] });\n\t\t\t\tconst { iss, sub, client_id: clientId, scope, roles } = claims;\n\t\t\t\tif (!isString(iss)) need('iss');\n\t\t\t\tif (!isString(sub)) need('sub');\n\t\t\t\tif (!isString(clientId)) need('client_id');\n\t\t\t\tif (scope !== undefined && typeof scope !== 'string') {\n\t\t\t\t\tissues.push({ message: 'scope must be a string', path: ['scope'] });\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\troles !== undefined &&\n\t\t\t\t\t!(Array.isArray(roles) && roles.every((r) => typeof r === 'string'))\n\t\t\t\t) {\n\t\t\t\t\tissues.push({\n\t\t\t\t\t\tmessage: 'roles must be an array of strings',\n\t\t\t\t\t\tpath: ['roles'],\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tconst tenant = isString(iss) ? tenantOf(iss) : undefined;\n\t\t\t\tif (isString(iss) && tenant === undefined) {\n\t\t\t\t\tissues.push({ message: 'the issuer has no tenant', path: ['iss'] });\n\t\t\t\t}\n\t\t\t\tif (issues.length > 0) return { issues };\n\t\t\t\treturn {\n\t\t\t\t\tvalue: {\n\t\t\t\t\t\tsubject: sub as string,\n\t\t\t\t\t\ttenant: tenant as string,\n\t\t\t\t\t\tissuer: iss as string,\n\t\t\t\t\t\tclientId: clientId as string,\n\t\t\t\t\t\tscopes:\n\t\t\t\t\t\t\ttypeof scope === 'string' ? scope.split(' ').filter(Boolean) : [],\n\t\t\t\t\t\troles: roles ?? [],\n\t\t\t\t\t\tclaims,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t};\n}\n",
|
|
9
|
+
"const isObject = (value: unknown): value is Record<string, unknown> =>\n\tvalue !== null && typeof value === 'object' && !Array.isArray(value);\n\n/** The `iss` of a token's payload, read WITHOUT verifying anything: it only picks whose keys to verify with. */\nexport function unverifiedIssuer(token: string): string | undefined {\n\tconst parts = token.split('.');\n\tconst payload = parts[1];\n\tif (parts.length !== 3 || payload === undefined) return undefined;\n\tif (!/^[A-Za-z0-9_-]+$/.test(payload)) return undefined;\n\ttry {\n\t\tconst claims: unknown = JSON.parse(\n\t\t\tnew TextDecoder('utf-8', { fatal: true }).decode(\n\t\t\t\tBuffer.from(payload, 'base64url'),\n\t\t\t),\n\t\t);\n\t\treturn isObject(claims) && typeof claims['iss'] === 'string'\n\t\t\t? claims['iss']\n\t\t\t: undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n",
|
|
10
|
+
"import {\n\tdefineMiddleware,\n\terrorFormat,\n\ttype Middleware,\n\tmarkFactory,\n\ttype Next,\n\ttype Problem,\n\tproblem,\n\tproblemOf,\n\ttype Reply,\n} from '@softistx/alxia';\n\n/** The body of the 403. */\nexport interface InsufficientScopeBody {\n\treadonly error: 'forbidden';\n\treadonly reason: 'insufficient_scope';\n\t/** The scopes the route needs, space-separated. */\n\treadonly scope: string;\n}\n\n/** The 403 under `alxia({ errors: 'problem' })`: `reason` and `scope` are its extensions. */\nexport type InsufficientScopeProblem = Problem<\n\t403,\n\tOmit<InsufficientScopeBody, 'error'>\n>;\n\n/**\n * What `requireScope()` makes: it reads the `user` that `bearer()` gives and\n * lets the request on, or answers the 403.\n */\nexport type RequireScope = Middleware<\n\t{ user: { readonly scopes: readonly string[] } },\n\tPromise<\n\t\tReply<403, InsufficientScopeBody | InsufficientScopeProblem> | Next<object>\n\t>\n>;\n\n/**\n * A guard after `bearer()`: the token must carry every one of `scopes`, or a\n * 403 whose `WWW-Authenticate: Bearer error=\"insufficient_scope\", scope=\"…\"`\n * names them (RFC 6750 section 3.1).\n *\n * ```ts\n * app.use(auth.bearer()).get('/invoices', requireScope('invoices:read'), ({ user, reply }) => …)\n * ```\n */\nexport function requireScope(...scopes: readonly string[]): RequireScope {\n\tif (\n\t\tscopes.length === 0 ||\n\t\tscopes.some((s) => !/^[\\x21\\x23-\\x5B\\x5D-\\x7E]+$/.test(s))\n\t) {\n\t\tthrow new TypeError(\n\t\t\t'requireScope: give scopes, each a non-empty token without spaces or quotes',\n\t\t);\n\t}\n\tconst scope = scopes.join(' ');\n\tconst challenge = {\n\t\theaders: {\n\t\t\t'www-authenticate': `Bearer error=\"insufficient_scope\", scope=\"${scope}\"`,\n\t\t},\n\t};\n\treturn defineMiddleware<{ user: { readonly scopes: readonly string[] } }>()(\n\t\tasync function requireScope(ctx, next) {\n\t\t\tif (scopes.every((s) => ctx.user.scopes.includes(s))) return next();\n\t\t\tconst why = { reason: 'insufficient_scope', scope } as const;\n\t\t\tif (errorFormat(ctx) === 'problem') {\n\t\t\t\treturn problem(\n\t\t\t\t\tproblemOf(ctx, {\n\t\t\t\t\t\tstatus: 403,\n\t\t\t\t\t\tdetail: `The access token lacks the scope: ${scope}`,\n\t\t\t\t\t\t...why,\n\t\t\t\t\t}),\n\t\t\t\t\tchallenge,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn ctx.reply(403, { error: 'forbidden', ...why }, challenge);\n\t\t},\n\t) as RequireScope;\n}\n\nmarkFactory(requireScope);\n"
|
|
11
|
+
],
|
|
12
|
+
"mappings": ";AACA;AAAA;AAAA;AAAA;;;ACOA,IAAM,QAAQ;AACd,IAAM,QAAQ,IAAI,IAAI,CAAC,aAAa,aAAa,OAAO,CAAC;AAGlD,SAAS,eAAe,CAAC,QAAwB;AAAA,EACvD,MAAM,OAAO,OACX,KAAK,EACL,YAAY,EACZ,QAAQ,OAAO,EAAE,EACjB,QAAQ,OAAO,EAAE;AAAA,EACnB,MAAM,SAAS,KAAK,MAAM,GAAG;AAAA,EAC7B,IACC,OAAO,SAAS,KAChB,KAAK,SAAS,OACd,CAAC,OAAO,MAAM,CAAC,UAAU,MAAM,KAAK,KAAK,KAAK,CAAC,MAAM,WAAW,MAAM,CAAC,GACtE;AAAA,IACD,MAAM,IAAI,UACT,0EAA0E,KAAK,UAAU,MAAM,GAChG;AAAA,EACD;AAAA,EACA,OAAO;AAAA;AAID,SAAS,WAAW,CAC1B,SACkC;AAAA,EAClC,MAAM,MAAM,IAAI;AAAA,EAChB,MAAM,UAA0C,MAAM,QAAQ,OAAO,IAClE,QAAQ,IAAI,CAAC,WAAW,CAAC,QAAQ,SAAS,CAAC,IAC3C,OAAO,QAAQ,OAAO;AAAA,EACzB,YAAY,QAAQ,WAAW,SAAS;AAAA,IACvC,I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,QACN,UAAU,KAAK;AAAA,QACd,QAAQ;AAAA,QACR,QAAQ,qCAAqC;AAAA,WAC1C;AAAA,MACJ,CAAC,GACD,SACD;AAAA,IACD;AAAA,IACA,OAAO,IAAI,MAAM,KAAK,EAAE,OAAO,gBAAgB,IAAI,GAAG,SAAS;AAAA,GAEjE;AAAA;AAGD,YAAY,YAAY;",
|
|
13
|
+
"debugId": "3B825E64FC0F2E6764756E2164756E21",
|
|
14
|
+
"names": []
|
|
15
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** The allowed issuers of a Clavix deployment, and the tenant each one stands for. */
|
|
2
|
+
export interface IssuerRules {
|
|
3
|
+
/** A lowercase DNS name without a dot at either end. */
|
|
4
|
+
readonly domain: string | undefined;
|
|
5
|
+
/** Issuer to tenant (`undefined` when the list gives none). */
|
|
6
|
+
readonly listed: ReadonlyMap<string, string | undefined>;
|
|
7
|
+
}
|
|
8
|
+
/** `domain` as a lowercase ASCII DNS name, or a `TypeError`. */
|
|
9
|
+
export declare function normaliseDomain(domain: string): string;
|
|
10
|
+
/** The listed issuers as a map; an issuer must be an `https` URL, or `http` on this machine. */
|
|
11
|
+
export declare function listIssuers(issuers: readonly string[] | Readonly<Record<string, string>>): Map<string, string | undefined>;
|
|
12
|
+
/**
|
|
13
|
+
* Whether `issuer` is allowed, and for which tenant: a listed issuer (byte
|
|
14
|
+
* for byte) first, then the domain pattern. `undefined` when refused.
|
|
15
|
+
*/
|
|
16
|
+
export declare function resolveIssuer(rules: IssuerRules, issuer: string): {
|
|
17
|
+
readonly tenant: string | undefined;
|
|
18
|
+
} | undefined;
|
|
19
|
+
//# sourceMappingURL=issuers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"issuers.d.ts","sourceRoot":"","sources":["../src/issuers.ts"],"names":[],"mappings":"AAAA,sFAAsF;AACtF,MAAM,WAAW,WAAW;IAC3B,wDAAwD;IACxD,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IACpC,+DAA+D;IAC/D,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC;CACzD;AAKD,gEAAgE;AAChE,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAiBtD;AAED,gGAAgG;AAChG,wBAAgB,WAAW,CAC1B,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GAC3D,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAwBjC;AAeD;;;GAGG;AACH,wBAAgB,aAAa,CAC5B,KAAK,EAAE,WAAW,EAClB,MAAM,EAAE,MAAM,GACZ;IAAE,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,GAAG,SAAS,CAKrD"}
|
package/dist/lru.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** A map that keeps at most `max` entries, dropping the least recently used. */
|
|
2
|
+
export declare class Lru<V> {
|
|
3
|
+
#private;
|
|
4
|
+
constructor(max: number);
|
|
5
|
+
get size(): number;
|
|
6
|
+
get(key: string): V | undefined;
|
|
7
|
+
delete(key: string): void;
|
|
8
|
+
set(key: string, value: V): void;
|
|
9
|
+
}
|
|
10
|
+
//# sourceMappingURL=lru.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lru.d.ts","sourceRoot":"","sources":["../src/lru.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,qBAAa,GAAG,CAAC,CAAC;;gBAIL,GAAG,EAAE,MAAM;IAIvB,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,CAAC,GAAG,SAAS;IAQ/B,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IAIzB,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,GAAG,IAAI;CAQhC"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { StandardSchemaV1 } from '@softistx/alxia';
|
|
2
|
+
import type { JwtClaims } from '@softistx/alxia-jwt';
|
|
3
|
+
/** Who a verified Clavix access token stands for: what routes behind `bearer()` read as `user`. */
|
|
4
|
+
export interface ClavixPrincipal {
|
|
5
|
+
/** The token's `sub`. */
|
|
6
|
+
readonly subject: string;
|
|
7
|
+
/** The tenant of the issuer: the slug of a pattern issuer, or the mapped name of a listed one. */
|
|
8
|
+
readonly tenant: string;
|
|
9
|
+
/** The token's `iss`. */
|
|
10
|
+
readonly issuer: string;
|
|
11
|
+
/** The client the token was issued to (`client_id`). */
|
|
12
|
+
readonly clientId: string;
|
|
13
|
+
/** The granted scopes: `scope` split on spaces, `[]` when absent. */
|
|
14
|
+
readonly scopes: readonly string[];
|
|
15
|
+
/** The subject's roles, `[]` when absent. */
|
|
16
|
+
readonly roles: readonly string[];
|
|
17
|
+
/** The verified claims, untouched (`permissions`, `cnf`, …). */
|
|
18
|
+
readonly claims: JwtClaims;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The Standard Schema that maps verified claims to a principal. A claim an
|
|
22
|
+
* RFC 9068 token must carry but does not is an issue, so a 401 `claims`.
|
|
23
|
+
*/
|
|
24
|
+
export declare function principalSchema(tenantOf: (issuer: string) => string | undefined): StandardSchemaV1<unknown, ClavixPrincipal>;
|
|
25
|
+
//# sourceMappingURL=principal.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"principal.d.ts","sourceRoot":"","sources":["../src/principal.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACxD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAErD,mGAAmG;AACnG,MAAM,WAAW,eAAe;IAC/B,yBAAyB;IACzB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,kGAAkG;IAClG,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,yBAAyB;IACzB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,wDAAwD;IACxD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,qEAAqE;IACrE,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC,6CAA6C;IAC7C,QAAQ,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IAClC,gEAAgE;IAChE,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC;CAC3B;AAKD;;;GAGG;AACH,wBAAgB,eAAe,CAC9B,QAAQ,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,GAC9C,gBAAgB,CAAC,OAAO,EAAE,eAAe,CAAC,CA8C5C"}
|
package/dist/scope.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type Middleware, type Next, type Problem, type Reply } from '@softistx/alxia';
|
|
2
|
+
/** The body of the 403. */
|
|
3
|
+
export interface InsufficientScopeBody {
|
|
4
|
+
readonly error: 'forbidden';
|
|
5
|
+
readonly reason: 'insufficient_scope';
|
|
6
|
+
/** The scopes the route needs, space-separated. */
|
|
7
|
+
readonly scope: string;
|
|
8
|
+
}
|
|
9
|
+
/** The 403 under `alxia({ errors: 'problem' })`: `reason` and `scope` are its extensions. */
|
|
10
|
+
export type InsufficientScopeProblem = Problem<403, Omit<InsufficientScopeBody, 'error'>>;
|
|
11
|
+
/**
|
|
12
|
+
* What `requireScope()` makes: it reads the `user` that `bearer()` gives and
|
|
13
|
+
* lets the request on, or answers the 403.
|
|
14
|
+
*/
|
|
15
|
+
export type RequireScope = Middleware<{
|
|
16
|
+
user: {
|
|
17
|
+
readonly scopes: readonly string[];
|
|
18
|
+
};
|
|
19
|
+
}, Promise<Reply<403, InsufficientScopeBody | InsufficientScopeProblem> | Next<object>>>;
|
|
20
|
+
/**
|
|
21
|
+
* A guard after `bearer()`: the token must carry every one of `scopes`, or a
|
|
22
|
+
* 403 whose `WWW-Authenticate: Bearer error="insufficient_scope", scope="…"`
|
|
23
|
+
* names them (RFC 6750 section 3.1).
|
|
24
|
+
*
|
|
25
|
+
* ```ts
|
|
26
|
+
* app.use(auth.bearer()).get('/invoices', requireScope('invoices:read'), ({ user, reply }) => …)
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
export declare function requireScope(...scopes: readonly string[]): RequireScope;
|
|
30
|
+
//# sourceMappingURL=scope.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scope.d.ts","sourceRoot":"","sources":["../src/scope.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,KAAK,UAAU,EAEf,KAAK,IAAI,EACT,KAAK,OAAO,EAGZ,KAAK,KAAK,EACV,MAAM,iBAAiB,CAAC;AAEzB,2BAA2B;AAC3B,MAAM,WAAW,qBAAqB;IACrC,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAC;IAC5B,QAAQ,CAAC,MAAM,EAAE,oBAAoB,CAAC;IACtC,mDAAmD;IACnD,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACvB;AAED,6FAA6F;AAC7F,MAAM,MAAM,wBAAwB,GAAG,OAAO,CAC7C,GAAG,EACH,IAAI,CAAC,qBAAqB,EAAE,OAAO,CAAC,CACpC,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,YAAY,GAAG,UAAU,CACpC;IAAE,IAAI,EAAE;QAAE,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAA;KAAE,CAAA;CAAE,EAChD,OAAO,CACN,KAAK,CAAC,GAAG,EAAE,qBAAqB,GAAG,wBAAwB,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,CAC3E,CACD,CAAC;AAEF;;;;;;;;GAQG;AACH,wBAAgB,YAAY,CAAC,GAAG,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,YAAY,CAgCvE"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"unverified-issuer.d.ts","sourceRoot":"","sources":["../src/unverified-issuer.ts"],"names":[],"mappings":"AAGA,gHAAgH;AAChH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAiBlE"}
|
package/docs/README.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# @softistx/alxia-clavix documentation
|
|
2
|
+
|
|
3
|
+
The [package README](../README.md) is the short version. This folder is the long one.
|
|
4
|
+
|
|
5
|
+
## Guide
|
|
6
|
+
|
|
7
|
+
| Page | Read it when |
|
|
8
|
+
| --- | --- |
|
|
9
|
+
| [Issuers and tenants](guide/issuers-and-tenants.md) | choosing `domain` or `issuers`, mapping a custom domain to a tenant, or reading why an issuer was refused |
|
|
10
|
+
| [The principal and scopes](guide/principal-and-scopes.md) | reading `user` in a route, guarding a route with `requireScope`, or reading the 401 and 403 |
|
|
11
|
+
| [Readiness and warm-up](guide/readiness.md) | wiring `/ready`, choosing `warm` issuers, or sizing `maxIssuers` |
|
|
12
|
+
| [Security notes](guide/security.md) | exposing the API to many tenants, wildcard DNS, DPoP, step-up |
|
|
13
|
+
| [Troubleshooting](troubleshooting.md) | something went wrong and you have the message |
|
|
14
|
+
| [Roadmap](roadmap.md) | wondering what is coming, and what is not planned |
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# Issuers and tenants
|
|
2
|
+
|
|
3
|
+
`clavix` reads the token's `iss` without verifying anything, only to decide whether that issuer is
|
|
4
|
+
allowed. An allowed issuer's keys are fetched (OpenID discovery) and the token is verified with them;
|
|
5
|
+
a refused one is `issuer`, with no network call.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { clavix } from '@softistx/alxia-clavix';
|
|
9
|
+
|
|
10
|
+
const auth = clavix({
|
|
11
|
+
domain: 'clavix.example.com',
|
|
12
|
+
issuers: { 'https://login.customer.example.org': 'customer' },
|
|
13
|
+
audience: 'https://api.example.com',
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
auth.tenantOf('https://acme.clavix.example.com'); // 'acme'
|
|
17
|
+
auth.tenantOf('https://login.customer.example.org'); // 'customer'
|
|
18
|
+
auth.tenantOf('https://evil.example.net'); // undefined
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## The pattern
|
|
22
|
+
|
|
23
|
+
With `domain: 'clavix.example.com'`, an issuer is allowed when it is exactly
|
|
24
|
+
`https://<label>.clavix.example.com`:
|
|
25
|
+
|
|
26
|
+
- one DNS label in front of the domain, lowercase ASCII letters, digits and hyphens;
|
|
27
|
+
- no port, userinfo, path, query, fragment, trailing slash or trailing dot;
|
|
28
|
+
- `https` only.
|
|
29
|
+
|
|
30
|
+
`domain` must be dedicated to Clavix tenants: every `https://<label>.<domain>` is trusted, so no other
|
|
31
|
+
host may live under it (a third-party `status.` or `docs.` host, or a dangling CNAME, would become a
|
|
32
|
+
trusted issuer). Other hosts go in `issuers`.
|
|
33
|
+
|
|
34
|
+
The label is the tenant. `domain` is trimmed, lowercased, and a leading or trailing dot is dropped;
|
|
35
|
+
it must be an ASCII DNS name of two labels or more.
|
|
36
|
+
|
|
37
|
+
Refused look-alikes, each `issuer`:
|
|
38
|
+
|
|
39
|
+
| Issuer | Why |
|
|
40
|
+
| --- | --- |
|
|
41
|
+
| `https://a.b.clavix.example.com` | two labels |
|
|
42
|
+
| `https://clavix.example.com` | no tenant label |
|
|
43
|
+
| `https://acme.clavix.example.com/` | trailing slash |
|
|
44
|
+
| `https://acme.clavix.example.com:8443` | port |
|
|
45
|
+
| `https://acme.clavix.example.com.evil.net` | the domain is not the suffix |
|
|
46
|
+
| `https://evilclavix.example.com` | no dot before the domain |
|
|
47
|
+
| `https://Acme.clavix.example.com` | upper case (the issuer is compared as written; the token's `iss` is never lowercased) |
|
|
48
|
+
| `https://xn--acme-9ua.clavix.example.com` | punycode (IDN) label |
|
|
49
|
+
| `http://acme.clavix.example.com` | not https |
|
|
50
|
+
|
|
51
|
+
## Custom domains
|
|
52
|
+
|
|
53
|
+
A tenant on its own domain is not covered by the pattern. List it in `issuers`: as an array, or as
|
|
54
|
+
`{ issuer: tenant }` to name the tenant it stands for. A listed issuer is compared byte for byte, so
|
|
55
|
+
list the exact string the token carries. Listed without a tenant (an array), it is verified but has no
|
|
56
|
+
tenant: `tenantOf` answers `undefined`, and `bearer()` answers 401 `claims` (the issuer has no tenant, `issues[0].path` is `['iss']`),
|
|
57
|
+
so use the map form for any issuer that signs in users.
|
|
58
|
+
|
|
59
|
+
`issuers` accepts `https` URLs, and `http` for `localhost`, `127.0.0.1` and `[::1]` (tests).
|
|
60
|
+
|
|
61
|
+
## Bounding the keys kept
|
|
62
|
+
|
|
63
|
+
Each allowed issuer gets its own key cache, in one of three places:
|
|
64
|
+
|
|
65
|
+
- `warm` issuers are pinned: never evicted, not counted in `maxIssuers`;
|
|
66
|
+
- an issuer met for the first time waits in a probation cache (`probation`, `min(maxIssuers, 16)` by
|
|
67
|
+
default), where forged issuers only push each other out;
|
|
68
|
+
- once a token from it verifies, it moves to the `maxIssuers` cache (default 100), which keeps the most
|
|
69
|
+
recently used ones; the least recently used is dropped past it and fetched again on its next token. See
|
|
70
|
+
[Readiness and warm-up](readiness.md) and [Security notes](security.md).
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# The principal and scopes
|
|
2
|
+
|
|
3
|
+
`auth.bearer()` is `@softistx/alxia-jwt`'s bearer guard with a schema: routes after it read a
|
|
4
|
+
`ClavixPrincipal` as `user`.
|
|
5
|
+
|
|
6
|
+
```ts
|
|
7
|
+
import { alxia } from '@softistx/alxia';
|
|
8
|
+
import { clavix, requireScope } from '@softistx/alxia-clavix';
|
|
9
|
+
|
|
10
|
+
const auth = clavix({ domain: 'clavix.example.com', audience: 'https://api.example.com' });
|
|
11
|
+
|
|
12
|
+
alxia()
|
|
13
|
+
.get('/ping', ({ reply }) => reply(200, 'pong')) // open: declared before the guard
|
|
14
|
+
.use(auth.bearer())
|
|
15
|
+
.get('/me', ({ user, reply }) => reply(200, { tenant: user.tenant, roles: user.roles }))
|
|
16
|
+
.post('/invoices', requireScope('invoices:write'), ({ user, reply }) => reply(201, { by: user.subject }))
|
|
17
|
+
.listen(3000);
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## `ClavixPrincipal`
|
|
21
|
+
|
|
22
|
+
| Field | From |
|
|
23
|
+
| --- | --- |
|
|
24
|
+
| `subject` | `sub` |
|
|
25
|
+
| `tenant` | the issuer: the slug of a pattern issuer, the mapped name of a listed one |
|
|
26
|
+
| `issuer` | `iss` |
|
|
27
|
+
| `clientId` | `client_id` |
|
|
28
|
+
| `scopes` | `scope` split on spaces, `[]` when absent |
|
|
29
|
+
| `roles` | `roles`, `[]` when absent |
|
|
30
|
+
| `claims` | the verified claims, untouched (`permissions`, `cnf`, …) |
|
|
31
|
+
|
|
32
|
+
A token with a missing or empty `sub`, `iss` or `client_id`, or a `scope`, `roles`, `permissions` or
|
|
33
|
+
`cnf` of the wrong shape, is a 401 `malformed`: the RFC 9068 profile refuses it before the principal is
|
|
34
|
+
built. Reason `claims` (with the `issues` listed, `iss` first) is only for an issuer that has no
|
|
35
|
+
tenant, one listed as an array: use `{ issuer: tenant }`. To read from a cookie
|
|
36
|
+
instead of the header: `auth.bearer({ cookie: 'access_token' })`.
|
|
37
|
+
|
|
38
|
+
## `requireScope`
|
|
39
|
+
|
|
40
|
+
`requireScope('a', 'b')` needs every scope and runs after `bearer()`. Without them it answers
|
|
41
|
+
|
|
42
|
+
```http
|
|
43
|
+
HTTP/1.1 403 Forbidden
|
|
44
|
+
www-authenticate: Bearer error="insufficient_scope", scope="a b"
|
|
45
|
+
|
|
46
|
+
{"error":"forbidden","reason":"insufficient_scope","scope":"a b"}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Under `alxia({ errors: 'problem' })` it is an RFC 9457 problem with `reason` and `scope` as
|
|
50
|
+
extensions. Scopes are non-empty strings without spaces or quotes; give at least one.
|
|
51
|
+
|
|
52
|
+
## 401 reasons
|
|
53
|
+
|
|
54
|
+
`missing` (no token), `malformed`, `issuer`, `audience`, `type`, `signature`, `algorithm`, `expired`,
|
|
55
|
+
`not_yet_valid`, `key`, `keys_unavailable`, `claims`. See [Troubleshooting](../troubleshooting.md).
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Readiness and warm-up
|
|
2
|
+
|
|
3
|
+
Keys are fetched from an issuer on the first token it signs. To have a probe say "not ready" until
|
|
4
|
+
important issuers' keys are loaded, list them in `warm` and give `auth.ready` to `health`:
|
|
5
|
+
|
|
6
|
+
```ts
|
|
7
|
+
import { alxia, health } from '@softistx/alxia';
|
|
8
|
+
import { clavix } from '@softistx/alxia-clavix';
|
|
9
|
+
|
|
10
|
+
const auth = clavix({
|
|
11
|
+
domain: 'clavix.example.com',
|
|
12
|
+
audience: 'https://api.example.com',
|
|
13
|
+
warm: ['https://acme.clavix.example.com', 'https://globex.clavix.example.com'],
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
alxia().plugin(health({ checks: { clavix: auth.ready } })).listen(3000);
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
`ready()` resolves `true` once every warm issuer's key set is loaded (fresh within `cacheMs`, or stale
|
|
20
|
+
within `staleMs`), `false` otherwise, and never throws. Calling it is what loads the keys, so the
|
|
21
|
+
probe itself warms them. With no `warm` issuer it is always `true`: a probe cannot wait for tenants it
|
|
22
|
+
does not know.
|
|
23
|
+
|
|
24
|
+
Every warm issuer must be allowed by the same rules as a token's issuer; `clavix` throws a `TypeError`
|
|
25
|
+
at startup otherwise.
|
|
26
|
+
|
|
27
|
+
## Pinned issuers
|
|
28
|
+
|
|
29
|
+
Warm issuers are pinned: their key sets live outside the `maxIssuers` cache and the probation cache,
|
|
30
|
+
are never evicted, and are not counted against `maxIssuers`. Traffic from other tenants, forged
|
|
31
|
+
issuers included, cannot push them out. Keep `warm` to the issuers you must serve at once.
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# Security notes
|
|
2
|
+
|
|
3
|
+
## What is checked
|
|
4
|
+
|
|
5
|
+
A token is accepted only when its issuer is allowed, its signature verifies with that issuer's
|
|
6
|
+
published keys, and the RFC 9068 profile holds: header `typ` `at+jwt`, `aud` containing `audience`,
|
|
7
|
+
`exp`, `iat`, `sub`, `client_id` and `jti` present. The `iss` is read unverified, but only to pick
|
|
8
|
+
whose keys to verify with; an attacker cannot make a token valid by choosing it.
|
|
9
|
+
|
|
10
|
+
## Wildcard DNS
|
|
11
|
+
|
|
12
|
+
With `domain`, any `https://<label>.<domain>` is allowed. If the domain has wildcard DNS, an attacker
|
|
13
|
+
can mint valid-shaped issuers (`https://r4nd0m.clavix.example.com`) in unlimited number. Each unknown
|
|
14
|
+
one costs a discovery fetch. Those issuers cannot evict real tenants: a new issuer waits in a small
|
|
15
|
+
probation cache (`probation`, `min(maxIssuers, 16)` by default) and moves to the `maxIssuers` cache only
|
|
16
|
+
after a token from it verifies, and `warm` issuers are pinned outside both. Forged issuers only push
|
|
17
|
+
each other out of probation. Each fetch is bounded by `timeoutMs` and the memory by the two caches; the
|
|
18
|
+
number of fetches is not, hence the mitigations below. A genuine new tenant whose first token arrives
|
|
19
|
+
during a flood may have to be fetched again. There is no bypass: a token from such an issuer verifies only if that host really
|
|
20
|
+
serves keys for it, which the attacker cannot do under your domain.
|
|
21
|
+
|
|
22
|
+
Dedicate `domain` to Clavix tenants: no other host may live under it. A third-party `status.` or
|
|
23
|
+
`docs.` host, or a dangling CNAME someone can claim, would be a trusted issuer. Host those names
|
|
24
|
+
elsewhere, or list the issuers you trust in `issuers` and leave `domain` out.
|
|
25
|
+
|
|
26
|
+
Mitigations:
|
|
27
|
+
|
|
28
|
+
- list tenants in `issuers` instead of `domain` when they are few and known;
|
|
29
|
+
- keep `maxIssuers` above the real tenant count, and put the tenants you cannot afford to refetch in `warm`;
|
|
30
|
+
- restrict the API's outbound network (egress) to the Clavix hosts;
|
|
31
|
+
- rate-limit unauthenticated requests upstream.
|
|
32
|
+
|
|
33
|
+
## DPoP
|
|
34
|
+
|
|
35
|
+
A token bound to a key carries `cnf.jkt` (RFC 9449). It is exposed on `user.claims.cnf`, but the
|
|
36
|
+
proof is NOT checked here: a stolen DPoP-bound token verifies like a bearer token. Check the proof
|
|
37
|
+
yourself if you rely on binding.
|
|
38
|
+
|
|
39
|
+
## Step-up
|
|
40
|
+
|
|
41
|
+
`acr` and `auth_time` are readable on `user.claims`, but this package does not enforce an
|
|
42
|
+
authentication strength: that is the identity provider's decision (see the [roadmap](../roadmap.md)).
|
package/docs/roadmap.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Roadmap
|
|
2
|
+
|
|
3
|
+
What `@softistx/alxia-clavix` gives an app, and what is coming. This page is a
|
|
4
|
+
direction, not a commitment: the version something shipped in is the only
|
|
5
|
+
number on it.
|
|
6
|
+
|
|
7
|
+
## Now
|
|
8
|
+
|
|
9
|
+
- **Moving to the `@softistx` scope.** The package is now `@softistx/alxia-clavix` (it was `@alxia/clavix`). Same code and API; replace the dependency and the imports ([migration guide](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/migrating-from-alxia-scope.md)). The old name is deprecated.
|
|
10
|
+
|
|
11
|
+
## Next
|
|
12
|
+
|
|
13
|
+
Nothing scheduled yet.
|
|
14
|
+
|
|
15
|
+
## Later
|
|
16
|
+
|
|
17
|
+
- **Reserved labels.** Keep names such as `www`, `status` or `docs` from being
|
|
18
|
+
accepted as a tenant under `domain`.
|
|
19
|
+
|
|
20
|
+
## Not planned
|
|
21
|
+
|
|
22
|
+
- **Step-up checks (`acr`, `auth_time`) in the API.** The identity provider
|
|
23
|
+
decides how strongly a user signed in.
|
|
24
|
+
|
|
25
|
+
## Shipped
|
|
26
|
+
|
|
27
|
+
### 0.1.0
|
|
28
|
+
|
|
29
|
+
- **Verify Clavix access tokens in an API.** A multi-tenant issuer allow-list
|
|
30
|
+
(a domain pattern and listed issuers, with the tenant of each), the RFC 9068
|
|
31
|
+
profile, the principal as `user`, `requireScope`, and readiness with `warm`.
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
# Troubleshooting
|
|
2
|
+
|
|
3
|
+
Each entry is headed by the text you see: an exception thrown by `clavix` or `requireScope` at
|
|
4
|
+
startup (`verify` never throws), or the body of a 401 or 403.
|
|
5
|
+
|
|
6
|
+
**Startup**
|
|
7
|
+
|
|
8
|
+
- [`TypeError: clavix: give domain, issuers, or both`](#typeerror-clavix-give-domain-issuers-or-both)
|
|
9
|
+
- [`TypeError: clavix: audience is required`](#typeerror-clavix-audience-is-required)
|
|
10
|
+
- [`TypeError: clavix: maxIssuers must be a positive integer`](#typeerror-clavix-maxissuers-must-be-a-positive-integer)
|
|
11
|
+
- [`TypeError: clavix: domain must be an ASCII DNS name such as "clavix.example", got …`](#typeerror-clavix-domain-must-be-an-ascii-dns-name-such-as-clavixexample-got-)
|
|
12
|
+
- [`TypeError: clavix: issuer is not a URL: …`](#typeerror-clavix-issuer-is-not-a-url-)
|
|
13
|
+
- [`TypeError: clavix: issuer must be an https URL: …`](#typeerror-clavix-issuer-must-be-an-https-url-)
|
|
14
|
+
- [`TypeError: clavix: probation must be a positive integer`](#typeerror-clavix-probation-must-be-a-positive-integer)
|
|
15
|
+
- [`TypeError: clavix: the tenant of … is empty`](#typeerror-clavix-the-tenant-of--is-empty)
|
|
16
|
+
- [`TypeError: clavix: warm issuer … is not allowed`](#typeerror-clavix-warm-issuer--is-not-allowed)
|
|
17
|
+
- [`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)
|
|
18
|
+
|
|
19
|
+
**Responses**
|
|
20
|
+
|
|
21
|
+
- [`401 { "error": "unauthorized", "reason": "issuer" }`](#401-reason-issuer)
|
|
22
|
+
- [`401 … "reason": "audience"`](#401-reason-audience)
|
|
23
|
+
- [`401 … "reason": "type"`](#401-reason-type)
|
|
24
|
+
- [`401 … "reason": "missing"`](#401-reason-missing)
|
|
25
|
+
- [`401 … "reason": "signature"` or `"algorithm"`](#401-reason-signature-or-algorithm)
|
|
26
|
+
- [`401 … "reason": "malformed"`](#401-reason-malformed)
|
|
27
|
+
- [`401 … "reason": "claims"`](#401-reason-claims)
|
|
28
|
+
- [`401 … "reason": "expired"` or `"not_yet_valid"`](#401-reason-expired-or-not_yet_valid)
|
|
29
|
+
- [`401 … "reason": "key"` or `"keys_unavailable"`](#401-reason-key-or-keys_unavailable)
|
|
30
|
+
- [`403 { "error": "forbidden", "reason": "insufficient_scope" }`](#403-insufficient_scope)
|
|
31
|
+
|
|
32
|
+
**Traps**
|
|
33
|
+
|
|
34
|
+
- [`/ready` stays 503 or flips back](#ready-stays-503-or-flips-back)
|
|
35
|
+
|
|
36
|
+
## Startup
|
|
37
|
+
|
|
38
|
+
### `TypeError: clavix: give domain, issuers, or both`
|
|
39
|
+
|
|
40
|
+
Neither `domain` nor `issuers` was given, or `issuers` is empty (`[]` or `{}`) with no `domain`, so no
|
|
41
|
+
issuer could ever be allowed.
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
import { clavix } from '@softistx/alxia-clavix';
|
|
45
|
+
|
|
46
|
+
clavix({ domain: 'clavix.example.com', audience: 'https://api.example.com' });
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### `TypeError: clavix: audience is required`
|
|
50
|
+
|
|
51
|
+
`audience` is missing or empty. Give the API's identifier, the one clients request tokens for (the
|
|
52
|
+
"Resource identifier" in Clavix). A token's `aud` must contain it exactly.
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
import { clavix } from '@softistx/alxia-clavix';
|
|
56
|
+
|
|
57
|
+
clavix({ domain: 'clavix.example.com', audience: 'https://api.example.com' });
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### `TypeError: clavix: maxIssuers must be a positive integer`
|
|
61
|
+
|
|
62
|
+
`maxIssuers` was `0`, negative, fractional or `NaN`. Leave it out for 100, or give an integer of 1 or more.
|
|
63
|
+
|
|
64
|
+
### `TypeError: clavix: domain must be an ASCII DNS name such as "clavix.example", got …`
|
|
65
|
+
|
|
66
|
+
`domain` has fewer than two labels, a label that is empty, too long or has characters other than
|
|
67
|
+
letters, digits and hyphens, or an `xn--` label. Give the bare domain, with no scheme, port or path
|
|
68
|
+
(a leading or trailing dot is dropped).
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
import { clavix } from '@softistx/alxia-clavix';
|
|
72
|
+
|
|
73
|
+
clavix({ domain: 'clavix.example.com', audience: 'https://api.example.com' }); // not 'https://clavix.example.com'
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### `TypeError: clavix: issuer is not a URL: …`
|
|
77
|
+
|
|
78
|
+
An entry of `issuers` does not parse as a URL. Give the full issuer, as the token carries it.
|
|
79
|
+
|
|
80
|
+
### `TypeError: clavix: issuer must be an https URL: …`
|
|
81
|
+
|
|
82
|
+
An entry of `issuers` is not `https`. Only `http` on `localhost`, `127.0.0.1` or `[::1]` is accepted,
|
|
83
|
+
for tests.
|
|
84
|
+
|
|
85
|
+
### `TypeError: clavix: probation must be a positive integer`
|
|
86
|
+
|
|
87
|
+
`probation` was `0`, negative, fractional or `NaN`. Leave it out for `min(maxIssuers, 16)`, or give an
|
|
88
|
+
integer of 1 or more.
|
|
89
|
+
|
|
90
|
+
### `TypeError: clavix: the tenant of … is empty`
|
|
91
|
+
|
|
92
|
+
In the `{ issuer: tenant }` form a tenant is `''`. Name it, or use the array form for an issuer with no tenant.
|
|
93
|
+
|
|
94
|
+
### `TypeError: clavix: warm issuer … is not allowed`
|
|
95
|
+
|
|
96
|
+
A `warm` entry fails the rules a token's issuer would: it is neither listed in `issuers` nor
|
|
97
|
+
`https://<one label>.<domain>`. Check for a trailing slash or a port.
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
import { clavix } from '@softistx/alxia-clavix';
|
|
101
|
+
|
|
102
|
+
clavix({
|
|
103
|
+
domain: 'clavix.example.com',
|
|
104
|
+
audience: 'https://api.example.com',
|
|
105
|
+
warm: ['https://acme.clavix.example.com'], // no trailing slash
|
|
106
|
+
});
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### `TypeError: requireScope: give scopes, each a non-empty token without spaces or quotes`
|
|
110
|
+
|
|
111
|
+
`requireScope()` got no scope, or one with a space, a quote or a backslash. One argument per scope:
|
|
112
|
+
`requireScope('invoices:read', 'invoices:write')`, not `requireScope('invoices:read invoices:write')`.
|
|
113
|
+
|
|
114
|
+
## Responses
|
|
115
|
+
|
|
116
|
+
### 401 reason `issuer`
|
|
117
|
+
|
|
118
|
+
The token's `iss` is readable but not allowed. Compare the token's `iss` (decode its payload)
|
|
119
|
+
with your options, byte for byte: a trailing slash (`https://acme.clavix.example.com/`), a port, a
|
|
120
|
+
different host or a second label (`a.b.clavix.example.com`) all refuse. A custom domain needs an entry
|
|
121
|
+
in `issuers`. See [Issuers and tenants](guide/issuers-and-tenants.md). Nothing is fetched for a refused issuer.
|
|
122
|
+
|
|
123
|
+
### 401 reason `audience`
|
|
124
|
+
|
|
125
|
+
The token's `aud` does not contain `audience`. The client asked Clavix for a token for another
|
|
126
|
+
resource. `audience` must equal the Resource identifier the client requested, character for character
|
|
127
|
+
(scheme, host, no extra trailing slash). It is not the request's `Host` header: the API's own host name
|
|
128
|
+
plays no part.
|
|
129
|
+
|
|
130
|
+
### 401 reason `type`
|
|
131
|
+
|
|
132
|
+
The token's header `typ` is not `at+jwt`: it is an ID token or another kind of JWT, not an RFC 9068
|
|
133
|
+
access token. The client must send the access token, not the ID token.
|
|
134
|
+
|
|
135
|
+
### 401 reason `missing`
|
|
136
|
+
|
|
137
|
+
No `Authorization: Bearer <token>` header (and no cookie, when `bearer({ cookie })` is set). The client must send the access token.
|
|
138
|
+
|
|
139
|
+
### 401 reason `signature` or `algorithm`
|
|
140
|
+
|
|
141
|
+
`signature`: the token was not signed by a key the issuer publishes (tampered, or signed by another issuer). `algorithm`: its `alg` is not one the verifier accepts (`none` and `HS*` are always refused; see `algorithms`). Ask the client to request a fresh token from Clavix.
|
|
142
|
+
|
|
143
|
+
### 401 reason `malformed`
|
|
144
|
+
|
|
145
|
+
The value is not a three-part JWT, its payload is not JSON with a string `iss`, an RFC 9068 claim
|
|
146
|
+
(`iss`, `aud`, `exp`, `iat`, `sub`, `client_id`, `jti`) is missing or empty, or `scope`, `roles`,
|
|
147
|
+
`permissions` or `cnf` has the wrong shape (the profile refuses these first, so they are never `claims`). Check the header sends
|
|
148
|
+
`Authorization: Bearer <token>` with nothing else around the token.
|
|
149
|
+
|
|
150
|
+
### 401 reason `claims`
|
|
151
|
+
|
|
152
|
+
The token is valid, but its issuer has no tenant: it is listed in `issuers` as an array. The body's
|
|
153
|
+
`issues` points at `iss`. Use `{ issuer: tenant }` for such an issuer. Missing or badly shaped claims
|
|
154
|
+
are `malformed`, not `claims`.
|
|
155
|
+
|
|
156
|
+
### 401 reason `expired` or `not_yet_valid`
|
|
157
|
+
|
|
158
|
+
The token's `exp` has passed, or its `nbf` is in the future. Refresh the token, or check the
|
|
159
|
+
clocks; `clockTolerance` (seconds) allows for small skew.
|
|
160
|
+
|
|
161
|
+
### 401 reason `key` or `keys_unavailable`
|
|
162
|
+
|
|
163
|
+
`key`: no published key matches the token's `kid` (after one refetch). `keys_unavailable`: the issuer's
|
|
164
|
+
keys could not be fetched and none is cached. Check that the issuer's discovery document is reachable
|
|
165
|
+
from the API (egress, DNS, `timeoutMs`). See
|
|
166
|
+
[`@softistx/alxia-jwt`'s JWKS guide](https://github.com/softistx/alxia/blob/develop/packages/jwt/docs/guide/jwks.md).
|
|
167
|
+
|
|
168
|
+
### 403 `insufficient_scope`
|
|
169
|
+
|
|
170
|
+
```json
|
|
171
|
+
{ "error": "forbidden", "reason": "insufficient_scope", "scope": "invoices:write" }
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
The token is valid but lacks a scope `requireScope` asks for (all are required); `scope` lists them
|
|
175
|
+
and `WWW-Authenticate` repeats them. The client must request the scope from Clavix.
|
|
176
|
+
|
|
177
|
+
## Traps
|
|
178
|
+
|
|
179
|
+
### `/ready` stays 503 or flips back
|
|
180
|
+
|
|
181
|
+
`ready` is `false` while a `warm` issuer's keys are not loaded. Warm issuers are pinned and never
|
|
182
|
+
evicted, so check the issuer's discovery URL is reachable. See [Readiness and warm-up](guide/readiness.md).
|
package/package.json
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@softistx/alxia-clavix",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Verify the access tokens Clavix issues in an alxia API: a multi-tenant issuer allow-list on the RFC 9068 profile of @softistx/alxia-jwt",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"files": [
|
|
10
|
+
"dist",
|
|
11
|
+
"docs",
|
|
12
|
+
"README.md",
|
|
13
|
+
"package.json",
|
|
14
|
+
"LICENSE"
|
|
15
|
+
],
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"import": "./dist/index.js",
|
|
20
|
+
"default": "./dist/index.js"
|
|
21
|
+
},
|
|
22
|
+
"./package.json": "./package.json"
|
|
23
|
+
},
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "git+https://github.com/softistx/alxia.git",
|
|
27
|
+
"directory": "packages/clavix"
|
|
28
|
+
},
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"registry": "https://registry.npmjs.org",
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "bun run ../../build.ts",
|
|
35
|
+
"test": "bun test src",
|
|
36
|
+
"typecheck": "tsc --noEmit"
|
|
37
|
+
},
|
|
38
|
+
"alxia": {
|
|
39
|
+
"entrypoints": [
|
|
40
|
+
"src/index.ts"
|
|
41
|
+
]
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@softistx/alxia": "^0.28.0",
|
|
45
|
+
"@softistx/alxia-jwt": "^0.9.0",
|
|
46
|
+
"@types/bun": "^1.4.4"
|
|
47
|
+
},
|
|
48
|
+
"peerDependencies": {
|
|
49
|
+
"@softistx/alxia": "^0.28.0",
|
|
50
|
+
"@softistx/alxia-jwt": "^0.9.0",
|
|
51
|
+
"typescript": "^6.0.3 || ^7.0.0"
|
|
52
|
+
}
|
|
53
|
+
}
|