@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.
- package/dist/api-guard.cjs +7 -2
- package/dist/api-guard.mjs +9 -135
- package/dist/backchannel.cjs +7 -2
- package/dist/backchannel.mjs +11 -299
- package/dist/browser.mjs +10 -707
- package/dist/callback.mjs +16 -23
- package/dist/{dpop-YPGCGL7S.mjs → chunk-27BGFJIY.mjs} +6 -6
- package/dist/chunk-2GLWT7XH.mjs +143 -0
- package/dist/chunk-3EICMAF7.mjs +22 -0
- package/dist/chunk-4OHJTTX7.mjs +398 -0
- package/dist/chunk-4QRYJ4TN.mjs +86 -0
- package/dist/chunk-5WX3EV2W.mjs +78 -0
- package/dist/chunk-7AMC336S.mjs +52 -0
- package/dist/chunk-AAN3YN4S.mjs +63 -0
- package/dist/chunk-AWVECOG7.mjs +404 -0
- package/dist/chunk-GN5SERAQ.mjs +189 -0
- package/dist/chunk-KIXTZEEW.mjs +80 -0
- package/dist/chunk-KVW2S6VY.mjs +36 -0
- package/dist/chunk-MHWZTXZZ.mjs +9 -0
- package/dist/chunk-QC2FFASM.mjs +67 -0
- package/dist/chunk-SJOBQPG6.mjs +77 -0
- package/dist/chunk-VCNXQCIH.mjs +26 -0
- package/dist/chunk-XQJTQV3C.mjs +91 -0
- package/dist/client-auth.mjs +6 -78
- package/dist/discovery.mjs +6 -64
- package/dist/dpop-store.mjs +6 -118
- package/dist/dpop.mjs +11 -95
- package/dist/env-config.mjs +5 -214
- package/dist/env-credentials.mjs +5 -47
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +48 -1010
- package/dist/module.mjs +5 -20
- package/dist/pkce.mjs +11 -56
- package/dist/presets.mjs +5 -214
- package/dist/return-to.mjs +4 -22
- package/dist/roles.mjs +4 -32
- package/dist/server-client.mjs +7 -107
- package/dist/server.cjs +61 -9
- package/dist/server.d.ts +8 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +80 -5
- package/dist/server.mjs +94 -433
- package/dist/service-client.cjs +1 -1
- package/dist/service-client.mjs +16 -138
- package/dist/service.mjs +14 -978
- package/dist/session-monitor.mjs +4 -74
- package/dist/tokens.mjs +5 -4
- package/dist/tsconfig.lib.tsbuildinfo +1 -1
- package/dist/types.mjs +4 -9
- package/dist/verify.cjs +8 -3
- package/dist/verify.mjs +17 -585
- package/package.json +21 -21
- package/dist/browser-XDRDM2J3.mjs +0 -3545
- package/dist/chunk-6ZLDEEM7.mjs +0 -15
- package/dist/chunk-D2N6T3DN.mjs +0 -10
- package/dist/chunk-KPBCIVN3.mjs +0 -108
- package/dist/dpop-KK5X2JTA.mjs +0 -100
- package/dist/dpop-SO6GDDZH.mjs +0 -22
- /package/dist/{chunk-OGSFNTKA.mjs → chunk-AXPSPTNP.mjs} +0 -0
package/dist/server.mjs
CHANGED
|
@@ -1,430 +1,45 @@
|
|
|
1
|
-
/*! @fluixi/oauth2 v1.0.0-alpha.
|
|
1
|
+
/*! @fluixi/oauth2 v1.0.0-alpha.109 | (c) 2026 Ibrahima Touré and Fluixi contributors | MIT */
|
|
2
|
+
import {
|
|
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 {
|
|
11
|
+
createPkcePair,
|
|
12
|
+
createStateValue,
|
|
13
|
+
expiryFrom,
|
|
14
|
+
timingSafeEqual
|
|
15
|
+
} from "./chunk-QC2FFASM.mjs";
|
|
16
|
+
import {
|
|
17
|
+
safeReturnTo
|
|
18
|
+
} from "./chunk-VCNXQCIH.mjs";
|
|
19
|
+
import {
|
|
20
|
+
applyClientAuth
|
|
21
|
+
} from "./chunk-SJOBQPG6.mjs";
|
|
22
|
+
import {
|
|
23
|
+
discover
|
|
24
|
+
} from "./chunk-AAN3YN4S.mjs";
|
|
2
25
|
import {
|
|
3
|
-
OAuthError,
|
|
4
26
|
createDpopKey,
|
|
5
27
|
exportDpopKey,
|
|
6
28
|
importDpopKey,
|
|
7
29
|
nonceFrom,
|
|
8
30
|
proofFor
|
|
9
|
-
} from "./chunk-
|
|
10
|
-
import
|
|
31
|
+
} from "./chunk-27BGFJIY.mjs";
|
|
32
|
+
import {
|
|
33
|
+
OAuthError
|
|
34
|
+
} from "./chunk-AXPSPTNP.mjs";
|
|
35
|
+
import "./chunk-7P6ASYW6.mjs";
|
|
11
36
|
|
|
12
37
|
// src/server.ts
|
|
13
38
|
import { createSessionCookie } from "@fluixi/session/server";
|
|
14
|
-
|
|
15
|
-
// src/return-to.ts
|
|
16
|
-
function safeReturnTo(candidate, options = {}) {
|
|
17
|
-
const fallback = options.fallback ?? "/";
|
|
18
|
-
if (!candidate || typeof candidate !== "string") return fallback;
|
|
19
|
-
const value = candidate.trim();
|
|
20
|
-
if (!value) return fallback;
|
|
21
|
-
if (/[\u0000-\u001f\u007f]/.test(value)) return fallback;
|
|
22
|
-
if (/^[/\\]{2}/.test(value)) return fallback;
|
|
23
|
-
if (value.startsWith("/")) return value;
|
|
24
|
-
const here = options.origin ?? (typeof location === "undefined" ? void 0 : location.origin);
|
|
25
|
-
const allowed = [here, ...options.allowedOrigins ?? []].filter(Boolean);
|
|
26
|
-
if (!allowed.length) return fallback;
|
|
27
|
-
let url;
|
|
28
|
-
try {
|
|
29
|
-
url = new URL(value);
|
|
30
|
-
} catch {
|
|
31
|
-
return fallback;
|
|
32
|
-
}
|
|
33
|
-
if (!allowed.includes(url.origin)) return fallback;
|
|
34
|
-
if (url.protocol !== "http:" && url.protocol !== "https:") return fallback;
|
|
35
|
-
return url.toString();
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
// src/client-auth.ts
|
|
39
|
-
var CANONICAL = {
|
|
40
|
-
basic: "client_secret_basic",
|
|
41
|
-
body: "client_secret_post",
|
|
42
|
-
client_secret_basic: "client_secret_basic",
|
|
43
|
-
client_secret_post: "client_secret_post",
|
|
44
|
-
private_key_jwt: "private_key_jwt",
|
|
45
|
-
none: "none"
|
|
46
|
-
};
|
|
47
|
-
function resolveMethod(auth) {
|
|
48
|
-
if (auth.method) return CANONICAL[auth.method] ?? "client_secret_basic";
|
|
49
|
-
if (auth.privateKey) return "private_key_jwt";
|
|
50
|
-
return auth.clientSecret ? "client_secret_basic" : "none";
|
|
51
|
-
}
|
|
52
|
-
async function loadJose() {
|
|
53
|
-
try {
|
|
54
|
-
return await import("./browser-XDRDM2J3.mjs");
|
|
55
|
-
} catch {
|
|
56
|
-
throw new OAuthError(
|
|
57
|
-
"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.",
|
|
58
|
-
"jose_missing"
|
|
59
|
-
);
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
async function signAssertion(auth, endpoint) {
|
|
63
|
-
const jose = await loadJose();
|
|
64
|
-
const alg = auth.assertionAlgorithm ?? "RS256";
|
|
65
|
-
const key = await jose.importJWK(auth.privateKey, alg);
|
|
66
|
-
const kid = auth.keyId ?? auth.privateKey.kid;
|
|
67
|
-
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);
|
|
68
|
-
}
|
|
69
|
-
async function applyClientAuth(auth, endpoint, headers, form) {
|
|
70
|
-
switch (resolveMethod(auth)) {
|
|
71
|
-
case "client_secret_basic": {
|
|
72
|
-
const pair = `${encodeURIComponent(auth.clientId)}:${encodeURIComponent(auth.clientSecret)}`;
|
|
73
|
-
headers.authorization = `Basic ${btoa(pair)}`;
|
|
74
|
-
break;
|
|
75
|
-
}
|
|
76
|
-
case "client_secret_post":
|
|
77
|
-
form.set("client_id", auth.clientId);
|
|
78
|
-
form.set("client_secret", auth.clientSecret);
|
|
79
|
-
break;
|
|
80
|
-
case "private_key_jwt":
|
|
81
|
-
form.set("client_id", auth.clientId);
|
|
82
|
-
form.set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
|
|
83
|
-
form.set("client_assertion", await signAssertion(auth, endpoint));
|
|
84
|
-
break;
|
|
85
|
-
case "none":
|
|
86
|
-
form.set("client_id", auth.clientId);
|
|
87
|
-
break;
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
// src/discovery.ts
|
|
92
|
-
var cache = /* @__PURE__ */ new Map();
|
|
93
|
-
function documentUrl(issuer) {
|
|
94
|
-
return `${issuer.replace(/\/$/, "")}/.well-known/openid-configuration`;
|
|
95
|
-
}
|
|
96
|
-
async function discover(issuer, fetcher = fetch) {
|
|
97
|
-
const cached = cache.get(issuer);
|
|
98
|
-
if (cached) return cached;
|
|
99
|
-
const pending = (async () => {
|
|
100
|
-
let response;
|
|
101
|
-
try {
|
|
102
|
-
response = await fetcher(documentUrl(issuer));
|
|
103
|
-
} catch (cause) {
|
|
104
|
-
const why = cause instanceof Error ? cause.message : String(cause);
|
|
105
|
-
throw new OAuthError(
|
|
106
|
-
typeof window === "undefined" ? (
|
|
107
|
-
// On a server nothing blocks the read: the provider is down, or the address is wrong.
|
|
108
|
-
`Could not reach the provider at ${documentUrl(issuer)}: is it running, and is the issuer right? (${why})`
|
|
109
|
-
) : `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})`,
|
|
110
|
-
"discovery_unreachable"
|
|
111
|
-
);
|
|
112
|
-
}
|
|
113
|
-
if (!response.ok) {
|
|
114
|
-
throw new OAuthError(
|
|
115
|
-
`Discovery failed for ${issuer}: ${response.status}`,
|
|
116
|
-
"discovery_failed"
|
|
117
|
-
);
|
|
118
|
-
}
|
|
119
|
-
const doc = await response.json();
|
|
120
|
-
if (!doc.authorization_endpoint || !doc.token_endpoint) {
|
|
121
|
-
throw new OAuthError(
|
|
122
|
-
`${issuer} published a discovery document with no authorization or token endpoint.`,
|
|
123
|
-
"discovery_incomplete"
|
|
124
|
-
);
|
|
125
|
-
}
|
|
126
|
-
return {
|
|
127
|
-
authorization: doc.authorization_endpoint,
|
|
128
|
-
token: doc.token_endpoint,
|
|
129
|
-
userinfo: doc.userinfo_endpoint,
|
|
130
|
-
endSession: doc.end_session_endpoint,
|
|
131
|
-
jwks: doc.jwks_uri,
|
|
132
|
-
introspection: doc.introspection_endpoint,
|
|
133
|
-
revocation: doc.revocation_endpoint,
|
|
134
|
-
checkSession: doc.check_session_iframe,
|
|
135
|
-
issuer: doc.issuer ?? issuer
|
|
136
|
-
};
|
|
137
|
-
})();
|
|
138
|
-
cache.set(issuer, pending);
|
|
139
|
-
pending.catch(() => cache.delete(issuer));
|
|
140
|
-
return pending;
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
// src/verify.ts
|
|
144
|
-
var TokenError = class extends OAuthError {
|
|
145
|
-
constructor(message, code = "invalid_token") {
|
|
146
|
-
super(message, code);
|
|
147
|
-
this.name = "TokenError";
|
|
148
|
-
}
|
|
149
|
-
};
|
|
150
|
-
function bearerOf(request) {
|
|
151
|
-
const header = request.headers.get("authorization");
|
|
152
|
-
if (!header) return null;
|
|
153
|
-
const match = header.match(/^(?:Bearer|DPoP)\s+(.+)$/i);
|
|
154
|
-
return match ? match[1].trim() : null;
|
|
155
|
-
}
|
|
156
|
-
async function loadJose2() {
|
|
157
|
-
try {
|
|
158
|
-
return await import("./browser-XDRDM2J3.mjs");
|
|
159
|
-
} catch {
|
|
160
|
-
throw new OAuthError(
|
|
161
|
-
"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.",
|
|
162
|
-
"jose_missing"
|
|
163
|
-
);
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
function createTokenVerifier(options) {
|
|
167
|
-
const issuers = (Array.isArray(options.issuer) ? options.issuer : [options.issuer]).filter(Boolean);
|
|
168
|
-
if (!issuers.length) {
|
|
169
|
-
throw new Error("[fluixi/oauth2] createTokenVerifier needs an issuer to accept tokens from.");
|
|
170
|
-
}
|
|
171
|
-
const discoveryIssuer = issuers[0];
|
|
172
|
-
if (options.audience === void 0) {
|
|
173
|
-
throw new Error(
|
|
174
|
-
"[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."
|
|
175
|
-
);
|
|
176
|
-
}
|
|
177
|
-
if (options.audience === false && options.authorizedParty === void 0) {
|
|
178
|
-
console.warn(
|
|
179
|
-
"[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."
|
|
180
|
-
);
|
|
181
|
-
}
|
|
182
|
-
const algorithms = options.algorithms ?? ["RS256"];
|
|
183
|
-
if (algorithms.some((alg) => !alg || alg.toLowerCase() === "none")) {
|
|
184
|
-
throw new Error("[fluixi/oauth2] `none` is not a signing algorithm and cannot be accepted.");
|
|
185
|
-
}
|
|
186
|
-
let keys = null;
|
|
187
|
-
async function keySet() {
|
|
188
|
-
if (keys) return keys;
|
|
189
|
-
const jose = await loadJose2();
|
|
190
|
-
if (options.jwks) {
|
|
191
|
-
keys = jose.createLocalJWKSet(options.jwks);
|
|
192
|
-
return keys;
|
|
193
|
-
}
|
|
194
|
-
let uri = options.jwksUri;
|
|
195
|
-
if (!uri) {
|
|
196
|
-
const endpoints = await discover(discoveryIssuer);
|
|
197
|
-
uri = endpoints.jwks;
|
|
198
|
-
}
|
|
199
|
-
if (!uri) {
|
|
200
|
-
throw new OAuthError(
|
|
201
|
-
`${discoveryIssuer} published no jwks_uri. Give the verifier one directly.`,
|
|
202
|
-
"no_jwks"
|
|
203
|
-
);
|
|
204
|
-
}
|
|
205
|
-
keys = jose.createRemoteJWKSet(new URL(uri));
|
|
206
|
-
return keys;
|
|
207
|
-
}
|
|
208
|
-
const checkProof = async (claims, token, request) => {
|
|
209
|
-
const jose = await loadJose2();
|
|
210
|
-
const { boundKeyOf, thumbprintOf } = await import("./dpop-SO6GDDZH.mjs");
|
|
211
|
-
const bound = boundKeyOf(claims);
|
|
212
|
-
if (!bound) {
|
|
213
|
-
throw new TokenError(
|
|
214
|
-
"This token is not bound to a key, and this service requires binding.",
|
|
215
|
-
"token_not_bound"
|
|
216
|
-
);
|
|
217
|
-
}
|
|
218
|
-
const proof = request.headers.get("dpop");
|
|
219
|
-
if (!proof) throw new TokenError("The request carried no DPoP proof.", "missing_dpop_proof");
|
|
220
|
-
let payload;
|
|
221
|
-
let header;
|
|
222
|
-
try {
|
|
223
|
-
const result = await jose.jwtVerify(proof, jose.EmbeddedJWK, { typ: "dpop+jwt" });
|
|
224
|
-
payload = result.payload;
|
|
225
|
-
header = result.protectedHeader;
|
|
226
|
-
} catch (cause) {
|
|
227
|
-
throw new TokenError(
|
|
228
|
-
`The DPoP proof did not verify: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
229
|
-
"invalid_dpop_proof"
|
|
230
|
-
);
|
|
231
|
-
}
|
|
232
|
-
const presented = await thumbprintOf(header.jwk);
|
|
233
|
-
if (presented !== bound) {
|
|
234
|
-
throw new TokenError(
|
|
235
|
-
"The DPoP proof was signed with a different key from the one this token is bound to.",
|
|
236
|
-
"dpop_key_mismatch"
|
|
237
|
-
);
|
|
238
|
-
}
|
|
239
|
-
const url = new URL(request.url);
|
|
240
|
-
url.search = "";
|
|
241
|
-
url.hash = "";
|
|
242
|
-
if (payload.htm !== request.method.toUpperCase()) {
|
|
243
|
-
throw new TokenError("The DPoP proof was made for a different method.", "invalid_dpop_proof");
|
|
244
|
-
}
|
|
245
|
-
if (payload.htu !== url.toString()) {
|
|
246
|
-
throw new TokenError("The DPoP proof was made for a different URL.", "invalid_dpop_proof");
|
|
247
|
-
}
|
|
248
|
-
if (typeof payload.ath === "string") {
|
|
249
|
-
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token));
|
|
250
|
-
let binary = "";
|
|
251
|
-
for (const byte of new Uint8Array(digest)) binary += String.fromCharCode(byte);
|
|
252
|
-
const expected = btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
253
|
-
if (payload.ath !== expected) {
|
|
254
|
-
throw new TokenError("The DPoP proof was made for a different token.", "invalid_dpop_proof");
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
const age = Math.abs(Date.now() / 1e3 - payload.iat);
|
|
258
|
-
if (!Number.isFinite(age) || age > (options.dpopProofAgeSec ?? 10)) {
|
|
259
|
-
throw new TokenError("The DPoP proof is too old to accept.", "invalid_dpop_proof");
|
|
260
|
-
}
|
|
261
|
-
};
|
|
262
|
-
const verify = async (token, request) => {
|
|
263
|
-
if (!token) throw new TokenError("No token to verify.", "no_token");
|
|
264
|
-
const jose = await loadJose2();
|
|
265
|
-
let payload;
|
|
266
|
-
try {
|
|
267
|
-
({ payload } = await jose.jwtVerify(token, await keySet(), {
|
|
268
|
-
// jose takes a list and accepts any of them, which is what a provider naming
|
|
269
|
-
// itself two ways needs.
|
|
270
|
-
issuer: issuers,
|
|
271
|
-
...options.audience === false ? {} : { audience: options.audience },
|
|
272
|
-
algorithms,
|
|
273
|
-
clockTolerance: options.clockToleranceSec ?? 5
|
|
274
|
-
}));
|
|
275
|
-
} catch (cause) {
|
|
276
|
-
throw new TokenError(
|
|
277
|
-
`The token was not accepted: ${cause instanceof Error ? cause.message : String(cause)}`
|
|
278
|
-
);
|
|
279
|
-
}
|
|
280
|
-
if (options.authorizedParty !== void 0) {
|
|
281
|
-
const allowed = Array.isArray(options.authorizedParty) ? options.authorizedParty : [options.authorizedParty];
|
|
282
|
-
const issuedTo = payload.azp ?? payload.client_id;
|
|
283
|
-
if (typeof issuedTo !== "string" || !allowed.includes(issuedTo)) {
|
|
284
|
-
throw new TokenError("The token was issued to a different client.", "invalid_azp");
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
if (options.dpop) {
|
|
288
|
-
if (!request) {
|
|
289
|
-
throw new Error(
|
|
290
|
-
"[fluixi/oauth2] `dpop: true` needs the request to read its proof. Use `verify.fromRequest(request)` rather than verifying a bare token."
|
|
291
|
-
);
|
|
292
|
-
}
|
|
293
|
-
await checkProof(payload, token, request);
|
|
294
|
-
}
|
|
295
|
-
if (options.require) {
|
|
296
|
-
const verdict = options.require(payload);
|
|
297
|
-
if (verdict !== true) {
|
|
298
|
-
throw new TokenError(
|
|
299
|
-
typeof verdict === "string" ? verdict : "The token did not meet this service's requirements.",
|
|
300
|
-
"insufficient_claims"
|
|
301
|
-
);
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
return payload;
|
|
305
|
-
};
|
|
306
|
-
const verifier = verify;
|
|
307
|
-
verifier.bearerOf = bearerOf;
|
|
308
|
-
verifier.fromRequest = async (request) => {
|
|
309
|
-
const token = verifier.bearerOf(request);
|
|
310
|
-
if (!token) {
|
|
311
|
-
throw new TokenError("The request carried no bearer token.", "no_token");
|
|
312
|
-
}
|
|
313
|
-
return verify(token, request);
|
|
314
|
-
};
|
|
315
|
-
return verifier;
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
// src/backchannel.ts
|
|
319
|
-
var LOGOUT_EVENT = "http://schemas.openid.net/event/backchannel-logout";
|
|
320
|
-
function memoryLogouts(ttlMs = 14 * 24 * 36e5) {
|
|
321
|
-
const sids = /* @__PURE__ */ new Map();
|
|
322
|
-
const subs = /* @__PURE__ */ new Map();
|
|
323
|
-
const prune = (now) => {
|
|
324
|
-
for (const map of [sids, subs]) for (const [key, at] of map) if (now - at > ttlMs) map.delete(key);
|
|
325
|
-
};
|
|
326
|
-
return {
|
|
327
|
-
add(entry) {
|
|
328
|
-
prune(Date.now());
|
|
329
|
-
if (entry.sid) sids.set(entry.sid, entry.at);
|
|
330
|
-
else if (entry.sub) subs.set(entry.sub, Math.max(entry.at, subs.get(entry.sub) ?? 0));
|
|
331
|
-
},
|
|
332
|
-
ended(session) {
|
|
333
|
-
if (session.sid && sids.has(session.sid)) return true;
|
|
334
|
-
const all = session.sub ? subs.get(session.sub) : void 0;
|
|
335
|
-
return all !== void 0 && session.since <= all;
|
|
336
|
-
}
|
|
337
|
-
};
|
|
338
|
-
}
|
|
339
|
-
function idTokenClaims(idToken) {
|
|
340
|
-
if (!idToken) return {};
|
|
341
|
-
try {
|
|
342
|
-
const part = idToken.split(".")[1] ?? "";
|
|
343
|
-
const json = atob(part.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(part.length / 4) * 4, "="));
|
|
344
|
-
const claims = JSON.parse(json);
|
|
345
|
-
return {
|
|
346
|
-
sid: typeof claims.sid === "string" ? claims.sid : void 0,
|
|
347
|
-
sub: typeof claims.sub === "string" ? claims.sub : void 0,
|
|
348
|
-
iat: typeof claims.iat === "number" ? claims.iat : void 0
|
|
349
|
-
};
|
|
350
|
-
} catch {
|
|
351
|
-
return {};
|
|
352
|
-
}
|
|
353
|
-
}
|
|
354
|
-
function headerOf(token) {
|
|
355
|
-
try {
|
|
356
|
-
const part = token.split(".")[0] ?? "";
|
|
357
|
-
return JSON.parse(atob(part.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(part.length / 4) * 4, "=")));
|
|
358
|
-
} catch {
|
|
359
|
-
return {};
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
function logoutTokenVerifier(options) {
|
|
363
|
-
const verify = createTokenVerifier({
|
|
364
|
-
issuer: options.issuer,
|
|
365
|
-
audience: options.clientId,
|
|
366
|
-
jwksUri: options.jwksUri,
|
|
367
|
-
jwks: options.jwks,
|
|
368
|
-
require: (claims) => {
|
|
369
|
-
const events = claims.events;
|
|
370
|
-
if (!events || typeof events !== "object" || !(LOGOUT_EVENT in events)) return "no logout event";
|
|
371
|
-
if ("nonce" in claims) return "a logout token has no nonce";
|
|
372
|
-
if (typeof claims.sid !== "string" && typeof claims.sub !== "string") return "names no session and no subject";
|
|
373
|
-
return true;
|
|
374
|
-
}
|
|
375
|
-
});
|
|
376
|
-
return async (token) => {
|
|
377
|
-
const typ = headerOf(token).typ;
|
|
378
|
-
if (typ !== void 0 && typ !== "logout+jwt") throw new Error("not a logout token");
|
|
379
|
-
const claims = await verify(token);
|
|
380
|
-
return {
|
|
381
|
-
sid: typeof claims.sid === "string" ? claims.sid : void 0,
|
|
382
|
-
sub: typeof claims.sub === "string" ? claims.sub : void 0,
|
|
383
|
-
at: (typeof claims.iat === "number" ? claims.iat : Math.floor(Date.now() / 1e3)) * 1e3
|
|
384
|
-
};
|
|
385
|
-
};
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
// src/pkce.ts
|
|
389
|
-
function base64url(bytes) {
|
|
390
|
-
let binary = "";
|
|
391
|
-
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
392
|
-
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
393
|
-
}
|
|
394
|
-
function randomBytes(length) {
|
|
395
|
-
const bytes = new Uint8Array(length);
|
|
396
|
-
crypto.getRandomValues(bytes);
|
|
397
|
-
return bytes;
|
|
398
|
-
}
|
|
399
|
-
function createVerifier() {
|
|
400
|
-
return base64url(randomBytes(32));
|
|
401
|
-
}
|
|
402
|
-
function createStateValue() {
|
|
403
|
-
return base64url(randomBytes(16));
|
|
404
|
-
}
|
|
405
|
-
async function createChallenge(verifier) {
|
|
406
|
-
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
|
|
407
|
-
return base64url(new Uint8Array(digest));
|
|
408
|
-
}
|
|
409
|
-
async function createPkcePair() {
|
|
410
|
-
const verifier = createVerifier();
|
|
411
|
-
return { verifier, challenge: await createChallenge(verifier) };
|
|
412
|
-
}
|
|
413
|
-
function timingSafeEqual(a, b) {
|
|
414
|
-
if (a.length !== b.length) return false;
|
|
415
|
-
let diff = 0;
|
|
416
|
-
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
417
|
-
return diff === 0;
|
|
418
|
-
}
|
|
419
|
-
function expiryFrom(expiresIn, now = Date.now()) {
|
|
420
|
-
const seconds = typeof expiresIn === "number" ? expiresIn : Number(expiresIn);
|
|
421
|
-
return Number.isFinite(seconds) && seconds > 0 ? now + seconds * 1e3 : void 0;
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
// src/server.ts
|
|
425
39
|
import { defineModule } from "@fluixi/start/app";
|
|
426
40
|
var RETRY_MARK = ".retry";
|
|
427
41
|
var PROMPTS = /* @__PURE__ */ new Set(["none", "login", "consent", "select_account", "create"]);
|
|
42
|
+
var DEFAULT_SCOPES = ["openid", "profile", "email"];
|
|
428
43
|
var CLIENT_PARAMS = /* @__PURE__ */ new Set(["response_type", "client_id", "redirect_uri", "scope", "state", "nonce", "code_challenge", "code_challenge_method", "prompt", "request", "request_uri"]);
|
|
429
44
|
var SILENT_REFUSALS = /* @__PURE__ */ new Set([
|
|
430
45
|
"login_required",
|
|
@@ -476,6 +91,42 @@ function signInRedirect(request, config) {
|
|
|
476
91
|
if (mode === "silent") login.set("prompt", "none");
|
|
477
92
|
return new Response(null, { status: 302, headers: { location: `${base}/login?${login}` } });
|
|
478
93
|
}
|
|
94
|
+
function jwtClaims(token) {
|
|
95
|
+
const part = token.split(".")[1];
|
|
96
|
+
if (!part) return {};
|
|
97
|
+
try {
|
|
98
|
+
const claims = JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
|
|
99
|
+
return claims && typeof claims === "object" ? claims : {};
|
|
100
|
+
} catch {
|
|
101
|
+
return {};
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
function missingScopes(config, session) {
|
|
105
|
+
if (session.scope === void 0) return [];
|
|
106
|
+
const granted = new Set(session.scope.split(" ").filter(Boolean));
|
|
107
|
+
return (config.scopes ?? DEFAULT_SCOPES).filter((scope) => scope !== "offline_access" && !granted.has(scope));
|
|
108
|
+
}
|
|
109
|
+
function rescopeCookie(config, missing) {
|
|
110
|
+
const name = `${config.cookieName ?? "fx_session"}_rescope`;
|
|
111
|
+
const secure = config.secureCookie ?? true;
|
|
112
|
+
const value = encodeURIComponent((missing ?? []).join(" "));
|
|
113
|
+
return { name, header: `${name}=${value}; Path=/; Max-Age=${60 * 60 * 24}; HttpOnly; SameSite=Lax${secure ? "; Secure" : ""}` };
|
|
114
|
+
}
|
|
115
|
+
function rescopeRedirect(request, config, session) {
|
|
116
|
+
if (!isPageRequest(request)) return null;
|
|
117
|
+
const missing = missingScopes(config, session);
|
|
118
|
+
if (!missing.length) return null;
|
|
119
|
+
const url = new URL(request.url);
|
|
120
|
+
const base = (config.basePath ?? "/auth").replace(/\/$/, "");
|
|
121
|
+
if ([base, ...config.publicPaths ?? []].some((path) => under(url.pathname, path))) return null;
|
|
122
|
+
const marker = rescopeCookie(config, missing);
|
|
123
|
+
if (cookieValue(request, marker.name) === encodeURIComponent(missing.join(" "))) return null;
|
|
124
|
+
const login = new URLSearchParams({ returnTo: url.pathname + url.search, prompt: "none" });
|
|
125
|
+
for (const [name, value] of Object.entries(config.rescopeParams?.(jwtClaims(session.accessToken)) ?? {})) {
|
|
126
|
+
if (value) login.set(name, value);
|
|
127
|
+
}
|
|
128
|
+
return new Response(null, { status: 302, headers: { location: `${base}/login?${login}`, "set-cookie": marker.header } });
|
|
129
|
+
}
|
|
479
130
|
var dpopNonces = /* @__PURE__ */ new Map();
|
|
480
131
|
async function prove(headers, key, method, url, accessToken) {
|
|
481
132
|
headers.dpop = await proofFor(key, { method, url, accessToken, nonce: dpopNonces.get(new URL(url).origin) });
|
|
@@ -608,7 +259,8 @@ function renew(current, tokenRequest) {
|
|
|
608
259
|
expiresAt: expiryFrom(payload.expires_in),
|
|
609
260
|
tokenType: typeof payload.token_type === "string" ? payload.token_type : current.tokenType,
|
|
610
261
|
dpop: current.dpop,
|
|
611
|
-
sessionState: current.sessionState
|
|
262
|
+
sessionState: current.sessionState,
|
|
263
|
+
scope: typeof payload.scope === "string" ? payload.scope : current.scope
|
|
612
264
|
};
|
|
613
265
|
})().catch((error) => {
|
|
614
266
|
if (error instanceof ProviderUnavailable) {
|
|
@@ -649,7 +301,7 @@ function oauthRoutes(config) {
|
|
|
649
301
|
headers: { "content-type": "application/json", ...headers }
|
|
650
302
|
});
|
|
651
303
|
const base = (config.basePath ?? "/auth").replace(/\/$/, "");
|
|
652
|
-
const scopes = config.scopes ??
|
|
304
|
+
const scopes = config.scopes ?? DEFAULT_SCOPES;
|
|
653
305
|
const cookie = createSessionCookie({
|
|
654
306
|
secret: config.cookieSecret,
|
|
655
307
|
name: config.cookieName,
|
|
@@ -695,8 +347,8 @@ function oauthRoutes(config) {
|
|
|
695
347
|
});
|
|
696
348
|
const target2 = new URL(back, url.origin);
|
|
697
349
|
target2.searchParams.set("auth_error", "provider_unreachable");
|
|
698
|
-
const
|
|
699
|
-
return new Response(null, { status: 302, headers: { location
|
|
350
|
+
const location = target2.origin === url.origin ? target2.pathname + target2.search : target2.toString();
|
|
351
|
+
return new Response(null, { status: 302, headers: { location } });
|
|
700
352
|
}
|
|
701
353
|
const { verifier, challenge } = await createPkcePair();
|
|
702
354
|
const retry = url.searchParams.get("retry") === "1";
|
|
@@ -715,9 +367,10 @@ function oauthRoutes(config) {
|
|
|
715
367
|
const value = url.searchParams.get(name);
|
|
716
368
|
if (value) target.searchParams.set(name, value);
|
|
717
369
|
}
|
|
370
|
+
const kept = prompt === "none" ? await session() : null;
|
|
718
371
|
const pendingCookie = await cookie.write(
|
|
719
372
|
{
|
|
720
|
-
accessToken: "",
|
|
373
|
+
...kept?.accessToken ? { ...kept, pending: void 0 } : { accessToken: "" },
|
|
721
374
|
pending: {
|
|
722
375
|
verifier,
|
|
723
376
|
state,
|
|
@@ -732,8 +385,8 @@ function oauthRoutes(config) {
|
|
|
732
385
|
}
|
|
733
386
|
},
|
|
734
387
|
// Ten minutes: long enough to sign in, short enough that an abandoned attempt
|
|
735
|
-
// does not sit in the browser.
|
|
736
|
-
{ maxAge: 600 }
|
|
388
|
+
// does not sit in the browser. A kept session keeps its own lifetime.
|
|
389
|
+
kept?.accessToken ? void 0 : { maxAge: 600 }
|
|
737
390
|
);
|
|
738
391
|
return new Response(null, {
|
|
739
392
|
status: 302,
|
|
@@ -749,21 +402,26 @@ function oauthRoutes(config) {
|
|
|
749
402
|
const error = url.searchParams.get("error");
|
|
750
403
|
if (error) {
|
|
751
404
|
const ours = !!pending && timingSafeEqual(pending.state, url.searchParams.get("state") ?? "");
|
|
752
|
-
let
|
|
405
|
+
let location = safeReturnTo(ours ? pending.returnTo ?? config.defaultReturnTo : config.defaultReturnTo, {
|
|
753
406
|
fallback: "/",
|
|
754
407
|
origin: url.origin,
|
|
755
408
|
allowedOrigins: config.allowedReturnOrigins
|
|
756
409
|
});
|
|
757
410
|
const headers = new Headers();
|
|
411
|
+
if (ours && pending.silent && SILENT_REFUSALS.has(error) && current?.accessToken) {
|
|
412
|
+
headers.set("set-cookie", await cookie.write({ ...current, pending: void 0 }));
|
|
413
|
+
headers.set("location", location);
|
|
414
|
+
return new Response(null, { status: 302, headers });
|
|
415
|
+
}
|
|
758
416
|
headers.append("set-cookie", cookie.clear());
|
|
759
417
|
if (ours && pending.silent && SILENT_REFUSALS.has(error)) {
|
|
760
418
|
headers.append("set-cookie", checkedCookie(config, sessionStateFrom(url)).header);
|
|
761
419
|
} else {
|
|
762
|
-
const target = new URL(
|
|
420
|
+
const target = new URL(location, url.origin);
|
|
763
421
|
target.searchParams.set("auth_error", error);
|
|
764
|
-
|
|
422
|
+
location = target.origin === url.origin ? target.pathname + target.search : target.toString();
|
|
765
423
|
}
|
|
766
|
-
headers.set("location",
|
|
424
|
+
headers.set("location", location);
|
|
767
425
|
return new Response(null, { status: 302, headers });
|
|
768
426
|
}
|
|
769
427
|
const code = url.searchParams.get("code");
|
|
@@ -822,7 +480,8 @@ function oauthRoutes(config) {
|
|
|
822
480
|
expiresAt: expiryFrom(payload.expires_in),
|
|
823
481
|
tokenType: typeof payload.token_type === "string" ? payload.token_type : void 0,
|
|
824
482
|
dpop: key ? await exportDpopKey(key) : void 0,
|
|
825
|
-
sessionState: sessionStateFrom(url)
|
|
483
|
+
sessionState: sessionStateFrom(url),
|
|
484
|
+
scope: typeof payload.scope === "string" ? payload.scope : void 0
|
|
826
485
|
});
|
|
827
486
|
return new Response(null, {
|
|
828
487
|
status: 302,
|
|
@@ -924,15 +583,15 @@ function sessionLocals(config) {
|
|
|
924
583
|
});
|
|
925
584
|
const { tokenRequest } = tokenClient(config);
|
|
926
585
|
const ttl = config.userCacheMs ?? 3e4;
|
|
927
|
-
const
|
|
586
|
+
const cache = /* @__PURE__ */ new Map();
|
|
928
587
|
const remember = (token, user) => {
|
|
929
588
|
if (ttl <= 0) return;
|
|
930
|
-
if (
|
|
589
|
+
if (cache.size > 500) {
|
|
931
590
|
const now = Date.now();
|
|
932
|
-
for (const [key, entry] of
|
|
933
|
-
if (
|
|
591
|
+
for (const [key, entry] of cache) if (entry.until <= now) cache.delete(key);
|
|
592
|
+
if (cache.size > 500) cache.delete(cache.keys().next().value);
|
|
934
593
|
}
|
|
935
|
-
|
|
594
|
+
cache.set(token, { user, until: Date.now() + ttl });
|
|
936
595
|
};
|
|
937
596
|
return async function middleware(request, next) {
|
|
938
597
|
const { getRequestLocals } = await import("@fluixi/server");
|
|
@@ -970,9 +629,11 @@ function sessionLocals(config) {
|
|
|
970
629
|
session = null;
|
|
971
630
|
return signedOut();
|
|
972
631
|
}
|
|
632
|
+
const rescope = rescopeRedirect(request, config, session);
|
|
633
|
+
if (rescope) return respond(rescope);
|
|
973
634
|
const live = session;
|
|
974
635
|
const fetchAs = (input, init) => sendAs(live, input, init);
|
|
975
|
-
const cached =
|
|
636
|
+
const cached = cache.get(live.accessToken);
|
|
976
637
|
if (cached && cached.until > Date.now()) {
|
|
977
638
|
locals.auth = { user: cached.user, session: { expiresAt: live.expiresAt }, fetch: fetchAs };
|
|
978
639
|
return respond(await next());
|
package/dist/service-client.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/*! @fluixi/oauth2 v1.0.0-alpha.
|
|
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;
|