@fluixi/oauth2 1.0.0-alpha.11 → 1.0.0-alpha.111
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 +8 -3
- package/dist/api-guard.mjs +9 -135
- package/dist/backchannel.cjs +467 -0
- package/dist/backchannel.d.ts +39 -0
- package/dist/backchannel.d.ts.map +1 -0
- package/dist/backchannel.js +97 -0
- package/dist/backchannel.mjs +19 -0
- package/dist/browser.cjs +6 -1
- package/dist/browser.mjs +10 -702
- package/dist/callback.cjs +2 -2
- package/dist/callback.d.ts +2 -2
- package/dist/callback.js +3 -3
- package/dist/callback.mjs +17 -24
- 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.cjs +6 -1
- package/dist/discovery.d.ts.map +1 -1
- package/dist/discovery.js +6 -1
- package/dist/discovery.mjs +6 -59
- package/dist/dpop-store.mjs +6 -118
- package/dist/dpop.mjs +11 -95
- package/dist/env-config.cjs +1 -1
- package/dist/env-config.mjs +5 -214
- package/dist/env-credentials.mjs +5 -47
- package/dist/index.cjs +108 -8
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.mjs +50 -912
- package/dist/module.cjs +1 -1
- package/dist/module.mjs +5 -20
- package/dist/pkce.mjs +11 -56
- package/dist/presets.cjs +1 -1
- package/dist/presets.mjs +5 -214
- package/dist/return-to.mjs +4 -22
- package/dist/roles.cjs +1 -1
- package/dist/roles.d.ts +1 -1
- package/dist/roles.js +1 -1
- package/dist/roles.mjs +4 -32
- package/dist/server-client.mjs +7 -107
- package/dist/server.cjs +795 -153
- package/dist/server.d.ts +85 -4
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +577 -75
- package/dist/server.mjs +442 -310
- package/dist/service-client.cjs +7 -2
- package/dist/service-client.mjs +16 -133
- package/dist/service.cjs +104 -5
- package/dist/service.d.ts +1 -1
- package/dist/service.d.ts.map +1 -1
- package/dist/service.js +38 -6
- package/dist/service.mjs +14 -879
- package/dist/session-monitor.cjs +98 -0
- package/dist/session-monitor.d.ts +32 -0
- package/dist/session-monitor.d.ts.map +1 -0
- package/dist/session-monitor.js +104 -0
- package/dist/session-monitor.mjs +7 -0
- package/dist/tokens.cjs +1 -1
- package/dist/tokens.d.ts +2 -2
- package/dist/tokens.d.ts.map +1 -1
- package/dist/tokens.js +1 -1
- package/dist/tokens.mjs +5 -4
- package/dist/tsconfig.lib.tsbuildinfo +1 -1
- package/dist/types.d.ts +8 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.mjs +4 -9
- package/dist/verify.cjs +15 -5
- package/dist/verify.d.ts +2 -2
- package/dist/verify.js +2 -2
- package/dist/verify.mjs +17 -580
- package/package.json +23 -17
- package/dist/browser-N432SMC3.mjs +0 -3545
- package/dist/chunk-4TPZVJSR.mjs +0 -10
- package/dist/chunk-ZVDC3JW7.mjs +0 -15
- package/dist/dpop-DYUR2CH2.mjs +0 -100
- /package/dist/{chunk-OGSFNTKA.mjs → chunk-AXPSPTNP.mjs} +0 -0
package/dist/server.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/*! @fluixi/oauth2 v1.0.0-alpha.
|
|
1
|
+
/*! @fluixi/oauth2 v1.0.0-alpha.111 | (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,6 +6,14 @@ 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, 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
|
+
}
|
|
16
|
+
};
|
|
9
17
|
var __export = (target, all) => {
|
|
10
18
|
for (var name in all)
|
|
11
19
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
@@ -28,11 +36,132 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
28
36
|
));
|
|
29
37
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
30
38
|
|
|
39
|
+
// src/types.ts
|
|
40
|
+
var OAuthError;
|
|
41
|
+
var init_types = __esm({
|
|
42
|
+
"src/types.ts"() {
|
|
43
|
+
"use strict";
|
|
44
|
+
OAuthError = class extends Error {
|
|
45
|
+
constructor(message, code, description) {
|
|
46
|
+
super(message);
|
|
47
|
+
this.code = code;
|
|
48
|
+
this.description = description;
|
|
49
|
+
this.name = "OAuthError";
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
// src/dpop.ts
|
|
56
|
+
var dpop_exports = {};
|
|
57
|
+
__export(dpop_exports, {
|
|
58
|
+
boundKeyOf: () => boundKeyOf,
|
|
59
|
+
createDpopKey: () => createDpopKey,
|
|
60
|
+
exportDpopKey: () => exportDpopKey,
|
|
61
|
+
importDpopKey: () => importDpopKey,
|
|
62
|
+
nonceFrom: () => nonceFrom,
|
|
63
|
+
proofFor: () => proofFor,
|
|
64
|
+
thumbprintOf: () => thumbprintOf,
|
|
65
|
+
wantsNonce: () => wantsNonce
|
|
66
|
+
});
|
|
67
|
+
async function loadJose2() {
|
|
68
|
+
try {
|
|
69
|
+
return await import("jose");
|
|
70
|
+
} catch {
|
|
71
|
+
throw new OAuthError(
|
|
72
|
+
"DPoP needs `jose`. Install it: npm i jose. It is an optional peer, so a client not using DPoP does not carry it.",
|
|
73
|
+
"jose_missing"
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
async function createDpopKey(alg = "ES256", options = {}) {
|
|
78
|
+
const jose = await loadJose2();
|
|
79
|
+
const { privateKey, publicKey } = await jose.generateKeyPair(alg, {
|
|
80
|
+
extractable: options.extractable ?? false
|
|
81
|
+
});
|
|
82
|
+
const publicJwk = { ...await jose.exportJWK(publicKey) };
|
|
83
|
+
return {
|
|
84
|
+
privateKey,
|
|
85
|
+
publicJwk,
|
|
86
|
+
thumbprint: await jose.calculateJwkThumbprint(publicJwk, "sha256"),
|
|
87
|
+
alg
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
async function exportDpopKey(key) {
|
|
91
|
+
const jose = await loadJose2();
|
|
92
|
+
return { jwk: { ...await jose.exportJWK(key.privateKey) }, alg: key.alg };
|
|
93
|
+
}
|
|
94
|
+
async function importDpopKey(stored) {
|
|
95
|
+
const jose = await loadJose2();
|
|
96
|
+
const privateKey = await jose.importJWK(stored.jwk, stored.alg);
|
|
97
|
+
const publicJwk = Object.fromEntries(Object.entries(stored.jwk).filter(([k]) => !PRIVATE_MEMBERS.has(k)));
|
|
98
|
+
return {
|
|
99
|
+
privateKey,
|
|
100
|
+
publicJwk,
|
|
101
|
+
thumbprint: await jose.calculateJwkThumbprint(publicJwk, "sha256"),
|
|
102
|
+
alg: stored.alg
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
async function thumbprintOf(jwk) {
|
|
106
|
+
const jose = await loadJose2();
|
|
107
|
+
return jose.calculateJwkThumbprint(jwk, "sha256");
|
|
108
|
+
}
|
|
109
|
+
async function proofFor(key, options) {
|
|
110
|
+
const jose = await loadJose2();
|
|
111
|
+
const htu = (() => {
|
|
112
|
+
try {
|
|
113
|
+
const url = new URL(options.url);
|
|
114
|
+
url.search = "";
|
|
115
|
+
url.hash = "";
|
|
116
|
+
return url.toString();
|
|
117
|
+
} catch {
|
|
118
|
+
return options.url;
|
|
119
|
+
}
|
|
120
|
+
})();
|
|
121
|
+
const claims = {
|
|
122
|
+
htm: options.method.toUpperCase(),
|
|
123
|
+
htu,
|
|
124
|
+
jti: crypto.randomUUID()
|
|
125
|
+
};
|
|
126
|
+
if (options.accessToken) {
|
|
127
|
+
const digest = await crypto.subtle.digest(
|
|
128
|
+
"SHA-256",
|
|
129
|
+
new TextEncoder().encode(options.accessToken)
|
|
130
|
+
);
|
|
131
|
+
let binary = "";
|
|
132
|
+
for (const byte of new Uint8Array(digest)) binary += String.fromCharCode(byte);
|
|
133
|
+
claims.ath = btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
134
|
+
}
|
|
135
|
+
if (options.nonce) claims.nonce = options.nonce;
|
|
136
|
+
return new jose.SignJWT(claims).setProtectedHeader({ typ: "dpop+jwt", alg: key.alg, jwk: key.publicJwk }).setIssuedAt().sign(key.privateKey);
|
|
137
|
+
}
|
|
138
|
+
function nonceFrom(response) {
|
|
139
|
+
return response.headers.get("dpop-nonce");
|
|
140
|
+
}
|
|
141
|
+
function wantsNonce(error, response) {
|
|
142
|
+
const code = typeof error === "string" ? error : error?.error;
|
|
143
|
+
return code === "use_dpop_nonce" || !!response && !!nonceFrom(response);
|
|
144
|
+
}
|
|
145
|
+
function boundKeyOf(claims) {
|
|
146
|
+
const cnf = claims.cnf;
|
|
147
|
+
return typeof cnf?.jkt === "string" ? cnf.jkt : null;
|
|
148
|
+
}
|
|
149
|
+
var PRIVATE_MEMBERS;
|
|
150
|
+
var init_dpop = __esm({
|
|
151
|
+
"src/dpop.ts"() {
|
|
152
|
+
"use strict";
|
|
153
|
+
init_types();
|
|
154
|
+
PRIVATE_MEMBERS = /* @__PURE__ */ new Set(["d", "p", "q", "dp", "dq", "qi", "oth"]);
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
|
|
31
158
|
// src/server.ts
|
|
32
159
|
var server_exports = {};
|
|
33
160
|
__export(server_exports, {
|
|
34
161
|
authServerModule: () => authServerModule,
|
|
162
|
+
memoryLogouts: () => memoryLogouts,
|
|
35
163
|
oauthRoutes: () => oauthRoutes,
|
|
164
|
+
requestAuth: () => requestAuth,
|
|
36
165
|
sessionLocals: () => sessionLocals
|
|
37
166
|
});
|
|
38
167
|
module.exports = __toCommonJS(server_exports);
|
|
@@ -61,17 +190,8 @@ function safeReturnTo(candidate, options = {}) {
|
|
|
61
190
|
return url.toString();
|
|
62
191
|
}
|
|
63
192
|
|
|
64
|
-
// src/types.ts
|
|
65
|
-
var OAuthError = class extends Error {
|
|
66
|
-
constructor(message, code, description) {
|
|
67
|
-
super(message);
|
|
68
|
-
this.code = code;
|
|
69
|
-
this.description = description;
|
|
70
|
-
this.name = "OAuthError";
|
|
71
|
-
}
|
|
72
|
-
};
|
|
73
|
-
|
|
74
193
|
// src/client-auth.ts
|
|
194
|
+
init_types();
|
|
75
195
|
var CANONICAL = {
|
|
76
196
|
basic: "client_secret_basic",
|
|
77
197
|
body: "client_secret_post",
|
|
@@ -125,6 +245,7 @@ async function applyClientAuth(auth, endpoint, headers, form) {
|
|
|
125
245
|
}
|
|
126
246
|
|
|
127
247
|
// src/discovery.ts
|
|
248
|
+
init_types();
|
|
128
249
|
var cache = /* @__PURE__ */ new Map();
|
|
129
250
|
function documentUrl(issuer) {
|
|
130
251
|
return `${issuer.replace(/\/$/, "")}/.well-known/openid-configuration`;
|
|
@@ -137,8 +258,12 @@ async function discover(issuer, fetcher = fetch) {
|
|
|
137
258
|
try {
|
|
138
259
|
response = await fetcher(documentUrl(issuer));
|
|
139
260
|
} catch (cause) {
|
|
261
|
+
const why = cause instanceof Error ? cause.message : String(cause);
|
|
140
262
|
throw new OAuthError(
|
|
141
|
-
|
|
263
|
+
typeof window === "undefined" ? (
|
|
264
|
+
// On a server nothing blocks the read: the provider is down, or the address is wrong.
|
|
265
|
+
`Could not reach the provider at ${documentUrl(issuer)}: is it running, and is the issuer right? (${why})`
|
|
266
|
+
) : `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})`,
|
|
142
267
|
"discovery_unreachable"
|
|
143
268
|
);
|
|
144
269
|
}
|
|
@@ -163,6 +288,7 @@ async function discover(issuer, fetcher = fetch) {
|
|
|
163
288
|
jwks: doc.jwks_uri,
|
|
164
289
|
introspection: doc.introspection_endpoint,
|
|
165
290
|
revocation: doc.revocation_endpoint,
|
|
291
|
+
checkSession: doc.check_session_iframe,
|
|
166
292
|
issuer: doc.issuer ?? issuer
|
|
167
293
|
};
|
|
168
294
|
})();
|
|
@@ -171,6 +297,252 @@ async function discover(issuer, fetcher = fetch) {
|
|
|
171
297
|
return pending;
|
|
172
298
|
}
|
|
173
299
|
|
|
300
|
+
// src/verify.ts
|
|
301
|
+
init_types();
|
|
302
|
+
var TokenError = class extends OAuthError {
|
|
303
|
+
constructor(message, code = "invalid_token") {
|
|
304
|
+
super(message, code);
|
|
305
|
+
this.name = "TokenError";
|
|
306
|
+
}
|
|
307
|
+
};
|
|
308
|
+
function bearerOf(request) {
|
|
309
|
+
const header = request.headers.get("authorization");
|
|
310
|
+
if (!header) return null;
|
|
311
|
+
const match = header.match(/^(?:Bearer|DPoP)\s+(.+)$/i);
|
|
312
|
+
return match ? match[1].trim() : null;
|
|
313
|
+
}
|
|
314
|
+
async function loadJose3() {
|
|
315
|
+
try {
|
|
316
|
+
return await import("jose");
|
|
317
|
+
} catch {
|
|
318
|
+
throw new OAuthError(
|
|
319
|
+
"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.",
|
|
320
|
+
"jose_missing"
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
function createTokenVerifier(options) {
|
|
325
|
+
const issuers = (Array.isArray(options.issuer) ? options.issuer : [options.issuer]).filter(Boolean);
|
|
326
|
+
if (!issuers.length) {
|
|
327
|
+
throw new Error("[fluixi/oauth2] createTokenVerifier needs an issuer to accept tokens from.");
|
|
328
|
+
}
|
|
329
|
+
const discoveryIssuer = issuers[0];
|
|
330
|
+
if (options.audience === void 0) {
|
|
331
|
+
throw new Error(
|
|
332
|
+
"[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."
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
if (options.audience === false && options.authorizedParty === void 0) {
|
|
336
|
+
console.warn(
|
|
337
|
+
"[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."
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
const algorithms = options.algorithms ?? ["RS256"];
|
|
341
|
+
if (algorithms.some((alg) => !alg || alg.toLowerCase() === "none")) {
|
|
342
|
+
throw new Error("[fluixi/oauth2] `none` is not a signing algorithm and cannot be accepted.");
|
|
343
|
+
}
|
|
344
|
+
let keys = null;
|
|
345
|
+
async function keySet() {
|
|
346
|
+
if (keys) return keys;
|
|
347
|
+
const jose = await loadJose3();
|
|
348
|
+
if (options.jwks) {
|
|
349
|
+
keys = jose.createLocalJWKSet(options.jwks);
|
|
350
|
+
return keys;
|
|
351
|
+
}
|
|
352
|
+
let uri = options.jwksUri;
|
|
353
|
+
if (!uri) {
|
|
354
|
+
const endpoints = await discover(discoveryIssuer);
|
|
355
|
+
uri = endpoints.jwks;
|
|
356
|
+
}
|
|
357
|
+
if (!uri) {
|
|
358
|
+
throw new OAuthError(
|
|
359
|
+
`${discoveryIssuer} published no jwks_uri. Give the verifier one directly.`,
|
|
360
|
+
"no_jwks"
|
|
361
|
+
);
|
|
362
|
+
}
|
|
363
|
+
keys = jose.createRemoteJWKSet(new URL(uri));
|
|
364
|
+
return keys;
|
|
365
|
+
}
|
|
366
|
+
const checkProof = async (claims, token, request) => {
|
|
367
|
+
const jose = await loadJose3();
|
|
368
|
+
const { boundKeyOf: boundKeyOf2, thumbprintOf: thumbprintOf2 } = await Promise.resolve().then(() => (init_dpop(), dpop_exports));
|
|
369
|
+
const bound = boundKeyOf2(claims);
|
|
370
|
+
if (!bound) {
|
|
371
|
+
throw new TokenError(
|
|
372
|
+
"This token is not bound to a key, and this service requires binding.",
|
|
373
|
+
"token_not_bound"
|
|
374
|
+
);
|
|
375
|
+
}
|
|
376
|
+
const proof = request.headers.get("dpop");
|
|
377
|
+
if (!proof) throw new TokenError("The request carried no DPoP proof.", "missing_dpop_proof");
|
|
378
|
+
let payload;
|
|
379
|
+
let header;
|
|
380
|
+
try {
|
|
381
|
+
const result = await jose.jwtVerify(proof, jose.EmbeddedJWK, { typ: "dpop+jwt" });
|
|
382
|
+
payload = result.payload;
|
|
383
|
+
header = result.protectedHeader;
|
|
384
|
+
} catch (cause) {
|
|
385
|
+
throw new TokenError(
|
|
386
|
+
`The DPoP proof did not verify: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
387
|
+
"invalid_dpop_proof"
|
|
388
|
+
);
|
|
389
|
+
}
|
|
390
|
+
const presented = await thumbprintOf2(header.jwk);
|
|
391
|
+
if (presented !== bound) {
|
|
392
|
+
throw new TokenError(
|
|
393
|
+
"The DPoP proof was signed with a different key from the one this token is bound to.",
|
|
394
|
+
"dpop_key_mismatch"
|
|
395
|
+
);
|
|
396
|
+
}
|
|
397
|
+
const url = new URL(request.url);
|
|
398
|
+
url.search = "";
|
|
399
|
+
url.hash = "";
|
|
400
|
+
if (payload.htm !== request.method.toUpperCase()) {
|
|
401
|
+
throw new TokenError("The DPoP proof was made for a different method.", "invalid_dpop_proof");
|
|
402
|
+
}
|
|
403
|
+
if (payload.htu !== url.toString()) {
|
|
404
|
+
throw new TokenError("The DPoP proof was made for a different URL.", "invalid_dpop_proof");
|
|
405
|
+
}
|
|
406
|
+
if (typeof payload.ath === "string") {
|
|
407
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token));
|
|
408
|
+
let binary = "";
|
|
409
|
+
for (const byte of new Uint8Array(digest)) binary += String.fromCharCode(byte);
|
|
410
|
+
const expected = btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
411
|
+
if (payload.ath !== expected) {
|
|
412
|
+
throw new TokenError("The DPoP proof was made for a different token.", "invalid_dpop_proof");
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
const age = Math.abs(Date.now() / 1e3 - payload.iat);
|
|
416
|
+
if (!Number.isFinite(age) || age > (options.dpopProofAgeSec ?? 10)) {
|
|
417
|
+
throw new TokenError("The DPoP proof is too old to accept.", "invalid_dpop_proof");
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
const verify = async (token, request) => {
|
|
421
|
+
if (!token) throw new TokenError("No token to verify.", "no_token");
|
|
422
|
+
const jose = await loadJose3();
|
|
423
|
+
let payload;
|
|
424
|
+
try {
|
|
425
|
+
({ payload } = await jose.jwtVerify(token, await keySet(), {
|
|
426
|
+
// jose takes a list and accepts any of them, which is what a provider naming
|
|
427
|
+
// itself two ways needs.
|
|
428
|
+
issuer: issuers,
|
|
429
|
+
...options.audience === false ? {} : { audience: options.audience },
|
|
430
|
+
algorithms,
|
|
431
|
+
clockTolerance: options.clockToleranceSec ?? 5
|
|
432
|
+
}));
|
|
433
|
+
} catch (cause) {
|
|
434
|
+
throw new TokenError(
|
|
435
|
+
`The token was not accepted: ${cause instanceof Error ? cause.message : String(cause)}`
|
|
436
|
+
);
|
|
437
|
+
}
|
|
438
|
+
if (options.authorizedParty !== void 0) {
|
|
439
|
+
const allowed = Array.isArray(options.authorizedParty) ? options.authorizedParty : [options.authorizedParty];
|
|
440
|
+
const issuedTo = payload.azp ?? payload.client_id;
|
|
441
|
+
if (typeof issuedTo !== "string" || !allowed.includes(issuedTo)) {
|
|
442
|
+
throw new TokenError("The token was issued to a different client.", "invalid_azp");
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
if (options.dpop) {
|
|
446
|
+
if (!request) {
|
|
447
|
+
throw new Error(
|
|
448
|
+
"[fluixi/oauth2] `dpop: true` needs the request to read its proof. Use `verify.fromRequest(request)` rather than verifying a bare token."
|
|
449
|
+
);
|
|
450
|
+
}
|
|
451
|
+
await checkProof(payload, token, request);
|
|
452
|
+
}
|
|
453
|
+
if (options.require) {
|
|
454
|
+
const verdict = options.require(payload);
|
|
455
|
+
if (verdict !== true) {
|
|
456
|
+
throw new TokenError(
|
|
457
|
+
typeof verdict === "string" ? verdict : "The token did not meet this service's requirements.",
|
|
458
|
+
"insufficient_claims"
|
|
459
|
+
);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
return payload;
|
|
463
|
+
};
|
|
464
|
+
const verifier = verify;
|
|
465
|
+
verifier.bearerOf = bearerOf;
|
|
466
|
+
verifier.fromRequest = async (request) => {
|
|
467
|
+
const token = verifier.bearerOf(request);
|
|
468
|
+
if (!token) {
|
|
469
|
+
throw new TokenError("The request carried no bearer token.", "no_token");
|
|
470
|
+
}
|
|
471
|
+
return verify(token, request);
|
|
472
|
+
};
|
|
473
|
+
return verifier;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
// src/backchannel.ts
|
|
477
|
+
var LOGOUT_EVENT = "http://schemas.openid.net/event/backchannel-logout";
|
|
478
|
+
function memoryLogouts(ttlMs = 14 * 24 * 36e5) {
|
|
479
|
+
const sids = /* @__PURE__ */ new Map();
|
|
480
|
+
const subs = /* @__PURE__ */ new Map();
|
|
481
|
+
const prune = (now) => {
|
|
482
|
+
for (const map of [sids, subs]) for (const [key, at] of map) if (now - at > ttlMs) map.delete(key);
|
|
483
|
+
};
|
|
484
|
+
return {
|
|
485
|
+
add(entry) {
|
|
486
|
+
prune(Date.now());
|
|
487
|
+
if (entry.sid) sids.set(entry.sid, entry.at);
|
|
488
|
+
else if (entry.sub) subs.set(entry.sub, Math.max(entry.at, subs.get(entry.sub) ?? 0));
|
|
489
|
+
},
|
|
490
|
+
ended(session) {
|
|
491
|
+
if (session.sid && sids.has(session.sid)) return true;
|
|
492
|
+
const all = session.sub ? subs.get(session.sub) : void 0;
|
|
493
|
+
return all !== void 0 && session.since <= all;
|
|
494
|
+
}
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
function idTokenClaims(idToken) {
|
|
498
|
+
if (!idToken) return {};
|
|
499
|
+
try {
|
|
500
|
+
const part = idToken.split(".")[1] ?? "";
|
|
501
|
+
const json = atob(part.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(part.length / 4) * 4, "="));
|
|
502
|
+
const claims = JSON.parse(json);
|
|
503
|
+
return {
|
|
504
|
+
sid: typeof claims.sid === "string" ? claims.sid : void 0,
|
|
505
|
+
sub: typeof claims.sub === "string" ? claims.sub : void 0,
|
|
506
|
+
iat: typeof claims.iat === "number" ? claims.iat : void 0
|
|
507
|
+
};
|
|
508
|
+
} catch {
|
|
509
|
+
return {};
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
function headerOf(token) {
|
|
513
|
+
try {
|
|
514
|
+
const part = token.split(".")[0] ?? "";
|
|
515
|
+
return JSON.parse(atob(part.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(part.length / 4) * 4, "=")));
|
|
516
|
+
} catch {
|
|
517
|
+
return {};
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
function logoutTokenVerifier(options) {
|
|
521
|
+
const verify = createTokenVerifier({
|
|
522
|
+
issuer: options.issuer,
|
|
523
|
+
audience: options.clientId,
|
|
524
|
+
jwksUri: options.jwksUri,
|
|
525
|
+
jwks: options.jwks,
|
|
526
|
+
require: (claims) => {
|
|
527
|
+
const events = claims.events;
|
|
528
|
+
if (!events || typeof events !== "object" || !(LOGOUT_EVENT in events)) return "no logout event";
|
|
529
|
+
if ("nonce" in claims) return "a logout token has no nonce";
|
|
530
|
+
if (typeof claims.sid !== "string" && typeof claims.sub !== "string") return "names no session and no subject";
|
|
531
|
+
return true;
|
|
532
|
+
}
|
|
533
|
+
});
|
|
534
|
+
return async (token) => {
|
|
535
|
+
const typ = headerOf(token).typ;
|
|
536
|
+
if (typ !== void 0 && typ !== "logout+jwt") throw new Error("not a logout token");
|
|
537
|
+
const claims = await verify(token);
|
|
538
|
+
return {
|
|
539
|
+
sid: typeof claims.sid === "string" ? claims.sid : void 0,
|
|
540
|
+
sub: typeof claims.sub === "string" ? claims.sub : void 0,
|
|
541
|
+
at: (typeof claims.iat === "number" ? claims.iat : Math.floor(Date.now() / 1e3)) * 1e3
|
|
542
|
+
};
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
|
|
174
546
|
// src/pkce.ts
|
|
175
547
|
function base64url(bytes) {
|
|
176
548
|
let binary = "";
|
|
@@ -207,81 +579,100 @@ function expiryFrom(expiresIn, now = Date.now()) {
|
|
|
207
579
|
return Number.isFinite(seconds) && seconds > 0 ? now + seconds * 1e3 : void 0;
|
|
208
580
|
}
|
|
209
581
|
|
|
210
|
-
// src/
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
582
|
+
// src/server.ts
|
|
583
|
+
init_types();
|
|
584
|
+
init_dpop();
|
|
585
|
+
var import_app = require("@fluixi/start/app");
|
|
586
|
+
var RETRY_MARK = ".retry";
|
|
587
|
+
var PROMPTS = /* @__PURE__ */ new Set(["none", "login", "consent", "select_account", "create"]);
|
|
588
|
+
var DEFAULT_SCOPES = ["openid", "profile", "email"];
|
|
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"]);
|
|
590
|
+
var SILENT_REFUSALS = /* @__PURE__ */ new Set([
|
|
591
|
+
"login_required",
|
|
592
|
+
"consent_required",
|
|
593
|
+
"interaction_required",
|
|
594
|
+
"account_selection_required"
|
|
595
|
+
]);
|
|
596
|
+
function checkedCookie(config, sessionState) {
|
|
597
|
+
const name = `${config.cookieName ?? "fx_session"}_checked`;
|
|
598
|
+
const secure = config.secureCookie ?? true;
|
|
599
|
+
const maxAge = Math.max(0, Math.floor(config.silentRecheck ?? 60));
|
|
600
|
+
const value = sessionState ?? "1";
|
|
601
|
+
return { name, header: `${name}=${value}; Path=/; Max-Age=${maxAge}; HttpOnly; SameSite=Lax${secure ? "; Secure" : ""}` };
|
|
602
|
+
}
|
|
603
|
+
function sessionStateFrom(url) {
|
|
604
|
+
const value = url.searchParams.get("session_state");
|
|
605
|
+
return value && /^[\w-]{1,128}\.[\w-]{1,64}$/.test(value) ? value : void 0;
|
|
606
|
+
}
|
|
607
|
+
function isPageRequest(request) {
|
|
608
|
+
if (request.method !== "GET") return false;
|
|
609
|
+
const dest = request.headers.get("sec-fetch-dest");
|
|
610
|
+
if (dest) return dest === "document";
|
|
611
|
+
return (request.headers.get("accept") ?? "").includes("text/html");
|
|
612
|
+
}
|
|
613
|
+
function cookieValue(request, name) {
|
|
614
|
+
for (const part of (request.headers.get("cookie") ?? "").split(";")) {
|
|
615
|
+
const [key, ...rest] = part.trim().split("=");
|
|
616
|
+
if (key === name) return rest.join("=");
|
|
219
617
|
}
|
|
618
|
+
return void 0;
|
|
220
619
|
}
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
const { privateKey, publicKey } = await jose.generateKeyPair(alg, {
|
|
224
|
-
extractable: options.extractable ?? false
|
|
225
|
-
});
|
|
226
|
-
const publicJwk = { ...await jose.exportJWK(publicKey) };
|
|
227
|
-
return {
|
|
228
|
-
privateKey,
|
|
229
|
-
publicJwk,
|
|
230
|
-
thumbprint: await jose.calculateJwkThumbprint(publicJwk, "sha256"),
|
|
231
|
-
alg
|
|
232
|
-
};
|
|
620
|
+
function hasCookie(request, name) {
|
|
621
|
+
return cookieValue(request, name) !== void 0;
|
|
233
622
|
}
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
return { jwk: { ...await jose.exportJWK(key.privateKey) }, alg: key.alg };
|
|
623
|
+
function under(pathname, path) {
|
|
624
|
+
return pathname === path || pathname.startsWith(path.endsWith("/") ? path : `${path}/`);
|
|
237
625
|
}
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
const
|
|
241
|
-
const
|
|
242
|
-
const
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
};
|
|
626
|
+
function signInRedirect(request, config) {
|
|
627
|
+
if (!isPageRequest(request)) return null;
|
|
628
|
+
const url = new URL(request.url);
|
|
629
|
+
const base = (config.basePath ?? "/auth").replace(/\/$/, "");
|
|
630
|
+
const guarded = (config.protectedPaths ?? []).some((path) => under(url.pathname, path));
|
|
631
|
+
const mode = guarded ? "required" : config.signIn ?? "manual";
|
|
632
|
+
if (mode === "manual") return null;
|
|
633
|
+
if ([base, ...config.publicPaths ?? []].some((path) => under(url.pathname, path))) return null;
|
|
634
|
+
if (url.searchParams.has("auth_error")) return null;
|
|
635
|
+
if (mode === "silent" && hasCookie(request, checkedCookie(config).name)) return null;
|
|
636
|
+
const login = new URLSearchParams({ returnTo: url.pathname + url.search });
|
|
637
|
+
if (mode === "silent") login.set("prompt", "none");
|
|
638
|
+
return new Response(null, { status: 302, headers: { location: `${base}/login?${login}` } });
|
|
249
639
|
}
|
|
250
|
-
|
|
251
|
-
const
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
} catch {
|
|
259
|
-
return options.url;
|
|
260
|
-
}
|
|
261
|
-
})();
|
|
262
|
-
const claims = {
|
|
263
|
-
htm: options.method.toUpperCase(),
|
|
264
|
-
htu,
|
|
265
|
-
jti: crypto.randomUUID()
|
|
266
|
-
};
|
|
267
|
-
if (options.accessToken) {
|
|
268
|
-
const digest = await crypto.subtle.digest(
|
|
269
|
-
"SHA-256",
|
|
270
|
-
new TextEncoder().encode(options.accessToken)
|
|
271
|
-
);
|
|
272
|
-
let binary = "";
|
|
273
|
-
for (const byte of new Uint8Array(digest)) binary += String.fromCharCode(byte);
|
|
274
|
-
claims.ath = btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
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 {};
|
|
275
648
|
}
|
|
276
|
-
if (options.nonce) claims.nonce = options.nonce;
|
|
277
|
-
return new jose.SignJWT(claims).setProtectedHeader({ typ: "dpop+jwt", alg: key.alg, jwk: key.publicJwk }).setIssuedAt().sign(key.privateKey);
|
|
278
649
|
}
|
|
279
|
-
function
|
|
280
|
-
|
|
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 } });
|
|
281
675
|
}
|
|
282
|
-
|
|
283
|
-
// src/server.ts
|
|
284
|
-
var import_app = require("@fluixi/start/app");
|
|
285
676
|
var dpopNonces = /* @__PURE__ */ new Map();
|
|
286
677
|
async function prove(headers, key, method, url, accessToken) {
|
|
287
678
|
headers.dpop = await proofFor(key, { method, url, accessToken, nonce: dpopNonces.get(new URL(url).origin) });
|
|
@@ -294,27 +685,52 @@ function learnNonce(url, response) {
|
|
|
294
685
|
dpopNonces.set(origin, offered);
|
|
295
686
|
return fresh && !response.ok;
|
|
296
687
|
}
|
|
297
|
-
async function
|
|
688
|
+
async function sendAs(session, input, init = {}) {
|
|
689
|
+
const url = String(input);
|
|
690
|
+
const method = (init.method ?? "GET").toUpperCase();
|
|
298
691
|
const key = session.dpop && session.tokenType?.toLowerCase() === "dpop" ? await importDpopKey(session.dpop) : null;
|
|
299
692
|
const send = async () => {
|
|
300
|
-
const
|
|
693
|
+
const credentials = {
|
|
301
694
|
authorization: `${key ? "DPoP" : "Bearer"} ${session.accessToken}`
|
|
302
695
|
};
|
|
303
|
-
if (key) await prove(
|
|
304
|
-
|
|
696
|
+
if (key) await prove(credentials, key, method, url, session.accessToken);
|
|
697
|
+
const headers = new Headers(init.headers);
|
|
698
|
+
for (const [name, value] of Object.entries(credentials)) headers.set(name, value);
|
|
699
|
+
return fetch(url, { ...init, method, headers });
|
|
305
700
|
};
|
|
306
701
|
let response = await send();
|
|
307
702
|
if (key && learnNonce(url, response)) response = await send();
|
|
308
703
|
return response;
|
|
309
704
|
}
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
705
|
+
var withToken = (url, session) => sendAs(session, url);
|
|
706
|
+
var ProviderUnavailable = class extends OAuthError {
|
|
707
|
+
constructor(retryAfterMs) {
|
|
708
|
+
super("The authorization server is unavailable.", "temporarily_unavailable");
|
|
709
|
+
this.retryAfterMs = retryAfterMs;
|
|
710
|
+
}
|
|
711
|
+
};
|
|
712
|
+
var AnswerLost = class extends OAuthError {
|
|
713
|
+
constructor(what) {
|
|
714
|
+
super(`The token request's answer was lost (${what}).`, "answer_lost");
|
|
715
|
+
}
|
|
716
|
+
};
|
|
717
|
+
var NOT_SENT = /* @__PURE__ */ new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "ENETUNREACH", "EHOSTUNREACH", "UND_ERR_CONNECT_TIMEOUT"]);
|
|
718
|
+
var RETRY_DEFAULT_MS = 5e3;
|
|
719
|
+
var RETRY_MAX_MS = 3e5;
|
|
720
|
+
function retryAfter(response) {
|
|
721
|
+
const header = response.headers.get("retry-after");
|
|
722
|
+
if (!header) return RETRY_DEFAULT_MS;
|
|
723
|
+
const seconds = Number(header);
|
|
724
|
+
const ms = Number.isFinite(seconds) ? seconds * 1e3 : Date.parse(header) - Date.now();
|
|
725
|
+
return Number.isFinite(ms) ? Math.min(Math.max(ms, 1e3), RETRY_MAX_MS) : RETRY_DEFAULT_MS;
|
|
726
|
+
}
|
|
727
|
+
function unanswered(error) {
|
|
728
|
+
const code = error?.cause?.code;
|
|
729
|
+
if (code && NOT_SENT.has(code)) return new ProviderUnavailable(RETRY_DEFAULT_MS);
|
|
730
|
+
return new AnswerLost(code ?? (error instanceof Error ? error.name : "no answer"));
|
|
731
|
+
}
|
|
732
|
+
function tokenClient(config) {
|
|
733
|
+
const timeoutMs = config.tokenTimeoutMs ?? 1e4;
|
|
318
734
|
let endpoints = config.endpoints ?? null;
|
|
319
735
|
const resolve = async () => {
|
|
320
736
|
if (endpoints) return endpoints;
|
|
@@ -324,10 +740,6 @@ function oauthRoutes(config) {
|
|
|
324
740
|
endpoints = await discover(config.issuer);
|
|
325
741
|
return endpoints;
|
|
326
742
|
};
|
|
327
|
-
const json = (body, status = 200, headers = {}) => new Response(JSON.stringify(body), {
|
|
328
|
-
status,
|
|
329
|
-
headers: { "content-type": "application/json", ...headers }
|
|
330
|
-
});
|
|
331
743
|
const clientAuth = {
|
|
332
744
|
clientId: config.clientId,
|
|
333
745
|
// `client_secret_post` by default here, which is what this half has always sent, so
|
|
@@ -347,30 +759,146 @@ function oauthRoutes(config) {
|
|
|
347
759
|
const form = new URLSearchParams(body);
|
|
348
760
|
await applyClientAuth(clientAuth, token, headers, form);
|
|
349
761
|
if (key) await prove(headers, key, "POST", token);
|
|
350
|
-
return fetch(token, { method: "POST", headers, body: form.toString() });
|
|
762
|
+
return fetch(token, { method: "POST", headers, body: form.toString(), signal: AbortSignal.timeout(timeoutMs) });
|
|
351
763
|
};
|
|
352
|
-
let response
|
|
353
|
-
|
|
354
|
-
|
|
764
|
+
let response;
|
|
765
|
+
let payload = null;
|
|
766
|
+
try {
|
|
767
|
+
response = await attempt();
|
|
768
|
+
if (key && learnNonce(token, response)) response = await attempt();
|
|
769
|
+
if (response.status === 429 || response.status >= 500) throw new ProviderUnavailable(retryAfter(response));
|
|
770
|
+
payload = await response.json().catch(() => null);
|
|
771
|
+
} catch (error) {
|
|
772
|
+
throw error instanceof OAuthError ? error : unanswered(error);
|
|
773
|
+
}
|
|
355
774
|
if (!response.ok) {
|
|
356
775
|
throw new OAuthError(
|
|
357
|
-
String(payload
|
|
358
|
-
String(payload
|
|
776
|
+
String(payload?.error ?? "token_request_failed"),
|
|
777
|
+
String(payload?.error ?? "token_request_failed")
|
|
359
778
|
);
|
|
360
779
|
}
|
|
780
|
+
if (typeof payload?.access_token !== "string" || !payload.access_token) {
|
|
781
|
+
throw new AnswerLost("a success without an access token");
|
|
782
|
+
}
|
|
361
783
|
return payload;
|
|
362
784
|
}
|
|
785
|
+
return { resolve, tokenRequest, clientAuth };
|
|
786
|
+
}
|
|
787
|
+
var renewals = /* @__PURE__ */ new Map();
|
|
788
|
+
var RENEWAL_REUSE_MS = 3e4;
|
|
789
|
+
var SPENT_MS = 5 * 6e4;
|
|
790
|
+
function renew(current, tokenRequest) {
|
|
791
|
+
const refreshToken = current.refreshToken;
|
|
792
|
+
const now = Date.now();
|
|
793
|
+
for (const [key, entry] of renewals) if (entry.until <= now) renewals.delete(key);
|
|
794
|
+
const known = renewals.get(refreshToken);
|
|
795
|
+
if (known) return known.result;
|
|
796
|
+
const result = (async () => {
|
|
797
|
+
const key = current.dpop ? await importDpopKey(current.dpop) : null;
|
|
798
|
+
const payload = await tokenRequest({ grant_type: "refresh_token", refresh_token: refreshToken }, key);
|
|
799
|
+
return {
|
|
800
|
+
accessToken: String(payload.access_token ?? ""),
|
|
801
|
+
// A provider that rotates refresh tokens sends a new one; one that does not
|
|
802
|
+
// expects the old one to keep working.
|
|
803
|
+
refreshToken: typeof payload.refresh_token === "string" ? payload.refresh_token : refreshToken,
|
|
804
|
+
idToken: typeof payload.id_token === "string" ? payload.id_token : current.idToken,
|
|
805
|
+
expiresAt: expiryFrom(payload.expires_in),
|
|
806
|
+
tokenType: typeof payload.token_type === "string" ? payload.token_type : current.tokenType,
|
|
807
|
+
dpop: current.dpop,
|
|
808
|
+
sessionState: current.sessionState,
|
|
809
|
+
scope: typeof payload.scope === "string" ? payload.scope : current.scope
|
|
810
|
+
};
|
|
811
|
+
})().catch((error) => {
|
|
812
|
+
if (error instanceof ProviderUnavailable) {
|
|
813
|
+
renewals.set(refreshToken, { until: Date.now() + error.retryAfterMs, result });
|
|
814
|
+
throw error;
|
|
815
|
+
}
|
|
816
|
+
if (error instanceof OAuthError) {
|
|
817
|
+
renewals.set(refreshToken, { until: Date.now() + SPENT_MS, result });
|
|
818
|
+
return null;
|
|
819
|
+
}
|
|
820
|
+
renewals.delete(refreshToken);
|
|
821
|
+
throw error;
|
|
822
|
+
});
|
|
823
|
+
renewals.set(refreshToken, { until: now + RENEWAL_REUSE_MS, result });
|
|
824
|
+
return result;
|
|
825
|
+
}
|
|
826
|
+
var EXPIRY_SKEW_MS = 3e4;
|
|
827
|
+
var expired = (session) => session.expiresAt !== void 0 && session.expiresAt - EXPIRY_SKEW_MS <= Date.now();
|
|
828
|
+
var defaultLogouts = /* @__PURE__ */ new WeakMap();
|
|
829
|
+
function logoutsOf(config) {
|
|
830
|
+
if (config.logouts) return config.logouts;
|
|
831
|
+
let store = defaultLogouts.get(config);
|
|
832
|
+
if (!store) defaultLogouts.set(config, store = memoryLogouts());
|
|
833
|
+
return store;
|
|
834
|
+
}
|
|
835
|
+
async function endedAtProvider(config, session) {
|
|
836
|
+
const id = idTokenClaims(session.idToken);
|
|
837
|
+
if (!id.sid && !id.sub) return false;
|
|
838
|
+
return logoutsOf(config).ended({ sid: id.sid, sub: id.sub, since: (id.iat ?? 0) * 1e3 });
|
|
839
|
+
}
|
|
840
|
+
function oauthRoutes(config) {
|
|
841
|
+
for (const name of config.authorizeParams ?? []) {
|
|
842
|
+
if (CLIENT_PARAMS.has(name)) throw new Error(`authorizeParams cannot include "${name}": the login route sets it.`);
|
|
843
|
+
}
|
|
844
|
+
const { resolve, tokenRequest, clientAuth } = tokenClient(config);
|
|
845
|
+
const json = (body, status = 200, headers = {}) => new Response(JSON.stringify(body), {
|
|
846
|
+
status,
|
|
847
|
+
headers: { "content-type": "application/json", ...headers }
|
|
848
|
+
});
|
|
849
|
+
const base = (config.basePath ?? "/auth").replace(/\/$/, "");
|
|
850
|
+
const scopes = config.scopes ?? DEFAULT_SCOPES;
|
|
851
|
+
const cookie = (0, import_server.createSessionCookie)({
|
|
852
|
+
secret: config.cookieSecret,
|
|
853
|
+
name: config.cookieName,
|
|
854
|
+
secure: config.secureCookie
|
|
855
|
+
});
|
|
363
856
|
return async function middleware(request, next) {
|
|
364
857
|
const url = new URL(request.url);
|
|
365
858
|
if (!url.pathname.startsWith(`${base}/`)) return next();
|
|
366
859
|
const route = url.pathname.slice(base.length);
|
|
367
860
|
const session = async () => {
|
|
368
|
-
|
|
861
|
+
const current = await cookie.read(request);
|
|
862
|
+
return current && await endedAtProvider(config, current) ? null : current;
|
|
369
863
|
};
|
|
864
|
+
if (route === "/backchannel-logout") {
|
|
865
|
+
const headers = { "cache-control": "no-store" };
|
|
866
|
+
if (request.method !== "POST") return json({ error: "invalid_request" }, 405, headers);
|
|
867
|
+
try {
|
|
868
|
+
const form = await request.formData();
|
|
869
|
+
const token = form.get("logout_token");
|
|
870
|
+
if (typeof token !== "string" || !token) throw new Error("no logout_token");
|
|
871
|
+
const endpoints = await resolve();
|
|
872
|
+
const issuer = endpoints.issuer ?? config.issuer;
|
|
873
|
+
if (!issuer) throw new Error("no issuer");
|
|
874
|
+
if (!endpoints.jwks) throw new Error("no jwks_uri");
|
|
875
|
+
const jwks = await (await fetch(endpoints.jwks)).json();
|
|
876
|
+
const entry = await logoutTokenVerifier({ issuer, clientId: config.clientId, jwks })(token);
|
|
877
|
+
await logoutsOf(config).add(entry);
|
|
878
|
+
return new Response(null, { status: 200, headers });
|
|
879
|
+
} catch {
|
|
880
|
+
return json({ error: "invalid_request" }, 400, headers);
|
|
881
|
+
}
|
|
882
|
+
}
|
|
370
883
|
if (route === "/login") {
|
|
371
|
-
|
|
884
|
+
let authorization;
|
|
885
|
+
try {
|
|
886
|
+
({ authorization } = await resolve());
|
|
887
|
+
} catch (error) {
|
|
888
|
+
if (!(error instanceof OAuthError) || error.code !== "discovery_unreachable") throw error;
|
|
889
|
+
const back = safeReturnTo(url.searchParams.get("returnTo"), {
|
|
890
|
+
fallback: config.defaultReturnTo ?? "/",
|
|
891
|
+
origin: url.origin,
|
|
892
|
+
allowedOrigins: config.allowedReturnOrigins
|
|
893
|
+
});
|
|
894
|
+
const target2 = new URL(back, url.origin);
|
|
895
|
+
target2.searchParams.set("auth_error", "provider_unreachable");
|
|
896
|
+
const location2 = target2.origin === url.origin ? target2.pathname + target2.search : target2.toString();
|
|
897
|
+
return new Response(null, { status: 302, headers: { location: location2 } });
|
|
898
|
+
}
|
|
372
899
|
const { verifier, challenge } = await createPkcePair();
|
|
373
|
-
const
|
|
900
|
+
const retry = url.searchParams.get("retry") === "1";
|
|
901
|
+
const state = createStateValue() + (retry ? RETRY_MARK : "");
|
|
374
902
|
const target = new URL(authorization);
|
|
375
903
|
target.searchParams.set("response_type", "code");
|
|
376
904
|
target.searchParams.set("client_id", config.clientId);
|
|
@@ -379,9 +907,16 @@ function oauthRoutes(config) {
|
|
|
379
907
|
target.searchParams.set("state", state);
|
|
380
908
|
target.searchParams.set("code_challenge", challenge);
|
|
381
909
|
target.searchParams.set("code_challenge_method", "S256");
|
|
910
|
+
const prompt = url.searchParams.get("prompt");
|
|
911
|
+
if (prompt && PROMPTS.has(prompt)) target.searchParams.set("prompt", prompt);
|
|
912
|
+
for (const name of config.authorizeParams ?? []) {
|
|
913
|
+
const value = url.searchParams.get(name);
|
|
914
|
+
if (value) target.searchParams.set(name, value);
|
|
915
|
+
}
|
|
916
|
+
const kept = prompt === "none" ? await session() : null;
|
|
382
917
|
const pendingCookie = await cookie.write(
|
|
383
918
|
{
|
|
384
|
-
accessToken: "",
|
|
919
|
+
...kept?.accessToken ? { ...kept, pending: void 0 } : { accessToken: "" },
|
|
385
920
|
pending: {
|
|
386
921
|
verifier,
|
|
387
922
|
state,
|
|
@@ -391,12 +926,13 @@ function oauthRoutes(config) {
|
|
|
391
926
|
fallback: "",
|
|
392
927
|
origin: url.origin,
|
|
393
928
|
allowedOrigins: config.allowedReturnOrigins
|
|
394
|
-
}) || void 0
|
|
929
|
+
}) || void 0,
|
|
930
|
+
silent: prompt === "none" || void 0
|
|
395
931
|
}
|
|
396
932
|
},
|
|
397
933
|
// Ten minutes: long enough to sign in, short enough that an abandoned attempt
|
|
398
|
-
// does not sit in the browser.
|
|
399
|
-
{ maxAge: 600 }
|
|
934
|
+
// does not sit in the browser. A kept session keeps its own lifetime.
|
|
935
|
+
kept?.accessToken ? void 0 : { maxAge: 600 }
|
|
400
936
|
);
|
|
401
937
|
return new Response(null, {
|
|
402
938
|
status: 302,
|
|
@@ -410,30 +946,88 @@ function oauthRoutes(config) {
|
|
|
410
946
|
const current = await session();
|
|
411
947
|
const pending = current?.pending;
|
|
412
948
|
const error = url.searchParams.get("error");
|
|
413
|
-
if (error)
|
|
949
|
+
if (error) {
|
|
950
|
+
const ours = !!pending && timingSafeEqual(pending.state, url.searchParams.get("state") ?? "");
|
|
951
|
+
let location2 = safeReturnTo(ours ? pending.returnTo ?? config.defaultReturnTo : config.defaultReturnTo, {
|
|
952
|
+
fallback: "/",
|
|
953
|
+
origin: url.origin,
|
|
954
|
+
allowedOrigins: config.allowedReturnOrigins
|
|
955
|
+
});
|
|
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
|
+
}
|
|
962
|
+
headers.append("set-cookie", cookie.clear());
|
|
963
|
+
if (ours && pending.silent && SILENT_REFUSALS.has(error)) {
|
|
964
|
+
headers.append("set-cookie", checkedCookie(config, sessionStateFrom(url)).header);
|
|
965
|
+
} else {
|
|
966
|
+
const target = new URL(location2, url.origin);
|
|
967
|
+
target.searchParams.set("auth_error", error);
|
|
968
|
+
location2 = target.origin === url.origin ? target.pathname + target.search : target.toString();
|
|
969
|
+
}
|
|
970
|
+
headers.set("location", location2);
|
|
971
|
+
return new Response(null, { status: 302, headers });
|
|
972
|
+
}
|
|
414
973
|
const code = url.searchParams.get("code");
|
|
415
974
|
const state = url.searchParams.get("state");
|
|
416
975
|
if (!code) return json({ error: "no_code" }, 400);
|
|
417
976
|
if (!pending || !state || !timingSafeEqual(pending.state, state)) {
|
|
418
|
-
|
|
977
|
+
const home = safeReturnTo(config.defaultReturnTo, { fallback: "/", origin: url.origin, allowedOrigins: config.allowedReturnOrigins });
|
|
978
|
+
if (current?.accessToken) return new Response(null, { status: 302, headers: { location: home } });
|
|
979
|
+
if (!state?.endsWith(RETRY_MARK)) {
|
|
980
|
+
return new Response(null, { status: 302, headers: { location: `${base}/login?retry=1` } });
|
|
981
|
+
}
|
|
982
|
+
const target = new URL(home, url.origin);
|
|
983
|
+
target.searchParams.set("auth_error", "state_mismatch");
|
|
984
|
+
return new Response(null, {
|
|
985
|
+
status: 302,
|
|
986
|
+
headers: {
|
|
987
|
+
location: target.origin === url.origin ? target.pathname + target.search : target.toString(),
|
|
988
|
+
"set-cookie": cookie.clear()
|
|
989
|
+
}
|
|
990
|
+
});
|
|
419
991
|
}
|
|
420
992
|
const key = config.dpop ? await createDpopKey(config.dpopAlgorithm, { extractable: true }) : null;
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
993
|
+
let payload;
|
|
994
|
+
try {
|
|
995
|
+
payload = await tokenRequest(
|
|
996
|
+
{
|
|
997
|
+
grant_type: "authorization_code",
|
|
998
|
+
code,
|
|
999
|
+
redirect_uri: config.redirectUri,
|
|
1000
|
+
code_verifier: pending.verifier
|
|
1001
|
+
},
|
|
1002
|
+
key
|
|
1003
|
+
);
|
|
1004
|
+
} catch (error2) {
|
|
1005
|
+
if (!(error2 instanceof OAuthError)) throw error2;
|
|
1006
|
+
const unreachable = error2.code === "temporarily_unavailable" || error2.code === "answer_lost";
|
|
1007
|
+
const back = safeReturnTo(pending.returnTo ?? config.defaultReturnTo, {
|
|
1008
|
+
fallback: "/",
|
|
1009
|
+
origin: url.origin,
|
|
1010
|
+
allowedOrigins: config.allowedReturnOrigins
|
|
1011
|
+
});
|
|
1012
|
+
const target = new URL(back, url.origin);
|
|
1013
|
+
target.searchParams.set("auth_error", unreachable ? "provider_unreachable" : error2.code);
|
|
1014
|
+
return new Response(null, {
|
|
1015
|
+
status: 302,
|
|
1016
|
+
headers: {
|
|
1017
|
+
location: target.origin === url.origin ? target.pathname + target.search : target.toString(),
|
|
1018
|
+
"set-cookie": cookie.clear()
|
|
1019
|
+
}
|
|
1020
|
+
});
|
|
1021
|
+
}
|
|
430
1022
|
const signedIn = await cookie.write({
|
|
431
1023
|
accessToken: String(payload.access_token ?? ""),
|
|
432
1024
|
refreshToken: typeof payload.refresh_token === "string" ? payload.refresh_token : void 0,
|
|
433
1025
|
idToken: typeof payload.id_token === "string" ? payload.id_token : void 0,
|
|
434
1026
|
expiresAt: expiryFrom(payload.expires_in),
|
|
435
1027
|
tokenType: typeof payload.token_type === "string" ? payload.token_type : void 0,
|
|
436
|
-
dpop: key ? await exportDpopKey(key) : void 0
|
|
1028
|
+
dpop: key ? await exportDpopKey(key) : void 0,
|
|
1029
|
+
sessionState: sessionStateFrom(url),
|
|
1030
|
+
scope: typeof payload.scope === "string" ? payload.scope : void 0
|
|
437
1031
|
});
|
|
438
1032
|
return new Response(null, {
|
|
439
1033
|
status: 302,
|
|
@@ -453,22 +1047,9 @@ function oauthRoutes(config) {
|
|
|
453
1047
|
if (route === "/refresh") {
|
|
454
1048
|
const current = await session();
|
|
455
1049
|
if (!current?.refreshToken) return json({ error: "no_session" }, 401);
|
|
456
|
-
const
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
key
|
|
460
|
-
);
|
|
461
|
-
const refreshed = await cookie.write({
|
|
462
|
-
accessToken: String(payload.access_token ?? ""),
|
|
463
|
-
// A provider that rotates refresh tokens sends a new one; one that does not
|
|
464
|
-
// expects the old one to keep working.
|
|
465
|
-
refreshToken: typeof payload.refresh_token === "string" ? payload.refresh_token : current.refreshToken,
|
|
466
|
-
idToken: current.idToken,
|
|
467
|
-
expiresAt: expiryFrom(payload.expires_in),
|
|
468
|
-
tokenType: typeof payload.token_type === "string" ? payload.token_type : current.tokenType,
|
|
469
|
-
dpop: current.dpop
|
|
470
|
-
});
|
|
471
|
-
return json({ ok: true }, 200, { "set-cookie": refreshed });
|
|
1050
|
+
const renewed = await renew(current, tokenRequest);
|
|
1051
|
+
if (!renewed) return json({ error: "refresh_refused" }, 401, { "set-cookie": cookie.clear() });
|
|
1052
|
+
return json({ ok: true }, 200, { "set-cookie": await cookie.write(renewed) });
|
|
472
1053
|
}
|
|
473
1054
|
if (route === "/me") {
|
|
474
1055
|
const current = await session();
|
|
@@ -480,6 +1061,13 @@ function oauthRoutes(config) {
|
|
|
480
1061
|
const claims = await response.json();
|
|
481
1062
|
return json(config.mapUser ? config.mapUser(claims, current.accessToken) : claims);
|
|
482
1063
|
}
|
|
1064
|
+
if (route === "/session-check") {
|
|
1065
|
+
const { checkSession } = await resolve().catch(() => ({ checkSession: void 0 }));
|
|
1066
|
+
const current = await session();
|
|
1067
|
+
const checked = cookieValue(request, checkedCookie(config).name);
|
|
1068
|
+
const state = current?.accessToken ? current.sessionState : checked !== "1" ? checked : void 0;
|
|
1069
|
+
return json({ frame: checkSession ?? null, clientId: config.clientId, state: state ?? null });
|
|
1070
|
+
}
|
|
483
1071
|
if (route === "/revoke") {
|
|
484
1072
|
const current = await session();
|
|
485
1073
|
const hint = url.searchParams.get("hint") === "access_token" ? "access_token" : "refresh_token";
|
|
@@ -502,31 +1090,33 @@ function oauthRoutes(config) {
|
|
|
502
1090
|
const { endSession } = await resolve().catch(() => ({ endSession: void 0 }));
|
|
503
1091
|
const { revocation } = await resolve().catch(() => ({ revocation: void 0 }));
|
|
504
1092
|
if (revocation && current?.refreshToken) {
|
|
505
|
-
const
|
|
1093
|
+
const headers2 = {
|
|
506
1094
|
"content-type": "application/x-www-form-urlencoded"
|
|
507
1095
|
};
|
|
508
1096
|
const form = new URLSearchParams({
|
|
509
1097
|
token: current.refreshToken,
|
|
510
1098
|
token_type_hint: "refresh_token"
|
|
511
1099
|
});
|
|
512
|
-
await applyClientAuth(clientAuth, revocation,
|
|
513
|
-
await fetch(revocation, { method: "POST", headers, body: form.toString() }).catch(
|
|
1100
|
+
await applyClientAuth(clientAuth, revocation, headers2, form);
|
|
1101
|
+
await fetch(revocation, { method: "POST", headers: headers2, body: form.toString() }).catch(
|
|
514
1102
|
() => void 0
|
|
515
1103
|
);
|
|
516
1104
|
}
|
|
517
1105
|
const cleared = cookie.clear();
|
|
1106
|
+
const headers = new Headers();
|
|
1107
|
+
headers.append("set-cookie", cleared);
|
|
1108
|
+
headers.append("set-cookie", checkedCookie(config).header);
|
|
518
1109
|
if (endSession && current?.idToken) {
|
|
519
1110
|
const target = new URL(endSession);
|
|
520
1111
|
target.searchParams.set("id_token_hint", current.idToken);
|
|
521
1112
|
if (config.defaultReturnTo) {
|
|
522
1113
|
target.searchParams.set("post_logout_redirect_uri", config.defaultReturnTo);
|
|
523
1114
|
}
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
headers: { location: target.toString(), "set-cookie": cleared }
|
|
527
|
-
});
|
|
1115
|
+
headers.set("location", target.toString());
|
|
1116
|
+
return new Response(null, { status: 302, headers });
|
|
528
1117
|
}
|
|
529
|
-
|
|
1118
|
+
headers.set("content-type", "application/json");
|
|
1119
|
+
return new Response(JSON.stringify({ ok: true }), { status: 200, headers });
|
|
530
1120
|
}
|
|
531
1121
|
return next();
|
|
532
1122
|
};
|
|
@@ -537,6 +1127,7 @@ function sessionLocals(config) {
|
|
|
537
1127
|
name: config.cookieName,
|
|
538
1128
|
secure: config.secureCookie
|
|
539
1129
|
});
|
|
1130
|
+
const { tokenRequest } = tokenClient(config);
|
|
540
1131
|
const ttl = config.userCacheMs ?? 3e4;
|
|
541
1132
|
const cache2 = /* @__PURE__ */ new Map();
|
|
542
1133
|
const remember = (token, user) => {
|
|
@@ -551,21 +1142,63 @@ function sessionLocals(config) {
|
|
|
551
1142
|
return async function middleware(request, next) {
|
|
552
1143
|
const { getRequestLocals } = await import("@fluixi/server");
|
|
553
1144
|
const locals = getRequestLocals(request);
|
|
554
|
-
|
|
555
|
-
|
|
1145
|
+
let session = await cookie.read(request);
|
|
1146
|
+
let setCookie;
|
|
1147
|
+
const respond = async (response) => {
|
|
1148
|
+
if (!setCookie) return response;
|
|
1149
|
+
const copy = new Response(response.body, response);
|
|
1150
|
+
copy.headers.append("set-cookie", setCookie);
|
|
1151
|
+
return copy;
|
|
1152
|
+
};
|
|
1153
|
+
const renewOrDrop = async (current2) => {
|
|
1154
|
+
const renewed = current2.refreshToken ? await renew(current2, tokenRequest) : null;
|
|
1155
|
+
setCookie = renewed ? await cookie.write(renewed) : cookie.clear();
|
|
1156
|
+
return renewed;
|
|
1157
|
+
};
|
|
1158
|
+
let paused = false;
|
|
1159
|
+
const keep = (current2) => (error) => {
|
|
1160
|
+
if (error instanceof ProviderUnavailable) paused = true;
|
|
1161
|
+
return current2;
|
|
1162
|
+
};
|
|
1163
|
+
if (session?.accessToken && expired(session)) {
|
|
1164
|
+
session = await renewOrDrop(session).catch(keep(session));
|
|
1165
|
+
}
|
|
1166
|
+
const signedOut = async () => {
|
|
1167
|
+
const redirect = signInRedirect(request, config);
|
|
1168
|
+
if (redirect) return respond(redirect);
|
|
556
1169
|
locals.auth = { user: null, session: null };
|
|
557
|
-
return next();
|
|
1170
|
+
return respond(await next());
|
|
1171
|
+
};
|
|
1172
|
+
if (!session?.accessToken) return signedOut();
|
|
1173
|
+
if (await endedAtProvider(config, session)) {
|
|
1174
|
+
setCookie = cookie.clear();
|
|
1175
|
+
session = null;
|
|
1176
|
+
return signedOut();
|
|
558
1177
|
}
|
|
559
|
-
const
|
|
1178
|
+
const rescope = rescopeRedirect(request, config, session);
|
|
1179
|
+
if (rescope) return respond(rescope);
|
|
1180
|
+
const live = session;
|
|
1181
|
+
const fetchAs = (input, init) => sendAs(live, input, init);
|
|
1182
|
+
const cached = cache2.get(live.accessToken);
|
|
560
1183
|
if (cached && cached.until > Date.now()) {
|
|
561
|
-
locals.auth = { user: cached.user, session: { expiresAt:
|
|
562
|
-
return next();
|
|
1184
|
+
locals.auth = { user: cached.user, session: { expiresAt: live.expiresAt }, fetch: fetchAs };
|
|
1185
|
+
return respond(await next());
|
|
563
1186
|
}
|
|
564
1187
|
let user = null;
|
|
1188
|
+
let unreachable = false;
|
|
565
1189
|
try {
|
|
566
1190
|
const endpoints = config.endpoints ?? (config.issuer ? await discover(config.issuer) : null);
|
|
567
1191
|
if (endpoints?.userinfo) {
|
|
568
|
-
|
|
1192
|
+
let response = await withToken(endpoints.userinfo, session);
|
|
1193
|
+
if (response.status === 401 && !setCookie && !paused) {
|
|
1194
|
+
session = await renewOrDrop(session).catch(keep(session));
|
|
1195
|
+
if (!session) return signedOut();
|
|
1196
|
+
response = await withToken(endpoints.userinfo, session);
|
|
1197
|
+
}
|
|
1198
|
+
if (response.status === 401) {
|
|
1199
|
+
if (!paused) setCookie = cookie.clear();
|
|
1200
|
+
return signedOut();
|
|
1201
|
+
}
|
|
569
1202
|
if (response.ok) {
|
|
570
1203
|
const claims = await response.json();
|
|
571
1204
|
user = config.mapUser ? config.mapUser(claims, session.accessToken) : claims;
|
|
@@ -573,11 +1206,20 @@ function sessionLocals(config) {
|
|
|
573
1206
|
}
|
|
574
1207
|
}
|
|
575
1208
|
} catch {
|
|
1209
|
+
unreachable = true;
|
|
576
1210
|
}
|
|
577
|
-
|
|
578
|
-
|
|
1211
|
+
if (!session) return signedOut();
|
|
1212
|
+
const current = session;
|
|
1213
|
+
const fetchCurrent = (input, init) => sendAs(current, input, init);
|
|
1214
|
+
locals.auth = user ? { user, session: { expiresAt: current.expiresAt }, fetch: fetchCurrent } : { user: null, session: null, ...unreachable ? { unreachable: true } : {} };
|
|
1215
|
+
return respond(await next());
|
|
579
1216
|
};
|
|
580
1217
|
}
|
|
1218
|
+
async function requestAuth(request) {
|
|
1219
|
+
const { getLocals, getRequestLocals } = await import("@fluixi/server");
|
|
1220
|
+
const locals = request ? getRequestLocals(request) : getLocals();
|
|
1221
|
+
return locals.auth ?? { user: null, session: null };
|
|
1222
|
+
}
|
|
581
1223
|
function authServerModule(config) {
|
|
582
1224
|
return (0, import_app.defineModule)({ name: "oauth2-server", middleware: [oauthRoutes(config), sessionLocals(config)] });
|
|
583
1225
|
}
|