@eminuckan/spine 0.2.1 → 0.2.4

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 (81) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +45 -6
  3. package/dist/access/evaluator.d.ts +3 -0
  4. package/dist/access/evaluator.d.ts.map +1 -0
  5. package/dist/access/index.d.ts +3 -0
  6. package/dist/access/index.d.ts.map +1 -0
  7. package/dist/access/index.js +4 -0
  8. package/dist/access/types.d.ts +30 -0
  9. package/dist/access/types.d.ts.map +1 -0
  10. package/dist/access-DlAqsVGQ.js +59 -0
  11. package/dist/access-DlAqsVGQ.js.map +1 -0
  12. package/dist/api-client/index.js +2 -2
  13. package/dist/api-client/server.js +3 -3
  14. package/dist/{api-client-DsrxK05Z.js → api-client-CZapXIF8.js} +1 -1
  15. package/dist/{api-client-DsrxK05Z.js.map → api-client-CZapXIF8.js.map} +1 -1
  16. package/dist/auth/auth.server.d.ts +21 -16
  17. package/dist/auth/auth.server.d.ts.map +1 -1
  18. package/dist/auth/index.d.ts +1 -1
  19. package/dist/auth/index.d.ts.map +1 -1
  20. package/dist/auth/redis-session-storage.server.d.ts +18 -1
  21. package/dist/auth/redis-session-storage.server.d.ts.map +1 -1
  22. package/dist/auth/route-protection.server.d.ts.map +1 -1
  23. package/dist/auth/server.d.ts +1 -1
  24. package/dist/auth/server.d.ts.map +1 -1
  25. package/dist/auth/server.js +4 -4
  26. package/dist/auth/types.d.ts +65 -20
  27. package/dist/auth/types.d.ts.map +1 -1
  28. package/dist/auth.server-B3ODGIX4.js +1057 -0
  29. package/dist/auth.server-B3ODGIX4.js.map +1 -0
  30. package/dist/auth.server-wdKsjQsn.js +5 -0
  31. package/dist/identity/index.js +1 -1
  32. package/dist/identity/server.js +2 -2
  33. package/dist/{identity-CFa1txoj.js → identity-yT2ijZF0.js} +1 -1
  34. package/dist/{identity-CFa1txoj.js.map → identity-yT2ijZF0.js.map} +1 -1
  35. package/dist/index.d.ts +1 -0
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +11 -9
  38. package/dist/permission-service-CvGpwI0d.js +95 -0
  39. package/dist/permission-service-CvGpwI0d.js.map +1 -0
  40. package/dist/permissions/index.js +2 -1
  41. package/dist/{permissions-D5ScGGnd.js → permissions-OUK8Eql2.js} +3 -95
  42. package/dist/permissions-OUK8Eql2.js.map +1 -0
  43. package/dist/query-client/index.js +1 -1
  44. package/dist/{query-client-Bpe08pk9.js → query-client-Bh3TyB8W.js} +2 -2
  45. package/dist/query-client-Bh3TyB8W.js.map +1 -0
  46. package/dist/react-router/index.js +11 -9
  47. package/dist/react-router/server.js +18 -16
  48. package/dist/redis-session-storage.server-D0-72FV-.js +500 -0
  49. package/dist/redis-session-storage.server-D0-72FV-.js.map +1 -0
  50. package/dist/{server-BHfKHKF_.js → server-B7JN86_0.js} +13 -9
  51. package/dist/server-B7JN86_0.js.map +1 -0
  52. package/dist/{server-C3L8J7iE.js → server-BmiuV28c.js} +2 -2
  53. package/dist/{server-C3L8J7iE.js.map → server-BmiuV28c.js.map} +1 -1
  54. package/dist/{server-BxvRxjCK.js → server-Ce9jQRdL.js} +2 -2
  55. package/dist/{server-BxvRxjCK.js.map → server-Ce9jQRdL.js.map} +1 -1
  56. package/dist/{server-DZmcd2Lr.js → server-DeBlxoaW.js} +3 -3
  57. package/dist/{server-DZmcd2Lr.js.map → server-DeBlxoaW.js.map} +1 -1
  58. package/dist/{server-CouYoZiw.js → server-hGrElJMG.js} +2 -2
  59. package/dist/{server-CouYoZiw.js.map → server-hGrElJMG.js.map} +1 -1
  60. package/dist/server.js +18 -16
  61. package/dist/signalr/index.js +1 -1
  62. package/dist/{signalr-SJ-1sIxw.js → signalr-CSfCz1Ik.js} +1 -1
  63. package/dist/{signalr-SJ-1sIxw.js.map → signalr-CSfCz1Ik.js.map} +1 -1
  64. package/dist/tenant/index.js +1 -1
  65. package/dist/tenant/server.js +2 -2
  66. package/dist/{tenant-C6KPaSCX.js → tenant-BErqEENp.js} +1 -1
  67. package/dist/{tenant-C6KPaSCX.js.map → tenant-BErqEENp.js.map} +1 -1
  68. package/dist/{types-BnKaWdfe.js → types-BaaE6wjY.js} +1 -1
  69. package/dist/{types-BnKaWdfe.js.map → types-BaaE6wjY.js.map} +1 -1
  70. package/package.json +7 -6
  71. package/dist/auth.server-BPiCtlJE.js +0 -5
  72. package/dist/auth.server-Cx2h2qu3.js +0 -724
  73. package/dist/auth.server-Cx2h2qu3.js.map +0 -1
  74. package/dist/permissions-D5ScGGnd.js.map +0 -1
  75. package/dist/query-client-Bpe08pk9.js.map +0 -1
  76. package/dist/redis-session-storage.server-BR_0y-QO.js +0 -250
  77. package/dist/redis-session-storage.server-BR_0y-QO.js.map +0 -1
  78. package/dist/server-BHfKHKF_.js.map +0 -1
  79. package/dist/utils.d.ts +0 -6
  80. package/dist/utils.d.ts.map +0 -1
  81. /package/dist/{src-CJ2RLi94.js → src-B9rDUgSb.js} +0 -0
@@ -0,0 +1,1057 @@
1
+ import { logger } from "./logging-_h2mi3L9.js";
2
+ import { AUTH_ERROR_COOKIE_PREFIX, createAuthSession, createOAuthState, deleteOAuthState, destroyAuthSession, destroyAuthSessionsByIdentitySession, destroyAuthSessionsBySid, destroyAuthSessionsForUser, getAuthSession, getOAuthState, listAuthSessionDataForUser, updateAuthSession } from "./redis-session-storage.server-D0-72FV-.js";
3
+ import * as oidc from "openid-client";
4
+ import { createRemoteJWKSet, jwtVerify } from "jose";
5
+
6
+ //#region src/http/response.ts
7
+ /**
8
+ * Create a redirect response without relying on a router/framework helper.
9
+ */
10
+ function createRedirectResponse(location, init = {}) {
11
+ const headers = new Headers(init.headers);
12
+ headers.set("Location", location);
13
+ return new Response(null, {
14
+ status: init.status ?? 302,
15
+ headers
16
+ });
17
+ }
18
+
19
+ //#endregion
20
+ //#region src/auth/auth.server.ts
21
+ /**
22
+ * Get effective hasLandingPage setting based on config
23
+ */
24
+ function getEffectiveHasLandingPage(config) {
25
+ if (config.hasLandingPage !== void 0) return config.hasLandingPage;
26
+ switch (config.applicationType) {
27
+ case "no-landing-page":
28
+ case "dashboard": return false;
29
+ case "landing-page":
30
+ case "tenant-app": return true;
31
+ default: return true;
32
+ }
33
+ }
34
+ /**
35
+ * Create OAuth configuration from environment variables
36
+ */
37
+ function createAuthConfig() {
38
+ const requiredEnvVars = {
39
+ authority: process.env.OIDC_AUTHORITY,
40
+ clientId: process.env.OIDC_CLIENT_ID,
41
+ redirectUri: process.env.OIDC_REDIRECT_URI
42
+ };
43
+ for (const [key, value] of Object.entries(requiredEnvVars)) if (!value) throw new Error(`Missing required environment variable: OIDC_${key.toUpperCase()}`);
44
+ const appTypeEnv = process.env.OIDC_APPLICATION_TYPE?.toLowerCase();
45
+ let applicationType = "custom";
46
+ if (appTypeEnv === "no-landing-page" || appTypeEnv === "no_landing_page") applicationType = "no-landing-page";
47
+ else if (appTypeEnv === "landing-page" || appTypeEnv === "landing_page") applicationType = "landing-page";
48
+ else if (appTypeEnv === "dashboard") applicationType = "dashboard";
49
+ else if (appTypeEnv === "tenant-app" || appTypeEnv === "tenant_app") applicationType = "tenant-app";
50
+ const clientAuthMethod = parseOidcClientAuthMethod(process.env.OIDC_CLIENT_AUTH_METHOD, process.env.OIDC_CLIENT_SECRET ? "client_secret_post" : "none");
51
+ const hasLandingPage = process.env.OIDC_HAS_LANDING_PAGE !== void 0 ? process.env.OIDC_HAS_LANDING_PAGE === "true" : void 0;
52
+ return {
53
+ authority: requiredEnvVars.authority,
54
+ clientId: requiredEnvVars.clientId,
55
+ clientSecret: process.env.OIDC_CLIENT_SECRET,
56
+ clientAuthMethod,
57
+ redirectUri: requiredEnvVars.redirectUri,
58
+ scope: process.env.OIDC_SCOPE || "openid profile email api",
59
+ postLogoutRedirectUri: process.env.OIDC_POST_LOGOUT_REDIRECT_URI,
60
+ applicationType,
61
+ hasLandingPage
62
+ };
63
+ }
64
+ function parseOidcClientAuthMethod(value, fallback) {
65
+ const normalized = value?.trim().toLowerCase();
66
+ switch (normalized) {
67
+ case void 0:
68
+ case "": return fallback;
69
+ case "none": return "none";
70
+ case "client_secret_post":
71
+ case "post": return "client_secret_post";
72
+ case "client_secret_basic":
73
+ case "basic": return "client_secret_basic";
74
+ default: throw new Error(`Unsupported OIDC_CLIENT_AUTH_METHOD: ${value}`);
75
+ }
76
+ }
77
+ let OIDC_CONFIG = null;
78
+ function getAuthConfig() {
79
+ if (!OIDC_CONFIG) OIDC_CONFIG = createAuthConfig();
80
+ return OIDC_CONFIG;
81
+ }
82
+ let authServerCache = null;
83
+ const CACHE_TTL = 60 * 60 * 1e3;
84
+ const jwksCache = new Map();
85
+ const RESERVED_AUTHORIZATION_PARAMETER_NAMES = new Set([
86
+ "client_id",
87
+ "code_challenge",
88
+ "code_challenge_method",
89
+ "kc_action",
90
+ "nonce",
91
+ "prompt",
92
+ "redirect_uri",
93
+ "response_mode",
94
+ "response_type",
95
+ "scope",
96
+ "state"
97
+ ]);
98
+ const ALLOWED_EXTRA_AUTHORIZATION_PARAMETER_NAMES = new Set([
99
+ "acr_values",
100
+ "kc_idp_hint",
101
+ "login_hint",
102
+ "ui_locales"
103
+ ]);
104
+ function normalizeIssuer(value) {
105
+ const normalized = value?.trim().replace(/\/+$/, "");
106
+ return normalized && normalized.length > 0 ? normalized : null;
107
+ }
108
+ function getJwtClaims(token) {
109
+ if (!token) return null;
110
+ try {
111
+ const [, payload] = token.split(".");
112
+ if (!payload) return null;
113
+ return JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
114
+ } catch {
115
+ return null;
116
+ }
117
+ }
118
+ function getJwtIssuer(token) {
119
+ const issuer = getJwtClaims(token)?.iss;
120
+ return typeof issuer === "string" ? normalizeIssuer(issuer) : null;
121
+ }
122
+ function canUseIdTokenHint(idToken, expectedIssuer) {
123
+ if (!idToken) return false;
124
+ const tokenIssuer = getJwtIssuer(idToken);
125
+ return tokenIssuer !== null && tokenIssuer === normalizeIssuer(expectedIssuer);
126
+ }
127
+ function sanitizeLogoutReturnUrl(returnUrl, request) {
128
+ if (!returnUrl) return null;
129
+ try {
130
+ const requestUrl = new URL(request.url);
131
+ const decodedReturnUrl = decodeURIComponent(returnUrl);
132
+ if (decodedReturnUrl.startsWith("/") && !decodedReturnUrl.startsWith("//")) return isAuthLoopPath(decodedReturnUrl) ? null : decodedReturnUrl;
133
+ const candidateUrl = new URL(decodedReturnUrl);
134
+ if (candidateUrl.origin !== requestUrl.origin) return null;
135
+ const sameOriginPath = `${candidateUrl.pathname}${candidateUrl.search}${candidateUrl.hash}`;
136
+ return isAuthLoopPath(sameOriginPath) ? null : sameOriginPath;
137
+ } catch {
138
+ return null;
139
+ }
140
+ }
141
+ function appendApplicationInitiatedActionResult(returnUrl, action, status) {
142
+ if (!action && !status) return returnUrl;
143
+ try {
144
+ const isRelative = returnUrl.startsWith("/") && !returnUrl.startsWith("//");
145
+ const url = new URL(returnUrl, isRelative ? "http://spine.local" : void 0);
146
+ if (action) url.searchParams.set("kc_action", action);
147
+ if (status) url.searchParams.set("kc_action_status", status);
148
+ return isRelative ? `${url.pathname}${url.search}${url.hash}` : url.toString();
149
+ } catch {
150
+ const params = new URLSearchParams();
151
+ if (action) params.set("kc_action", action);
152
+ if (status) params.set("kc_action_status", status);
153
+ const separator = returnUrl.includes("?") ? "&" : "?";
154
+ return `${returnUrl}${separator}${params.toString()}`;
155
+ }
156
+ }
157
+ function isAuthLoopPath(path) {
158
+ const normalized = path.split("#")[0].split("?")[0].replace(/\/+$/, "") || "/";
159
+ return normalized === "/auth/logout" || normalized === "/auth/callback";
160
+ }
161
+ function isLocalInsecureIssuer(authority) {
162
+ try {
163
+ const issuer = new URL(authority);
164
+ return issuer.protocol === "http:" && [
165
+ "localhost",
166
+ "127.0.0.1",
167
+ "::1",
168
+ "[::1]"
169
+ ].includes(issuer.hostname);
170
+ } catch {
171
+ return false;
172
+ }
173
+ }
174
+ function shouldAllowInsecureOidcRequests(authority) {
175
+ if (process.env.NODE_ENV === "production") return false;
176
+ if (process.env.OIDC_ALLOW_INSECURE_REQUESTS === "true") return true;
177
+ return isLocalInsecureIssuer(authority);
178
+ }
179
+ function getDiscoveryOptions() {
180
+ const config = getAuthConfig();
181
+ return shouldAllowInsecureOidcRequests(config.authority) ? {
182
+ algorithm: "oidc",
183
+ execute: [oidc.allowInsecureRequests]
184
+ } : { algorithm: "oidc" };
185
+ }
186
+ function getClientMetadata(config) {
187
+ return config.clientAuthMethod === "none" ? void 0 : config.clientSecret;
188
+ }
189
+ function sanitizeExtraAuthorizationParameters(params) {
190
+ if (!params) return {};
191
+ const sanitized = {};
192
+ for (const [key, value] of Object.entries(params)) {
193
+ const normalizedKey = key.trim();
194
+ if (normalizedKey.length === 0 || RESERVED_AUTHORIZATION_PARAMETER_NAMES.has(normalizedKey.toLowerCase()) || !isAllowedExtraAuthorizationParameter(normalizedKey) || value === null || value === void 0) continue;
195
+ const normalizedValue = String(value).trim();
196
+ if (normalizedValue.length === 0) continue;
197
+ sanitized[normalizedKey] = normalizedValue;
198
+ }
199
+ return sanitized;
200
+ }
201
+ function isAllowedExtraAuthorizationParameter(key) {
202
+ const normalized = key.toLowerCase();
203
+ return ALLOWED_EXTRA_AUTHORIZATION_PARAMETER_NAMES.has(normalized) || normalized.startsWith("uf_");
204
+ }
205
+ function buildAuthorizationState(baseState, extraParams) {
206
+ const uiContext = buildPublicAuthorizationUiContext(extraParams);
207
+ if (!uiContext) return baseState;
208
+ return `${baseState}.${Buffer.from(JSON.stringify(uiContext), "utf8").toString("base64url")}`;
209
+ }
210
+ function buildPublicAuthorizationUiContext(extraParams) {
211
+ const inviteKind = extraParams.uf_invite;
212
+ if (inviteKind !== "organization") return null;
213
+ const context = { uf_invite: inviteKind };
214
+ if (extraParams.uf_invite_mode) context.uf_invite_mode = extraParams.uf_invite_mode;
215
+ if (extraParams.login_hint) context.login_hint = extraParams.login_hint;
216
+ return context;
217
+ }
218
+ function getClientAuthentication(config) {
219
+ switch (config.clientAuthMethod) {
220
+ case "client_secret_basic":
221
+ if (!config.clientSecret) throw new Error("OIDC_CLIENT_SECRET is required for client_secret_basic authentication");
222
+ return oidc.ClientSecretBasic(config.clientSecret);
223
+ case "client_secret_post":
224
+ if (!config.clientSecret) throw new Error("OIDC_CLIENT_SECRET is required for client_secret_post authentication");
225
+ return oidc.ClientSecretPost(config.clientSecret);
226
+ case "none":
227
+ default: return oidc.None();
228
+ }
229
+ }
230
+ function getOAuthErrorMessage(error) {
231
+ if (error instanceof oidc.ResponseBodyError) return error.error_description || error.error || error.message;
232
+ if (error instanceof Error) return error.message;
233
+ return "Unknown error";
234
+ }
235
+ function shouldLogoutAfterOAuthError(error) {
236
+ if (error instanceof oidc.ResponseBodyError) return error.status === 400 || error.status === 401 || error.error === "invalid_grant" || error.error === "invalid_token";
237
+ const message = error instanceof Error ? error.message.toLowerCase() : "";
238
+ return message.includes("invalid_grant") || message.includes("invalid_token") || message.includes("unauthorized");
239
+ }
240
+ function getLogoutScope(url) {
241
+ const requestedScope = url.searchParams.get("logout") ?? url.searchParams.get("logout_scope") ?? url.searchParams.get("scope");
242
+ const normalized = requestedScope?.trim().toLowerCase();
243
+ if (normalized === "local" || normalized === "application" || normalized === "app" || normalized === "current-device") return "local";
244
+ if (normalized === "all" || normalized === "all-local" || normalized === "all-devices" || normalized === "everywhere") return "all";
245
+ if (url.searchParams.get("local_only") === "true" || url.searchParams.get("client_id_only") === "true") return "local";
246
+ return "identity";
247
+ }
248
+ function getAbsoluteRedirectUrl(request, redirectUrl) {
249
+ if (/^https?:\/\//i.test(redirectUrl)) return redirectUrl;
250
+ return new URL(redirectUrl, new URL(request.url).origin).toString();
251
+ }
252
+ async function revokeTokenBestEffort(configuration, token, tokenTypeHint) {
253
+ if (!token) return;
254
+ try {
255
+ await oidc.tokenRevocation(configuration, token, { token_type_hint: tokenTypeHint });
256
+ } catch (error) {
257
+ logger.warn("OIDC token revocation failed", {
258
+ tokenTypeHint,
259
+ error: getOAuthErrorMessage(error)
260
+ });
261
+ }
262
+ }
263
+ async function revokeSessionTokensBestEffort(sessionData) {
264
+ if (!sessionData.refreshToken && !sessionData.accessToken) return;
265
+ try {
266
+ const configuration = await getOAuthConfig();
267
+ await revokeTokenBestEffort(configuration, sessionData.refreshToken, "refresh_token");
268
+ await revokeTokenBestEffort(configuration, sessionData.accessToken, "access_token");
269
+ } catch (error) {
270
+ logger.warn("Skipping OIDC token revocation because provider configuration is unavailable", { error: getOAuthErrorMessage(error) });
271
+ }
272
+ }
273
+ async function revokeAndDestroyAllUserSessionsBestEffort(userId) {
274
+ const sessions = await listAuthSessionDataForUser(userId);
275
+ try {
276
+ const configuration = await getOAuthConfig();
277
+ for (const { data } of sessions) {
278
+ await revokeTokenBestEffort(configuration, data.refreshToken, "refresh_token");
279
+ await revokeTokenBestEffort(configuration, data.accessToken, "access_token");
280
+ }
281
+ } catch (error) {
282
+ logger.warn("Skipping all-session token revocation because provider configuration is unavailable", { error: getOAuthErrorMessage(error) });
283
+ }
284
+ return await destroyAuthSessionsForUser(userId);
285
+ }
286
+ function getClaimsFromTokenResponse(tokenResult) {
287
+ const claims = tokenResult.claims();
288
+ if (claims) return claims;
289
+ return getJwtClaims(tokenResult.id_token) ?? {};
290
+ }
291
+ /**
292
+ * Get OIDC configuration with caching.
293
+ */
294
+ async function getOAuthConfig() {
295
+ const config = getAuthConfig();
296
+ const now = Date.now();
297
+ if (authServerCache && now - authServerCache.cachedAt < CACHE_TTL) return authServerCache.configuration;
298
+ try {
299
+ const configuration = await oidc.discovery(new URL(config.authority), config.clientId, getClientMetadata(config), getClientAuthentication(config), getDiscoveryOptions());
300
+ authServerCache = {
301
+ configuration,
302
+ cachedAt: now
303
+ };
304
+ logger.info("OIDC discovery completed successfully", {
305
+ issuer: configuration.serverMetadata().issuer,
306
+ clientId: config.clientId,
307
+ clientAuthMethod: config.clientAuthMethod
308
+ });
309
+ return configuration;
310
+ } catch (error) {
311
+ logger.error("OIDC discovery failed", error instanceof Error ? error : void 0, {
312
+ authority: config.authority,
313
+ clientId: config.clientId
314
+ });
315
+ throw new Error(`OIDC discovery failed: ${getOAuthErrorMessage(error)}`);
316
+ }
317
+ }
318
+ function getJwks(jwksUri) {
319
+ const cachedJwks = jwksCache.get(jwksUri);
320
+ if (cachedJwks) return cachedJwks;
321
+ const jwks = createRemoteJWKSet(new URL(jwksUri));
322
+ jwksCache.set(jwksUri, jwks);
323
+ return jwks;
324
+ }
325
+ async function getLogoutTokenFromRequest(request) {
326
+ const contentType = request.headers.get("content-type") ?? "";
327
+ if (contentType.includes("application/json")) {
328
+ const body = await request.json().catch(() => null);
329
+ return typeof body?.logout_token === "string" ? body.logout_token : null;
330
+ }
331
+ const formData = await request.formData().catch(() => null);
332
+ const logoutToken = formData?.get("logout_token");
333
+ return typeof logoutToken === "string" ? logoutToken : null;
334
+ }
335
+ function validateBackChannelLogoutClaims(payload, clientId) {
336
+ const events = payload.events;
337
+ const hasBackChannelEvent = events && typeof events === "object" && !Array.isArray(events) && "http://schemas.openid.net/event/backchannel-logout" in events;
338
+ if (!hasBackChannelEvent) throw new Error("Invalid back-channel logout token: missing back-channel logout event");
339
+ if ("nonce" in payload) throw new Error("Invalid back-channel logout token: nonce is not allowed");
340
+ const audience = payload.aud;
341
+ const hasClientAudience = Array.isArray(audience) ? audience.includes(clientId) : audience === clientId;
342
+ if (!hasClientAudience) throw new Error("Invalid back-channel logout token: audience mismatch");
343
+ const subject = typeof payload.sub === "string" ? payload.sub : void 0;
344
+ const sid = typeof payload.sid === "string" ? payload.sid : void 0;
345
+ if (!subject && !sid) throw new Error("Invalid back-channel logout token: subject or sid is required");
346
+ return {
347
+ issuer: typeof payload.iss === "string" ? payload.iss : void 0,
348
+ subject,
349
+ sid
350
+ };
351
+ }
352
+ const DEFAULT_AUTH_CLAIM_MAPPING = {
353
+ subject: ["sub"],
354
+ name: [
355
+ "name",
356
+ "preferred_username",
357
+ "email"
358
+ ],
359
+ email: ["email"],
360
+ givenName: ["given_name", "givenName"],
361
+ familyName: ["family_name", "familyName"],
362
+ picture: ["picture", "avatar_url"],
363
+ locale: ["locale"],
364
+ zoneinfo: ["zoneinfo"],
365
+ updatedAt: ["updated_at"],
366
+ tenantIds: ["tenant_ids"],
367
+ tenantRoles: ["tenant_roles"],
368
+ permissions: [
369
+ "app_perms",
370
+ "permissions",
371
+ "scope"
372
+ ],
373
+ isOnboarded: ["is_onboarded"]
374
+ };
375
+ let authClaimMapping = { ...DEFAULT_AUTH_CLAIM_MAPPING };
376
+ function normalizeClaimKeys(keys) {
377
+ if (!Array.isArray(keys)) return [];
378
+ return Array.from(new Set(keys.map((key) => key.trim()).filter((key) => key.length > 0)));
379
+ }
380
+ /**
381
+ * Configure claim mapping so different providers/backends can project their
382
+ * own claim names onto the shared auth/session primitives.
383
+ */
384
+ function configureAuthClaimMapping(mapping) {
385
+ authClaimMapping = {
386
+ subject: mapping.subject !== void 0 ? normalizeClaimKeys(mapping.subject) : DEFAULT_AUTH_CLAIM_MAPPING.subject,
387
+ name: mapping.name !== void 0 ? normalizeClaimKeys(mapping.name) : DEFAULT_AUTH_CLAIM_MAPPING.name,
388
+ email: mapping.email !== void 0 ? normalizeClaimKeys(mapping.email) : DEFAULT_AUTH_CLAIM_MAPPING.email,
389
+ givenName: mapping.givenName !== void 0 ? normalizeClaimKeys(mapping.givenName) : DEFAULT_AUTH_CLAIM_MAPPING.givenName,
390
+ familyName: mapping.familyName !== void 0 ? normalizeClaimKeys(mapping.familyName) : DEFAULT_AUTH_CLAIM_MAPPING.familyName,
391
+ picture: mapping.picture !== void 0 ? normalizeClaimKeys(mapping.picture) : DEFAULT_AUTH_CLAIM_MAPPING.picture,
392
+ locale: mapping.locale !== void 0 ? normalizeClaimKeys(mapping.locale) : DEFAULT_AUTH_CLAIM_MAPPING.locale,
393
+ zoneinfo: mapping.zoneinfo !== void 0 ? normalizeClaimKeys(mapping.zoneinfo) : DEFAULT_AUTH_CLAIM_MAPPING.zoneinfo,
394
+ updatedAt: mapping.updatedAt !== void 0 ? normalizeClaimKeys(mapping.updatedAt) : DEFAULT_AUTH_CLAIM_MAPPING.updatedAt,
395
+ tenantIds: mapping.tenantIds !== void 0 ? normalizeClaimKeys(mapping.tenantIds) : DEFAULT_AUTH_CLAIM_MAPPING.tenantIds,
396
+ tenantRoles: mapping.tenantRoles !== void 0 ? normalizeClaimKeys(mapping.tenantRoles) : DEFAULT_AUTH_CLAIM_MAPPING.tenantRoles,
397
+ permissions: mapping.permissions !== void 0 ? normalizeClaimKeys(mapping.permissions) : DEFAULT_AUTH_CLAIM_MAPPING.permissions,
398
+ isOnboarded: mapping.isOnboarded !== void 0 ? normalizeClaimKeys(mapping.isOnboarded) : DEFAULT_AUTH_CLAIM_MAPPING.isOnboarded
399
+ };
400
+ }
401
+ /**
402
+ * Reset claim mapping to the built-in defaults.
403
+ */
404
+ function resetAuthClaimMapping() {
405
+ authClaimMapping = { ...DEFAULT_AUTH_CLAIM_MAPPING };
406
+ }
407
+ function getConfiguredAuthClaimMapping() {
408
+ return authClaimMapping;
409
+ }
410
+ function getFirstClaimValue(claims, claimKeys) {
411
+ for (const claimKey of claimKeys) if (claimKey in claims) return {
412
+ key: claimKey,
413
+ value: claims[claimKey]
414
+ };
415
+ return {};
416
+ }
417
+ function getStringClaim(claims, claimKeys) {
418
+ const { value } = getFirstClaimValue(claims, claimKeys);
419
+ if (typeof value === "string") {
420
+ const trimmed = value.trim();
421
+ return trimmed.length > 0 ? trimmed : void 0;
422
+ }
423
+ if (typeof value === "number" || typeof value === "boolean") return `${value}`;
424
+ return void 0;
425
+ }
426
+ function getNumberClaim(claims, claimKeys) {
427
+ const { value } = getFirstClaimValue(claims, claimKeys);
428
+ if (typeof value === "number" && Number.isFinite(value)) return value;
429
+ if (typeof value === "string") {
430
+ const parsed = Number(value);
431
+ return Number.isFinite(parsed) ? parsed : void 0;
432
+ }
433
+ return void 0;
434
+ }
435
+ function getBooleanClaim(claims, claimKeys, defaultValue = false) {
436
+ const { value } = getFirstClaimValue(claims, claimKeys);
437
+ if (typeof value === "boolean") return value;
438
+ if (typeof value === "string") return value.toLowerCase() === "true";
439
+ return defaultValue;
440
+ }
441
+ /**
442
+ * Parse JSON safely
443
+ */
444
+ function parseJson(value) {
445
+ try {
446
+ return JSON.parse(value);
447
+ } catch {
448
+ return null;
449
+ }
450
+ }
451
+ /**
452
+ * Convert value to string array
453
+ */
454
+ function toStringArray(value) {
455
+ if (!value) return [];
456
+ if (Array.isArray(value)) return value.map((item) => typeof item === "string" ? item.trim() : `${item}`.trim()).filter((item) => item.length > 0);
457
+ if (typeof value === "string") {
458
+ const trimmed = value.trim();
459
+ if (!trimmed) return [];
460
+ if (trimmed.startsWith("[")) {
461
+ const parsed = parseJson(trimmed);
462
+ if (Array.isArray(parsed)) return parsed.map((item) => typeof item === "string" ? item.trim() : `${item}`.trim()).filter((item) => item.length > 0);
463
+ }
464
+ if (trimmed.includes(",")) return trimmed.split(",").map((item) => item.trim()).filter((item) => item.length > 0);
465
+ return [trimmed];
466
+ }
467
+ return [];
468
+ }
469
+ function toScopeArray(value) {
470
+ if (typeof value === "string") return value.trim().split(/\s+/).filter((item) => item.length > 0);
471
+ return toStringArray(value);
472
+ }
473
+ /**
474
+ * Extract user info from ID token claims
475
+ */
476
+ function extractUserInfo(claims) {
477
+ const claimMapping = getConfiguredAuthClaimMapping();
478
+ let tenants = [];
479
+ const { value: rawTenantIds } = getFirstClaimValue(claims, claimMapping.tenantIds);
480
+ if (rawTenantIds !== void 0) if (typeof rawTenantIds === "string" && rawTenantIds.trim().startsWith("[")) {
481
+ const parsed = parseJson(rawTenantIds.trim());
482
+ if (Array.isArray(parsed)) tenants = parsed.map((id) => typeof id === "string" ? id.trim() : `${id}`.trim()).filter((id) => id.length > 0);
483
+ } else tenants = toStringArray(rawTenantIds);
484
+ const tenantRoles = {};
485
+ const { value: rawRoles } = getFirstClaimValue(claims, claimMapping.tenantRoles);
486
+ if (rawRoles !== void 0) {
487
+ let parsedRoles = rawRoles;
488
+ if (typeof rawRoles === "string" && rawRoles.trim().startsWith("{")) parsedRoles = parseJson(rawRoles.trim()) ?? rawRoles;
489
+ if (parsedRoles && typeof parsedRoles === "object" && !Array.isArray(parsedRoles)) for (const [tenantId, roleValue] of Object.entries(parsedRoles)) {
490
+ const roleIds = toStringArray(roleValue);
491
+ if (roleIds.length > 0) tenantRoles[tenantId] = roleIds;
492
+ }
493
+ }
494
+ const permissionClaim = getFirstClaimValue(claims, claimMapping.permissions);
495
+ const permissions = permissionClaim.key === "scope" ? toScopeArray(permissionClaim.value) : toStringArray(permissionClaim.value);
496
+ const isOnboarded = getBooleanClaim(claims, claimMapping.isOnboarded);
497
+ return {
498
+ tenants,
499
+ isOnboarded,
500
+ tenantRoles,
501
+ permissions
502
+ };
503
+ }
504
+ /**
505
+ * Create session data from token result
506
+ */
507
+ async function createSessionData(tokenResult, claims) {
508
+ const claimMapping = getConfiguredAuthClaimMapping();
509
+ const baseUser = {
510
+ sub: getStringClaim(claims, claimMapping.subject) || "unknown",
511
+ name: getStringClaim(claims, claimMapping.name) || getStringClaim(claims, claimMapping.email) || "User",
512
+ email: getStringClaim(claims, claimMapping.email),
513
+ givenName: getStringClaim(claims, claimMapping.givenName),
514
+ familyName: getStringClaim(claims, claimMapping.familyName),
515
+ picture: getStringClaim(claims, claimMapping.picture),
516
+ locale: getStringClaim(claims, claimMapping.locale),
517
+ zoneinfo: getStringClaim(claims, claimMapping.zoneinfo),
518
+ updated_at: getNumberClaim(claims, claimMapping.updatedAt)
519
+ };
520
+ const expiresAt = tokenResult.expires_in ? Date.now() + tokenResult.expires_in * 1e3 : void 0;
521
+ const now = Date.now();
522
+ const sessionState = tokenResult.session_state;
523
+ return {
524
+ userId: baseUser.sub,
525
+ accessToken: tokenResult.access_token,
526
+ refreshToken: tokenResult.refresh_token,
527
+ idToken: tokenResult.id_token,
528
+ expiresAt,
529
+ issuer: getStringClaim(claims, ["iss"]),
530
+ sid: getStringClaim(claims, ["sid"]),
531
+ sessionState: typeof sessionState === "string" ? sessionState : void 0,
532
+ clientId: getAuthConfig().clientId,
533
+ user: baseUser,
534
+ createdAt: now,
535
+ lastActivity: now
536
+ };
537
+ }
538
+ const AUTH_ERROR_COOKIE = `${AUTH_ERROR_COOKIE_PREFIX}_auth_error`;
539
+ const AUTH_ERROR_DESC_COOKIE = `${AUTH_ERROR_COOKIE_PREFIX}_auth_error_desc`;
540
+ const OAUTH_STATE_COOKIE = `${AUTH_ERROR_COOKIE_PREFIX}_oauth_state_id`;
541
+ /**
542
+ * Check if there's an auth error in cookies
543
+ *
544
+ * This should be called by apps (especially those without landing pages like Dashboard)
545
+ * BEFORE starting OAuth flow to prevent redirect loops.
546
+ *
547
+ * @example
548
+ * ```ts
549
+ * // In dashboard's index route loader
550
+ * const authError = getAuthError(request);
551
+ * if (authError) {
552
+ * return { authError }; // Show error to user
553
+ * }
554
+ * // No error, proceed with session check
555
+ * const user = await getUser(request);
556
+ * if (!user) {
557
+ * return login(request);
558
+ * }
559
+ * ```
560
+ */
561
+ function getAuthError(request) {
562
+ const cookies = request.headers.get("Cookie");
563
+ if (!cookies) return null;
564
+ const errorRegex = new RegExp(`${AUTH_ERROR_COOKIE}=([^;]+)`);
565
+ const errorMatch = cookies.match(errorRegex);
566
+ if (!errorMatch) return null;
567
+ const error = decodeURIComponent(errorMatch[1]);
568
+ if (!error) return null;
569
+ const descRegex = new RegExp(`${AUTH_ERROR_DESC_COOKIE}=([^;]+)`);
570
+ const descMatch = cookies.match(descRegex);
571
+ const description = descMatch ? decodeURIComponent(descMatch[1]) : void 0;
572
+ return {
573
+ error,
574
+ description
575
+ };
576
+ }
577
+ /**
578
+ * Clear auth error cookies
579
+ *
580
+ * Call this after displaying the error to the user
581
+ */
582
+ function clearAuthErrorHeaders() {
583
+ const headers = new Headers();
584
+ headers.append("Set-Cookie", `${AUTH_ERROR_COOKIE}=; Path=/; Max-Age=0`);
585
+ headers.append("Set-Cookie", `${AUTH_ERROR_DESC_COOKIE}=; Path=/; Max-Age=0`);
586
+ return headers;
587
+ }
588
+ /**
589
+ * Check if request has auth error (quick check without parsing)
590
+ */
591
+ function hasAuthError(request) {
592
+ const cookies = request.headers.get("Cookie");
593
+ return cookies?.includes(`${AUTH_ERROR_COOKIE}=`) ?? false;
594
+ }
595
+ /**
596
+ * Initiate OAuth login flow
597
+ *
598
+ * @param request - The incoming request
599
+ * @param returnUrlOrOptions - Either a return URL string or LoginOptions object
600
+ */
601
+ async function login(request, returnUrlOrOptions) {
602
+ try {
603
+ const config = getAuthConfig();
604
+ const options = typeof returnUrlOrOptions === "string" ? { returnUrl: returnUrlOrOptions } : returnUrlOrOptions || {};
605
+ const cookies = request.headers.get("Cookie");
606
+ const hasError = cookies?.includes(`${AUTH_ERROR_COOKIE}=`);
607
+ if (hasError) {
608
+ logger.warn("Auth error cookie detected, preventing redirect loop");
609
+ const headers$1 = new Headers();
610
+ headers$1.append("Set-Cookie", `${AUTH_ERROR_COOKIE}=; Path=/; Max-Age=0`);
611
+ const redirectUri = new URL(config.redirectUri);
612
+ const baseUrl = redirectUri.origin;
613
+ return createRedirectResponse(baseUrl, { headers: headers$1 });
614
+ }
615
+ const oidcConfig = await getOAuthConfig();
616
+ const codeVerifier = oidc.randomPKCECodeVerifier();
617
+ const codeChallenge = await oidc.calculatePKCECodeChallenge(codeVerifier);
618
+ const extraAuthParams = sanitizeExtraAuthorizationParameters(options.extraAuthParams);
619
+ const state = buildAuthorizationState(oidc.randomState(), extraAuthParams);
620
+ const nonce = oidc.randomNonce();
621
+ const oauthState = {
622
+ state,
623
+ codeVerifier,
624
+ nonce,
625
+ returnUrl: options.returnUrl,
626
+ kcAction: options.kcAction,
627
+ createdAt: Date.now()
628
+ };
629
+ logger.info("Creating OAuth state", {
630
+ returnUrl: options.returnUrl,
631
+ prompt: options.prompt,
632
+ kcAction: options.kcAction,
633
+ extraAuthParamKeys: Object.keys(extraAuthParams)
634
+ });
635
+ const stateId = await createOAuthState(oauthState);
636
+ const authorizationParameters = {
637
+ redirect_uri: config.redirectUri,
638
+ scope: config.scope,
639
+ state,
640
+ nonce,
641
+ code_challenge: codeChallenge,
642
+ code_challenge_method: "S256",
643
+ ...extraAuthParams
644
+ };
645
+ if (options.prompt) authorizationParameters.prompt = options.prompt;
646
+ if (options.kcAction) authorizationParameters.kc_action = options.kcAction;
647
+ const authorizationUrl = oidc.buildAuthorizationUrl(oidcConfig, authorizationParameters);
648
+ const headers = new Headers();
649
+ headers.append("Set-Cookie", `${OAUTH_STATE_COOKIE}=${stateId}; Path=/; HttpOnly; SameSite=Lax; Max-Age=600`);
650
+ logger.info("OIDC authorization flow initiated", {
651
+ clientId: config.clientId,
652
+ redirectUri: config.redirectUri,
653
+ scope: config.scope,
654
+ authorizationEndpoint: oidcConfig.serverMetadata().authorization_endpoint,
655
+ stateId,
656
+ prompt: options.prompt,
657
+ kcAction: options.kcAction
658
+ });
659
+ return createRedirectResponse(authorizationUrl.toString(), { headers });
660
+ } catch (error) {
661
+ logger.error("Failed to initiate OAuth login", error instanceof Error ? error : void 0);
662
+ throw new Error("Login failed");
663
+ }
664
+ }
665
+ /**
666
+ * Handle OAuth callback
667
+ *
668
+ * Handles OAuth authorization response including success and error cases.
669
+ *
670
+ * Error Handling:
671
+ * - `access_denied`: User doesn't have access to this application
672
+ * - For apps with landing page: Redirect home with error cookie
673
+ * - For apps without landing page: Redirect home with error cookie (must handle specially)
674
+ * - `login_required`: No active identity session
675
+ * - Redirect to home to start fresh login
676
+ */
677
+ async function handleCallback(request) {
678
+ try {
679
+ const config = getAuthConfig();
680
+ const hasLandingPage = getEffectiveHasLandingPage(config);
681
+ const url = new URL(request.url);
682
+ const code = url.searchParams.get("code");
683
+ const state = url.searchParams.get("state");
684
+ const error = url.searchParams.get("error");
685
+ const errorDescription = url.searchParams.get("error_description");
686
+ const kcAction = url.searchParams.get("kc_action");
687
+ const kcActionStatus = url.searchParams.get("kc_action_status");
688
+ logger.info("OIDC callback received", {
689
+ hasCode: !!code,
690
+ hasState: !!state,
691
+ error,
692
+ errorDescription,
693
+ kcAction,
694
+ kcActionStatus,
695
+ clientId: config.clientId,
696
+ redirectUri: config.redirectUri
697
+ });
698
+ if (error) {
699
+ if (kcActionStatus && state) {
700
+ const cookies$1 = request.headers.get("Cookie");
701
+ const oauthStateRegex$1 = new RegExp(`${OAUTH_STATE_COOKIE}=([^;]+)`);
702
+ const cookieMatch$1 = cookies$1?.match(oauthStateRegex$1);
703
+ const stateId$1 = cookieMatch$1?.[1];
704
+ if (stateId$1) {
705
+ const oauthState$1 = await getOAuthState(stateId$1);
706
+ const stateAge$1 = oauthState$1 ? Date.now() - oauthState$1.createdAt : Number.POSITIVE_INFINITY;
707
+ if (oauthState$1 && oauthState$1.state === state && stateAge$1 <= 10 * 60 * 1e3) {
708
+ await deleteOAuthState(stateId$1);
709
+ const headers$2 = new Headers();
710
+ headers$2.append("Set-Cookie", `${OAUTH_STATE_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`);
711
+ const redirectUrl$1 = appendApplicationInitiatedActionResult(oauthState$1.returnUrl || "/", kcAction || oauthState$1.kcAction, kcActionStatus);
712
+ logger.info("Application initiated action returned with OAuth error", {
713
+ error,
714
+ errorDescription,
715
+ kcAction: kcAction || oauthState$1.kcAction,
716
+ kcActionStatus
717
+ });
718
+ return createRedirectResponse(redirectUrl$1, { headers: headers$2 });
719
+ }
720
+ }
721
+ }
722
+ logger.error("OAuth callback error", void 0, {
723
+ error,
724
+ errorDescription,
725
+ clientId: config.clientId,
726
+ applicationType: config.applicationType,
727
+ hasLandingPage
728
+ });
729
+ if (error === "access_denied") {
730
+ logger.warn("Access denied for this application", { clientId: config.clientId });
731
+ const headers$2 = await destroyAuthSession(request);
732
+ headers$2.append("Set-Cookie", `${AUTH_ERROR_COOKIE}=access_denied; Path=/; HttpOnly; SameSite=Lax; Max-Age=300`);
733
+ headers$2.append("Set-Cookie", `${AUTH_ERROR_DESC_COOKIE}=${encodeURIComponent(errorDescription || "You do not have access to this application.")}; Path=/; SameSite=Lax; Max-Age=300`);
734
+ const redirectUri$1 = new URL(config.redirectUri);
735
+ const baseUrl$1 = redirectUri$1.origin;
736
+ logger.info("Redirecting to /auth/login to show access_denied error", {
737
+ hasLandingPage,
738
+ baseUrl: baseUrl$1,
739
+ configRedirectUri: config.redirectUri
740
+ });
741
+ return createRedirectResponse(`${baseUrl$1}/auth/login`, { headers: headers$2 });
742
+ }
743
+ if (error === "login_required") {
744
+ logger.info("Login required, user session may have expired");
745
+ const headers$2 = await destroyAuthSession(request);
746
+ const redirectUri$1 = new URL(config.redirectUri);
747
+ const baseUrl$1 = redirectUri$1.origin;
748
+ return createRedirectResponse(baseUrl$1, { headers: headers$2 });
749
+ }
750
+ const headers$1 = await destroyAuthSession(request);
751
+ headers$1.append("Set-Cookie", `${AUTH_ERROR_COOKIE}=${encodeURIComponent(error)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=300`);
752
+ if (errorDescription) headers$1.append("Set-Cookie", `${AUTH_ERROR_DESC_COOKIE}=${encodeURIComponent(errorDescription)}; Path=/; SameSite=Lax; Max-Age=300`);
753
+ const redirectUri = new URL(config.redirectUri);
754
+ const baseUrl = redirectUri.origin;
755
+ return createRedirectResponse(baseUrl, { headers: headers$1 });
756
+ }
757
+ const cookies = request.headers.get("Cookie");
758
+ const oauthStateRegex = new RegExp(`${OAUTH_STATE_COOKIE}=([^;]+)`);
759
+ const cookieMatch = cookies?.match(oauthStateRegex);
760
+ const stateId = cookieMatch?.[1];
761
+ if (!stateId) throw new Error("OAuth state ID not found in cookie");
762
+ const oauthState = await getOAuthState(stateId);
763
+ if (!oauthState) throw new Error("No OAuth state found - state may have expired");
764
+ if (!state) throw new Error("Missing required callback state parameter");
765
+ if (oauthState.state !== state) throw new Error(`OAuth state mismatch`);
766
+ const stateAge = Date.now() - oauthState.createdAt;
767
+ if (stateAge > 10 * 60 * 1e3) throw new Error("OAuth state expired");
768
+ if (!code) {
769
+ if (kcActionStatus) {
770
+ await deleteOAuthState(stateId);
771
+ const headers$1 = new Headers();
772
+ headers$1.append("Set-Cookie", `${OAUTH_STATE_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`);
773
+ const redirectUrl$1 = appendApplicationInitiatedActionResult(oauthState.returnUrl || "/", kcAction || oauthState.kcAction, kcActionStatus);
774
+ logger.info("Application initiated action returned without authorization code", {
775
+ kcAction: kcAction || oauthState.kcAction,
776
+ kcActionStatus
777
+ });
778
+ return createRedirectResponse(redirectUrl$1, { headers: headers$1 });
779
+ }
780
+ throw new Error("Missing required callback code parameter");
781
+ }
782
+ logger.info("Initiating token exchange");
783
+ const oidcConfig = await getOAuthConfig();
784
+ const tokenResult = await oidc.authorizationCodeGrant(oidcConfig, url, {
785
+ pkceCodeVerifier: oauthState.codeVerifier,
786
+ expectedState: oauthState.state,
787
+ expectedNonce: oauthState.nonce,
788
+ idTokenExpected: config.scope.split(/\s+/).includes("openid")
789
+ });
790
+ logger.info("Token exchange completed successfully");
791
+ const claims = getClaimsFromTokenResponse(tokenResult);
792
+ const newSessionData = await createSessionData(tokenResult, claims);
793
+ const sessionHeaders = await createAuthSession(request, newSessionData);
794
+ await deleteOAuthState(stateId);
795
+ const headers = new Headers(sessionHeaders);
796
+ headers.append("Set-Cookie", `${OAUTH_STATE_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`);
797
+ logger.info("OAuth callback processed successfully");
798
+ const redirectUrl = appendApplicationInitiatedActionResult(oauthState.returnUrl || "/", kcAction || oauthState.kcAction, kcActionStatus);
799
+ return createRedirectResponse(redirectUrl, { headers });
800
+ } catch (error) {
801
+ logger.error("OAuth callback failed", error instanceof Error ? error : void 0);
802
+ try {
803
+ const cookies = request.headers.get("Cookie");
804
+ const oauthStateRegex = new RegExp(`${OAUTH_STATE_COOKIE}=([^;]+)`);
805
+ const cookieMatch = cookies?.match(oauthStateRegex);
806
+ const stateId = cookieMatch?.[1];
807
+ if (stateId) await deleteOAuthState(stateId);
808
+ } catch {}
809
+ await destroyAuthSession(request);
810
+ throw new Error("Authentication failed");
811
+ }
812
+ }
813
+ /**
814
+ * Logout user.
815
+ *
816
+ * Default logout follows OIDC RP-Initiated Logout and ends the identity
817
+ * provider session. Automatic/session-expiry cleanup can request
818
+ * `/auth/logout?logout=local` to clear only this app's Redis session without
819
+ * bouncing the browser through the identity provider or revoking SSO tokens.
820
+ */
821
+ async function logout(request) {
822
+ try {
823
+ const config = getAuthConfig();
824
+ const url = new URL(request.url);
825
+ const logoutScope = getLogoutScope(url);
826
+ const returnUrl = sanitizeLogoutReturnUrl(url.searchParams.get("returnUrl"), request);
827
+ logger.info("Logout initiated", {
828
+ clientId: config.clientId,
829
+ logoutScope
830
+ });
831
+ const sessionData = await getAuthSession(request);
832
+ const idToken = sessionData.idToken;
833
+ if (logoutScope === "local") {
834
+ const headers$1 = await destroyAuthSession(request);
835
+ const redirectUrl = returnUrl || "/";
836
+ const absoluteRedirectUrl = getAbsoluteRedirectUrl(request, redirectUrl);
837
+ headers$1.append("Set-Cookie", "logout_return_url=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0");
838
+ logger.info("Local application logout completed", { redirectUrl: absoluteRedirectUrl });
839
+ return createRedirectResponse(absoluteRedirectUrl, { headers: headers$1 });
840
+ }
841
+ const sessionHeaders = new Headers();
842
+ if (logoutScope === "all" && sessionData.userId) {
843
+ await revokeAndDestroyAllUserSessionsBestEffort(sessionData.userId);
844
+ sessionHeaders.append("Set-Cookie", "logout_return_url=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0");
845
+ const expiredHeaders = await destroyAuthSession(request);
846
+ expiredHeaders.forEach((value, key) => sessionHeaders.append(key, value));
847
+ } else {
848
+ await revokeSessionTokensBestEffort(sessionData);
849
+ const expiredHeaders = await destroyAuthSession(request);
850
+ expiredHeaders.forEach((value, key) => sessionHeaders.append(key, value));
851
+ }
852
+ const headers = new Headers(sessionHeaders);
853
+ if (returnUrl) headers.append("Set-Cookie", `logout_return_url=${encodeURIComponent(returnUrl)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=300`);
854
+ else headers.append("Set-Cookie", "logout_return_url=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0");
855
+ try {
856
+ const oidcConfig = await getOAuthConfig();
857
+ const serverMetadata = oidcConfig.serverMetadata();
858
+ const logoutParameters = {};
859
+ const expectedIssuer = serverMetadata.issuer ?? config.authority;
860
+ if (idToken && canUseIdTokenHint(idToken, expectedIssuer)) logoutParameters.id_token_hint = idToken;
861
+ else if (idToken) logger.warn("Skipping id_token_hint because the session token issuer does not match the active OIDC provider", {
862
+ tokenIssuer: getJwtIssuer(idToken),
863
+ expectedIssuer: normalizeIssuer(expectedIssuer),
864
+ clientId: config.clientId
865
+ });
866
+ if (config.postLogoutRedirectUri) logoutParameters.post_logout_redirect_uri = config.postLogoutRedirectUri;
867
+ const endSessionUrl = oidc.buildEndSessionUrl(oidcConfig, logoutParameters);
868
+ logger.info("RP-Initiated Logout redirect created", {
869
+ endSessionEndpoint: serverMetadata.end_session_endpoint,
870
+ hasIdTokenHint: Boolean(logoutParameters.id_token_hint)
871
+ });
872
+ return createRedirectResponse(endSessionUrl.toString(), { headers });
873
+ } catch (error) {
874
+ logger.warn("OIDC end_session endpoint unavailable, falling back to local redirect", { error: getOAuthErrorMessage(error) });
875
+ }
876
+ const registeredPath = config.postLogoutRedirectUri || "/";
877
+ const finalRedirectUrl = getAbsoluteRedirectUrl(request, registeredPath);
878
+ logger.info("Logout completed", { redirectUrl: finalRedirectUrl });
879
+ return createRedirectResponse(finalRedirectUrl, { headers });
880
+ } catch (error) {
881
+ logger.error("Logout failed", error instanceof Error ? error : void 0);
882
+ const headers = await destroyAuthSession(request);
883
+ return createRedirectResponse("/", { headers });
884
+ }
885
+ }
886
+ /**
887
+ * Handle an OIDC Back-Channel Logout request from Keycloak or another OP.
888
+ *
889
+ * Configure the client Backchannel logout URL to this endpoint. The logout
890
+ * token is signature-verified against the provider JWKS, issuer/audience are
891
+ * checked, and all matching local Redis sessions are destroyed by `sid` first,
892
+ * falling back to `sub` when the OP omits a session id.
893
+ */
894
+ async function handleBackChannelLogout(request) {
895
+ if (request.method !== "POST") return Response.json({ error: "method_not_allowed" }, { status: 405 });
896
+ try {
897
+ const config = getAuthConfig();
898
+ const oidcConfig = await getOAuthConfig();
899
+ const serverMetadata = oidcConfig.serverMetadata();
900
+ const logoutToken = await getLogoutTokenFromRequest(request);
901
+ if (!logoutToken) return Response.json({ error: "missing_logout_token" }, { status: 400 });
902
+ if (!serverMetadata.jwks_uri) throw new Error("OIDC provider does not expose jwks_uri");
903
+ const { payload } = await jwtVerify(logoutToken, getJwks(serverMetadata.jwks_uri), {
904
+ issuer: serverMetadata.issuer ?? config.authority,
905
+ audience: config.clientId,
906
+ clockTolerance: 60
907
+ });
908
+ const claims = validateBackChannelLogoutClaims(payload, config.clientId);
909
+ const destroyedSessions = await destroyAuthSessionsByIdentitySession({
910
+ sid: claims.sid,
911
+ userId: claims.subject
912
+ });
913
+ const result = {
914
+ destroyedSessions,
915
+ issuer: claims.issuer,
916
+ subject: claims.subject,
917
+ sid: claims.sid
918
+ };
919
+ logger.info("Back-channel logout processed", { ...result });
920
+ return Response.json({
921
+ success: true,
922
+ ...result
923
+ });
924
+ } catch (error) {
925
+ logger.error("Back-channel logout failed", error instanceof Error ? error : void 0);
926
+ return Response.json({
927
+ error: "invalid_logout_token",
928
+ error_description: getOAuthErrorMessage(error)
929
+ }, { status: 400 });
930
+ }
931
+ }
932
+ /**
933
+ * Handle OIDC Front-Channel Logout iframe/browser requests.
934
+ *
935
+ * Front-channel logout cannot carry a signed logout token, so this validates the
936
+ * issuer and applies local cleanup only when a `sid` is present.
937
+ */
938
+ async function handleFrontChannelLogout(request) {
939
+ try {
940
+ const config = getAuthConfig();
941
+ const oidcConfig = await getOAuthConfig();
942
+ const serverMetadata = oidcConfig.serverMetadata();
943
+ const url = new URL(request.url);
944
+ const issuer = url.searchParams.get("iss");
945
+ const sid = url.searchParams.get("sid");
946
+ const expectedIssuer = normalizeIssuer(serverMetadata.issuer ?? config.authority);
947
+ if (!issuer || normalizeIssuer(issuer) !== expectedIssuer) return new Response(null, { status: 204 });
948
+ const destroyedSessions = sid ? await destroyAuthSessionsBySid(sid) : 0;
949
+ const result = {
950
+ destroyedSessions,
951
+ issuer,
952
+ sid: sid ?? void 0
953
+ };
954
+ logger.info("Front-channel logout processed", { ...result });
955
+ return new Response(null, {
956
+ status: 204,
957
+ headers: { "Cache-Control": "no-store" }
958
+ });
959
+ } catch (error) {
960
+ logger.warn("Front-channel logout ignored", { error: getOAuthErrorMessage(error) });
961
+ return new Response(null, { status: 204 });
962
+ }
963
+ }
964
+ /**
965
+ * Get current user from session
966
+ */
967
+ async function getUser(request) {
968
+ try {
969
+ const sessionData = await getAuthSession(request);
970
+ return sessionData.user || null;
971
+ } catch (error) {
972
+ logger.error("Failed to get user", error instanceof Error ? error : void 0);
973
+ return null;
974
+ }
975
+ }
976
+ /**
977
+ * Require authenticated user (throws redirect to login if not authenticated)
978
+ */
979
+ async function requireAuth(request) {
980
+ const user = await getUser(request);
981
+ if (!user) {
982
+ const url = new URL(request.url);
983
+ const returnUrl = `${url.pathname}${url.search}`;
984
+ logger.info("No user found, starting OAuth flow", { returnUrl });
985
+ throw await login(request, returnUrl);
986
+ }
987
+ return user;
988
+ }
989
+ /**
990
+ * Get access token from session
991
+ */
992
+ async function getAccessToken(request) {
993
+ try {
994
+ const sessionData = await getAuthSession(request);
995
+ return sessionData.accessToken || null;
996
+ } catch (error) {
997
+ logger.error("Failed to get access token", error instanceof Error ? error : void 0);
998
+ return null;
999
+ }
1000
+ }
1001
+ /**
1002
+ * Refresh tokens
1003
+ */
1004
+ async function refreshTokens(request, refreshToken) {
1005
+ try {
1006
+ const sessionData = await getAuthSession(request);
1007
+ const tokenToRefresh = refreshToken || sessionData.refreshToken;
1008
+ if (!tokenToRefresh) {
1009
+ logger.warn("No refresh token available");
1010
+ return {
1011
+ success: false,
1012
+ error: "No refresh token available",
1013
+ shouldLogout: true
1014
+ };
1015
+ }
1016
+ logger.info("Initiating token refresh");
1017
+ const oidcConfig = await getOAuthConfig();
1018
+ const refreshResult = await oidc.refreshTokenGrant(oidcConfig, tokenToRefresh);
1019
+ logger.info("Token refresh successful");
1020
+ const newRefreshToken = refreshResult.refresh_token || tokenToRefresh;
1021
+ const expiresAt = refreshResult.expires_in ? Date.now() + refreshResult.expires_in * 1e3 : sessionData.expiresAt;
1022
+ await updateAuthSession(request, {
1023
+ accessToken: refreshResult.access_token,
1024
+ refreshToken: newRefreshToken,
1025
+ idToken: refreshResult.id_token,
1026
+ expiresAt,
1027
+ lastActivity: Date.now()
1028
+ });
1029
+ return {
1030
+ success: true,
1031
+ tokens: {
1032
+ access_token: refreshResult.access_token,
1033
+ refresh_token: newRefreshToken,
1034
+ id_token: refreshResult.id_token,
1035
+ expires_in: refreshResult.expires_in
1036
+ }
1037
+ };
1038
+ } catch (error) {
1039
+ logger.error("Token refresh failed with exception", error instanceof Error ? error : void 0);
1040
+ return {
1041
+ success: false,
1042
+ error: getOAuthErrorMessage(error),
1043
+ shouldLogout: shouldLogoutAfterOAuthError(error)
1044
+ };
1045
+ }
1046
+ }
1047
+ /**
1048
+ * Clear auth server cache (useful for testing)
1049
+ */
1050
+ function clearAuthServerCache() {
1051
+ authServerCache = null;
1052
+ jwksCache.clear();
1053
+ }
1054
+
1055
+ //#endregion
1056
+ export { clearAuthErrorHeaders, clearAuthServerCache, configureAuthClaimMapping, createRedirectResponse, extractUserInfo, getAccessToken, getAuthError, getUser, handleBackChannelLogout, handleCallback, handleFrontChannelLogout, hasAuthError, login, logout, refreshTokens, requireAuth, resetAuthClaimMapping };
1057
+ //# sourceMappingURL=auth.server-B3ODGIX4.js.map