@fluixi/oauth2 1.0.0-alpha.108 → 1.0.0-alpha.109

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.
Files changed (59) hide show
  1. package/dist/api-guard.cjs +7 -2
  2. package/dist/api-guard.mjs +9 -135
  3. package/dist/backchannel.cjs +7 -2
  4. package/dist/backchannel.mjs +11 -299
  5. package/dist/browser.mjs +10 -707
  6. package/dist/callback.mjs +16 -23
  7. package/dist/{dpop-YPGCGL7S.mjs → chunk-27BGFJIY.mjs} +6 -6
  8. package/dist/chunk-2GLWT7XH.mjs +143 -0
  9. package/dist/chunk-3EICMAF7.mjs +22 -0
  10. package/dist/chunk-4OHJTTX7.mjs +398 -0
  11. package/dist/chunk-4QRYJ4TN.mjs +86 -0
  12. package/dist/chunk-5WX3EV2W.mjs +78 -0
  13. package/dist/chunk-7AMC336S.mjs +52 -0
  14. package/dist/chunk-AAN3YN4S.mjs +63 -0
  15. package/dist/chunk-AWVECOG7.mjs +404 -0
  16. package/dist/chunk-GN5SERAQ.mjs +189 -0
  17. package/dist/chunk-KIXTZEEW.mjs +80 -0
  18. package/dist/chunk-KVW2S6VY.mjs +36 -0
  19. package/dist/chunk-MHWZTXZZ.mjs +9 -0
  20. package/dist/chunk-QC2FFASM.mjs +67 -0
  21. package/dist/chunk-SJOBQPG6.mjs +77 -0
  22. package/dist/chunk-VCNXQCIH.mjs +26 -0
  23. package/dist/chunk-XQJTQV3C.mjs +91 -0
  24. package/dist/client-auth.mjs +6 -78
  25. package/dist/discovery.mjs +6 -64
  26. package/dist/dpop-store.mjs +6 -118
  27. package/dist/dpop.mjs +11 -95
  28. package/dist/env-config.mjs +5 -214
  29. package/dist/env-credentials.mjs +5 -47
  30. package/dist/index.cjs +1 -1
  31. package/dist/index.mjs +48 -1010
  32. package/dist/module.mjs +5 -20
  33. package/dist/pkce.mjs +11 -56
  34. package/dist/presets.mjs +5 -214
  35. package/dist/return-to.mjs +4 -22
  36. package/dist/roles.mjs +4 -32
  37. package/dist/server-client.mjs +7 -107
  38. package/dist/server.cjs +61 -9
  39. package/dist/server.d.ts +8 -0
  40. package/dist/server.d.ts.map +1 -1
  41. package/dist/server.js +80 -5
  42. package/dist/server.mjs +94 -433
  43. package/dist/service-client.cjs +1 -1
  44. package/dist/service-client.mjs +16 -138
  45. package/dist/service.mjs +14 -978
  46. package/dist/session-monitor.mjs +4 -74
  47. package/dist/tokens.mjs +5 -4
  48. package/dist/tsconfig.lib.tsbuildinfo +1 -1
  49. package/dist/types.mjs +4 -9
  50. package/dist/verify.cjs +8 -3
  51. package/dist/verify.mjs +17 -585
  52. package/package.json +21 -21
  53. package/dist/browser-XDRDM2J3.mjs +0 -3545
  54. package/dist/chunk-6ZLDEEM7.mjs +0 -15
  55. package/dist/chunk-D2N6T3DN.mjs +0 -10
  56. package/dist/chunk-KPBCIVN3.mjs +0 -108
  57. package/dist/dpop-KK5X2JTA.mjs +0 -100
  58. package/dist/dpop-SO6GDDZH.mjs +0 -22
  59. /package/dist/{chunk-OGSFNTKA.mjs → chunk-AXPSPTNP.mjs} +0 -0
@@ -3,8 +3,13 @@ var __defProp = Object.defineProperty;
3
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __esm = (fn, res) => function __init() {
7
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
+ var __esm = (fn, res, err) => function __init() {
7
+ if (err) throw err[0];
8
+ try {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ } catch (e) {
11
+ throw err = [e], e;
12
+ }
8
13
  };
9
14
  var __export = (target, all) => {
10
15
  for (var name in all)
@@ -1,140 +1,14 @@
1
1
  import {
2
- OAuthError
3
- } from "./chunk-OGSFNTKA.mjs";
2
+ createApiGuard
3
+ } from "./chunk-4OHJTTX7.mjs";
4
+ import "./chunk-7AMC336S.mjs";
5
+ import {
6
+ rolesFrom
7
+ } from "./chunk-KVW2S6VY.mjs";
8
+ import "./chunk-SJOBQPG6.mjs";
9
+ import "./chunk-AAN3YN4S.mjs";
10
+ import "./chunk-AXPSPTNP.mjs";
4
11
  import "./chunk-7P6ASYW6.mjs";
5
-
6
- // src/verify.ts
7
- var TokenError = class extends OAuthError {
8
- constructor(message, code = "invalid_token") {
9
- super(message, code);
10
- this.name = "TokenError";
11
- }
12
- };
13
-
14
- // src/roles.ts
15
- var rolesFrom = {
16
- /** Keycloak, realm roles. Where it puts them unless a client mapper is configured. */
17
- keycloakRealm: (claims) => {
18
- const realm = claims.realm_access;
19
- return realm?.roles ?? [];
20
- },
21
- /** Keycloak, roles scoped to one client rather than the realm. */
22
- keycloakClient: (clientId) => (claims) => {
23
- const all = claims.resource_access;
24
- return all?.[clientId]?.roles ?? [];
25
- },
26
- /** Okta, and anything else using a groups claim. Needs a groups claim on the token. */
27
- groups: (claims) => Array.isArray(claims.groups) ? claims.groups : [],
28
- /** Cognito, which namespaces the claim. */
29
- cognito: (claims) => {
30
- const groups = claims["cognito:groups"];
31
- return Array.isArray(groups) ? groups : [];
32
- },
33
- /**
34
- * Auth0, which requires a namespaced custom claim added by an action.
35
- *
36
- * `rolesFrom.namespaced('https://acme.com/roles')`. Auth0 silently drops a custom claim
37
- * that is not a URI, so an empty list here usually means the namespace, not the action.
38
- */
39
- namespaced: (claim) => (claims) => {
40
- const value = claims[claim];
41
- return Array.isArray(value) ? value : [];
42
- },
43
- /** The `scope` claim read as a role list, for a provider issuing no roles at all. */
44
- scope: (claims) => typeof claims.scope === "string" ? claims.scope.split(" ") : []
45
- };
46
-
47
- // src/api-guard.ts
48
- var asList = (value) => value === void 0 ? [] : Array.isArray(value) ? value : [value];
49
- function refuse(refusal) {
50
- const body = { error: refusal.code };
51
- if (refusal.detail) body.detail = refusal.detail;
52
- return new Response(JSON.stringify(body), {
53
- status: refusal.status,
54
- headers: { "content-type": "application/json" }
55
- });
56
- }
57
- function createApiGuard(options) {
58
- const answer = (refusal, request) => {
59
- const response = options.onRefused ? options.onRefused(refusal, request) : refuse(refusal);
60
- if (refusal.status === 401 && !response.headers.has("www-authenticate")) {
61
- response.headers.set("www-authenticate", `Bearer error="${refusal.code}"`);
62
- }
63
- return response;
64
- };
65
- const rolesOf = (claims, what) => {
66
- if (!options.roles) {
67
- throw new Error(
68
- `[fluixi/oauth2] this route requires ${what}, but createApiGuard was given no \`roles\`. Providers disagree on where roles live, so there is no default: pass one of \`rolesFrom\`, or a function reading the claim your provider uses.`
69
- );
70
- }
71
- return options.roles(claims);
72
- };
73
- return (handler, requirements = {}) => async (request) => {
74
- let claims;
75
- try {
76
- claims = await options.verify.fromRequest(request);
77
- } catch (cause) {
78
- const code = cause instanceof TokenError ? cause.code : "invalid_token";
79
- return answer({ status: 401, code }, request);
80
- }
81
- const wanted = asList(requirements.role);
82
- if (wanted.length) {
83
- const held = rolesOf(claims, "a role");
84
- if (!wanted.some((role) => held.includes(role))) {
85
- return answer(
86
- {
87
- status: 403,
88
- code: "insufficient_role",
89
- detail: `needs ${wanted.length > 1 ? "one of " : ""}${wanted.join(", ")}`,
90
- claims
91
- },
92
- request
93
- );
94
- }
95
- }
96
- if (requirements.allRoles?.length) {
97
- const held = rolesOf(claims, "roles");
98
- const missing = requirements.allRoles.filter((role) => !held.includes(role));
99
- if (missing.length) {
100
- return answer(
101
- { status: 403, code: "insufficient_role", detail: `needs ${missing.join(", ")}`, claims },
102
- request
103
- );
104
- }
105
- }
106
- const scopes = asList(requirements.scope);
107
- if (scopes.length) {
108
- const held = typeof claims.scope === "string" ? claims.scope.split(" ") : [];
109
- if (!scopes.some((scope) => held.includes(scope))) {
110
- return answer(
111
- {
112
- status: 403,
113
- code: "insufficient_scope",
114
- detail: `needs ${scopes.length > 1 ? "one of " : ""}${scopes.join(", ")}`,
115
- claims
116
- },
117
- request
118
- );
119
- }
120
- }
121
- if (requirements.require) {
122
- const verdict = requirements.require(claims, request);
123
- if (verdict !== true) {
124
- return answer(
125
- {
126
- status: 403,
127
- code: "forbidden",
128
- detail: typeof verdict === "string" ? verdict : void 0,
129
- claims
130
- },
131
- request
132
- );
133
- }
134
- }
135
- return handler(request, claims);
136
- };
137
- }
138
12
  export {
139
13
  createApiGuard,
140
14
  rolesFrom
@@ -5,8 +5,13 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __esm = (fn, res) => function __init() {
9
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
8
+ var __esm = (fn, res, err) => function __init() {
9
+ if (err) throw err[0];
10
+ try {
11
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
12
+ } catch (e) {
13
+ throw err = [e], e;
14
+ }
10
15
  };
11
16
  var __export = (target, all) => {
12
17
  for (var name in all)
@@ -1,304 +1,16 @@
1
1
  import {
2
- OAuthError
3
- } from "./chunk-OGSFNTKA.mjs";
2
+ LOGOUT_EVENT,
3
+ idTokenClaims,
4
+ logoutTokenVerifier,
5
+ memoryLogouts
6
+ } from "./chunk-KIXTZEEW.mjs";
7
+ import "./chunk-4OHJTTX7.mjs";
8
+ import "./chunk-7AMC336S.mjs";
9
+ import "./chunk-KVW2S6VY.mjs";
10
+ import "./chunk-SJOBQPG6.mjs";
11
+ import "./chunk-AAN3YN4S.mjs";
12
+ import "./chunk-AXPSPTNP.mjs";
4
13
  import "./chunk-7P6ASYW6.mjs";
5
-
6
- // src/discovery.ts
7
- var cache = /* @__PURE__ */ new Map();
8
- function documentUrl(issuer) {
9
- return `${issuer.replace(/\/$/, "")}/.well-known/openid-configuration`;
10
- }
11
- async function discover(issuer, fetcher = fetch) {
12
- const cached = cache.get(issuer);
13
- if (cached) return cached;
14
- const pending = (async () => {
15
- let response;
16
- try {
17
- response = await fetcher(documentUrl(issuer));
18
- } catch (cause) {
19
- const why = cause instanceof Error ? cause.message : String(cause);
20
- throw new OAuthError(
21
- typeof window === "undefined" ? (
22
- // On a server nothing blocks the read: the provider is down, or the address is wrong.
23
- `Could not reach the provider at ${documentUrl(issuer)}: is it running, and is the issuer right? (${why})`
24
- ) : `Could not read the discovery document at ${documentUrl(issuer)}. In a browser this is usually the provider refusing a cross-origin read: give \`endpoints\` directly, or resolve them on a server. (${why})`,
25
- "discovery_unreachable"
26
- );
27
- }
28
- if (!response.ok) {
29
- throw new OAuthError(
30
- `Discovery failed for ${issuer}: ${response.status}`,
31
- "discovery_failed"
32
- );
33
- }
34
- const doc = await response.json();
35
- if (!doc.authorization_endpoint || !doc.token_endpoint) {
36
- throw new OAuthError(
37
- `${issuer} published a discovery document with no authorization or token endpoint.`,
38
- "discovery_incomplete"
39
- );
40
- }
41
- return {
42
- authorization: doc.authorization_endpoint,
43
- token: doc.token_endpoint,
44
- userinfo: doc.userinfo_endpoint,
45
- endSession: doc.end_session_endpoint,
46
- jwks: doc.jwks_uri,
47
- introspection: doc.introspection_endpoint,
48
- revocation: doc.revocation_endpoint,
49
- checkSession: doc.check_session_iframe,
50
- issuer: doc.issuer ?? issuer
51
- };
52
- })();
53
- cache.set(issuer, pending);
54
- pending.catch(() => cache.delete(issuer));
55
- return pending;
56
- }
57
-
58
- // src/verify.ts
59
- var TokenError = class extends OAuthError {
60
- constructor(message, code = "invalid_token") {
61
- super(message, code);
62
- this.name = "TokenError";
63
- }
64
- };
65
- function bearerOf(request) {
66
- const header = request.headers.get("authorization");
67
- if (!header) return null;
68
- const match = header.match(/^(?:Bearer|DPoP)\s+(.+)$/i);
69
- return match ? match[1].trim() : null;
70
- }
71
- async function loadJose() {
72
- try {
73
- return await import("./browser-FDUOEUM2.mjs");
74
- } catch {
75
- throw new OAuthError(
76
- "Token verification needs `jose`. Install it: npm i jose. It is an optional peer so an app that does not verify does not carry it.",
77
- "jose_missing"
78
- );
79
- }
80
- }
81
- function createTokenVerifier(options) {
82
- const issuers = (Array.isArray(options.issuer) ? options.issuer : [options.issuer]).filter(Boolean);
83
- if (!issuers.length) {
84
- throw new Error("[fluixi/oauth2] createTokenVerifier needs an issuer to accept tokens from.");
85
- }
86
- const discoveryIssuer = issuers[0];
87
- if (options.audience === void 0) {
88
- throw new Error(
89
- "[fluixi/oauth2] createTokenVerifier needs an audience, or `audience: false` to say this service really does accept a token minted for any client of the issuer."
90
- );
91
- }
92
- if (options.audience === false && options.authorizedParty === void 0) {
93
- console.warn(
94
- "[fluixi/oauth2] This verifier checks neither `aud` nor `azp`, so a token minted for any client of the issuer is accepted. Set `authorizedParty` if that is not what you meant."
95
- );
96
- }
97
- const algorithms = options.algorithms ?? ["RS256"];
98
- if (algorithms.some((alg) => !alg || alg.toLowerCase() === "none")) {
99
- throw new Error("[fluixi/oauth2] `none` is not a signing algorithm and cannot be accepted.");
100
- }
101
- let keys = null;
102
- async function keySet() {
103
- if (keys) return keys;
104
- const jose = await loadJose();
105
- if (options.jwks) {
106
- keys = jose.createLocalJWKSet(options.jwks);
107
- return keys;
108
- }
109
- let uri = options.jwksUri;
110
- if (!uri) {
111
- const endpoints = await discover(discoveryIssuer);
112
- uri = endpoints.jwks;
113
- }
114
- if (!uri) {
115
- throw new OAuthError(
116
- `${discoveryIssuer} published no jwks_uri. Give the verifier one directly.`,
117
- "no_jwks"
118
- );
119
- }
120
- keys = jose.createRemoteJWKSet(new URL(uri));
121
- return keys;
122
- }
123
- const checkProof = async (claims, token, request) => {
124
- const jose = await loadJose();
125
- const { boundKeyOf, thumbprintOf } = await import("./dpop-YPGCGL7S.mjs");
126
- const bound = boundKeyOf(claims);
127
- if (!bound) {
128
- throw new TokenError(
129
- "This token is not bound to a key, and this service requires binding.",
130
- "token_not_bound"
131
- );
132
- }
133
- const proof = request.headers.get("dpop");
134
- if (!proof) throw new TokenError("The request carried no DPoP proof.", "missing_dpop_proof");
135
- let payload;
136
- let header;
137
- try {
138
- const result = await jose.jwtVerify(proof, jose.EmbeddedJWK, { typ: "dpop+jwt" });
139
- payload = result.payload;
140
- header = result.protectedHeader;
141
- } catch (cause) {
142
- throw new TokenError(
143
- `The DPoP proof did not verify: ${cause instanceof Error ? cause.message : String(cause)}`,
144
- "invalid_dpop_proof"
145
- );
146
- }
147
- const presented = await thumbprintOf(header.jwk);
148
- if (presented !== bound) {
149
- throw new TokenError(
150
- "The DPoP proof was signed with a different key from the one this token is bound to.",
151
- "dpop_key_mismatch"
152
- );
153
- }
154
- const url = new URL(request.url);
155
- url.search = "";
156
- url.hash = "";
157
- if (payload.htm !== request.method.toUpperCase()) {
158
- throw new TokenError("The DPoP proof was made for a different method.", "invalid_dpop_proof");
159
- }
160
- if (payload.htu !== url.toString()) {
161
- throw new TokenError("The DPoP proof was made for a different URL.", "invalid_dpop_proof");
162
- }
163
- if (typeof payload.ath === "string") {
164
- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token));
165
- let binary = "";
166
- for (const byte of new Uint8Array(digest)) binary += String.fromCharCode(byte);
167
- const expected = btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
168
- if (payload.ath !== expected) {
169
- throw new TokenError("The DPoP proof was made for a different token.", "invalid_dpop_proof");
170
- }
171
- }
172
- const age = Math.abs(Date.now() / 1e3 - payload.iat);
173
- if (!Number.isFinite(age) || age > (options.dpopProofAgeSec ?? 10)) {
174
- throw new TokenError("The DPoP proof is too old to accept.", "invalid_dpop_proof");
175
- }
176
- };
177
- const verify = async (token, request) => {
178
- if (!token) throw new TokenError("No token to verify.", "no_token");
179
- const jose = await loadJose();
180
- let payload;
181
- try {
182
- ({ payload } = await jose.jwtVerify(token, await keySet(), {
183
- // jose takes a list and accepts any of them, which is what a provider naming
184
- // itself two ways needs.
185
- issuer: issuers,
186
- ...options.audience === false ? {} : { audience: options.audience },
187
- algorithms,
188
- clockTolerance: options.clockToleranceSec ?? 5
189
- }));
190
- } catch (cause) {
191
- throw new TokenError(
192
- `The token was not accepted: ${cause instanceof Error ? cause.message : String(cause)}`
193
- );
194
- }
195
- if (options.authorizedParty !== void 0) {
196
- const allowed = Array.isArray(options.authorizedParty) ? options.authorizedParty : [options.authorizedParty];
197
- const issuedTo = payload.azp ?? payload.client_id;
198
- if (typeof issuedTo !== "string" || !allowed.includes(issuedTo)) {
199
- throw new TokenError("The token was issued to a different client.", "invalid_azp");
200
- }
201
- }
202
- if (options.dpop) {
203
- if (!request) {
204
- throw new Error(
205
- "[fluixi/oauth2] `dpop: true` needs the request to read its proof. Use `verify.fromRequest(request)` rather than verifying a bare token."
206
- );
207
- }
208
- await checkProof(payload, token, request);
209
- }
210
- if (options.require) {
211
- const verdict = options.require(payload);
212
- if (verdict !== true) {
213
- throw new TokenError(
214
- typeof verdict === "string" ? verdict : "The token did not meet this service's requirements.",
215
- "insufficient_claims"
216
- );
217
- }
218
- }
219
- return payload;
220
- };
221
- const verifier = verify;
222
- verifier.bearerOf = bearerOf;
223
- verifier.fromRequest = async (request) => {
224
- const token = verifier.bearerOf(request);
225
- if (!token) {
226
- throw new TokenError("The request carried no bearer token.", "no_token");
227
- }
228
- return verify(token, request);
229
- };
230
- return verifier;
231
- }
232
-
233
- // src/backchannel.ts
234
- var LOGOUT_EVENT = "http://schemas.openid.net/event/backchannel-logout";
235
- function memoryLogouts(ttlMs = 14 * 24 * 36e5) {
236
- const sids = /* @__PURE__ */ new Map();
237
- const subs = /* @__PURE__ */ new Map();
238
- const prune = (now) => {
239
- for (const map of [sids, subs]) for (const [key, at] of map) if (now - at > ttlMs) map.delete(key);
240
- };
241
- return {
242
- add(entry) {
243
- prune(Date.now());
244
- if (entry.sid) sids.set(entry.sid, entry.at);
245
- else if (entry.sub) subs.set(entry.sub, Math.max(entry.at, subs.get(entry.sub) ?? 0));
246
- },
247
- ended(session) {
248
- if (session.sid && sids.has(session.sid)) return true;
249
- const all = session.sub ? subs.get(session.sub) : void 0;
250
- return all !== void 0 && session.since <= all;
251
- }
252
- };
253
- }
254
- function idTokenClaims(idToken) {
255
- if (!idToken) return {};
256
- try {
257
- const part = idToken.split(".")[1] ?? "";
258
- const json = atob(part.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(part.length / 4) * 4, "="));
259
- const claims = JSON.parse(json);
260
- return {
261
- sid: typeof claims.sid === "string" ? claims.sid : void 0,
262
- sub: typeof claims.sub === "string" ? claims.sub : void 0,
263
- iat: typeof claims.iat === "number" ? claims.iat : void 0
264
- };
265
- } catch {
266
- return {};
267
- }
268
- }
269
- function headerOf(token) {
270
- try {
271
- const part = token.split(".")[0] ?? "";
272
- return JSON.parse(atob(part.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(part.length / 4) * 4, "=")));
273
- } catch {
274
- return {};
275
- }
276
- }
277
- function logoutTokenVerifier(options) {
278
- const verify = createTokenVerifier({
279
- issuer: options.issuer,
280
- audience: options.clientId,
281
- jwksUri: options.jwksUri,
282
- jwks: options.jwks,
283
- require: (claims) => {
284
- const events = claims.events;
285
- if (!events || typeof events !== "object" || !(LOGOUT_EVENT in events)) return "no logout event";
286
- if ("nonce" in claims) return "a logout token has no nonce";
287
- if (typeof claims.sid !== "string" && typeof claims.sub !== "string") return "names no session and no subject";
288
- return true;
289
- }
290
- });
291
- return async (token) => {
292
- const typ = headerOf(token).typ;
293
- if (typ !== void 0 && typ !== "logout+jwt") throw new Error("not a logout token");
294
- const claims = await verify(token);
295
- return {
296
- sid: typeof claims.sid === "string" ? claims.sid : void 0,
297
- sub: typeof claims.sub === "string" ? claims.sub : void 0,
298
- at: (typeof claims.iat === "number" ? claims.iat : Math.floor(Date.now() / 1e3)) * 1e3
299
- };
300
- };
301
- }
302
14
  export {
303
15
  LOGOUT_EVENT,
304
16
  idTokenClaims,