@softistx/alxia-clavix 0.0.0-stage → 0.3.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 +122 -2
- package/dist/clavix.d.ts +85 -0
- package/dist/clavix.d.ts.map +1 -0
- package/dist/dpop/htu.d.ts +11 -0
- package/dist/dpop/htu.d.ts.map +1 -0
- package/dist/dpop/index.d.ts +6 -0
- package/dist/dpop/index.d.ts.map +1 -0
- package/dist/dpop/jwk.d.ts +20 -0
- package/dist/dpop/jwk.d.ts.map +1 -0
- package/dist/dpop/nonce.d.ts +29 -0
- package/dist/dpop/nonce.d.ts.map +1 -0
- package/dist/dpop/options.d.ts +33 -0
- package/dist/dpop/options.d.ts.map +1 -0
- package/dist/dpop/proof.d.ts +32 -0
- package/dist/dpop/proof.d.ts.map +1 -0
- package/dist/dpop/replay-store.d.ts +24 -0
- package/dist/dpop/replay-store.d.ts.map +1 -0
- package/dist/guard.d.ts +19 -0
- package/dist/guard.d.ts.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +615 -0
- package/dist/index.js.map +22 -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 +59 -0
- package/docs/guide/readiness.md +31 -0
- package/docs/guide/security.md +128 -0
- package/docs/roadmap.md +38 -0
- package/docs/troubleshooting.md +269 -0
- package/package.json +52 -5
package/dist/index.js
ADDED
|
@@ -0,0 +1,615 @@
|
|
|
1
|
+
// src/clavix.ts
|
|
2
|
+
import {
|
|
3
|
+
createJwt
|
|
4
|
+
} from "@softistx/alxia-jwt";
|
|
5
|
+
|
|
6
|
+
// src/dpop/jwk.ts
|
|
7
|
+
var encoder = new TextEncoder;
|
|
8
|
+
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
9
|
+
function decode(part) {
|
|
10
|
+
try {
|
|
11
|
+
const value = JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
|
|
12
|
+
return isObject(value) ? value : undefined;
|
|
13
|
+
} catch {
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function publicKey(jwk, alg) {
|
|
18
|
+
if (jwk.d !== undefined)
|
|
19
|
+
return;
|
|
20
|
+
const text = (name) => {
|
|
21
|
+
const value = jwk[name];
|
|
22
|
+
return typeof value === "string" ? value : undefined;
|
|
23
|
+
};
|
|
24
|
+
const [kty, crv, x, y] = [text("kty"), text("crv"), text("x"), text("y")];
|
|
25
|
+
if (alg === "ES256") {
|
|
26
|
+
if (kty !== "EC" || crv !== "P-256" || !x || !y)
|
|
27
|
+
return;
|
|
28
|
+
return {
|
|
29
|
+
jwk: { kty, crv, x, y },
|
|
30
|
+
params: { name: "ECDSA", namedCurve: "P-256" }
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
if (kty !== "OKP" || crv !== "Ed25519" || !x)
|
|
34
|
+
return;
|
|
35
|
+
return { jwk: { kty, crv, x }, params: { name: "Ed25519" } };
|
|
36
|
+
}
|
|
37
|
+
async function jwkThumbprint(jwk) {
|
|
38
|
+
const members = jwk.kty === "EC" ? { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y } : { crv: jwk.crv, kty: jwk.kty, x: jwk.x };
|
|
39
|
+
const digest = await crypto.subtle.digest("SHA-256", encoder.encode(JSON.stringify(members)));
|
|
40
|
+
return Buffer.from(digest).toString("base64url");
|
|
41
|
+
}
|
|
42
|
+
// src/dpop/nonce.ts
|
|
43
|
+
var encoder2 = new TextEncoder;
|
|
44
|
+
function timingSafeEqual(a, b) {
|
|
45
|
+
const x = encoder2.encode(a);
|
|
46
|
+
const y = encoder2.encode(b);
|
|
47
|
+
if (x.length !== y.length)
|
|
48
|
+
return false;
|
|
49
|
+
let diff = 0;
|
|
50
|
+
for (let i = 0;i < x.length; i++) {
|
|
51
|
+
diff |= x[i] ^ y[i];
|
|
52
|
+
}
|
|
53
|
+
return diff === 0;
|
|
54
|
+
}
|
|
55
|
+
function hmacDpopNonce(options) {
|
|
56
|
+
const ttlMs = options.ttlMs ?? 300000;
|
|
57
|
+
if (!(Number.isFinite(ttlMs) && ttlMs > 0)) {
|
|
58
|
+
throw new TypeError("clavix: the dpop nonce ttlMs must be a finite number above 0");
|
|
59
|
+
}
|
|
60
|
+
if (typeof options.secret !== "string" || options.secret.length < 16) {
|
|
61
|
+
throw new TypeError("clavix: the dpop nonce secret needs 16 characters");
|
|
62
|
+
}
|
|
63
|
+
const hmac = (raw) => crypto.subtle.importKey("raw", raw, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
64
|
+
const key = (async () => {
|
|
65
|
+
const master = await hmac(encoder2.encode(options.secret));
|
|
66
|
+
const derived = await crypto.subtle.sign("HMAC", master, encoder2.encode("@softistx/alxia-clavix dpop nonce v1"));
|
|
67
|
+
return hmac(derived);
|
|
68
|
+
})();
|
|
69
|
+
const mac = async (stamp) => Buffer.from(await crypto.subtle.sign("HMAC", await key, encoder2.encode(stamp))).toString("base64url");
|
|
70
|
+
const issue = async () => {
|
|
71
|
+
const stamp = String(Date.now());
|
|
72
|
+
return `${stamp}.${await mac(stamp)}`;
|
|
73
|
+
};
|
|
74
|
+
return {
|
|
75
|
+
issue,
|
|
76
|
+
async accepts(nonce) {
|
|
77
|
+
const [stamp, signature, ...rest] = nonce.split(".");
|
|
78
|
+
if (stamp === undefined || signature === undefined || rest.length > 0) {
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
if (!/^\d{1,16}$/.test(stamp))
|
|
82
|
+
return false;
|
|
83
|
+
const age = Date.now() - Number(stamp);
|
|
84
|
+
if (age < -1000 || age > ttlMs)
|
|
85
|
+
return false;
|
|
86
|
+
return timingSafeEqual(signature, await mac(stamp));
|
|
87
|
+
},
|
|
88
|
+
async renew(nonce) {
|
|
89
|
+
const age = Date.now() - Number(nonce.split(".")[0]);
|
|
90
|
+
return age > ttlMs / 2 ? await issue() : undefined;
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
// src/dpop/options.ts
|
|
95
|
+
function resolveDpop(options) {
|
|
96
|
+
let origin;
|
|
97
|
+
try {
|
|
98
|
+
const url = new URL(options.origin);
|
|
99
|
+
if (url.protocol !== "https:" && url.protocol !== "http:" || url.pathname !== "/" || url.search !== "" || url.hash !== "" || url.username !== "" || url.password !== "") {
|
|
100
|
+
throw new Error("not an origin");
|
|
101
|
+
}
|
|
102
|
+
origin = url.origin;
|
|
103
|
+
} catch {
|
|
104
|
+
throw new TypeError(`clavix: dpop.origin must be an origin such as "https://api.example.com", got ${JSON.stringify(options.origin)}`);
|
|
105
|
+
}
|
|
106
|
+
if (typeof options.replay?.claim !== "function") {
|
|
107
|
+
throw new TypeError("clavix: dpop.replay is required");
|
|
108
|
+
}
|
|
109
|
+
const algorithms = options.algorithms ?? ["ES256", "EdDSA"];
|
|
110
|
+
if (algorithms.length === 0 || !algorithms.every((a) => a === "ES256" || a === "EdDSA")) {
|
|
111
|
+
throw new TypeError("clavix: dpop.algorithms takes ES256, EdDSA or both");
|
|
112
|
+
}
|
|
113
|
+
const maxAgeSec = options.maxAgeSec ?? 60;
|
|
114
|
+
const clockSkewSec = options.clockSkewSec ?? 5;
|
|
115
|
+
if (!(Number.isFinite(maxAgeSec) && maxAgeSec > 0)) {
|
|
116
|
+
throw new TypeError("clavix: dpop.maxAgeSec must be a finite number above 0");
|
|
117
|
+
}
|
|
118
|
+
if (!(Number.isFinite(clockSkewSec) && clockSkewSec >= 0)) {
|
|
119
|
+
throw new TypeError("clavix: dpop.clockSkewSec must be a finite number, 0 or more");
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
origin,
|
|
123
|
+
replay: options.replay,
|
|
124
|
+
algorithms,
|
|
125
|
+
maxAgeSec,
|
|
126
|
+
clockSkewSec,
|
|
127
|
+
nonce: options.nonce
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
// src/dpop/htu.ts
|
|
131
|
+
function sameUrl(htu, origin, path) {
|
|
132
|
+
try {
|
|
133
|
+
const claimed = new URL(htu);
|
|
134
|
+
if (claimed.username !== "" || claimed.password !== "")
|
|
135
|
+
return false;
|
|
136
|
+
return claimed.origin === origin && claimed.pathname === path;
|
|
137
|
+
} catch {
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// src/dpop/proof.ts
|
|
143
|
+
var MAX_JTI = 256;
|
|
144
|
+
var REMEMBER_MARGIN_MS = 5000;
|
|
145
|
+
var fail = (reason) => ({ ok: false, reason });
|
|
146
|
+
function parse(proof) {
|
|
147
|
+
const parts = proof.split(".");
|
|
148
|
+
if (parts.length !== 3)
|
|
149
|
+
return "dpop_proof_malformed";
|
|
150
|
+
const [head, body, signature] = parts;
|
|
151
|
+
const header = decode(head);
|
|
152
|
+
const claims = decode(body);
|
|
153
|
+
if (header === undefined || claims === undefined || "crit" in header) {
|
|
154
|
+
return "dpop_proof_malformed";
|
|
155
|
+
}
|
|
156
|
+
return { head, body, signature, header, claims };
|
|
157
|
+
}
|
|
158
|
+
async function verifySignature(parsed, algorithms) {
|
|
159
|
+
const { header } = parsed;
|
|
160
|
+
if (header.typ !== "dpop+jwt")
|
|
161
|
+
return "dpop_proof_type";
|
|
162
|
+
const alg = algorithms.find((a) => a === header.alg);
|
|
163
|
+
if (alg === undefined)
|
|
164
|
+
return "dpop_proof_algorithm";
|
|
165
|
+
if (!isObject(header.jwk))
|
|
166
|
+
return "dpop_proof_key";
|
|
167
|
+
const key = publicKey(header.jwk, alg);
|
|
168
|
+
if (key === undefined)
|
|
169
|
+
return "dpop_proof_key";
|
|
170
|
+
try {
|
|
171
|
+
const valid = await crypto.subtle.verify(alg === "ES256" ? { name: "ECDSA", hash: "SHA-256" } : { name: "Ed25519" }, await crypto.subtle.importKey("jwk", key.jwk, key.params, false, [
|
|
172
|
+
"verify"
|
|
173
|
+
]), Buffer.from(parsed.signature, "base64url"), encoder.encode(`${parsed.head}.${parsed.body}`));
|
|
174
|
+
return valid ? key : "dpop_proof_signature";
|
|
175
|
+
} catch {
|
|
176
|
+
return "dpop_proof_signature";
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
async function checkClaims(claims, input, options, key) {
|
|
180
|
+
if (claims.htm !== input.method)
|
|
181
|
+
return "dpop_proof_method";
|
|
182
|
+
if (typeof claims.htu !== "string" || !sameUrl(claims.htu, options.origin, input.path)) {
|
|
183
|
+
return "dpop_proof_url";
|
|
184
|
+
}
|
|
185
|
+
const nowSec = Date.now() / 1000;
|
|
186
|
+
const { iat, jti } = claims;
|
|
187
|
+
if (typeof iat !== "number" || !Number.isFinite(iat) || iat < nowSec - options.maxAgeSec || iat > nowSec + options.clockSkewSec) {
|
|
188
|
+
return "dpop_proof_iat";
|
|
189
|
+
}
|
|
190
|
+
if (typeof jti !== "string" || jti === "" || jti.length > MAX_JTI) {
|
|
191
|
+
return "dpop_proof_jti";
|
|
192
|
+
}
|
|
193
|
+
const hash = await crypto.subtle.digest("SHA-256", encoder.encode(input.accessToken));
|
|
194
|
+
if (typeof claims.ath !== "string" || !timingSafeEqual(claims.ath, Buffer.from(hash).toString("base64url"))) {
|
|
195
|
+
return "dpop_proof_ath";
|
|
196
|
+
}
|
|
197
|
+
if (!timingSafeEqual(await jwkThumbprint(key.jwk), input.jkt)) {
|
|
198
|
+
return "dpop_proof_thumbprint";
|
|
199
|
+
}
|
|
200
|
+
return { jti };
|
|
201
|
+
}
|
|
202
|
+
async function verifyProof(input, options) {
|
|
203
|
+
if (input.proof === null || input.proof === "") {
|
|
204
|
+
return fail("dpop_proof_missing");
|
|
205
|
+
}
|
|
206
|
+
const parsed = parse(input.proof);
|
|
207
|
+
if (typeof parsed === "string")
|
|
208
|
+
return fail(parsed);
|
|
209
|
+
const key = await verifySignature(parsed, options.algorithms);
|
|
210
|
+
if (typeof key === "string")
|
|
211
|
+
return fail(key);
|
|
212
|
+
const checked = await checkClaims(parsed.claims, input, options, key);
|
|
213
|
+
if (typeof checked === "string")
|
|
214
|
+
return fail(checked);
|
|
215
|
+
let renewed;
|
|
216
|
+
if (options.nonce !== undefined) {
|
|
217
|
+
const { nonce } = parsed.claims;
|
|
218
|
+
if (typeof nonce === "string" && await options.nonce.accepts(nonce)) {
|
|
219
|
+
renewed = await options.nonce.renew?.(nonce);
|
|
220
|
+
} else {
|
|
221
|
+
return {
|
|
222
|
+
ok: false,
|
|
223
|
+
reason: "dpop_nonce",
|
|
224
|
+
nonce: await options.nonce.issue()
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
const ttlMs = (options.maxAgeSec + options.clockSkewSec) * 1000 + REMEMBER_MARGIN_MS;
|
|
229
|
+
const first = await options.replay.claim(`${input.jkt}:${checked.jti}`, ttlMs);
|
|
230
|
+
if (!first)
|
|
231
|
+
return fail("dpop_proof_replay");
|
|
232
|
+
return renewed === undefined ? { ok: true } : { ok: true, nonce: renewed };
|
|
233
|
+
}
|
|
234
|
+
// src/dpop/replay-store.ts
|
|
235
|
+
function memoryDpopReplayStore(options = {}) {
|
|
236
|
+
const max = options.maxEntries ?? 1e4;
|
|
237
|
+
const seen = new Map;
|
|
238
|
+
return {
|
|
239
|
+
async claim(key, ttlMs) {
|
|
240
|
+
const now = Date.now();
|
|
241
|
+
const until = seen.get(key);
|
|
242
|
+
if (until !== undefined && until > now)
|
|
243
|
+
return false;
|
|
244
|
+
if (seen.size >= max) {
|
|
245
|
+
for (const [stored, expiry] of seen) {
|
|
246
|
+
if (expiry <= now)
|
|
247
|
+
seen.delete(stored);
|
|
248
|
+
}
|
|
249
|
+
if (seen.size >= max) {
|
|
250
|
+
throw new Error("memoryDpopReplayStore: full (use a shared store)");
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
seen.set(key, now + ttlMs);
|
|
254
|
+
return true;
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
// src/guard.ts
|
|
259
|
+
import {
|
|
260
|
+
bearer
|
|
261
|
+
} from "@softistx/alxia-jwt";
|
|
262
|
+
function boundKey(claims) {
|
|
263
|
+
const { cnf } = claims;
|
|
264
|
+
if (cnf === undefined)
|
|
265
|
+
return;
|
|
266
|
+
if (typeof cnf !== "object" || cnf === null || Array.isArray(cnf)) {
|
|
267
|
+
return null;
|
|
268
|
+
}
|
|
269
|
+
if (!("jkt" in cnf))
|
|
270
|
+
return;
|
|
271
|
+
return typeof cnf.jkt === "string" && cnf.jkt !== "" ? cnf.jkt : null;
|
|
272
|
+
}
|
|
273
|
+
var isProofReason = (reason) => reason.startsWith("dpop_proof_");
|
|
274
|
+
function dpopExtension(dpop) {
|
|
275
|
+
const algs = dpop?.algorithms.join(" ") ?? "";
|
|
276
|
+
const scheme = (error, description) => `DPoP error="${error}"${description === undefined ? "" : `, error_description="${description}"`}, algs="${algs}"`;
|
|
277
|
+
return {
|
|
278
|
+
schemes: ["DPoP"],
|
|
279
|
+
async bound({ request, token, scheme: used, claims }) {
|
|
280
|
+
const jkt = boundKey(claims);
|
|
281
|
+
if (jkt === null)
|
|
282
|
+
return { reason: "dpop_malformed" };
|
|
283
|
+
if (used !== "DPoP") {
|
|
284
|
+
return jkt === undefined ? undefined : { reason: "dpop_required" };
|
|
285
|
+
}
|
|
286
|
+
if (dpop === undefined)
|
|
287
|
+
return { reason: "dpop_unsupported" };
|
|
288
|
+
if (jkt === undefined)
|
|
289
|
+
return { reason: "dpop_unbound" };
|
|
290
|
+
const proof = await verifyProof({
|
|
291
|
+
proof: request.headers.get("dpop"),
|
|
292
|
+
method: request.method,
|
|
293
|
+
path: new URL(request.url).pathname,
|
|
294
|
+
accessToken: token,
|
|
295
|
+
jkt
|
|
296
|
+
}, dpop);
|
|
297
|
+
if (proof.ok) {
|
|
298
|
+
return proof.nonce === undefined ? undefined : { headers: { "dpop-nonce": proof.nonce } };
|
|
299
|
+
}
|
|
300
|
+
return {
|
|
301
|
+
reason: proof.reason,
|
|
302
|
+
...proof.nonce === undefined ? {} : { headers: { "dpop-nonce": proof.nonce } }
|
|
303
|
+
};
|
|
304
|
+
},
|
|
305
|
+
challenge(reason, used) {
|
|
306
|
+
if (dpop === undefined)
|
|
307
|
+
return;
|
|
308
|
+
if (reason === "missing")
|
|
309
|
+
return `Bearer, DPoP algs="${algs}"`;
|
|
310
|
+
if (reason === "dpop_required") {
|
|
311
|
+
return scheme("invalid_token", "the token is bound to a key: use the DPoP scheme with a proof");
|
|
312
|
+
}
|
|
313
|
+
if (reason === "dpop_unbound") {
|
|
314
|
+
return scheme("invalid_token", "the token is not bound to a key: use the Bearer scheme");
|
|
315
|
+
}
|
|
316
|
+
if (reason === "dpop_nonce")
|
|
317
|
+
return scheme("use_dpop_nonce");
|
|
318
|
+
if (isProofReason(reason))
|
|
319
|
+
return scheme("invalid_dpop_proof");
|
|
320
|
+
if (used === "DPoP" && reason !== "insufficient_user_authentication") {
|
|
321
|
+
return scheme("invalid_token");
|
|
322
|
+
}
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
function guard(options) {
|
|
328
|
+
return bearer({
|
|
329
|
+
jwt: options.jwt,
|
|
330
|
+
schema: options.schema,
|
|
331
|
+
...options.cookie === undefined ? {} : { cookie: options.cookie },
|
|
332
|
+
extension: dpopExtension(options.dpop)
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// src/issuers.ts
|
|
337
|
+
var LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
338
|
+
var LOCAL = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
339
|
+
function normaliseDomain(domain) {
|
|
340
|
+
const name = domain.trim().toLowerCase().replace(/^\./, "").replace(/\.$/, "");
|
|
341
|
+
const labels = name.split(".");
|
|
342
|
+
if (labels.length < 2 || name.length > 253 || !labels.every((label) => LABEL.test(label) && !label.startsWith("xn--"))) {
|
|
343
|
+
throw new TypeError(`clavix: domain must be an ASCII DNS name such as "clavix.example", got ${JSON.stringify(domain)}`);
|
|
344
|
+
}
|
|
345
|
+
return name;
|
|
346
|
+
}
|
|
347
|
+
function listIssuers(issuers) {
|
|
348
|
+
const map = new Map;
|
|
349
|
+
const entries = Array.isArray(issuers) ? issuers.map((issuer) => [issuer, undefined]) : Object.entries(issuers);
|
|
350
|
+
for (const [issuer, tenant] of entries) {
|
|
351
|
+
let url;
|
|
352
|
+
try {
|
|
353
|
+
url = new URL(issuer);
|
|
354
|
+
} catch {
|
|
355
|
+
throw new TypeError(`clavix: issuer is not a URL: ${issuer}`);
|
|
356
|
+
}
|
|
357
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && LOCAL.has(url.hostname))) {
|
|
358
|
+
throw new TypeError(`clavix: issuer must be an https URL: ${issuer}`);
|
|
359
|
+
}
|
|
360
|
+
if (tenant === "") {
|
|
361
|
+
throw new TypeError(`clavix: the tenant of ${issuer} is empty`);
|
|
362
|
+
}
|
|
363
|
+
map.set(issuer, tenant);
|
|
364
|
+
}
|
|
365
|
+
return map;
|
|
366
|
+
}
|
|
367
|
+
function slugOf(issuer, domain) {
|
|
368
|
+
const prefix = "https://";
|
|
369
|
+
const suffix = `.${domain}`;
|
|
370
|
+
if (!issuer.startsWith(prefix) || !issuer.endsWith(suffix))
|
|
371
|
+
return;
|
|
372
|
+
const label = issuer.slice(prefix.length, issuer.length - suffix.length);
|
|
373
|
+
return LABEL.test(label) && !label.startsWith("xn--") ? label : undefined;
|
|
374
|
+
}
|
|
375
|
+
function resolveIssuer(rules, issuer) {
|
|
376
|
+
if (rules.listed.has(issuer))
|
|
377
|
+
return { tenant: rules.listed.get(issuer) };
|
|
378
|
+
if (rules.domain === undefined)
|
|
379
|
+
return;
|
|
380
|
+
const slug = slugOf(issuer, rules.domain);
|
|
381
|
+
return slug === undefined ? undefined : { tenant: slug };
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// src/lru.ts
|
|
385
|
+
class Lru {
|
|
386
|
+
#entries = new Map;
|
|
387
|
+
#max;
|
|
388
|
+
constructor(max) {
|
|
389
|
+
this.#max = max;
|
|
390
|
+
}
|
|
391
|
+
get size() {
|
|
392
|
+
return this.#entries.size;
|
|
393
|
+
}
|
|
394
|
+
get(key) {
|
|
395
|
+
const value = this.#entries.get(key);
|
|
396
|
+
if (value === undefined)
|
|
397
|
+
return;
|
|
398
|
+
this.#entries.delete(key);
|
|
399
|
+
this.#entries.set(key, value);
|
|
400
|
+
return value;
|
|
401
|
+
}
|
|
402
|
+
delete(key) {
|
|
403
|
+
this.#entries.delete(key);
|
|
404
|
+
}
|
|
405
|
+
set(key, value) {
|
|
406
|
+
this.#entries.delete(key);
|
|
407
|
+
this.#entries.set(key, value);
|
|
408
|
+
if (this.#entries.size > this.#max) {
|
|
409
|
+
const oldest = this.#entries.keys().next();
|
|
410
|
+
if (!oldest.done)
|
|
411
|
+
this.#entries.delete(oldest.value);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// src/principal.ts
|
|
417
|
+
var isString = (value) => typeof value === "string" && value !== "";
|
|
418
|
+
function principalSchema(tenantOf) {
|
|
419
|
+
return {
|
|
420
|
+
"~standard": {
|
|
421
|
+
version: 1,
|
|
422
|
+
vendor: "@softistx/alxia-clavix",
|
|
423
|
+
validate(value) {
|
|
424
|
+
const claims = value;
|
|
425
|
+
const issues = [];
|
|
426
|
+
const need = (name) => issues.push({ message: `${name} is required`, path: [name] });
|
|
427
|
+
const { iss, sub, client_id: clientId, scope, roles } = claims;
|
|
428
|
+
if (!isString(iss))
|
|
429
|
+
need("iss");
|
|
430
|
+
if (!isString(sub))
|
|
431
|
+
need("sub");
|
|
432
|
+
if (!isString(clientId))
|
|
433
|
+
need("client_id");
|
|
434
|
+
if (scope !== undefined && typeof scope !== "string") {
|
|
435
|
+
issues.push({ message: "scope must be a string", path: ["scope"] });
|
|
436
|
+
}
|
|
437
|
+
if (roles !== undefined && !(Array.isArray(roles) && roles.every((r) => typeof r === "string"))) {
|
|
438
|
+
issues.push({
|
|
439
|
+
message: "roles must be an array of strings",
|
|
440
|
+
path: ["roles"]
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
const tenant = isString(iss) ? tenantOf(iss) : undefined;
|
|
444
|
+
if (isString(iss) && tenant === undefined) {
|
|
445
|
+
issues.push({ message: "the issuer has no tenant", path: ["iss"] });
|
|
446
|
+
}
|
|
447
|
+
if (issues.length > 0)
|
|
448
|
+
return { issues };
|
|
449
|
+
return {
|
|
450
|
+
value: {
|
|
451
|
+
subject: sub,
|
|
452
|
+
tenant,
|
|
453
|
+
issuer: iss,
|
|
454
|
+
clientId,
|
|
455
|
+
scopes: typeof scope === "string" ? scope.split(" ").filter(Boolean) : [],
|
|
456
|
+
roles: roles ?? [],
|
|
457
|
+
claims
|
|
458
|
+
}
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// src/unverified-issuer.ts
|
|
466
|
+
var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
467
|
+
function unverifiedIssuer(token) {
|
|
468
|
+
const parts = token.split(".");
|
|
469
|
+
const payload = parts[1];
|
|
470
|
+
if (parts.length !== 3 || payload === undefined)
|
|
471
|
+
return;
|
|
472
|
+
if (!/^[A-Za-z0-9_-]+$/.test(payload))
|
|
473
|
+
return;
|
|
474
|
+
try {
|
|
475
|
+
const claims = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(payload, "base64url")));
|
|
476
|
+
return isObject2(claims) && typeof claims["iss"] === "string" ? claims["iss"] : undefined;
|
|
477
|
+
} catch {
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// src/clavix.ts
|
|
483
|
+
var PASSTHROUGH = [
|
|
484
|
+
"audience",
|
|
485
|
+
"cacheMs",
|
|
486
|
+
"staleMs",
|
|
487
|
+
"refetchMs",
|
|
488
|
+
"timeoutMs",
|
|
489
|
+
"clockTolerance",
|
|
490
|
+
"algorithms"
|
|
491
|
+
];
|
|
492
|
+
function pick(source, keys) {
|
|
493
|
+
const picked = {};
|
|
494
|
+
for (const key of keys) {
|
|
495
|
+
if (source[key] !== undefined)
|
|
496
|
+
picked[key] = source[key];
|
|
497
|
+
}
|
|
498
|
+
return picked;
|
|
499
|
+
}
|
|
500
|
+
function issuerRules(options) {
|
|
501
|
+
if (options.domain === undefined && options.issuers === undefined) {
|
|
502
|
+
throw new TypeError("clavix: give domain, issuers, or both");
|
|
503
|
+
}
|
|
504
|
+
if (typeof options.audience !== "string" || options.audience === "") {
|
|
505
|
+
throw new TypeError("clavix: audience is required");
|
|
506
|
+
}
|
|
507
|
+
const listed = listIssuers(options.issuers ?? []);
|
|
508
|
+
if (options.domain === undefined && listed.size === 0) {
|
|
509
|
+
throw new TypeError("clavix: give domain, issuers, or both");
|
|
510
|
+
}
|
|
511
|
+
return {
|
|
512
|
+
domain: options.domain === undefined ? undefined : normaliseDomain(options.domain),
|
|
513
|
+
listed
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
function count(name, value, fallback) {
|
|
517
|
+
const n = value ?? fallback;
|
|
518
|
+
if (!Number.isInteger(n) || n < 1) {
|
|
519
|
+
throw new TypeError(`clavix: ${name} must be a positive integer`);
|
|
520
|
+
}
|
|
521
|
+
return n;
|
|
522
|
+
}
|
|
523
|
+
function clavix(options) {
|
|
524
|
+
const rules = issuerRules(options);
|
|
525
|
+
const max = count("maxIssuers", options.maxIssuers, 100);
|
|
526
|
+
const probationSize = count("probation", options.probation, Math.min(max, 16));
|
|
527
|
+
const passthrough = pick(options, PASSTHROUGH);
|
|
528
|
+
const create = (issuer) => createJwt({ ...passthrough, discovery: issuer, profile: "rfc9068" });
|
|
529
|
+
const pinned = new Map;
|
|
530
|
+
for (const issuer of options.warm ?? []) {
|
|
531
|
+
if (resolveIssuer(rules, issuer) === undefined) {
|
|
532
|
+
throw new TypeError(`clavix: warm issuer ${issuer} is not allowed`);
|
|
533
|
+
}
|
|
534
|
+
pinned.set(issuer, create(issuer));
|
|
535
|
+
}
|
|
536
|
+
const proven = new Lru(max);
|
|
537
|
+
const probation = new Lru(probationSize);
|
|
538
|
+
const verifierOf = (issuer) => {
|
|
539
|
+
const known = pinned.get(issuer) ?? proven.get(issuer);
|
|
540
|
+
if (known !== undefined)
|
|
541
|
+
return known;
|
|
542
|
+
let verifier = probation.get(issuer);
|
|
543
|
+
if (verifier === undefined) {
|
|
544
|
+
verifier = create(issuer);
|
|
545
|
+
probation.set(issuer, verifier);
|
|
546
|
+
}
|
|
547
|
+
return verifier;
|
|
548
|
+
};
|
|
549
|
+
const tenantOf = (issuer) => resolveIssuer(rules, issuer)?.tenant;
|
|
550
|
+
const schema = principalSchema(tenantOf);
|
|
551
|
+
const dpop = options.dpop === undefined ? undefined : resolveDpop(options.dpop);
|
|
552
|
+
const self = {
|
|
553
|
+
tenantOf,
|
|
554
|
+
ready: async () => (await Promise.all([...pinned.values()].map((v) => v.ready()))).every(Boolean),
|
|
555
|
+
bearer: (guardOptions) => guard({ jwt: self, schema, dpop, cookie: guardOptions?.cookie }),
|
|
556
|
+
async verify(token) {
|
|
557
|
+
const issuer = unverifiedIssuer(token);
|
|
558
|
+
if (issuer === undefined)
|
|
559
|
+
return { ok: false, reason: "malformed" };
|
|
560
|
+
if (resolveIssuer(rules, issuer) === undefined) {
|
|
561
|
+
return { ok: false, reason: "issuer" };
|
|
562
|
+
}
|
|
563
|
+
const verifier = verifierOf(issuer);
|
|
564
|
+
const result = await verifier.verify(token);
|
|
565
|
+
if (result.ok && probation.get(issuer) === verifier) {
|
|
566
|
+
probation.delete(issuer);
|
|
567
|
+
proven.set(issuer, verifier);
|
|
568
|
+
}
|
|
569
|
+
return result;
|
|
570
|
+
}
|
|
571
|
+
};
|
|
572
|
+
return self;
|
|
573
|
+
}
|
|
574
|
+
// src/scope.ts
|
|
575
|
+
import {
|
|
576
|
+
defineMiddleware,
|
|
577
|
+
errorFormat,
|
|
578
|
+
markFactory,
|
|
579
|
+
problem,
|
|
580
|
+
problemOf
|
|
581
|
+
} from "@softistx/alxia";
|
|
582
|
+
function requireScope(...scopes) {
|
|
583
|
+
if (scopes.length === 0 || scopes.some((s) => !/^[\x21\x23-\x5B\x5D-\x7E]+$/.test(s))) {
|
|
584
|
+
throw new TypeError("requireScope: give scopes, each a non-empty token without spaces or quotes");
|
|
585
|
+
}
|
|
586
|
+
const scope = scopes.join(" ");
|
|
587
|
+
const challenge = {
|
|
588
|
+
headers: {
|
|
589
|
+
"www-authenticate": `Bearer error="insufficient_scope", scope="${scope}"`
|
|
590
|
+
}
|
|
591
|
+
};
|
|
592
|
+
return defineMiddleware()(async function requireScope(ctx, next) {
|
|
593
|
+
if (scopes.every((s) => ctx.user.scopes.includes(s)))
|
|
594
|
+
return next();
|
|
595
|
+
const why = { reason: "insufficient_scope", scope };
|
|
596
|
+
if (errorFormat(ctx) === "problem") {
|
|
597
|
+
return problem(problemOf(ctx, {
|
|
598
|
+
status: 403,
|
|
599
|
+
detail: `The access token lacks the scope: ${scope}`,
|
|
600
|
+
...why
|
|
601
|
+
}), challenge);
|
|
602
|
+
}
|
|
603
|
+
return ctx.reply(403, { error: "forbidden", ...why }, challenge);
|
|
604
|
+
});
|
|
605
|
+
}
|
|
606
|
+
markFactory(requireScope);
|
|
607
|
+
export {
|
|
608
|
+
clavix,
|
|
609
|
+
hmacDpopNonce,
|
|
610
|
+
memoryDpopReplayStore,
|
|
611
|
+
requireScope
|
|
612
|
+
};
|
|
613
|
+
|
|
614
|
+
//# debugId=A0E8A24ACF0832D464756E2164756E21
|
|
615
|
+
//# sourceMappingURL=index.js.map
|