@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
package/dist/callback.mjs CHANGED
@@ -1,32 +1,25 @@
1
+ import {
2
+ paramsFromUrl
3
+ } from "./chunk-2GLWT7XH.mjs";
4
+ import "./chunk-4QRYJ4TN.mjs";
5
+ import "./chunk-5WX3EV2W.mjs";
6
+ import {
7
+ AuthServiceToken
8
+ } from "./chunk-MHWZTXZZ.mjs";
9
+ import "./chunk-AWVECOG7.mjs";
10
+ import "./chunk-QC2FFASM.mjs";
11
+ import "./chunk-VCNXQCIH.mjs";
12
+ import "./chunk-SJOBQPG6.mjs";
13
+ import "./chunk-AAN3YN4S.mjs";
14
+ import "./chunk-XQJTQV3C.mjs";
15
+ import "./chunk-27BGFJIY.mjs";
16
+ import "./chunk-AXPSPTNP.mjs";
1
17
  import "./chunk-7P6ASYW6.mjs";
2
18
 
3
19
  // src/callback.ts
4
20
  import { onMount } from "@fluixi/core";
5
21
  import { signal } from "@fluixi/reactive/signal";
6
22
  import { inject } from "@fluixi/di";
7
-
8
- // src/tokens.ts
9
- import { injectionToken } from "@fluixi/di";
10
- var AuthServiceToken = injectionToken("AuthService");
11
- var AuthClientToken = injectionToken("AuthClient");
12
-
13
- // src/service.ts
14
- import { createSignal, markReactiveScope, openReactiveScope, withReactiveScope } from "@fluixi/reactive/signal";
15
- import { createSession } from "@fluixi/session";
16
- import { createAuthHooks } from "@fluixi/auth/client";
17
- function paramsFromUrl(url) {
18
- const href = url ?? (typeof location === "undefined" ? null : location.href);
19
- if (!href) return {};
20
- const { searchParams } = new URL(String(href));
21
- return {
22
- code: searchParams.get("code") ?? void 0,
23
- state: searchParams.get("state") ?? void 0,
24
- error: searchParams.get("error") ?? void 0,
25
- errorDescription: searchParams.get("error_description") ?? void 0
26
- };
27
- }
28
-
29
- // src/callback.ts
30
23
  function reasonFor(cause) {
31
24
  if (cause instanceof Error) return cause.message;
32
25
  return String(cause);
@@ -1,7 +1,6 @@
1
1
  import {
2
2
  OAuthError
3
- } from "./chunk-OGSFNTKA.mjs";
4
- import "./chunk-7P6ASYW6.mjs";
3
+ } from "./chunk-AXPSPTNP.mjs";
5
4
 
6
5
  // src/dpop.ts
7
6
  async function loadJose() {
@@ -87,13 +86,14 @@ function boundKeyOf(claims) {
87
86
  const cnf = claims.cnf;
88
87
  return typeof cnf?.jkt === "string" ? cnf.jkt : null;
89
88
  }
89
+
90
90
  export {
91
- boundKeyOf,
92
91
  createDpopKey,
93
92
  exportDpopKey,
94
93
  importDpopKey,
95
- nonceFrom,
96
- proofFor,
97
94
  thumbprintOf,
98
- wantsNonce
95
+ proofFor,
96
+ nonceFrom,
97
+ wantsNonce,
98
+ boundKeyOf
99
99
  };
@@ -0,0 +1,143 @@
1
+ import {
2
+ COOKIE_SESSION,
3
+ createServerClient
4
+ } from "./chunk-4QRYJ4TN.mjs";
5
+ import {
6
+ watchProviderSession
7
+ } from "./chunk-5WX3EV2W.mjs";
8
+ import {
9
+ createBrowserClient
10
+ } from "./chunk-AWVECOG7.mjs";
11
+ import {
12
+ expiryFromJwt
13
+ } from "./chunk-QC2FFASM.mjs";
14
+ import {
15
+ safeReturnTo
16
+ } from "./chunk-VCNXQCIH.mjs";
17
+ import {
18
+ OAuthError
19
+ } from "./chunk-AXPSPTNP.mjs";
20
+
21
+ // src/service.ts
22
+ import { createSignal, markReactiveScope, openReactiveScope, withReactiveScope } from "@fluixi/reactive/signal";
23
+ import { createSession } from "@fluixi/session";
24
+ import { createAuthHooks } from "@fluixi/auth/client";
25
+ function paramsFromUrl(url) {
26
+ const href = url ?? (typeof location === "undefined" ? null : location.href);
27
+ if (!href) return {};
28
+ const { searchParams } = new URL(String(href));
29
+ return {
30
+ code: searchParams.get("code") ?? void 0,
31
+ state: searchParams.get("state") ?? void 0,
32
+ error: searchParams.get("error") ?? void 0,
33
+ errorDescription: searchParams.get("error_description") ?? void 0
34
+ };
35
+ }
36
+ function clientFor(options) {
37
+ if (options.client) return options.client;
38
+ return options.config.tokens === "server" ? createServerClient(options.config) : createBrowserClient(options.config);
39
+ }
40
+ function createAuthService(options) {
41
+ const tokens = options.config.tokens;
42
+ const scope = openReactiveScope({ kind: "service", name: "AuthService", ...tokens ? { detail: `tokens: ${tokens}` } : {} });
43
+ const service = withReactiveScope(scope, () => buildAuthService(options));
44
+ markReactiveScope(service, scope);
45
+ return service;
46
+ }
47
+ function buildAuthService(options) {
48
+ const client = clientFor(options);
49
+ let latest = null;
50
+ const fetchUserFor = async (token) => {
51
+ if (options.fetchUser) return options.fetchUser(token);
52
+ return client.fetchUser(token === COOKIE_SESSION ? void 0 : token);
53
+ };
54
+ const resumesFromCookie = options.config.tokens === "server" && typeof window !== "undefined";
55
+ const [ready, setReady] = createSignal(!resumesFromCookie);
56
+ const session = createSession({
57
+ /** The credential is the callback, so this is the code exchange. */
58
+ async login(params) {
59
+ latest = await client.handleCallback(params);
60
+ return { token: latest.accessToken, expiresAt: latest.expiresAt };
61
+ },
62
+ fetchUser: fetchUserFor,
63
+ async refresh() {
64
+ latest = await client.refresh();
65
+ return { token: latest.accessToken, expiresAt: latest.expiresAt };
66
+ },
67
+ async logout() {
68
+ latest = null;
69
+ await client.logout();
70
+ },
71
+ getExpiry(token) {
72
+ if (token === COOKIE_SESSION) return null;
73
+ return latest?.expiresAt ?? expiryFromJwt(token);
74
+ },
75
+ access: options.access,
76
+ storageKeys: options.storageKeys,
77
+ refreshSkewMs: options.refreshSkewMs,
78
+ onLogin: options.onLogin,
79
+ onLogout: options.onLogout,
80
+ onExpired: options.onExpired,
81
+ onError: options.onError
82
+ });
83
+ const hooks = createAuthHooks({
84
+ session,
85
+ ready,
86
+ navigate: options.navigate,
87
+ loginPath: options.loginPath ?? "/login",
88
+ homePath: options.homePath ?? "/",
89
+ forbiddenPath: options.forbiddenPath ?? "/403"
90
+ });
91
+ if (resumesFromCookie && options.config.tokens === "server" && options.config.watchSession !== false) {
92
+ watchProviderSession({ basePath: options.config.basePath });
93
+ }
94
+ const renderedSignedOut = hooks.store.seeded && hooks.store.value().user == null;
95
+ if (resumesFromCookie && renderedSignedOut) setReady(true);
96
+ else if (resumesFromCookie) {
97
+ void (async () => {
98
+ try {
99
+ await session.adopt(COOKIE_SESSION, await fetchUserFor(COOKIE_SESSION));
100
+ } catch {
101
+ } finally {
102
+ setReady(true);
103
+ }
104
+ })();
105
+ }
106
+ return Object.assign(session, {
107
+ client,
108
+ protectedRoute: hooks.protectedRoute,
109
+ Can: hooks.Can,
110
+ Protect: hooks.Protect,
111
+ useAuth: hooks.useAuth,
112
+ useUser: hooks.useUser,
113
+ useCan: hooks.useCan,
114
+ signIn(loginOptions = {}) {
115
+ return client.login(loginOptions);
116
+ },
117
+ /**
118
+ * Finish a login and say where to go.
119
+ *
120
+ * The destination is checked before it is handed back, so an app that navigates to it
121
+ * without looking cannot be turned into an open redirect by a poisoned login link.
122
+ */
123
+ async complete(params) {
124
+ const callback = params ?? paramsFromUrl();
125
+ if (!callback.code && !callback.error) {
126
+ throw new OAuthError(
127
+ "complete() found no callback parameters. It runs in the browser, on the redirect URI, where the code and the PKCE verifier both are.",
128
+ "no_callback_params"
129
+ );
130
+ }
131
+ await session.login(callback);
132
+ return safeReturnTo(client.consumeReturnTo?.(), {
133
+ fallback: "/",
134
+ allowedOrigins: "allowedReturnOrigins" in options.config ? options.config.allowedReturnOrigins : void 0
135
+ });
136
+ }
137
+ });
138
+ }
139
+
140
+ export {
141
+ paramsFromUrl,
142
+ createAuthService
143
+ };
@@ -0,0 +1,22 @@
1
+ import {
2
+ AuthClientToken,
3
+ AuthServiceToken
4
+ } from "./chunk-MHWZTXZZ.mjs";
5
+
6
+ // src/module.ts
7
+ import { defineModule } from "@fluixi/start/app";
8
+ function authModule(auth) {
9
+ return defineModule({
10
+ name: "oauth2",
11
+ providers: [
12
+ // One instance for every request on the server. It holds no per-visitor state there:
13
+ // the signed-in user comes from request locals, which `sessionLocals` fills per request.
14
+ { provide: AuthServiceToken, useValue: auth },
15
+ { provide: AuthClientToken, useValue: auth.client }
16
+ ]
17
+ });
18
+ }
19
+
20
+ export {
21
+ authModule
22
+ };
@@ -0,0 +1,398 @@
1
+ import {
2
+ applyClientAuth,
3
+ assertUsable,
4
+ resolveMethod
5
+ } from "./chunk-SJOBQPG6.mjs";
6
+ import {
7
+ discover
8
+ } from "./chunk-AAN3YN4S.mjs";
9
+ import {
10
+ OAuthError
11
+ } from "./chunk-AXPSPTNP.mjs";
12
+
13
+ // src/api-guard.ts
14
+ var asList = (value) => value === void 0 ? [] : Array.isArray(value) ? value : [value];
15
+ function refuse(refusal) {
16
+ const body = { error: refusal.code };
17
+ if (refusal.detail) body.detail = refusal.detail;
18
+ return new Response(JSON.stringify(body), {
19
+ status: refusal.status,
20
+ headers: { "content-type": "application/json" }
21
+ });
22
+ }
23
+ function createApiGuard(options) {
24
+ const answer = (refusal, request) => {
25
+ const response = options.onRefused ? options.onRefused(refusal, request) : refuse(refusal);
26
+ if (refusal.status === 401 && !response.headers.has("www-authenticate")) {
27
+ response.headers.set("www-authenticate", `Bearer error="${refusal.code}"`);
28
+ }
29
+ return response;
30
+ };
31
+ const rolesOf = (claims, what) => {
32
+ if (!options.roles) {
33
+ throw new Error(
34
+ `[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.`
35
+ );
36
+ }
37
+ return options.roles(claims);
38
+ };
39
+ return (handler, requirements = {}) => async (request) => {
40
+ let claims;
41
+ try {
42
+ claims = await options.verify.fromRequest(request);
43
+ } catch (cause) {
44
+ const code = cause instanceof TokenError ? cause.code : "invalid_token";
45
+ return answer({ status: 401, code }, request);
46
+ }
47
+ const wanted = asList(requirements.role);
48
+ if (wanted.length) {
49
+ const held = rolesOf(claims, "a role");
50
+ if (!wanted.some((role) => held.includes(role))) {
51
+ return answer(
52
+ {
53
+ status: 403,
54
+ code: "insufficient_role",
55
+ detail: `needs ${wanted.length > 1 ? "one of " : ""}${wanted.join(", ")}`,
56
+ claims
57
+ },
58
+ request
59
+ );
60
+ }
61
+ }
62
+ if (requirements.allRoles?.length) {
63
+ const held = rolesOf(claims, "roles");
64
+ const missing = requirements.allRoles.filter((role) => !held.includes(role));
65
+ if (missing.length) {
66
+ return answer(
67
+ { status: 403, code: "insufficient_role", detail: `needs ${missing.join(", ")}`, claims },
68
+ request
69
+ );
70
+ }
71
+ }
72
+ const scopes = asList(requirements.scope);
73
+ if (scopes.length) {
74
+ const held = typeof claims.scope === "string" ? claims.scope.split(" ") : [];
75
+ if (!scopes.some((scope) => held.includes(scope))) {
76
+ return answer(
77
+ {
78
+ status: 403,
79
+ code: "insufficient_scope",
80
+ detail: `needs ${scopes.length > 1 ? "one of " : ""}${scopes.join(", ")}`,
81
+ claims
82
+ },
83
+ request
84
+ );
85
+ }
86
+ }
87
+ if (requirements.require) {
88
+ const verdict = requirements.require(claims, request);
89
+ if (verdict !== true) {
90
+ return answer(
91
+ {
92
+ status: 403,
93
+ code: "forbidden",
94
+ detail: typeof verdict === "string" ? verdict : void 0,
95
+ claims
96
+ },
97
+ request
98
+ );
99
+ }
100
+ }
101
+ return handler(request, claims);
102
+ };
103
+ }
104
+
105
+ // src/verify.ts
106
+ var TokenError = class extends OAuthError {
107
+ constructor(message, code = "invalid_token") {
108
+ super(message, code);
109
+ this.name = "TokenError";
110
+ }
111
+ };
112
+ function bearerOf(request) {
113
+ const header = request.headers.get("authorization");
114
+ if (!header) return null;
115
+ const match = header.match(/^(?:Bearer|DPoP)\s+(.+)$/i);
116
+ return match ? match[1].trim() : null;
117
+ }
118
+ async function loadJose() {
119
+ try {
120
+ return await import("./browser-FDUOEUM2.mjs");
121
+ } catch {
122
+ throw new OAuthError(
123
+ "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.",
124
+ "jose_missing"
125
+ );
126
+ }
127
+ }
128
+ function createTokenVerifier(options) {
129
+ const issuers = (Array.isArray(options.issuer) ? options.issuer : [options.issuer]).filter(Boolean);
130
+ if (!issuers.length) {
131
+ throw new Error("[fluixi/oauth2] createTokenVerifier needs an issuer to accept tokens from.");
132
+ }
133
+ const discoveryIssuer = issuers[0];
134
+ if (options.audience === void 0) {
135
+ throw new Error(
136
+ "[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."
137
+ );
138
+ }
139
+ if (options.audience === false && options.authorizedParty === void 0) {
140
+ console.warn(
141
+ "[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."
142
+ );
143
+ }
144
+ const algorithms = options.algorithms ?? ["RS256"];
145
+ if (algorithms.some((alg) => !alg || alg.toLowerCase() === "none")) {
146
+ throw new Error("[fluixi/oauth2] `none` is not a signing algorithm and cannot be accepted.");
147
+ }
148
+ let keys = null;
149
+ async function keySet() {
150
+ if (keys) return keys;
151
+ const jose = await loadJose();
152
+ if (options.jwks) {
153
+ keys = jose.createLocalJWKSet(options.jwks);
154
+ return keys;
155
+ }
156
+ let uri = options.jwksUri;
157
+ if (!uri) {
158
+ const endpoints = await discover(discoveryIssuer);
159
+ uri = endpoints.jwks;
160
+ }
161
+ if (!uri) {
162
+ throw new OAuthError(
163
+ `${discoveryIssuer} published no jwks_uri. Give the verifier one directly.`,
164
+ "no_jwks"
165
+ );
166
+ }
167
+ keys = jose.createRemoteJWKSet(new URL(uri));
168
+ return keys;
169
+ }
170
+ const checkProof = async (claims, token, request) => {
171
+ const jose = await loadJose();
172
+ const { boundKeyOf, thumbprintOf } = await import("./dpop.mjs");
173
+ const bound = boundKeyOf(claims);
174
+ if (!bound) {
175
+ throw new TokenError(
176
+ "This token is not bound to a key, and this service requires binding.",
177
+ "token_not_bound"
178
+ );
179
+ }
180
+ const proof = request.headers.get("dpop");
181
+ if (!proof) throw new TokenError("The request carried no DPoP proof.", "missing_dpop_proof");
182
+ let payload;
183
+ let header;
184
+ try {
185
+ const result = await jose.jwtVerify(proof, jose.EmbeddedJWK, { typ: "dpop+jwt" });
186
+ payload = result.payload;
187
+ header = result.protectedHeader;
188
+ } catch (cause) {
189
+ throw new TokenError(
190
+ `The DPoP proof did not verify: ${cause instanceof Error ? cause.message : String(cause)}`,
191
+ "invalid_dpop_proof"
192
+ );
193
+ }
194
+ const presented = await thumbprintOf(header.jwk);
195
+ if (presented !== bound) {
196
+ throw new TokenError(
197
+ "The DPoP proof was signed with a different key from the one this token is bound to.",
198
+ "dpop_key_mismatch"
199
+ );
200
+ }
201
+ const url = new URL(request.url);
202
+ url.search = "";
203
+ url.hash = "";
204
+ if (payload.htm !== request.method.toUpperCase()) {
205
+ throw new TokenError("The DPoP proof was made for a different method.", "invalid_dpop_proof");
206
+ }
207
+ if (payload.htu !== url.toString()) {
208
+ throw new TokenError("The DPoP proof was made for a different URL.", "invalid_dpop_proof");
209
+ }
210
+ if (typeof payload.ath === "string") {
211
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token));
212
+ let binary = "";
213
+ for (const byte of new Uint8Array(digest)) binary += String.fromCharCode(byte);
214
+ const expected = btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
215
+ if (payload.ath !== expected) {
216
+ throw new TokenError("The DPoP proof was made for a different token.", "invalid_dpop_proof");
217
+ }
218
+ }
219
+ const age = Math.abs(Date.now() / 1e3 - payload.iat);
220
+ if (!Number.isFinite(age) || age > (options.dpopProofAgeSec ?? 10)) {
221
+ throw new TokenError("The DPoP proof is too old to accept.", "invalid_dpop_proof");
222
+ }
223
+ };
224
+ const verify = async (token, request) => {
225
+ if (!token) throw new TokenError("No token to verify.", "no_token");
226
+ const jose = await loadJose();
227
+ let payload;
228
+ try {
229
+ ({ payload } = await jose.jwtVerify(token, await keySet(), {
230
+ // jose takes a list and accepts any of them, which is what a provider naming
231
+ // itself two ways needs.
232
+ issuer: issuers,
233
+ ...options.audience === false ? {} : { audience: options.audience },
234
+ algorithms,
235
+ clockTolerance: options.clockToleranceSec ?? 5
236
+ }));
237
+ } catch (cause) {
238
+ throw new TokenError(
239
+ `The token was not accepted: ${cause instanceof Error ? cause.message : String(cause)}`
240
+ );
241
+ }
242
+ if (options.authorizedParty !== void 0) {
243
+ const allowed = Array.isArray(options.authorizedParty) ? options.authorizedParty : [options.authorizedParty];
244
+ const issuedTo = payload.azp ?? payload.client_id;
245
+ if (typeof issuedTo !== "string" || !allowed.includes(issuedTo)) {
246
+ throw new TokenError("The token was issued to a different client.", "invalid_azp");
247
+ }
248
+ }
249
+ if (options.dpop) {
250
+ if (!request) {
251
+ throw new Error(
252
+ "[fluixi/oauth2] `dpop: true` needs the request to read its proof. Use `verify.fromRequest(request)` rather than verifying a bare token."
253
+ );
254
+ }
255
+ await checkProof(payload, token, request);
256
+ }
257
+ if (options.require) {
258
+ const verdict = options.require(payload);
259
+ if (verdict !== true) {
260
+ throw new TokenError(
261
+ typeof verdict === "string" ? verdict : "The token did not meet this service's requirements.",
262
+ "insufficient_claims"
263
+ );
264
+ }
265
+ }
266
+ return payload;
267
+ };
268
+ const verifier = verify;
269
+ verifier.bearerOf = bearerOf;
270
+ verifier.fromRequest = async (request) => {
271
+ const token = verifier.bearerOf(request);
272
+ if (!token) {
273
+ throw new TokenError("The request carried no bearer token.", "no_token");
274
+ }
275
+ return verify(token, request);
276
+ };
277
+ return verifier;
278
+ }
279
+ function createTokenIntrospector(options) {
280
+ const issuers = (Array.isArray(options.issuer) ? options.issuer : [options.issuer]).filter(Boolean);
281
+ if (!issuers.length) {
282
+ throw new Error("[fluixi/oauth2] createTokenIntrospector needs an issuer.");
283
+ }
284
+ const discoveryIssuer = issuers[0];
285
+ const auth = {
286
+ clientId: options.clientId,
287
+ method: options.clientAuthMethod,
288
+ clientSecret: options.clientSecret,
289
+ privateKey: options.privateKey,
290
+ keyId: options.keyId,
291
+ assertionAlgorithm: options.assertionAlgorithm
292
+ };
293
+ if (resolveMethod(auth) === "none") {
294
+ throw new Error(
295
+ "[fluixi/oauth2] createTokenIntrospector needs credentials: a secret, or private_key_jwt with a key."
296
+ );
297
+ }
298
+ assertUsable(auth, "createTokenIntrospector");
299
+ if (options.audience === void 0) {
300
+ throw new Error(
301
+ "[fluixi/oauth2] createTokenIntrospector needs an audience, or `audience: false` to say this service accepts a token minted for any client of the issuer."
302
+ );
303
+ }
304
+ const ttl = options.cacheMs ?? 0;
305
+ const cache = /* @__PURE__ */ new Map();
306
+ let endpoint = options.introspectionEndpoint ?? null;
307
+ async function resolveEndpoint() {
308
+ if (endpoint) return endpoint;
309
+ const endpoints = await discover(discoveryIssuer);
310
+ if (!endpoints.introspection) {
311
+ throw new OAuthError(
312
+ `${discoveryIssuer} published no introspection_endpoint. Give the introspector one directly, or verify JWTs with createTokenVerifier.`,
313
+ "no_introspection"
314
+ );
315
+ }
316
+ endpoint = endpoints.introspection;
317
+ return endpoint;
318
+ }
319
+ const introspect = async (token) => {
320
+ if (!token) throw new TokenError("No token to verify.", "no_token");
321
+ const cached = cache.get(token);
322
+ if (cached && cached.until > Date.now()) return cached.claims;
323
+ const url = await resolveEndpoint();
324
+ const headers = {
325
+ "content-type": "application/x-www-form-urlencoded",
326
+ accept: "application/json"
327
+ };
328
+ const form = new URLSearchParams({ token, token_type_hint: "access_token" });
329
+ await applyClientAuth(auth, url, headers, form);
330
+ const response = await fetch(url, { method: "POST", headers, body: form.toString() });
331
+ if (!response.ok) {
332
+ const method = resolveMethod(auth);
333
+ const check = method === "private_key_jwt" ? `Check clientId, and that the provider holds the public half of this key${auth.keyId ? ` under kid ${auth.keyId}` : ""}. A key registered to a different client than clientId is refused this way.` : "Check clientId and clientSecret.";
334
+ const said = await response.text().catch(() => "");
335
+ throw new OAuthError(
336
+ `The introspection endpoint refused this service: ${response.status}. ${check}${said ? ` It said: ${said}` : ""}`,
337
+ "introspection_failed"
338
+ );
339
+ }
340
+ const body = await response.json();
341
+ if (body.active !== true) {
342
+ throw new TokenError(
343
+ "The provider reports this token is not active. If it was just issued, check that this client is in the token audience: some providers refuse to introspect a token minted for someone else and say only this.",
344
+ "inactive_token"
345
+ );
346
+ }
347
+ if (typeof body.iss === "string" && !issuers.includes(body.iss)) {
348
+ throw new TokenError("The token was issued by a different issuer.", "invalid_issuer");
349
+ }
350
+ if (options.audience !== false && body.aud !== void 0) {
351
+ const wanted = Array.isArray(options.audience) ? options.audience : [options.audience];
352
+ const got = Array.isArray(body.aud) ? body.aud : [body.aud];
353
+ if (!got.some((a) => wanted.includes(a))) {
354
+ throw new TokenError("The token was minted for a different audience.", "invalid_audience");
355
+ }
356
+ }
357
+ if (options.authorizedParty !== void 0) {
358
+ const allowed = Array.isArray(options.authorizedParty) ? options.authorizedParty : [options.authorizedParty];
359
+ const issuedTo = body.client_id ?? body.azp;
360
+ if (!issuedTo || !allowed.includes(issuedTo)) {
361
+ throw new TokenError("The token was issued to a different client.", "invalid_azp");
362
+ }
363
+ }
364
+ if (options.require) {
365
+ const verdict = options.require(body);
366
+ if (verdict !== true) {
367
+ throw new TokenError(
368
+ typeof verdict === "string" ? verdict : "The token did not meet this service's requirements.",
369
+ "insufficient_claims"
370
+ );
371
+ }
372
+ }
373
+ if (ttl > 0) {
374
+ if (cache.size > 500) {
375
+ const now = Date.now();
376
+ for (const [key, entry] of cache) if (entry.until <= now) cache.delete(key);
377
+ if (cache.size > 500) cache.delete(cache.keys().next().value);
378
+ }
379
+ cache.set(token, { claims: body, until: Date.now() + ttl });
380
+ }
381
+ return body;
382
+ };
383
+ const verifier = introspect;
384
+ verifier.bearerOf = bearerOf;
385
+ verifier.fromRequest = async (request) => {
386
+ const token = bearerOf(request);
387
+ if (!token) throw new TokenError("The request carried no bearer token.", "no_token");
388
+ return introspect(token);
389
+ };
390
+ return verifier;
391
+ }
392
+
393
+ export {
394
+ TokenError,
395
+ createTokenVerifier,
396
+ createTokenIntrospector,
397
+ createApiGuard
398
+ };