@softistx/alxia-clavix 0.3.3 → 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.
package/README.md CHANGED
@@ -38,6 +38,35 @@ A request without a valid token is a 401 `{ error: 'unauthorized', reason }` (a
38
38
  scope is a 403 `{ error: 'forbidden', reason: 'insufficient_scope', scope }` with a
39
39
  `WWW-Authenticate` challenge.
40
40
 
41
+ ## An API on Clavix in a few lines
42
+
43
+ `clavixEnv()` reads the `CLAVIX_*` variables at start-up and refuses each wrong one by name (`zod` is an optional peer, needed by the `/env` subpath only); `clavixResource({ viewerOf })` wires the verifier, the DPoP replay store and a `viewer` middleware, and the app writes only `viewerOf(principal)`.
44
+
45
+ ```ts
46
+ import { alxia } from '@softistx/alxia';
47
+ import { clavixResource } from '@softistx/alxia-clavix';
48
+ import { clavixEnv } from '@softistx/alxia-clavix/env';
49
+ import { redisDpopReplayStore } from '@softistx/alxia-redis';
50
+ import { connectRedis } from '@softistx/redis';
51
+
52
+ const redis = await connectRedis(Bun.env['REDIS_URL']!);
53
+ const settings = clavixEnv({ resource: true }); // throws a ClavixEnvError naming every refused variable
54
+
55
+ const resource = clavixResource({
56
+ issuer: settings.issuer,
57
+ audience: settings.audience,
58
+ origin: settings.origin,
59
+ replay: redisDpopReplayStore(redis.client, { name: 'dpop' }),
60
+ viewerOf: async (principal) => ({ id: principal.subject, tenant: principal.tenant }),
61
+ });
62
+
63
+ alxia()
64
+ .use(resource.viewer) // routes read `viewer`: 401 refused, 403 scope, 503 issuer or store down
65
+ .get('/me', ({ viewer, reply }) => reply(200, { viewer }));
66
+ ```
67
+
68
+ See [Wiring an API to Clavix](https://github.com/softistx/alxia/blob/develop/packages/clavix/docs/guide/wiring-an-api.md).
69
+
41
70
  ## Issuers and tenants
42
71
 
43
72
  An issuer is allowed when it is listed (byte for byte) or is exactly `https://<one label>.<domain>`
@@ -84,7 +113,7 @@ clavix({
84
113
  });
85
114
  ```
86
115
 
87
- `memoryDpopReplayStore()` is the replay store for tests and one instance only. No peer on
116
+ `memoryDpopReplayStore()` is the replay store for development and tests only (use it when Redis is absent, rather than a fallback of your own). No peer on
88
117
  `@softistx/alxia-redis` is needed: its store is typed by shape.
89
118
 
90
119
  See [Security notes](https://github.com/softistx/alxia/blob/develop/packages/clavix/docs/guide/security.md#dpop).
@@ -107,8 +136,10 @@ See [Security notes](https://github.com/softistx/alxia/blob/develop/packages/cla
107
136
  | `auth.ready()` | `Promise<boolean>`, never throws: `true` once every `warm` issuer's keys are loaded (always `true` with none) |
108
137
  | `auth.tenantOf(issuer)` | the tenant of an allowed issuer; `undefined` if refused or listed without a tenant |
109
138
  | `requireScope(...scopes)` | a guard after `bearer()`: every scope required, else a 403 `insufficient_scope` |
139
+ | `clavixResource({ issuer, audience, origin, replay, viewerOf, scope?, nonce?, tenant?, carries?, body?, onError? })` | a `ClavixResource<Viewer>`: `viewer` (middleware giving routes `viewer`), `streamViewer(request)` and `ready()` |
140
+ | `clavixEnv({ source?, production?, resource? })`, `clavixEnvShape({ production? })`, `ClavixEnvError` (`@softistx/alxia-clavix/env`) | the `CLAVIX_*` variables parsed eagerly into a `ClavixEnv`, or the zod shape to compose; each refused variable named in `error.issues` |
110
141
  | `ClavixPrincipal` | `subject`, `tenant`, `issuer`, `clientId`, `scopes`, `roles`, `claims` |
111
- | `ClavixOptions`, `ClavixVerifier`, `DpopOptions`, `DpopReplayStore`, `DpopNonce`, `DpopReason`, `ClavixGuard`, `ClavixUnauthorizedBody`, `ClavixUnauthorizedProblem`, `ClavixUnavailableBody`, `ClavixUnavailableProblem`, `RequireScope`, `InsufficientScopeBody`, `InsufficientScopeProblem` | the types |
142
+ | `ClavixOptions`, `ClavixVerifier`, `DpopOptions`, `DpopReplayStore`, `DpopNonce`, `DpopReason`, `ClavixGuard`, `ClavixUnauthorizedBody`, `ClavixUnauthorizedProblem`, `ClavixUnavailableBody`, `ClavixUnavailableProblem`, `RequireScope`, `InsufficientScopeBody`, `InsufficientScopeProblem`, `ClavixResource`, `ClavixResourceOptions`, `ClavixViewerContext`, `ClavixViewerMiddleware`, `ClavixRefusal`, `ViewerOf` (and from `/env`: `ClavixEnv`, `ClavixResourceEnv`, `ClavixEnvOptions`, `ClavixEnvIssue`, `ClavixEnvSource`) | the types |
112
143
 
113
144
  Why a token is refused (`verify` result, or the 401 `reason`; `keys_unavailable` is answered as a 503): `malformed` (not a JWT, no readable
114
145
  `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),
@@ -117,7 +148,7 @@ Why a token is refused (`verify` result, or the 401 `reason`; `keys_unavailable`
117
148
 
118
149
  ## Documentation
119
150
 
120
- - [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.
151
+ - [Guide](https://github.com/softistx/alxia/blob/develop/packages/clavix/docs/README.md): wiring an API to Clavix, issuers and tenants, the principal and scopes, readiness and warm-up, security notes.
121
152
  - [Troubleshooting](https://github.com/softistx/alxia/blob/develop/packages/clavix/docs/troubleshooting.md): an error message, and what to do about it.
122
153
  - [Roadmap](https://github.com/softistx/alxia/blob/develop/packages/clavix/docs/roadmap.md): what is coming, and what is not planned.
123
154
  - [Authenticate requests](https://github.com/softistx/alxia/blob/develop/docs/recipes/authentication.md): the recipe for bearer tokens in general.
@@ -0,0 +1,99 @@
1
+ import { z } from 'zod';
2
+ /** Where the variables are read from: `process.env` by default. */
3
+ export type ClavixEnvSource = Readonly<Record<string, string | undefined>>;
4
+ export interface ClavixEnvOptions {
5
+ /** The variables to read. `process.env` by default. */
6
+ readonly source?: ClavixEnvSource;
7
+ /**
8
+ * Whether `CLAVIX_API_ORIGIN` must be an `https` origin. `NODE_ENV ===
9
+ * 'production'` of the source by default.
10
+ */
11
+ readonly production?: boolean;
12
+ /**
13
+ * `true` when the API verifies Clavix access tokens (it is a resource
14
+ * server): `CLAVIX_ISSUER`, `CLAVIX_AUDIENCE` and `CLAVIX_API_ORIGIN`
15
+ * are then required. `false` by default: every variable is optional, and
16
+ * a partial set is the only error.
17
+ */
18
+ readonly resource?: boolean;
19
+ }
20
+ /** One refused variable. */
21
+ export interface ClavixEnvIssue {
22
+ /** The variable's name, such as `CLAVIX_CLIENT_SECRET_FILE`. */
23
+ readonly name: string;
24
+ /** What is wrong with it, never its value. */
25
+ readonly message: string;
26
+ }
27
+ /** Thrown by `clavixEnv()`: every refused variable at once, each by name. */
28
+ export declare class ClavixEnvError extends Error {
29
+ readonly issues: readonly ClavixEnvIssue[];
30
+ constructor(issues: readonly ClavixEnvIssue[]);
31
+ }
32
+ /** The Clavix settings of an API, read from its environment. */
33
+ export interface ClavixEnv {
34
+ /** `CLAVIX_ISSUER`: the tenant's issuer, `https` (`http` on localhost outside production). */
35
+ readonly issuer: string | undefined;
36
+ /** `CLAVIX_AUDIENCE`: the API's identifier, which a token's `aud` must contain. */
37
+ readonly audience: string | undefined;
38
+ /**
39
+ * `CLAVIX_API_ORIGIN`: the public origin of the API (scheme and host, no
40
+ * path), what a DPoP proof's `htu` must start with.
41
+ */
42
+ readonly origin: string | undefined;
43
+ /** `CLAVIX_SCOPE`: the scope every access token must carry, when set. */
44
+ readonly scope: string | undefined;
45
+ /** `CLAVIX_CLIENT_ID`: the id of the client registered with Clavix. */
46
+ readonly clientId: string | undefined;
47
+ /** `CLAVIX_CLIENT_SECRET_FILE`: the path of the file holding the client secret. */
48
+ readonly clientSecretFile: string | undefined;
49
+ /** `CLAVIX_WEBHOOK_SECRET_FILE`: the path of the file holding the webhook signing secret. */
50
+ readonly webhookSecretFile: string | undefined;
51
+ /** `CLAVIX_MACHINE_CLIENT_ID`: the machine client that calls Clavix's management API. */
52
+ readonly machineClientId: string | undefined;
53
+ /** `CLAVIX_MACHINE_SECRET_FILE`: the path of the file holding its secret. */
54
+ readonly machineSecretFile: string | undefined;
55
+ }
56
+ /** What `clavixEnv({ resource: true })` gives: the resource server's three settings are set. */
57
+ export type ClavixResourceEnv = ClavixEnv & {
58
+ readonly issuer: string;
59
+ readonly audience: string;
60
+ readonly origin: string;
61
+ };
62
+ /**
63
+ * The zod shape of the `CLAVIX_*` variables, to compose in an app's own
64
+ * `z.object`. Each variable is optional and an empty one counts as unset;
65
+ * a `*_FILE` variable is refused, by name, when it points at a directory,
66
+ * at a missing or unreadable file, or at an empty one. The rules that look
67
+ * at several variables (a partial set) are `clavixEnv()`'s.
68
+ *
69
+ * ```ts
70
+ * const env = z.object({ PORT: z.coerce.number(), ...clavixEnvShape() }).parse(process.env);
71
+ * ```
72
+ */
73
+ export declare function clavixEnvShape(options?: {
74
+ readonly production?: boolean;
75
+ }): {
76
+ CLAVIX_ISSUER: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodString, z.ZodTransform<string | undefined, string>>, z.ZodOptional<z.ZodType<string, string, z.core.$ZodTypeInternals<string, string>>>>>;
77
+ CLAVIX_AUDIENCE: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodString, z.ZodTransform<string | undefined, string>>, z.ZodOptional<z.ZodType<string, string, z.core.$ZodTypeInternals<string, string>>>>>;
78
+ CLAVIX_API_ORIGIN: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodString, z.ZodTransform<string | undefined, string>>, z.ZodOptional<z.ZodType<string, string, z.core.$ZodTypeInternals<string, string>>>>>;
79
+ CLAVIX_SCOPE: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodString, z.ZodTransform<string | undefined, string>>, z.ZodOptional<z.ZodType<string, string, z.core.$ZodTypeInternals<string, string>>>>>;
80
+ CLAVIX_CLIENT_ID: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodString, z.ZodTransform<string | undefined, string>>, z.ZodOptional<z.ZodType<string, string, z.core.$ZodTypeInternals<string, string>>>>>;
81
+ CLAVIX_CLIENT_SECRET_FILE: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodString, z.ZodTransform<string | undefined, string>>, z.ZodOptional<z.ZodType<string, string, z.core.$ZodTypeInternals<string, string>>>>>;
82
+ CLAVIX_WEBHOOK_SECRET_FILE: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodString, z.ZodTransform<string | undefined, string>>, z.ZodOptional<z.ZodType<string, string, z.core.$ZodTypeInternals<string, string>>>>>;
83
+ CLAVIX_MACHINE_CLIENT_ID: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodString, z.ZodTransform<string | undefined, string>>, z.ZodOptional<z.ZodType<string, string, z.core.$ZodTypeInternals<string, string>>>>>;
84
+ CLAVIX_MACHINE_SECRET_FILE: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodString, z.ZodTransform<string | undefined, string>>, z.ZodOptional<z.ZodType<string, string, z.core.$ZodTypeInternals<string, string>>>>>;
85
+ };
86
+ /**
87
+ * The Clavix settings of an API, parsed eagerly: call it once at start-up
88
+ * and a wrong or partial configuration stops the process with one
89
+ * `ClavixEnvError` naming every refused variable (never a value).
90
+ *
91
+ * ```ts
92
+ * const clavixSettings = clavixEnv({ resource: true });
93
+ * ```
94
+ */
95
+ export declare function clavixEnv(options: ClavixEnvOptions & {
96
+ readonly resource: true;
97
+ }): ClavixResourceEnv;
98
+ export declare function clavixEnv(options?: ClavixEnvOptions): ClavixEnv;
99
+ //# sourceMappingURL=env.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.d.ts","sourceRoot":"","sources":["../../src/env/env.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,mEAAmE;AACnE,MAAM,MAAM,eAAe,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAC;AAE3E,MAAM,WAAW,gBAAgB;IAChC,uDAAuD;IACvD,QAAQ,CAAC,MAAM,CAAC,EAAE,eAAe,CAAC;IAClC;;;OAGG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,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IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACxB,CAAC;AAwDF;;;;;;;;;;GAUG;AACH,wBAAgB,cAAc,CAC7B,OAAO,GAAE;IAAE,QAAQ,CAAC,UAAU,CAAC,EAAE,OAAO,CAAA;CAAO;;;;;;;;;;EAa/C;AAmDD;;;;;;;;GAQG;AACH,wBAAgB,SAAS,CACxB,OAAO,EAAE,gBAAgB,GAAG;IAAE,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAA;CAAE,GACrD,iBAAiB,CAAC;AACrB,wBAAgB,SAAS,CAAC,OAAO,CAAC,EAAE,gBAAgB,GAAG,SAAS,CAAC"}
@@ -0,0 +1,2 @@
1
+ export { type ClavixEnv, ClavixEnvError, type ClavixEnvIssue, type ClavixEnvOptions, type ClavixEnvSource, type ClavixResourceEnv, clavixEnv, clavixEnvShape, } from './env';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/env/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,SAAS,EACd,cAAc,EACd,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,KAAK,iBAAiB,EACtB,SAAS,EACT,cAAc,GACd,MAAM,OAAO,CAAC"}
@@ -0,0 +1,142 @@
1
+ // src/env/env.ts
2
+ import { z } from "zod";
3
+
4
+ // src/env/secret-file.ts
5
+ import { readFileSync, statSync } from "node:fs";
6
+ function secretFileProblem(name, path) {
7
+ let stat;
8
+ try {
9
+ stat = statSync(path);
10
+ } catch {
11
+ return `${name} points at a file that does not exist or cannot be reached`;
12
+ }
13
+ if (stat.isDirectory()) {
14
+ return `${name} points at a directory, not a file`;
15
+ }
16
+ if (!stat.isFile())
17
+ return `${name} does not point at a regular file`;
18
+ if ((stat.mode & 63) !== 0) {
19
+ return `${name} is readable by group or others (mode ${(stat.mode & 511).toString(8)}); restrict it to its owner, such as chmod 600`;
20
+ }
21
+ let text;
22
+ try {
23
+ text = readFileSync(path, "utf8");
24
+ } catch {
25
+ return `${name} points at a file that cannot be read: check its permissions`;
26
+ }
27
+ if (text.trim() === "")
28
+ return `${name} points at an empty file`;
29
+ return;
30
+ }
31
+
32
+ // src/env/env.ts
33
+ class ClavixEnvError extends Error {
34
+ issues;
35
+ constructor(issues) {
36
+ super(`Invalid CLAVIX_* environment:
37
+ ${issues.map((i) => ` ${i.message.startsWith(i.name) ? i.message : `${i.name}: ${i.message}`}`).join(`
38
+ `)}`);
39
+ this.name = "ClavixEnvError";
40
+ this.issues = issues;
41
+ }
42
+ }
43
+ var optional = (schema) => z.string().transform((value) => value === "" ? undefined : value).pipe(schema.optional()).optional();
44
+ var secretFile = (name) => optional(z.string().superRefine((path, ctx) => {
45
+ const problem = secretFileProblem(name, path);
46
+ if (problem !== undefined)
47
+ ctx.addIssue({ code: "custom", message: problem });
48
+ }));
49
+ var LOCAL = new Set(["localhost", "127.0.0.1", "[::1]"]);
50
+ var issuerOf = (production) => optional(z.url({ protocol: /^https?$/ }).refine((value) => {
51
+ if (!URL.canParse(value))
52
+ return true;
53
+ const url = new URL(value);
54
+ if (url.protocol !== "https:" && url.protocol !== "http:")
55
+ return true;
56
+ return url.protocol === "https:" || !production && LOCAL.has(url.hostname);
57
+ }, production ? "must be an https URL" : "must be an https URL (http only on localhost)"));
58
+ var origin = (production) => optional(z.url().refine((value) => {
59
+ const url = new URL(value);
60
+ return url.origin === value && (!production || url.protocol === "https:");
61
+ }, production ? "must be an https origin (scheme and host, no path or trailing slash)" : "must be an origin (scheme and host, no path or trailing slash)"));
62
+ function clavixEnvShape(options = {}) {
63
+ return {
64
+ CLAVIX_ISSUER: issuerOf(options.production ?? false),
65
+ CLAVIX_AUDIENCE: optional(z.string().min(1)),
66
+ CLAVIX_API_ORIGIN: origin(options.production ?? false),
67
+ CLAVIX_SCOPE: optional(z.string().min(1)),
68
+ CLAVIX_CLIENT_ID: optional(z.string().min(1)),
69
+ CLAVIX_CLIENT_SECRET_FILE: secretFile("CLAVIX_CLIENT_SECRET_FILE"),
70
+ CLAVIX_WEBHOOK_SECRET_FILE: secretFile("CLAVIX_WEBHOOK_SECRET_FILE"),
71
+ CLAVIX_MACHINE_CLIENT_ID: optional(z.string().min(1)),
72
+ CLAVIX_MACHINE_SECRET_FILE: secretFile("CLAVIX_MACHINE_SECRET_FILE")
73
+ };
74
+ }
75
+ function missing(parsed, names, message) {
76
+ return names.filter((name) => parsed[name] === undefined).map((name) => ({ name, message: message(name) }));
77
+ }
78
+ function crossChecks(parsed, resource) {
79
+ const issues = [];
80
+ if (resource) {
81
+ issues.push(...missing(parsed, ["CLAVIX_ISSUER", "CLAVIX_AUDIENCE", "CLAVIX_API_ORIGIN"], () => "required: the API verifies Clavix access tokens"));
82
+ }
83
+ const signIn = ["CLAVIX_CLIENT_ID", "CLAVIX_CLIENT_SECRET_FILE"];
84
+ const machine = [
85
+ "CLAVIX_MACHINE_CLIENT_ID",
86
+ "CLAVIX_MACHINE_SECRET_FILE"
87
+ ];
88
+ for (const pair of [signIn, machine]) {
89
+ const unset = pair.filter((name) => parsed[name] === undefined);
90
+ if (unset.length === 1) {
91
+ issues.push({
92
+ name: unset[0],
93
+ message: `unset while ${pair.find((name) => name !== unset[0])} is set: set both of ${pair.join(", ")}, or none`
94
+ });
95
+ }
96
+ const some = pair.some((name) => parsed[name] !== undefined);
97
+ if (some && parsed.CLAVIX_ISSUER === undefined && !resource) {
98
+ issues.push({
99
+ name: "CLAVIX_ISSUER",
100
+ message: `required when ${pair.join(" and ")} are set`
101
+ });
102
+ }
103
+ }
104
+ return issues;
105
+ }
106
+ function clavixEnv(options = {}) {
107
+ const source = options.source ?? process.env;
108
+ const production = options.production ?? source["NODE_ENV"] === "production";
109
+ const resource = options.resource ?? false;
110
+ const result = z.object(clavixEnvShape({ production })).safeParse(source);
111
+ const issues = [];
112
+ if (!result.success) {
113
+ for (const issue of result.error.issues) {
114
+ const name = String(issue.path[0] ?? "CLAVIX_*");
115
+ issues.push({ name, message: issue.message });
116
+ }
117
+ } else {
118
+ issues.push(...crossChecks(result.data, resource));
119
+ }
120
+ if (issues.length > 0 || !result.success)
121
+ throw new ClavixEnvError(issues);
122
+ const parsed = result.data;
123
+ return {
124
+ issuer: parsed.CLAVIX_ISSUER,
125
+ audience: parsed.CLAVIX_AUDIENCE,
126
+ origin: parsed.CLAVIX_API_ORIGIN,
127
+ scope: parsed.CLAVIX_SCOPE,
128
+ clientId: parsed.CLAVIX_CLIENT_ID,
129
+ clientSecretFile: parsed.CLAVIX_CLIENT_SECRET_FILE,
130
+ webhookSecretFile: parsed.CLAVIX_WEBHOOK_SECRET_FILE,
131
+ machineClientId: parsed.CLAVIX_MACHINE_CLIENT_ID,
132
+ machineSecretFile: parsed.CLAVIX_MACHINE_SECRET_FILE
133
+ };
134
+ }
135
+ export {
136
+ ClavixEnvError,
137
+ clavixEnv,
138
+ clavixEnvShape
139
+ };
140
+
141
+ //# debugId=67B1D6A6A03DABA364756E2164756E21
142
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,11 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/env/env.ts", "../src/env/secret-file.ts"],
4
+ "sourcesContent": [
5
+ "import { z } from 'zod';\nimport { secretFileProblem } from './secret-file';\n\n/** Where the variables are read from: `process.env` by default. */\nexport type ClavixEnvSource = Readonly<Record<string, string | undefined>>;\n\nexport interface ClavixEnvOptions {\n\t/** The variables to read. `process.env` by default. */\n\treadonly source?: ClavixEnvSource;\n\t/**\n\t * Whether `CLAVIX_API_ORIGIN` must be an `https` origin. `NODE_ENV ===\n\t * 'production'` of the source by default.\n\t */\n\treadonly production?: boolean;\n\t/**\n\t * `true` when the API verifies Clavix access tokens (it is a resource\n\t * server): `CLAVIX_ISSUER`, `CLAVIX_AUDIENCE` and `CLAVIX_API_ORIGIN`\n\t * are then required. `false` by default: every variable is optional, and\n\t * a partial set is the only error.\n\t */\n\treadonly resource?: boolean;\n}\n\n/** One refused variable. */\nexport interface ClavixEnvIssue {\n\t/** The variable's name, such as `CLAVIX_CLIENT_SECRET_FILE`. */\n\treadonly name: string;\n\t/** What is wrong with it, never its value. */\n\treadonly message: string;\n}\n\n/** Thrown by `clavixEnv()`: every refused variable at once, each by name. */\nexport class ClavixEnvError extends Error {\n\treadonly issues: readonly ClavixEnvIssue[];\n\tconstructor(issues: readonly ClavixEnvIssue[]) {\n\t\tsuper(\n\t\t\t`Invalid CLAVIX_* environment:\\n${issues.map((i) => ` ${i.message.startsWith(i.name) ? i.message : `${i.name}: ${i.message}`}`).join('\\n')}`,\n\t\t);\n\t\tthis.name = 'ClavixEnvError';\n\t\tthis.issues = issues;\n\t}\n}\n\n/** The Clavix settings of an API, read from its environment. */\nexport interface ClavixEnv {\n\t/** `CLAVIX_ISSUER`: the tenant's issuer, `https` (`http` on localhost outside production). */\n\treadonly issuer: string | undefined;\n\t/** `CLAVIX_AUDIENCE`: the API's identifier, which a token's `aud` must contain. */\n\treadonly audience: string | undefined;\n\t/**\n\t * `CLAVIX_API_ORIGIN`: the public origin of the API (scheme and host, no\n\t * path), what a DPoP proof's `htu` must start with.\n\t */\n\treadonly origin: string | undefined;\n\t/** `CLAVIX_SCOPE`: the scope every access token must carry, when set. */\n\treadonly scope: string | undefined;\n\t/** `CLAVIX_CLIENT_ID`: the id of the client registered with Clavix. */\n\treadonly clientId: string | undefined;\n\t/** `CLAVIX_CLIENT_SECRET_FILE`: the path of the file holding the client secret. */\n\treadonly clientSecretFile: string | undefined;\n\t/** `CLAVIX_WEBHOOK_SECRET_FILE`: the path of the file holding the webhook signing secret. */\n\treadonly webhookSecretFile: string | undefined;\n\t/** `CLAVIX_MACHINE_CLIENT_ID`: the machine client that calls Clavix's management API. */\n\treadonly machineClientId: string | undefined;\n\t/** `CLAVIX_MACHINE_SECRET_FILE`: the path of the file holding its secret. */\n\treadonly machineSecretFile: string | undefined;\n}\n\n/** What `clavixEnv({ resource: true })` gives: the resource server's three settings are set. */\nexport type ClavixResourceEnv = ClavixEnv & {\n\treadonly issuer: string;\n\treadonly audience: string;\n\treadonly origin: string;\n};\n\n// An empty variable counts as unset, as `docker compose` leaves one\n// interpolated from nothing.\nconst optional = (schema: z.ZodType<string, string>) =>\n\tz\n\t\t.string()\n\t\t.transform((value) => (value === '' ? undefined : value))\n\t\t.pipe(schema.optional())\n\t\t.optional();\n\nconst secretFile = (name: string) =>\n\toptional(\n\t\tz.string().superRefine((path, ctx) => {\n\t\t\tconst problem = secretFileProblem(name, path);\n\t\t\tif (problem !== undefined)\n\t\t\t\tctx.addIssue({ code: 'custom', message: problem });\n\t\t}),\n\t);\n\nconst LOCAL = new Set(['localhost', '127.0.0.1', '[::1]']);\n\n/** `https`; outside production also `http` on localhost, as `clavix()` accepts. */\nconst issuerOf = (production: boolean) =>\n\toptional(\n\t\tz.url({ protocol: /^https?$/ }).refine(\n\t\t\t(value) => {\n\t\t\t\t// Not a URL, or not http(s): the checks above already refused it.\n\t\t\t\tif (!URL.canParse(value)) return true;\n\t\t\t\tconst url = new URL(value);\n\t\t\t\tif (url.protocol !== 'https:' && url.protocol !== 'http:') return true;\n\t\t\t\treturn (\n\t\t\t\t\turl.protocol === 'https:' || (!production && LOCAL.has(url.hostname))\n\t\t\t\t);\n\t\t\t},\n\t\t\tproduction\n\t\t\t\t? 'must be an https URL'\n\t\t\t\t: 'must be an https URL (http only on localhost)',\n\t\t),\n\t);\n\nconst origin = (production: boolean) =>\n\toptional(\n\t\tz.url().refine(\n\t\t\t(value) => {\n\t\t\t\tconst url = new URL(value);\n\t\t\t\treturn (\n\t\t\t\t\turl.origin === value && (!production || url.protocol === 'https:')\n\t\t\t\t);\n\t\t\t},\n\t\t\tproduction\n\t\t\t\t? 'must be an https origin (scheme and host, no path or trailing slash)'\n\t\t\t\t: 'must be an origin (scheme and host, no path or trailing slash)',\n\t\t),\n\t);\n\n/**\n * The zod shape of the `CLAVIX_*` variables, to compose in an app's own\n * `z.object`. Each variable is optional and an empty one counts as unset;\n * a `*_FILE` variable is refused, by name, when it points at a directory,\n * at a missing or unreadable file, or at an empty one. The rules that look\n * at several variables (a partial set) are `clavixEnv()`'s.\n *\n * ```ts\n * const env = z.object({ PORT: z.coerce.number(), ...clavixEnvShape() }).parse(process.env);\n * ```\n */\nexport function clavixEnvShape(\n\toptions: { readonly production?: boolean } = {},\n) {\n\treturn {\n\t\tCLAVIX_ISSUER: issuerOf(options.production ?? false),\n\t\tCLAVIX_AUDIENCE: optional(z.string().min(1)),\n\t\tCLAVIX_API_ORIGIN: origin(options.production ?? false),\n\t\tCLAVIX_SCOPE: optional(z.string().min(1)),\n\t\tCLAVIX_CLIENT_ID: optional(z.string().min(1)),\n\t\tCLAVIX_CLIENT_SECRET_FILE: secretFile('CLAVIX_CLIENT_SECRET_FILE'),\n\t\tCLAVIX_WEBHOOK_SECRET_FILE: secretFile('CLAVIX_WEBHOOK_SECRET_FILE'),\n\t\tCLAVIX_MACHINE_CLIENT_ID: optional(z.string().min(1)),\n\t\tCLAVIX_MACHINE_SECRET_FILE: secretFile('CLAVIX_MACHINE_SECRET_FILE'),\n\t};\n}\n\ntype Parsed = z.output<z.ZodObject<ReturnType<typeof clavixEnvShape>>>;\n\n/** Every unset name of `names`, as an issue of `whole`'s own wording. */\nfunction missing(\n\tparsed: Parsed,\n\tnames: readonly (keyof Parsed)[],\n\tmessage: (unset: string) => string,\n): ClavixEnvIssue[] {\n\treturn names\n\t\t.filter((name) => parsed[name] === undefined)\n\t\t.map((name) => ({ name, message: message(name) }));\n}\n\n/** The rules over several variables. */\nfunction crossChecks(parsed: Parsed, resource: boolean): ClavixEnvIssue[] {\n\tconst issues: ClavixEnvIssue[] = [];\n\tif (resource) {\n\t\tissues.push(\n\t\t\t...missing(\n\t\t\t\tparsed,\n\t\t\t\t['CLAVIX_ISSUER', 'CLAVIX_AUDIENCE', 'CLAVIX_API_ORIGIN'],\n\t\t\t\t() => 'required: the API verifies Clavix access tokens',\n\t\t\t),\n\t\t);\n\t}\n\tconst signIn = ['CLAVIX_CLIENT_ID', 'CLAVIX_CLIENT_SECRET_FILE'] as const;\n\tconst machine = [\n\t\t'CLAVIX_MACHINE_CLIENT_ID',\n\t\t'CLAVIX_MACHINE_SECRET_FILE',\n\t] as const;\n\tfor (const pair of [signIn, machine]) {\n\t\tconst unset = pair.filter((name) => parsed[name] === undefined);\n\t\tif (unset.length === 1) {\n\t\t\tissues.push({\n\t\t\t\tname: unset[0] as string,\n\t\t\t\tmessage: `unset while ${pair.find((name) => name !== unset[0])} is set: set both of ${pair.join(', ')}, or none`,\n\t\t\t});\n\t\t}\n\t\tconst some = pair.some((name) => parsed[name] !== undefined);\n\t\tif (some && parsed.CLAVIX_ISSUER === undefined && !resource) {\n\t\t\tissues.push({\n\t\t\t\tname: 'CLAVIX_ISSUER',\n\t\t\t\tmessage: `required when ${pair.join(' and ')} are set`,\n\t\t\t});\n\t\t}\n\t}\n\treturn issues;\n}\n\n/**\n * The Clavix settings of an API, parsed eagerly: call it once at start-up\n * and a wrong or partial configuration stops the process with one\n * `ClavixEnvError` naming every refused variable (never a value).\n *\n * ```ts\n * const clavixSettings = clavixEnv({ resource: true });\n * ```\n */\nexport function clavixEnv(\n\toptions: ClavixEnvOptions & { readonly resource: true },\n): ClavixResourceEnv;\nexport function clavixEnv(options?: ClavixEnvOptions): ClavixEnv;\nexport function clavixEnv(options: ClavixEnvOptions = {}): ClavixEnv {\n\tconst source = options.source ?? process.env;\n\tconst production = options.production ?? source['NODE_ENV'] === 'production';\n\tconst resource = options.resource ?? false;\n\tconst result = z.object(clavixEnvShape({ production })).safeParse(source);\n\tconst issues: ClavixEnvIssue[] = [];\n\tif (!result.success) {\n\t\tfor (const issue of result.error.issues) {\n\t\t\tconst name = String(issue.path[0] ?? 'CLAVIX_*');\n\t\t\tissues.push({ name, message: issue.message });\n\t\t}\n\t} else {\n\t\tissues.push(...crossChecks(result.data, resource));\n\t}\n\tif (issues.length > 0 || !result.success) throw new ClavixEnvError(issues);\n\tconst parsed = result.data;\n\treturn {\n\t\tissuer: parsed.CLAVIX_ISSUER,\n\t\taudience: parsed.CLAVIX_AUDIENCE,\n\t\torigin: parsed.CLAVIX_API_ORIGIN,\n\t\tscope: parsed.CLAVIX_SCOPE,\n\t\tclientId: parsed.CLAVIX_CLIENT_ID,\n\t\tclientSecretFile: parsed.CLAVIX_CLIENT_SECRET_FILE,\n\t\twebhookSecretFile: parsed.CLAVIX_WEBHOOK_SECRET_FILE,\n\t\tmachineClientId: parsed.CLAVIX_MACHINE_CLIENT_ID,\n\t\tmachineSecretFile: parsed.CLAVIX_MACHINE_SECRET_FILE,\n\t};\n}\n",
6
+ "import { readFileSync, statSync } from 'node:fs';\n\n/**\n * Why the file at `path` cannot be a secret, worded with the variable's\n * name; `undefined` when it can. Neither the path nor the content is ever\n * put in the message, and the content is read only to see that it is not\n * blank.\n */\nexport function secretFileProblem(\n\tname: string,\n\tpath: string,\n): string | undefined {\n\tlet stat: ReturnType<typeof statSync>;\n\ttry {\n\t\tstat = statSync(path);\n\t} catch {\n\t\treturn `${name} points at a file that does not exist or cannot be reached`;\n\t}\n\tif (stat.isDirectory()) {\n\t\treturn `${name} points at a directory, not a file`;\n\t}\n\tif (!stat.isFile()) return `${name} does not point at a regular file`;\n\tif ((stat.mode & 0o077) !== 0) {\n\t\treturn `${name} is readable by group or others (mode ${(stat.mode & 0o777).toString(8)}); restrict it to its owner, such as chmod 600`;\n\t}\n\tlet text: string;\n\ttry {\n\t\ttext = readFileSync(path, 'utf8');\n\t} catch {\n\t\treturn `${name} points at a file that cannot be read: check its permissions`;\n\t}\n\tif (text.trim() === '') return `${name} points at an empty file`;\n\treturn undefined;\n}\n"
7
+ ],
8
+ "mappings": ";AAAA;;;ACAA;AAQO,SAAS,iBAAiB,CAChC,MACA,MACqB;AAAA,EACrB,IAAI;AAAA,EACJ,IAAI;AAAA,IACH,OAAO,SAAS,IAAI;AAAA,IACnB,MAAM;AAAA,IACP,OAAO,GAAG;AAAA;AAAA,EAEX,IAAI,KAAK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MAAM,OAAO,OAAO,MAAM,KAAK,MAAM,UAAU;AAAA,MAC/C,OAAO,KAAK,EAAE,MAAM,SAAS,MAAM,QAAQ,CAAC;AAAA,IAC7C;AAAA,EACD,EAAE,KAAK;AAAA,IACN,OAAO,KAAK,GAAG,YAAY,OAAO,MAAM,QAAQ,CAAC;AAAA;AAAA,EAElD,IAAI,OAAO,SAAS,KAAK,CAAC,OAAO;AAAA,IAAS,MAAM,IAAI,eAAe,MAAM;AAAA,EACzE,MAAM,SAAS,OAAO;AAAA,EACtB,OAAO;AAAA,IACN,QAAQ,OAAO;AAAA,IACf,UAAU,OAAO;AAAA,IACjB,QAAQ,OAAO;AAAA,IACf,OAAO,OAAO;AAAA,IACd,UAAU,OAAO;AAAA,IACjB,kBAAkB,OAAO;AAAA,IACzB,mBAAmB,OAAO;AAAA,IAC1B,iBAAiB,OAAO;AAAA,IACxB,mBAAmB,OAAO;AAAA,EAC3B;AAAA;",
9
+ "debugId": "67B1D6A6A03DABA364756E2164756E21",
10
+ "names": []
11
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Why the file at `path` cannot be a secret, worded with the variable's
3
+ * name; `undefined` when it can. Neither the path nor the content is ever
4
+ * put in the message, and the content is read only to see that it is not
5
+ * blank.
6
+ */
7
+ export declare function secretFileProblem(name: string, path: string): string | undefined;
8
+ //# sourceMappingURL=secret-file.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secret-file.d.ts","sourceRoot":"","sources":["../../src/env/secret-file.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAChC,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,GACV,MAAM,GAAG,SAAS,CAsBpB"}
package/dist/guard.d.ts CHANGED
@@ -18,6 +18,15 @@ export interface GuardOptions {
18
18
  readonly cookie?: string | undefined;
19
19
  readonly dpop?: ResolvedDpop | undefined;
20
20
  }
21
+ /**
22
+ * The token's `cnf.jkt`: `undefined` for a token with no key binding,
23
+ * `null` when `cnf` is present but not a plain object, or has a `jkt` that
24
+ * is not a non-empty string (so the
25
+ * guard does not depend on the verifier's profile to refuse it).
26
+ */
27
+ export declare function boundKey(claims: {
28
+ readonly cnf?: unknown;
29
+ }): string | null | undefined;
21
30
  /** The guard of `clavix().bearer()`: `Bearer` and, with `dpop`, `DPoP` tokens. */
22
31
  export declare function guard(options: GuardOptions): ClavixGuard;
23
32
  //# sourceMappingURL=guard.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"guard.d.ts","sourceRoot":"","sources":["../src/guard.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACxD,OAAO,EACN,KAAK,MAAM,EAGX,KAAK,gBAAgB,EACrB,KAAK,mBAAmB,EACxB,KAAK,eAAe,EACpB,KAAK,kBAAkB,EACvB,KAAK,QAAQ,EACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,KAAK,UAAU,EAAE,KAAK,YAAY,EAAe,MAAM,QAAQ,CAAC;AACzE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEnD,2FAA2F;AAC3F,MAAM,MAAM,sBAAsB,GAAG,gBAAgB,CAAC,UAAU,CAAC,CAAC;AAElE,oDAAoD;AACpD,MAAM,MAAM,yBAAyB,GAAG,mBAAmB,CAAC,UAAU,CAAC,CAAC;AAExE,mGAAmG;AACnG,MAAM,MAAM,qBAAqB,GAAG,eAAe,CAAC;AAEpD,oDAAoD;AACpD,MAAM,MAAM,wBAAwB,GAAG,kBAAkB,CAAC;AAE1D,kJAAkJ;AAClJ,MAAM,MAAM,WAAW,GAAG,MAAM,CAC/B,gBAAgB,CAAC,OAAO,EAAE,eAAe,CAAC,EAC1C,UAAU,CACV,CAAC;AAEF,MAAM,WAAW,YAAY;IAC5B,QAAQ,CAAC,GAAG,EAAE,QAAQ,CAAC;IACvB,QAAQ,CAAC,MAAM,EAAE,gBAAgB,CAAC,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C,EAAE,MAAM,GAAG,SAAS,CAAC;IACrC,QAAQ,CAAC,IAAI,CAAC,EAAE,YAAY,GAAG,SAAS,CAAC;CACzC;AAED;;;;;GAKG;AACH,wBAAgB,QAAQ,CAAC,MAAM,EAAE;IAChC,QAAQ,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC;CACvB,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,CAQ5B;AAuED,kFAAkF;AAClF,wBAAgB,KAAK,CAAC,OAAO,EAAE,YAAY,GAAG,WAAW,CAOxD"}
package/dist/index.d.ts CHANGED
@@ -2,5 +2,6 @@ export { type ClavixOptions, type ClavixVerifier, clavix } from './clavix';
2
2
  export { type DpopAlgorithm, type DpopNonce, type DpopOptions, type DpopReason, type DpopReplayStore, hmacDpopNonce, memoryDpopReplayStore, } from './dpop';
3
3
  export type { ClavixGuard, ClavixUnauthorizedBody, ClavixUnauthorizedProblem, ClavixUnavailableBody, ClavixUnavailableProblem, } from './guard';
4
4
  export type { ClavixPrincipal } from './principal';
5
+ export { type ClavixRefusal, type ClavixResource, type ClavixResourceOptions, type ClavixViewerContext, type ClavixViewerMiddleware, clavixResource, type ViewerOf, } from './resource';
5
6
  export { type InsufficientScopeBody, type InsufficientScopeProblem, type RequireScope, requireScope, } from './scope';
6
7
  //# sourceMappingURL=index.d.ts.map
@@ -1 +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,OAAO,EACN,KAAK,aAAa,EAClB,KAAK,SAAS,EACd,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,eAAe,EACpB,aAAa,EACb,qBAAqB,GACrB,MAAM,QAAQ,CAAC;AAChB,YAAY,EACX,WAAW,EACX,sBAAsB,EACtB,yBAAyB,EACzB,qBAAqB,EACrB,wBAAwB,GACxB,MAAM,SAAS,CAAC;AACjB,YAAY,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EACN,KAAK,qBAAqB,EAC1B,KAAK,wBAAwB,EAC7B,KAAK,YAAY,EACjB,YAAY,GACZ,MAAM,SAAS,CAAC"}
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,OAAO,EACN,KAAK,aAAa,EAClB,KAAK,SAAS,EACd,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,eAAe,EACpB,aAAa,EACb,qBAAqB,GACrB,MAAM,QAAQ,CAAC;AAChB,YAAY,EACX,WAAW,EACX,sBAAsB,EACtB,yBAAyB,EACzB,qBAAqB,EACrB,wBAAwB,GACxB,MAAM,SAAS,CAAC;AACjB,YAAY,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EACN,KAAK,aAAa,EAClB,KAAK,cAAc,EACnB,KAAK,qBAAqB,EAC1B,KAAK,mBAAmB,EACxB,KAAK,sBAAsB,EAC3B,cAAc,EACd,KAAK,QAAQ,GACb,MAAM,YAAY,CAAC;AACpB,OAAO,EACN,KAAK,qBAAqB,EAC1B,KAAK,wBAAwB,EAC7B,KAAK,YAAY,EACjB,YAAY,GACZ,MAAM,SAAS,CAAC"}
package/dist/index.js CHANGED
@@ -571,13 +571,169 @@ function clavix(options) {
571
571
  };
572
572
  return self;
573
573
  }
574
+ // src/resource/viewer.ts
575
+ import { errorFormat, problem, problemOf } from "@softistx/alxia";
576
+ var NAMES = {
577
+ 401: "unauthorized",
578
+ 403: "forbidden",
579
+ 503: "unavailable"
580
+ };
581
+ function refuse(ctx, options, refusal, extra = {}, challenge) {
582
+ const headers = { "cache-control": "no-store" };
583
+ if (challenge !== undefined)
584
+ headers["www-authenticate"] = challenge;
585
+ if (options.body !== undefined) {
586
+ return ctx.reply(refusal.status, options.body(refusal), { headers });
587
+ }
588
+ if (errorFormat(ctx) === "problem") {
589
+ return problem(problemOf(ctx, {
590
+ status: refusal.status,
591
+ detail: refusal.reason,
592
+ reason: refusal.reason,
593
+ ...extra
594
+ }), { headers });
595
+ }
596
+ return ctx.reply(refusal.status, { error: NAMES[refusal.status], reason: refusal.reason, ...extra }, { headers });
597
+ }
598
+ function reshape(ctx, result, body) {
599
+ const replied = result;
600
+ if (replied === null || typeof replied !== "object")
601
+ return result;
602
+ const { status } = replied;
603
+ if (status !== 401 && status !== 503)
604
+ return result;
605
+ const headers = new Headers(replied.headers);
606
+ if (!(headers.get("content-type") ?? "").includes("problem+json")) {
607
+ return result;
608
+ }
609
+ headers.delete("content-type");
610
+ const reason = replied.body?.reason;
611
+ return ctx.reply(status, body({
612
+ status,
613
+ reason: typeof reason === "string" ? reason : "unauthorized"
614
+ }), { headers });
615
+ }
616
+ function viewerMiddleware(options, guard) {
617
+ const scope = options.scope ?? "";
618
+ const carries = options.carries ?? (() => true);
619
+ const body = options.body;
620
+ const run = guard;
621
+ const middleware = async (context, next) => {
622
+ const ctx = context;
623
+ const { request } = ctx;
624
+ if (!carries(request) || !request.headers.has("authorization")) {
625
+ return next({ viewer: null });
626
+ }
627
+ const guarded = body === undefined ? ctx : Object.create(ctx, {
628
+ reply: {
629
+ value: (status, replied, init) => {
630
+ if (status !== 401 && status !== 503) {
631
+ return ctx.reply(status, replied, init);
632
+ }
633
+ const reason = replied?.reason;
634
+ return ctx.reply(status, body({ status, reason: reason ?? "unauthorized" }), init);
635
+ }
636
+ }
637
+ });
638
+ let proceeded = false;
639
+ let entered = false;
640
+ try {
641
+ const result = await run(guarded, async ({ user }) => {
642
+ entered = true;
643
+ if (scope && !user.scopes.includes(scope)) {
644
+ const scheme = /^dpop\s/i.test(request.headers.get("authorization") ?? "") ? "DPoP" : "Bearer";
645
+ return refuse(ctx, options, { status: 403, reason: "insufficient_scope" }, { scope }, `${scheme} error="insufficient_scope", scope="${scope}"`);
646
+ }
647
+ const viewer = await options.viewerOf(user);
648
+ if (viewer === null) {
649
+ return refuse(ctx, options, { status: 401, reason: "inactive" });
650
+ }
651
+ proceeded = true;
652
+ return next({ viewer });
653
+ });
654
+ if (body !== undefined && !entered)
655
+ return reshape(ctx, result, body);
656
+ return result;
657
+ } catch (error) {
658
+ if (proceeded)
659
+ throw error;
660
+ options.onError?.(error);
661
+ return refuse(ctx, options, { status: 503, reason: "unavailable" });
662
+ }
663
+ };
664
+ return middleware;
665
+ }
666
+
667
+ // src/resource/resource.ts
668
+ var credentials = /^(Bearer|DPoP)\s+(\S+)$/i;
669
+ var tenantOf = (issuer) => new URL(issuer).hostname.split(".")[0] ?? "";
670
+ function clavixResource(options) {
671
+ const { issuer, audience, origin, replay } = options;
672
+ if (options.scope !== undefined && !/^[\x21\x23-\x5B\x5D-\x7E]*$/.test(options.scope)) {
673
+ throw new TypeError("clavixResource: scope is one token, without spaces or quotes");
674
+ }
675
+ const tenant = options.tenant ?? tenantOf(issuer);
676
+ const verifier = clavix({
677
+ issuers: { [issuer]: tenant },
678
+ audience,
679
+ warm: [issuer],
680
+ dpop: {
681
+ origin,
682
+ replay,
683
+ ...options.nonce === undefined ? {} : { nonce: options.nonce }
684
+ }
685
+ });
686
+ const scope = options.scope ?? "";
687
+ const proofOptions = resolveDpop({
688
+ origin,
689
+ replay,
690
+ ...options.nonce === undefined ? {} : { nonce: options.nonce }
691
+ });
692
+ const guard = verifier.bearer();
693
+ const schema = principalSchema(verifier.tenantOf)["~standard"];
694
+ return {
695
+ viewer: viewerMiddleware(options, guard),
696
+ ready: verifier.ready,
697
+ async streamViewer(request) {
698
+ const found = credentials.exec(request.headers.get("authorization") ?? "");
699
+ const token = found?.[2];
700
+ if (token === undefined)
701
+ return null;
702
+ const verified = await verifier.verify(token);
703
+ if (!verified.ok)
704
+ return null;
705
+ const jkt = boundKey(verified.claims);
706
+ const viaDpop = found?.[1]?.toLowerCase() === "dpop";
707
+ if (jkt === null || viaDpop !== (jkt !== undefined))
708
+ return null;
709
+ if (jkt !== undefined) {
710
+ const proof = await verifyProof({
711
+ proof: request.headers.get("dpop"),
712
+ method: request.method,
713
+ path: new URL(request.url).pathname,
714
+ accessToken: token,
715
+ jkt
716
+ }, proofOptions);
717
+ if (!proof.ok)
718
+ return null;
719
+ }
720
+ const checked = await schema.validate(verified.claims);
721
+ if (checked.issues !== undefined)
722
+ return null;
723
+ const principal = checked.value;
724
+ if (scope && !principal.scopes.includes(scope))
725
+ return null;
726
+ return options.viewerOf(principal);
727
+ }
728
+ };
729
+ }
574
730
  // src/scope.ts
575
731
  import {
576
732
  defineMiddleware,
577
- errorFormat,
733
+ errorFormat as errorFormat2,
578
734
  markFactory,
579
- problem,
580
- problemOf
735
+ problem as problem2,
736
+ problemOf as problemOf2
581
737
  } from "@softistx/alxia";
582
738
  function requireScope(...scopes) {
583
739
  if (scopes.length === 0 || scopes.some((s) => !/^[\x21\x23-\x5B\x5D-\x7E]+$/.test(s))) {
@@ -593,8 +749,8 @@ function requireScope(...scopes) {
593
749
  if (scopes.every((s) => ctx.user.scopes.includes(s)))
594
750
  return next();
595
751
  const why = { reason: "insufficient_scope", scope };
596
- if (errorFormat(ctx) === "problem") {
597
- return problem(problemOf(ctx, {
752
+ if (errorFormat2(ctx) === "problem") {
753
+ return problem2(problemOf2(ctx, {
598
754
  status: 403,
599
755
  detail: `The access token lacks the scope: ${scope}`,
600
756
  ...why
@@ -606,10 +762,11 @@ function requireScope(...scopes) {
606
762
  markFactory(requireScope);
607
763
  export {
608
764
  clavix,
765
+ clavixResource,
609
766
  hmacDpopNonce,
610
767
  memoryDpopReplayStore,
611
768
  requireScope
612
769
  };
613
770
 
614
- //# debugId=A0E8A24ACF0832D464756E2164756E21
771
+ //# debugId=43C84EA7DE32806464756E2164756E21
615
772
  //# sourceMappingURL=index.js.map