@fluixi/oauth2 1.0.0-alpha.107 → 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-RHLXMWQ2.mjs +0 -3545
  54. package/dist/chunk-NRB7JOZV.mjs +0 -15
  55. package/dist/chunk-WE2RTKJY.mjs +0 -10
  56. package/dist/chunk-ZIX4ITGP.mjs +0 -108
  57. package/dist/dpop-UCBLIUQC.mjs +0 -100
  58. package/dist/dpop-W2ACBDEM.mjs +0 -22
  59. /package/dist/{chunk-OGSFNTKA.mjs → chunk-AXPSPTNP.mjs} +0 -0
@@ -0,0 +1,189 @@
1
+ import {
2
+ rolesFrom
3
+ } from "./chunk-KVW2S6VY.mjs";
4
+
5
+ // src/presets.ts
6
+ var trim = (url) => url.replace(/\/+$/, "");
7
+ var presets = {
8
+ /**
9
+ * Any OIDC provider publishing a discovery document.
10
+ *
11
+ * The agnostic path, and the one to reach for first. A provider not listed below almost
12
+ * certainly works through this.
13
+ */
14
+ oidc(options) {
15
+ return {
16
+ label: options.issuer,
17
+ client: { issuer: trim(options.issuer), scopes: options.scopes },
18
+ roles: options.roles ?? rolesFrom.scope,
19
+ verifier: (clientId) => ({
20
+ issuer: trim(options.issuer),
21
+ audience: options.audience ?? clientId,
22
+ ...options.audience === false ? { authorizedParty: clientId } : {}
23
+ }),
24
+ constraints: []
25
+ };
26
+ },
27
+ /**
28
+ * A plain OAuth2 server with no discovery document.
29
+ *
30
+ * Every endpoint is given, because there is nothing to ask. Token verification needs an
31
+ * issuer regardless, since a verifier will not accept a token without one.
32
+ */
33
+ oauth2(options) {
34
+ return {
35
+ label: options.issuer,
36
+ client: { endpoints: options.endpoints, scopes: options.scopes },
37
+ roles: options.roles ?? rolesFrom.scope,
38
+ verifier: (clientId) => ({
39
+ issuer: trim(options.issuer),
40
+ audience: options.audience ?? clientId,
41
+ ...options.audience === false ? { authorizedParty: clientId } : {}
42
+ }),
43
+ constraints: ["Publishes no discovery document, so every endpoint is configured by hand."]
44
+ };
45
+ },
46
+ /** Keycloak. A realm is its own issuer. */
47
+ keycloak(options) {
48
+ const issuer = `${trim(options.baseUrl)}/realms/${options.realm}`;
49
+ return {
50
+ label: "Keycloak",
51
+ client: {
52
+ issuer,
53
+ scopes: options.scopes ?? ["openid", "profile", "email"]
54
+ },
55
+ roles: rolesFrom.keycloakRealm,
56
+ // No `aud` on an access token until an audience mapper is configured, and the client is
57
+ // named in `azp` instead. So the check moves to `authorizedParty` rather than being
58
+ // dropped: `audience: false` alone would accept a token minted for any client of the
59
+ // realm, which is the check being skipped.
60
+ verifier: (clientId) => ({ issuer, audience: false, authorizedParty: clientId }),
61
+ constraints: [
62
+ "Puts no `aud` on an access token until a dedicated audience mapper is configured. Configure one and switch the verifier to `audience: clientId`.",
63
+ "Revokes the whole session when an authorization code is replayed, so a replay test has to run last."
64
+ ]
65
+ };
66
+ },
67
+ /**
68
+ * Auth0.
69
+ *
70
+ * `audience` is the field that decides what kind of token comes back. Without it Auth0
71
+ * issues an opaque token for its own userinfo endpoint and the JWT checks have nothing to
72
+ * work with.
73
+ */
74
+ auth0(options) {
75
+ const issuer = `https://${options.domain.replace(/^https?:\/\//, "").replace(/\/+$/, "")}/`;
76
+ return {
77
+ label: "Auth0",
78
+ client: {
79
+ issuer,
80
+ scopes: options.scopes ?? ["openid", "profile", "email", "offline_access"],
81
+ ...options.audience ? { extraParams: { audience: options.audience } } : {}
82
+ },
83
+ roles: options.rolesClaim ? rolesFrom.namespaced(options.rolesClaim) : rolesFrom.scope,
84
+ verifier: (clientId) => ({
85
+ issuer,
86
+ // The API identifier is the audience of an access token. Without one the token is
87
+ // opaque and there is nothing for a verifier to check.
88
+ audience: options.audience ?? false,
89
+ ...options.audience ? {} : { authorizedParty: clientId }
90
+ }),
91
+ constraints: [
92
+ "Issues an opaque access token unless `audience` names an API, so token verification needs it.",
93
+ "A refresh token needs three things together: `offline_access` in the scopes, an audience whose API has Allow Offline Access on, and Refresh Token Rotation enabled on the application. Any one missing and the scope is ignored silently.",
94
+ "Has no roles claim of its own. An action must add a namespaced one, and Auth0 drops a custom claim that is not a URI.",
95
+ "The issuer carries a trailing slash. A verifier pinned without it rejects every token."
96
+ ]
97
+ };
98
+ },
99
+ /**
100
+ * Okta.
101
+ *
102
+ * Two authorization servers that are not interchangeable: a custom one per application,
103
+ * and the org itself for Okta's own management API.
104
+ */
105
+ okta(options) {
106
+ const host = `https://${options.domain.replace(/^https?:\/\//, "").replace(/\/+$/, "")}`;
107
+ const server = options.authorizationServer === void 0 ? "default" : options.authorizationServer;
108
+ const issuer = server === null ? host : `${host}/oauth2/${server}`;
109
+ return {
110
+ label: "Okta",
111
+ client: {
112
+ issuer,
113
+ scopes: options.scopes ?? ["openid", "profile", "email", "offline_access"],
114
+ dpop: options.dpop ?? true
115
+ },
116
+ roles: rolesFrom.groups,
117
+ verifier: (clientId) => ({
118
+ issuer,
119
+ // An access token from a custom server is minted for that server's audience, named in
120
+ // the console and `api://default` by default. It does not carry the client id.
121
+ audience: false,
122
+ authorizedParty: clientId
123
+ }),
124
+ constraints: [
125
+ "Two authorization servers: /oauth2/<name> for an application, the bare domain for the management API. They are not interchangeable.",
126
+ "Turns DPoP on by default for a new application, and an integrator org will not let you untick it.",
127
+ "Binds the refresh token to the DPoP key as well as the access token, so a refresh must be proved with the key that obtained it.",
128
+ "A public SPA cannot introspect at all. An API Services client with `private_key_jwt` has to ask instead.",
129
+ "Client credentials against the org server must use `private_key_jwt`, whatever the application is set to."
130
+ ]
131
+ };
132
+ },
133
+ /**
134
+ * Google.
135
+ *
136
+ * Refuses a public client outright, so server mode is the only option: the token endpoint
137
+ * checks for a client secret before it looks at PKCE.
138
+ */
139
+ google(options = {}) {
140
+ return {
141
+ label: "Google",
142
+ client: {
143
+ issuer: "https://accounts.google.com",
144
+ scopes: options.scopes ?? ["openid", "profile", "email"],
145
+ ...options.hostedDomain ? { extraParams: { hd: options.hostedDomain } } : {}
146
+ },
147
+ roles: rolesFrom.scope,
148
+ verifier: (clientId) => ({
149
+ // Names itself two ways, and a service pinned to one rejects tokens carrying the
150
+ // other. Discovery uses the first.
151
+ issuer: ["https://accounts.google.com", "accounts.google.com"],
152
+ audience: clientId
153
+ }),
154
+ constraints: [
155
+ "Refuses a public client: the token endpoint reports `client_secret is missing` before checking PKCE, so browser mode cannot work.",
156
+ "Publishes its issuer both with and without a scheme, so a verifier needs both spellings.",
157
+ "Issues a refresh token only on the first consent unless `prompt=consent` and `access_type=offline` are sent."
158
+ ]
159
+ };
160
+ },
161
+ /**
162
+ * Dex.
163
+ *
164
+ * Sends no CORS headers, on discovery or the token endpoint, so a browser cannot talk to it
165
+ * at all. Server mode only, and giving endpoints explicitly does not help: the token request
166
+ * is blocked too.
167
+ */
168
+ dex(options) {
169
+ const issuer = trim(options.baseUrl);
170
+ return {
171
+ label: "Dex",
172
+ client: {
173
+ issuer,
174
+ scopes: options.scopes ?? ["openid", "profile", "email", "offline_access"]
175
+ },
176
+ roles: rolesFrom.groups,
177
+ verifier: (clientId) => ({ issuer, audience: clientId }),
178
+ constraints: [
179
+ "Sends no CORS headers on discovery or the token endpoint, so browser mode cannot work. Naming the endpoints explicitly only moves the failure to the token request.",
180
+ "Has no admin interface. Users are static entries in its config file, and a password is a bcrypt hash.",
181
+ "Publishes no revocation endpoint."
182
+ ]
183
+ };
184
+ }
185
+ };
186
+
187
+ export {
188
+ presets
189
+ };
@@ -0,0 +1,80 @@
1
+ import {
2
+ createTokenVerifier
3
+ } from "./chunk-4OHJTTX7.mjs";
4
+
5
+ // src/backchannel.ts
6
+ var LOGOUT_EVENT = "http://schemas.openid.net/event/backchannel-logout";
7
+ function memoryLogouts(ttlMs = 14 * 24 * 36e5) {
8
+ const sids = /* @__PURE__ */ new Map();
9
+ const subs = /* @__PURE__ */ new Map();
10
+ const prune = (now) => {
11
+ for (const map of [sids, subs]) for (const [key, at] of map) if (now - at > ttlMs) map.delete(key);
12
+ };
13
+ return {
14
+ add(entry) {
15
+ prune(Date.now());
16
+ if (entry.sid) sids.set(entry.sid, entry.at);
17
+ else if (entry.sub) subs.set(entry.sub, Math.max(entry.at, subs.get(entry.sub) ?? 0));
18
+ },
19
+ ended(session) {
20
+ if (session.sid && sids.has(session.sid)) return true;
21
+ const all = session.sub ? subs.get(session.sub) : void 0;
22
+ return all !== void 0 && session.since <= all;
23
+ }
24
+ };
25
+ }
26
+ function idTokenClaims(idToken) {
27
+ if (!idToken) return {};
28
+ try {
29
+ const part = idToken.split(".")[1] ?? "";
30
+ const json = atob(part.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(part.length / 4) * 4, "="));
31
+ const claims = JSON.parse(json);
32
+ return {
33
+ sid: typeof claims.sid === "string" ? claims.sid : void 0,
34
+ sub: typeof claims.sub === "string" ? claims.sub : void 0,
35
+ iat: typeof claims.iat === "number" ? claims.iat : void 0
36
+ };
37
+ } catch {
38
+ return {};
39
+ }
40
+ }
41
+ function headerOf(token) {
42
+ try {
43
+ const part = token.split(".")[0] ?? "";
44
+ return JSON.parse(atob(part.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(part.length / 4) * 4, "=")));
45
+ } catch {
46
+ return {};
47
+ }
48
+ }
49
+ function logoutTokenVerifier(options) {
50
+ const verify = createTokenVerifier({
51
+ issuer: options.issuer,
52
+ audience: options.clientId,
53
+ jwksUri: options.jwksUri,
54
+ jwks: options.jwks,
55
+ require: (claims) => {
56
+ const events = claims.events;
57
+ if (!events || typeof events !== "object" || !(LOGOUT_EVENT in events)) return "no logout event";
58
+ if ("nonce" in claims) return "a logout token has no nonce";
59
+ if (typeof claims.sid !== "string" && typeof claims.sub !== "string") return "names no session and no subject";
60
+ return true;
61
+ }
62
+ });
63
+ return async (token) => {
64
+ const typ = headerOf(token).typ;
65
+ if (typ !== void 0 && typ !== "logout+jwt") throw new Error("not a logout token");
66
+ const claims = await verify(token);
67
+ return {
68
+ sid: typeof claims.sid === "string" ? claims.sid : void 0,
69
+ sub: typeof claims.sub === "string" ? claims.sub : void 0,
70
+ at: (typeof claims.iat === "number" ? claims.iat : Math.floor(Date.now() / 1e3)) * 1e3
71
+ };
72
+ };
73
+ }
74
+
75
+ export {
76
+ LOGOUT_EVENT,
77
+ memoryLogouts,
78
+ idTokenClaims,
79
+ logoutTokenVerifier
80
+ };
@@ -0,0 +1,36 @@
1
+ // src/roles.ts
2
+ var rolesFrom = {
3
+ /** Keycloak, realm roles. Where it puts them unless a client mapper is configured. */
4
+ keycloakRealm: (claims) => {
5
+ const realm = claims.realm_access;
6
+ return realm?.roles ?? [];
7
+ },
8
+ /** Keycloak, roles scoped to one client rather than the realm. */
9
+ keycloakClient: (clientId) => (claims) => {
10
+ const all = claims.resource_access;
11
+ return all?.[clientId]?.roles ?? [];
12
+ },
13
+ /** Okta, and anything else using a groups claim. Needs a groups claim on the token. */
14
+ groups: (claims) => Array.isArray(claims.groups) ? claims.groups : [],
15
+ /** Cognito, which namespaces the claim. */
16
+ cognito: (claims) => {
17
+ const groups = claims["cognito:groups"];
18
+ return Array.isArray(groups) ? groups : [];
19
+ },
20
+ /**
21
+ * Auth0, which requires a namespaced custom claim added by an action.
22
+ *
23
+ * `rolesFrom.namespaced('https://acme.com/roles')`. Auth0 silently drops a custom claim
24
+ * that is not a URI, so an empty list here usually means the namespace, not the action.
25
+ */
26
+ namespaced: (claim) => (claims) => {
27
+ const value = claims[claim];
28
+ return Array.isArray(value) ? value : [];
29
+ },
30
+ /** The `scope` claim read as a role list, for a provider issuing no roles at all. */
31
+ scope: (claims) => typeof claims.scope === "string" ? claims.scope.split(" ") : []
32
+ };
33
+
34
+ export {
35
+ rolesFrom
36
+ };
@@ -0,0 +1,9 @@
1
+ // src/tokens.ts
2
+ import { injectionToken } from "@fluixi/di";
3
+ var AuthServiceToken = injectionToken("AuthService");
4
+ var AuthClientToken = injectionToken("AuthClient");
5
+
6
+ export {
7
+ AuthServiceToken,
8
+ AuthClientToken
9
+ };
@@ -0,0 +1,67 @@
1
+ // src/pkce.ts
2
+ function base64url(bytes) {
3
+ let binary = "";
4
+ for (const byte of bytes) binary += String.fromCharCode(byte);
5
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
6
+ }
7
+ function randomBytes(length) {
8
+ const bytes = new Uint8Array(length);
9
+ crypto.getRandomValues(bytes);
10
+ return bytes;
11
+ }
12
+ function createVerifier() {
13
+ return base64url(randomBytes(32));
14
+ }
15
+ function createStateValue() {
16
+ return base64url(randomBytes(16));
17
+ }
18
+ async function createChallenge(verifier) {
19
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
20
+ return base64url(new Uint8Array(digest));
21
+ }
22
+ async function createPkcePair() {
23
+ const verifier = createVerifier();
24
+ return { verifier, challenge: await createChallenge(verifier) };
25
+ }
26
+ function timingSafeEqual(a, b) {
27
+ if (a.length !== b.length) return false;
28
+ let diff = 0;
29
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
30
+ return diff === 0;
31
+ }
32
+ function expiryFrom(expiresIn, now = Date.now()) {
33
+ const seconds = typeof expiresIn === "number" ? expiresIn : Number(expiresIn);
34
+ return Number.isFinite(seconds) && seconds > 0 ? now + seconds * 1e3 : void 0;
35
+ }
36
+ function claimsOf(token) {
37
+ const parts = token.split(".");
38
+ if (parts.length < 2) return null;
39
+ try {
40
+ const payload = parts[1].replace(/-/g, "+").replace(/_/g, "/");
41
+ return JSON.parse(atob(payload.padEnd(Math.ceil(payload.length / 4) * 4, "=")));
42
+ } catch {
43
+ return null;
44
+ }
45
+ }
46
+ function expiryFromJwt(token) {
47
+ const parts = token.split(".");
48
+ if (parts.length < 2) return null;
49
+ try {
50
+ const payload = parts[1].replace(/-/g, "+").replace(/_/g, "/");
51
+ const json = JSON.parse(atob(payload.padEnd(Math.ceil(payload.length / 4) * 4, "=")));
52
+ return typeof json.exp === "number" ? json.exp * 1e3 : null;
53
+ } catch {
54
+ return null;
55
+ }
56
+ }
57
+
58
+ export {
59
+ createVerifier,
60
+ createStateValue,
61
+ createChallenge,
62
+ createPkcePair,
63
+ timingSafeEqual,
64
+ expiryFrom,
65
+ claimsOf,
66
+ expiryFromJwt
67
+ };
@@ -0,0 +1,77 @@
1
+ import {
2
+ OAuthError
3
+ } from "./chunk-AXPSPTNP.mjs";
4
+
5
+ // src/client-auth.ts
6
+ var CANONICAL = {
7
+ basic: "client_secret_basic",
8
+ body: "client_secret_post",
9
+ client_secret_basic: "client_secret_basic",
10
+ client_secret_post: "client_secret_post",
11
+ private_key_jwt: "private_key_jwt",
12
+ none: "none"
13
+ };
14
+ function resolveMethod(auth) {
15
+ if (auth.method) return CANONICAL[auth.method] ?? "client_secret_basic";
16
+ if (auth.privateKey) return "private_key_jwt";
17
+ return auth.clientSecret ? "client_secret_basic" : "none";
18
+ }
19
+ function assertUsable(auth, who) {
20
+ if (!auth.clientId) throw new Error(`[fluixi/oauth2] ${who} needs a clientId.`);
21
+ const method = resolveMethod(auth);
22
+ if (method === "private_key_jwt" && !auth.privateKey) {
23
+ throw new Error(
24
+ `[fluixi/oauth2] ${who}: private_key_jwt needs \`privateKey\`, the JWK whose public half the provider holds.`
25
+ );
26
+ }
27
+ if ((method === "client_secret_basic" || method === "client_secret_post") && !auth.clientSecret) {
28
+ throw new Error(
29
+ `[fluixi/oauth2] ${who}: ${method} needs a \`clientSecret\`. A public client should use \`method: 'none'\`, which PKCE is what protects.`
30
+ );
31
+ }
32
+ return method;
33
+ }
34
+ async function loadJose() {
35
+ try {
36
+ return await import("./browser-FDUOEUM2.mjs");
37
+ } catch {
38
+ throw new OAuthError(
39
+ "private_key_jwt needs `jose`. Install it: npm i jose. It is an optional peer, so a client using a secret does not carry it.",
40
+ "jose_missing"
41
+ );
42
+ }
43
+ }
44
+ async function signAssertion(auth, endpoint) {
45
+ const jose = await loadJose();
46
+ const alg = auth.assertionAlgorithm ?? "RS256";
47
+ const key = await jose.importJWK(auth.privateKey, alg);
48
+ const kid = auth.keyId ?? auth.privateKey.kid;
49
+ return new jose.SignJWT({}).setProtectedHeader(kid ? { alg, kid } : { alg }).setIssuer(auth.clientId).setSubject(auth.clientId).setAudience(endpoint).setJti(crypto.randomUUID()).setIssuedAt().setExpirationTime("1m").sign(key);
50
+ }
51
+ async function applyClientAuth(auth, endpoint, headers, form) {
52
+ switch (resolveMethod(auth)) {
53
+ case "client_secret_basic": {
54
+ const pair = `${encodeURIComponent(auth.clientId)}:${encodeURIComponent(auth.clientSecret)}`;
55
+ headers.authorization = `Basic ${btoa(pair)}`;
56
+ break;
57
+ }
58
+ case "client_secret_post":
59
+ form.set("client_id", auth.clientId);
60
+ form.set("client_secret", auth.clientSecret);
61
+ break;
62
+ case "private_key_jwt":
63
+ form.set("client_id", auth.clientId);
64
+ form.set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
65
+ form.set("client_assertion", await signAssertion(auth, endpoint));
66
+ break;
67
+ case "none":
68
+ form.set("client_id", auth.clientId);
69
+ break;
70
+ }
71
+ }
72
+
73
+ export {
74
+ resolveMethod,
75
+ assertUsable,
76
+ applyClientAuth
77
+ };
@@ -0,0 +1,26 @@
1
+ // src/return-to.ts
2
+ function safeReturnTo(candidate, options = {}) {
3
+ const fallback = options.fallback ?? "/";
4
+ if (!candidate || typeof candidate !== "string") return fallback;
5
+ const value = candidate.trim();
6
+ if (!value) return fallback;
7
+ if (/[\u0000-\u001f\u007f]/.test(value)) return fallback;
8
+ if (/^[/\\]{2}/.test(value)) return fallback;
9
+ if (value.startsWith("/")) return value;
10
+ const here = options.origin ?? (typeof location === "undefined" ? void 0 : location.origin);
11
+ const allowed = [here, ...options.allowedOrigins ?? []].filter(Boolean);
12
+ if (!allowed.length) return fallback;
13
+ let url;
14
+ try {
15
+ url = new URL(value);
16
+ } catch {
17
+ return fallback;
18
+ }
19
+ if (!allowed.includes(url.origin)) return fallback;
20
+ if (url.protocol !== "http:" && url.protocol !== "https:") return fallback;
21
+ return url.toString();
22
+ }
23
+
24
+ export {
25
+ safeReturnTo
26
+ };
@@ -0,0 +1,91 @@
1
+ import {
2
+ createDpopKey
3
+ } from "./chunk-27BGFJIY.mjs";
4
+
5
+ // src/dpop-store.ts
6
+ var DB = "fluixi-oauth2-dpop";
7
+ var STORE = "keys";
8
+ function available() {
9
+ return typeof indexedDB !== "undefined";
10
+ }
11
+ function open() {
12
+ return new Promise((resolve, reject) => {
13
+ const request = indexedDB.open(DB, 1);
14
+ request.onupgradeneeded = () => {
15
+ const db = request.result;
16
+ if (!db.objectStoreNames.contains(STORE)) db.createObjectStore(STORE);
17
+ };
18
+ request.onsuccess = () => resolve(request.result);
19
+ request.onerror = () => reject(request.error ?? new Error("indexedDB.open failed"));
20
+ });
21
+ }
22
+ function act(mode, run) {
23
+ return open().then(
24
+ (db) => new Promise((resolve, reject) => {
25
+ const tx = db.transaction(STORE, mode);
26
+ const request = run(tx.objectStore(STORE));
27
+ request.onsuccess = () => resolve(request.result);
28
+ request.onerror = () => reject(request.error ?? new Error("DPoP key request failed"));
29
+ tx.oncomplete = () => db.close();
30
+ })
31
+ );
32
+ }
33
+ function usable(value) {
34
+ const stored = value;
35
+ return !!stored && typeof stored.thumbprint === "string" && typeof stored.alg === "string" && !!stored.publicJwk && // A CryptoKey survives the round trip as a CryptoKey. Anything else means the record was
36
+ // written by something other than this, and binding to it would fail at the provider.
37
+ typeof stored.privateKey?.type === "string";
38
+ }
39
+ async function keyFor(clientKey, alg = "ES256", onEphemeral) {
40
+ if (!available()) {
41
+ onEphemeral?.("This environment has no IndexedDB, so the key lasts only as long as this document.");
42
+ return createDpopKey(alg);
43
+ }
44
+ try {
45
+ const found = await act("readonly", (store) => store.get(clientKey));
46
+ if (usable(found) && found.alg === alg) {
47
+ return {
48
+ privateKey: found.privateKey,
49
+ publicJwk: found.publicJwk,
50
+ thumbprint: found.thumbprint,
51
+ alg: found.alg
52
+ };
53
+ }
54
+ } catch (cause) {
55
+ onEphemeral?.(
56
+ `The stored DPoP key could not be read (${cause instanceof Error ? cause.message : String(cause)}), so a new one was made.`
57
+ );
58
+ }
59
+ const key = await createDpopKey(alg);
60
+ try {
61
+ await act(
62
+ "readwrite",
63
+ (store) => store.put(
64
+ {
65
+ privateKey: key.privateKey,
66
+ publicJwk: key.publicJwk,
67
+ thumbprint: key.thumbprint,
68
+ alg: key.alg
69
+ },
70
+ clientKey
71
+ )
72
+ );
73
+ } catch (cause) {
74
+ onEphemeral?.(
75
+ `The DPoP key could not be stored (${cause instanceof Error ? cause.message : String(cause)}), so a refresh after the next navigation will be refused.`
76
+ );
77
+ }
78
+ return key;
79
+ }
80
+ async function forgetKey(clientKey) {
81
+ if (!available()) return;
82
+ try {
83
+ await act("readwrite", (store) => store.delete(clientKey));
84
+ } catch {
85
+ }
86
+ }
87
+
88
+ export {
89
+ keyFor,
90
+ forgetKey
91
+ };
@@ -1,82 +1,10 @@
1
+ import {
2
+ applyClientAuth,
3
+ assertUsable,
4
+ resolveMethod
5
+ } from "./chunk-SJOBQPG6.mjs";
6
+ import "./chunk-AXPSPTNP.mjs";
1
7
  import "./chunk-7P6ASYW6.mjs";
2
-
3
- // src/types.ts
4
- var OAuthError = class extends Error {
5
- constructor(message, code, description) {
6
- super(message);
7
- this.code = code;
8
- this.description = description;
9
- this.name = "OAuthError";
10
- }
11
- };
12
-
13
- // src/client-auth.ts
14
- var CANONICAL = {
15
- basic: "client_secret_basic",
16
- body: "client_secret_post",
17
- client_secret_basic: "client_secret_basic",
18
- client_secret_post: "client_secret_post",
19
- private_key_jwt: "private_key_jwt",
20
- none: "none"
21
- };
22
- function resolveMethod(auth) {
23
- if (auth.method) return CANONICAL[auth.method] ?? "client_secret_basic";
24
- if (auth.privateKey) return "private_key_jwt";
25
- return auth.clientSecret ? "client_secret_basic" : "none";
26
- }
27
- function assertUsable(auth, who) {
28
- if (!auth.clientId) throw new Error(`[fluixi/oauth2] ${who} needs a clientId.`);
29
- const method = resolveMethod(auth);
30
- if (method === "private_key_jwt" && !auth.privateKey) {
31
- throw new Error(
32
- `[fluixi/oauth2] ${who}: private_key_jwt needs \`privateKey\`, the JWK whose public half the provider holds.`
33
- );
34
- }
35
- if ((method === "client_secret_basic" || method === "client_secret_post") && !auth.clientSecret) {
36
- throw new Error(
37
- `[fluixi/oauth2] ${who}: ${method} needs a \`clientSecret\`. A public client should use \`method: 'none'\`, which PKCE is what protects.`
38
- );
39
- }
40
- return method;
41
- }
42
- async function loadJose() {
43
- try {
44
- return await import("./browser-FDUOEUM2.mjs");
45
- } catch {
46
- throw new OAuthError(
47
- "private_key_jwt needs `jose`. Install it: npm i jose. It is an optional peer, so a client using a secret does not carry it.",
48
- "jose_missing"
49
- );
50
- }
51
- }
52
- async function signAssertion(auth, endpoint) {
53
- const jose = await loadJose();
54
- const alg = auth.assertionAlgorithm ?? "RS256";
55
- const key = await jose.importJWK(auth.privateKey, alg);
56
- const kid = auth.keyId ?? auth.privateKey.kid;
57
- return new jose.SignJWT({}).setProtectedHeader(kid ? { alg, kid } : { alg }).setIssuer(auth.clientId).setSubject(auth.clientId).setAudience(endpoint).setJti(crypto.randomUUID()).setIssuedAt().setExpirationTime("1m").sign(key);
58
- }
59
- async function applyClientAuth(auth, endpoint, headers, form) {
60
- switch (resolveMethod(auth)) {
61
- case "client_secret_basic": {
62
- const pair = `${encodeURIComponent(auth.clientId)}:${encodeURIComponent(auth.clientSecret)}`;
63
- headers.authorization = `Basic ${btoa(pair)}`;
64
- break;
65
- }
66
- case "client_secret_post":
67
- form.set("client_id", auth.clientId);
68
- form.set("client_secret", auth.clientSecret);
69
- break;
70
- case "private_key_jwt":
71
- form.set("client_id", auth.clientId);
72
- form.set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
73
- form.set("client_assertion", await signAssertion(auth, endpoint));
74
- break;
75
- case "none":
76
- form.set("client_id", auth.clientId);
77
- break;
78
- }
79
- }
80
8
  export {
81
9
  applyClientAuth,
82
10
  assertUsable,