@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/module.mjs CHANGED
@@ -1,23 +1,8 @@
1
- // src/module.ts
2
- import { defineModule } from "@fluixi/start/app";
3
-
4
- // src/tokens.ts
5
- import { injectionToken } from "@fluixi/di";
6
- var AuthServiceToken = injectionToken("AuthService");
7
- var AuthClientToken = injectionToken("AuthClient");
8
-
9
- // src/module.ts
10
- function authModule(auth) {
11
- return defineModule({
12
- name: "oauth2",
13
- providers: [
14
- // One instance for every request on the server. It holds no per-visitor state there:
15
- // the signed-in user comes from request locals, which `sessionLocals` fills per request.
16
- { provide: AuthServiceToken, useValue: auth },
17
- { provide: AuthClientToken, useValue: auth.client }
18
- ]
19
- });
20
- }
1
+ import {
2
+ authModule
3
+ } from "./chunk-3EICMAF7.mjs";
4
+ import "./chunk-MHWZTXZZ.mjs";
5
+ import "./chunk-7P6ASYW6.mjs";
21
6
  export {
22
7
  authModule
23
8
  };
package/dist/pkce.mjs CHANGED
@@ -1,59 +1,14 @@
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
- }
1
+ import {
2
+ claimsOf,
3
+ createChallenge,
4
+ createPkcePair,
5
+ createStateValue,
6
+ createVerifier,
7
+ expiryFrom,
8
+ expiryFromJwt,
9
+ timingSafeEqual
10
+ } from "./chunk-QC2FFASM.mjs";
11
+ import "./chunk-7P6ASYW6.mjs";
57
12
  export {
58
13
  claimsOf,
59
14
  createChallenge,
package/dist/presets.mjs CHANGED
@@ -1,217 +1,8 @@
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
- // src/presets.ts
35
- var trim = (url) => url.replace(/\/+$/, "");
36
- var presets = {
37
- /**
38
- * Any OIDC provider publishing a discovery document.
39
- *
40
- * The agnostic path, and the one to reach for first. A provider not listed below almost
41
- * certainly works through this.
42
- */
43
- oidc(options) {
44
- return {
45
- label: options.issuer,
46
- client: { issuer: trim(options.issuer), scopes: options.scopes },
47
- roles: options.roles ?? rolesFrom.scope,
48
- verifier: (clientId) => ({
49
- issuer: trim(options.issuer),
50
- audience: options.audience ?? clientId,
51
- ...options.audience === false ? { authorizedParty: clientId } : {}
52
- }),
53
- constraints: []
54
- };
55
- },
56
- /**
57
- * A plain OAuth2 server with no discovery document.
58
- *
59
- * Every endpoint is given, because there is nothing to ask. Token verification needs an
60
- * issuer regardless, since a verifier will not accept a token without one.
61
- */
62
- oauth2(options) {
63
- return {
64
- label: options.issuer,
65
- client: { endpoints: options.endpoints, scopes: options.scopes },
66
- roles: options.roles ?? rolesFrom.scope,
67
- verifier: (clientId) => ({
68
- issuer: trim(options.issuer),
69
- audience: options.audience ?? clientId,
70
- ...options.audience === false ? { authorizedParty: clientId } : {}
71
- }),
72
- constraints: ["Publishes no discovery document, so every endpoint is configured by hand."]
73
- };
74
- },
75
- /** Keycloak. A realm is its own issuer. */
76
- keycloak(options) {
77
- const issuer = `${trim(options.baseUrl)}/realms/${options.realm}`;
78
- return {
79
- label: "Keycloak",
80
- client: {
81
- issuer,
82
- scopes: options.scopes ?? ["openid", "profile", "email"]
83
- },
84
- roles: rolesFrom.keycloakRealm,
85
- // No `aud` on an access token until an audience mapper is configured, and the client is
86
- // named in `azp` instead. So the check moves to `authorizedParty` rather than being
87
- // dropped: `audience: false` alone would accept a token minted for any client of the
88
- // realm, which is the check being skipped.
89
- verifier: (clientId) => ({ issuer, audience: false, authorizedParty: clientId }),
90
- constraints: [
91
- "Puts no `aud` on an access token until a dedicated audience mapper is configured. Configure one and switch the verifier to `audience: clientId`.",
92
- "Revokes the whole session when an authorization code is replayed, so a replay test has to run last."
93
- ]
94
- };
95
- },
96
- /**
97
- * Auth0.
98
- *
99
- * `audience` is the field that decides what kind of token comes back. Without it Auth0
100
- * issues an opaque token for its own userinfo endpoint and the JWT checks have nothing to
101
- * work with.
102
- */
103
- auth0(options) {
104
- const issuer = `https://${options.domain.replace(/^https?:\/\//, "").replace(/\/+$/, "")}/`;
105
- return {
106
- label: "Auth0",
107
- client: {
108
- issuer,
109
- scopes: options.scopes ?? ["openid", "profile", "email", "offline_access"],
110
- ...options.audience ? { extraParams: { audience: options.audience } } : {}
111
- },
112
- roles: options.rolesClaim ? rolesFrom.namespaced(options.rolesClaim) : rolesFrom.scope,
113
- verifier: (clientId) => ({
114
- issuer,
115
- // The API identifier is the audience of an access token. Without one the token is
116
- // opaque and there is nothing for a verifier to check.
117
- audience: options.audience ?? false,
118
- ...options.audience ? {} : { authorizedParty: clientId }
119
- }),
120
- constraints: [
121
- "Issues an opaque access token unless `audience` names an API, so token verification needs it.",
122
- "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.",
123
- "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.",
124
- "The issuer carries a trailing slash. A verifier pinned without it rejects every token."
125
- ]
126
- };
127
- },
128
- /**
129
- * Okta.
130
- *
131
- * Two authorization servers that are not interchangeable: a custom one per application,
132
- * and the org itself for Okta's own management API.
133
- */
134
- okta(options) {
135
- const host = `https://${options.domain.replace(/^https?:\/\//, "").replace(/\/+$/, "")}`;
136
- const server = options.authorizationServer === void 0 ? "default" : options.authorizationServer;
137
- const issuer = server === null ? host : `${host}/oauth2/${server}`;
138
- return {
139
- label: "Okta",
140
- client: {
141
- issuer,
142
- scopes: options.scopes ?? ["openid", "profile", "email", "offline_access"],
143
- dpop: options.dpop ?? true
144
- },
145
- roles: rolesFrom.groups,
146
- verifier: (clientId) => ({
147
- issuer,
148
- // An access token from a custom server is minted for that server's audience, named in
149
- // the console and `api://default` by default. It does not carry the client id.
150
- audience: false,
151
- authorizedParty: clientId
152
- }),
153
- constraints: [
154
- "Two authorization servers: /oauth2/<name> for an application, the bare domain for the management API. They are not interchangeable.",
155
- "Turns DPoP on by default for a new application, and an integrator org will not let you untick it.",
156
- "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.",
157
- "A public SPA cannot introspect at all. An API Services client with `private_key_jwt` has to ask instead.",
158
- "Client credentials against the org server must use `private_key_jwt`, whatever the application is set to."
159
- ]
160
- };
161
- },
162
- /**
163
- * Google.
164
- *
165
- * Refuses a public client outright, so server mode is the only option: the token endpoint
166
- * checks for a client secret before it looks at PKCE.
167
- */
168
- google(options = {}) {
169
- return {
170
- label: "Google",
171
- client: {
172
- issuer: "https://accounts.google.com",
173
- scopes: options.scopes ?? ["openid", "profile", "email"],
174
- ...options.hostedDomain ? { extraParams: { hd: options.hostedDomain } } : {}
175
- },
176
- roles: rolesFrom.scope,
177
- verifier: (clientId) => ({
178
- // Names itself two ways, and a service pinned to one rejects tokens carrying the
179
- // other. Discovery uses the first.
180
- issuer: ["https://accounts.google.com", "accounts.google.com"],
181
- audience: clientId
182
- }),
183
- constraints: [
184
- "Refuses a public client: the token endpoint reports `client_secret is missing` before checking PKCE, so browser mode cannot work.",
185
- "Publishes its issuer both with and without a scheme, so a verifier needs both spellings.",
186
- "Issues a refresh token only on the first consent unless `prompt=consent` and `access_type=offline` are sent."
187
- ]
188
- };
189
- },
190
- /**
191
- * Dex.
192
- *
193
- * Sends no CORS headers, on discovery or the token endpoint, so a browser cannot talk to it
194
- * at all. Server mode only, and giving endpoints explicitly does not help: the token request
195
- * is blocked too.
196
- */
197
- dex(options) {
198
- const issuer = trim(options.baseUrl);
199
- return {
200
- label: "Dex",
201
- client: {
202
- issuer,
203
- scopes: options.scopes ?? ["openid", "profile", "email", "offline_access"]
204
- },
205
- roles: rolesFrom.groups,
206
- verifier: (clientId) => ({ issuer, audience: clientId }),
207
- constraints: [
208
- "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.",
209
- "Has no admin interface. Users are static entries in its config file, and a password is a bcrypt hash.",
210
- "Publishes no revocation endpoint."
211
- ]
212
- };
213
- }
214
- };
1
+ import {
2
+ presets
3
+ } from "./chunk-GN5SERAQ.mjs";
4
+ import "./chunk-KVW2S6VY.mjs";
5
+ import "./chunk-7P6ASYW6.mjs";
215
6
  export {
216
7
  presets
217
8
  };
@@ -1,25 +1,7 @@
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
- }
1
+ import {
2
+ safeReturnTo
3
+ } from "./chunk-VCNXQCIH.mjs";
4
+ import "./chunk-7P6ASYW6.mjs";
23
5
  export {
24
6
  safeReturnTo
25
7
  };
package/dist/roles.mjs CHANGED
@@ -1,35 +1,7 @@
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
- };
1
+ import {
2
+ rolesFrom
3
+ } from "./chunk-KVW2S6VY.mjs";
4
+ import "./chunk-7P6ASYW6.mjs";
33
5
  export {
34
6
  rolesFrom
35
7
  };
@@ -1,110 +1,10 @@
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
- // src/types.ts
25
- var OAuthError = class extends Error {
26
- constructor(message, code, description) {
27
- super(message);
28
- this.code = code;
29
- this.description = description;
30
- this.name = "OAuthError";
31
- }
32
- };
33
-
34
- // src/server-client.ts
35
- var COOKIE_SESSION = "cookie";
36
- function createServerClient(config, fetcher = fetch) {
37
- const base = (config.basePath ?? "/auth").replace(/\/$/, "");
38
- const url = (path) => `${base}${path}`;
39
- const call = (path, init = {}) => fetcher(url(path), { credentials: "same-origin", ...init });
40
- return {
41
- async login(options = {}) {
42
- const target = new URL(url("/login"), location.origin);
43
- if (options.returnTo) target.searchParams.set("returnTo", options.returnTo);
44
- for (const [key, value] of Object.entries(options.params ?? {})) {
45
- target.searchParams.set(key, value);
46
- }
47
- location.assign(target.toString());
48
- },
49
- async handleCallback(params) {
50
- const response = await call("/callback", {
51
- method: "POST",
52
- headers: { "content-type": "application/json" },
53
- body: JSON.stringify(params)
54
- });
55
- if (!response.ok) {
56
- const body = await response.json().catch(() => ({}));
57
- throw new OAuthError(
58
- String(body.error ?? `Callback failed: ${response.status}`),
59
- String(body.error ?? "callback_failed")
60
- );
61
- }
62
- return { accessToken: COOKIE_SESSION };
63
- },
64
- async refresh() {
65
- const response = await call("/refresh", { method: "POST" });
66
- if (!response.ok) {
67
- throw new OAuthError("The server could not extend the session.", "refresh_failed");
68
- }
69
- return { accessToken: COOKIE_SESSION };
70
- },
71
- async fetchUser() {
72
- const custom = config.userInfo;
73
- const response = custom?.url ? await fetcher(custom.url, {
74
- method: custom.method ?? "GET",
75
- credentials: custom.credentials ?? "same-origin",
76
- headers: { accept: "application/json", ...custom.headers }
77
- }) : await call("/me");
78
- if (!response.ok) {
79
- throw new OAuthError(`The server refused the user request: ${response.status}`, "me_failed");
80
- }
81
- const raw = await response.json();
82
- return custom?.map ? await custom.map(raw, COOKIE_SESSION) : raw;
83
- },
84
- /**
85
- * Retire the session's tokens, which only the server can do here.
86
- *
87
- * The browser holds a cookie and no token, so it has nothing to send to a revocation
88
- * endpoint. This asks the server's own route, which opens the cookie and revokes what
89
- * is inside.
90
- */
91
- async revoke(_token, hint = "refresh_token") {
92
- await call(`/revoke?hint=${hint}`, { method: "POST" }).catch(() => void 0);
93
- },
94
- async logout(options = {}) {
95
- await call("/logout", { method: "POST" }).catch(() => void 0);
96
- const target = options.returnTo ? safeReturnTo(options.returnTo, {
97
- fallback: config.postLogoutRedirectUri ?? "/",
98
- allowedOrigins: config.allowedReturnOrigins
99
- }) : config.postLogoutRedirectUri ?? "/";
100
- if (typeof location !== "undefined") location.assign(target);
101
- },
102
- async restore() {
103
- const response = await call("/me");
104
- return response.ok ? { accessToken: COOKIE_SESSION } : null;
105
- }
106
- };
107
- }
1
+ import {
2
+ COOKIE_SESSION,
3
+ createServerClient
4
+ } from "./chunk-4QRYJ4TN.mjs";
5
+ import "./chunk-VCNXQCIH.mjs";
6
+ import "./chunk-AXPSPTNP.mjs";
7
+ import "./chunk-7P6ASYW6.mjs";
108
8
  export {
109
9
  COOKIE_SESSION,
110
10
  createServerClient
package/dist/server.cjs CHANGED
@@ -1,4 +1,4 @@
1
- /*! @fluixi/oauth2 v1.0.0-alpha.108 | (c) 2026 Ibrahima Touré and Fluixi contributors | MIT */
1
+ /*! @fluixi/oauth2 v1.0.0-alpha.109 | (c) 2026 Ibrahima Touré and Fluixi contributors | MIT */
2
2
  "use strict";
3
3
  var __create = Object.create;
4
4
  var __defProp = Object.defineProperty;
@@ -6,8 +6,13 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __esm = (fn, res) => function __init() {
10
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
9
+ var __esm = (fn, res, err) => function __init() {
10
+ if (err) throw err[0];
11
+ try {
12
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
13
+ } catch (e) {
14
+ throw err = [e], e;
15
+ }
11
16
  };
12
17
  var __export = (target, all) => {
13
18
  for (var name in all)
@@ -580,6 +585,7 @@ init_dpop();
580
585
  var import_app = require("@fluixi/start/app");
581
586
  var RETRY_MARK = ".retry";
582
587
  var PROMPTS = /* @__PURE__ */ new Set(["none", "login", "consent", "select_account", "create"]);
588
+ var DEFAULT_SCOPES = ["openid", "profile", "email"];
583
589
  var CLIENT_PARAMS = /* @__PURE__ */ new Set(["response_type", "client_id", "redirect_uri", "scope", "state", "nonce", "code_challenge", "code_challenge_method", "prompt", "request", "request_uri"]);
584
590
  var SILENT_REFUSALS = /* @__PURE__ */ new Set([
585
591
  "login_required",
@@ -631,6 +637,42 @@ function signInRedirect(request, config) {
631
637
  if (mode === "silent") login.set("prompt", "none");
632
638
  return new Response(null, { status: 302, headers: { location: `${base}/login?${login}` } });
633
639
  }
640
+ function jwtClaims(token) {
641
+ const part = token.split(".")[1];
642
+ if (!part) return {};
643
+ try {
644
+ const claims = JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
645
+ return claims && typeof claims === "object" ? claims : {};
646
+ } catch {
647
+ return {};
648
+ }
649
+ }
650
+ function missingScopes(config, session) {
651
+ if (session.scope === void 0) return [];
652
+ const granted = new Set(session.scope.split(" ").filter(Boolean));
653
+ return (config.scopes ?? DEFAULT_SCOPES).filter((scope) => scope !== "offline_access" && !granted.has(scope));
654
+ }
655
+ function rescopeCookie(config, missing) {
656
+ const name = `${config.cookieName ?? "fx_session"}_rescope`;
657
+ const secure = config.secureCookie ?? true;
658
+ const value = encodeURIComponent((missing ?? []).join(" "));
659
+ return { name, header: `${name}=${value}; Path=/; Max-Age=${60 * 60 * 24}; HttpOnly; SameSite=Lax${secure ? "; Secure" : ""}` };
660
+ }
661
+ function rescopeRedirect(request, config, session) {
662
+ if (!isPageRequest(request)) return null;
663
+ const missing = missingScopes(config, session);
664
+ if (!missing.length) return null;
665
+ const url = new URL(request.url);
666
+ const base = (config.basePath ?? "/auth").replace(/\/$/, "");
667
+ if ([base, ...config.publicPaths ?? []].some((path) => under(url.pathname, path))) return null;
668
+ const marker = rescopeCookie(config, missing);
669
+ if (cookieValue(request, marker.name) === encodeURIComponent(missing.join(" "))) return null;
670
+ const login = new URLSearchParams({ returnTo: url.pathname + url.search, prompt: "none" });
671
+ for (const [name, value] of Object.entries(config.rescopeParams?.(jwtClaims(session.accessToken)) ?? {})) {
672
+ if (value) login.set(name, value);
673
+ }
674
+ return new Response(null, { status: 302, headers: { location: `${base}/login?${login}`, "set-cookie": marker.header } });
675
+ }
634
676
  var dpopNonces = /* @__PURE__ */ new Map();
635
677
  async function prove(headers, key, method, url, accessToken) {
636
678
  headers.dpop = await proofFor(key, { method, url, accessToken, nonce: dpopNonces.get(new URL(url).origin) });
@@ -763,7 +805,8 @@ function renew(current, tokenRequest) {
763
805
  expiresAt: expiryFrom(payload.expires_in),
764
806
  tokenType: typeof payload.token_type === "string" ? payload.token_type : current.tokenType,
765
807
  dpop: current.dpop,
766
- sessionState: current.sessionState
808
+ sessionState: current.sessionState,
809
+ scope: typeof payload.scope === "string" ? payload.scope : current.scope
767
810
  };
768
811
  })().catch((error) => {
769
812
  if (error instanceof ProviderUnavailable) {
@@ -804,7 +847,7 @@ function oauthRoutes(config) {
804
847
  headers: { "content-type": "application/json", ...headers }
805
848
  });
806
849
  const base = (config.basePath ?? "/auth").replace(/\/$/, "");
807
- const scopes = config.scopes ?? ["openid", "profile", "email"];
850
+ const scopes = config.scopes ?? DEFAULT_SCOPES;
808
851
  const cookie = (0, import_server.createSessionCookie)({
809
852
  secret: config.cookieSecret,
810
853
  name: config.cookieName,
@@ -870,9 +913,10 @@ function oauthRoutes(config) {
870
913
  const value = url.searchParams.get(name);
871
914
  if (value) target.searchParams.set(name, value);
872
915
  }
916
+ const kept = prompt === "none" ? await session() : null;
873
917
  const pendingCookie = await cookie.write(
874
918
  {
875
- accessToken: "",
919
+ ...kept?.accessToken ? { ...kept, pending: void 0 } : { accessToken: "" },
876
920
  pending: {
877
921
  verifier,
878
922
  state,
@@ -887,8 +931,8 @@ function oauthRoutes(config) {
887
931
  }
888
932
  },
889
933
  // Ten minutes: long enough to sign in, short enough that an abandoned attempt
890
- // does not sit in the browser.
891
- { maxAge: 600 }
934
+ // does not sit in the browser. A kept session keeps its own lifetime.
935
+ kept?.accessToken ? void 0 : { maxAge: 600 }
892
936
  );
893
937
  return new Response(null, {
894
938
  status: 302,
@@ -910,6 +954,11 @@ function oauthRoutes(config) {
910
954
  allowedOrigins: config.allowedReturnOrigins
911
955
  });
912
956
  const headers = new Headers();
957
+ if (ours && pending.silent && SILENT_REFUSALS.has(error) && current?.accessToken) {
958
+ headers.set("set-cookie", await cookie.write({ ...current, pending: void 0 }));
959
+ headers.set("location", location2);
960
+ return new Response(null, { status: 302, headers });
961
+ }
913
962
  headers.append("set-cookie", cookie.clear());
914
963
  if (ours && pending.silent && SILENT_REFUSALS.has(error)) {
915
964
  headers.append("set-cookie", checkedCookie(config, sessionStateFrom(url)).header);
@@ -977,7 +1026,8 @@ function oauthRoutes(config) {
977
1026
  expiresAt: expiryFrom(payload.expires_in),
978
1027
  tokenType: typeof payload.token_type === "string" ? payload.token_type : void 0,
979
1028
  dpop: key ? await exportDpopKey(key) : void 0,
980
- sessionState: sessionStateFrom(url)
1029
+ sessionState: sessionStateFrom(url),
1030
+ scope: typeof payload.scope === "string" ? payload.scope : void 0
981
1031
  });
982
1032
  return new Response(null, {
983
1033
  status: 302,
@@ -1125,6 +1175,8 @@ function sessionLocals(config) {
1125
1175
  session = null;
1126
1176
  return signedOut();
1127
1177
  }
1178
+ const rescope = rescopeRedirect(request, config, session);
1179
+ if (rescope) return respond(rescope);
1128
1180
  const live = session;
1129
1181
  const fetchAs = (input, init) => sendAs(live, input, init);
1130
1182
  const cached = cache2.get(live.accessToken);
package/dist/server.d.ts CHANGED
@@ -112,6 +112,14 @@ export interface OAuthRoutesConfig {
112
112
  * sign in, and shows the other pages as `signIn` decides.
113
113
  */
114
114
  protectedPaths?: string[];
115
+ /**
116
+ * Authorize parameters a silent sign-in for a missing scope carries over, read from the
117
+ * current access token's claims (a JWT's payload; empty for an opaque token). When `scopes`
118
+ * gains one that sessions made earlier lack, the next page load signs in again with
119
+ * `prompt=none` to get it, and a token bound to something (an organization) has to stay
120
+ * bound: `(claims) => ({ organization: String(claims.org_id ?? '') })`. Empty values are left out.
121
+ */
122
+ rescopeParams?: (claims: Record<string, unknown>) => Record<string, string>;
115
123
  }
116
124
  /**
117
125
  * A request carrying the session's access token: the `DPoP` scheme and a proof bound to the