@bymax-one/nest-auth 1.0.0

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.
@@ -0,0 +1,1083 @@
1
+ import { AUTH_DASHBOARD_ROUTES, AUTH_PROXY_ROUTES } from '@bymax-one/nest-auth/shared';
2
+ import { NextResponse } from 'next/server';
3
+
4
+ var __defProp = Object.defineProperty;
5
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
6
+
7
+ // src/nextjs/helpers/isBackgroundRequest.ts
8
+ function isBackgroundRequest(request) {
9
+ const { headers } = request;
10
+ return isNonEmptyHeader(headers.get("rsc")) || isNonEmptyHeader(headers.get("next-router-prefetch")) || isNonEmptyHeader(headers.get("next-router-state-tree"));
11
+ }
12
+ __name(isBackgroundRequest, "isBackgroundRequest");
13
+ function isNonEmptyHeader(value) {
14
+ return value !== null && value.length > 0;
15
+ }
16
+ __name(isNonEmptyHeader, "isNonEmptyHeader");
17
+ function buildSilentRefreshUrl(request, redirectTo) {
18
+ const requestUrl = new URL(request.url);
19
+ if (requestUrl.protocol !== "http:" && requestUrl.protocol !== "https:") {
20
+ throw new TypeError(`buildSilentRefreshUrl: unsupported URL protocol "${requestUrl.protocol}"`);
21
+ }
22
+ const silentRefreshUrl = new URL(AUTH_PROXY_ROUTES.silentRefresh, requestUrl.origin);
23
+ const destination = resolveDestination(request, requestUrl, redirectTo);
24
+ silentRefreshUrl.searchParams.set("redirect", destination);
25
+ return silentRefreshUrl.toString();
26
+ }
27
+ __name(buildSilentRefreshUrl, "buildSilentRefreshUrl");
28
+ function resolveDestination(request, requestUrl, redirectTo) {
29
+ if (typeof redirectTo === "string" && redirectTo.length > 0) {
30
+ return redirectTo;
31
+ }
32
+ if (request.nextUrl !== void 0) {
33
+ const hasOwnSearch = Object.prototype.hasOwnProperty.call(request.nextUrl, "search");
34
+ const search = hasOwnSearch ? request.nextUrl.search ?? "" : "";
35
+ return `${request.nextUrl.pathname}${search}`;
36
+ }
37
+ return `${requestUrl.pathname}${requestUrl.search}`;
38
+ }
39
+ __name(resolveDestination, "resolveDestination");
40
+
41
+ // src/nextjs/helpers/dedupeSetCookieHeaders.ts
42
+ var MAX_SET_COOKIE_LENGTH = 8192;
43
+ var MAX_SET_COOKIE_COUNT = 64;
44
+ function parseSetCookieHeader(raw) {
45
+ if (containsHeaderSmugglingBytes(raw)) return emptyParsedCookie();
46
+ if (raw.length > MAX_SET_COOKIE_LENGTH) return emptyParsedCookie();
47
+ const segments = raw.split(";").map((part) => part.trim());
48
+ const nameValueSegment = segments[0] ?? "";
49
+ const attributeSegments = segments.slice(1);
50
+ const firstEquals = nameValueSegment.indexOf("=");
51
+ const name = firstEquals >= 0 ? nameValueSegment.slice(0, firstEquals).trim() : "";
52
+ const value = firstEquals >= 0 ? nameValueSegment.slice(firstEquals + 1) : "";
53
+ const attributes = parseCookieAttributes(attributeSegments);
54
+ return {
55
+ name,
56
+ value,
57
+ ...attributes,
58
+ rawAttributes: attributeSegments
59
+ };
60
+ }
61
+ __name(parseSetCookieHeader, "parseSetCookieHeader");
62
+ function parseCookieAttributes(attributeSegments) {
63
+ let httpOnly = false;
64
+ let secure = false;
65
+ let sameSite;
66
+ let path;
67
+ let domain;
68
+ let maxAge;
69
+ let expires;
70
+ for (const attribute of attributeSegments) {
71
+ if (attribute.length === 0) continue;
72
+ const [attrName, attrValue] = splitAttribute(attribute);
73
+ switch (attrName) {
74
+ case "httponly":
75
+ httpOnly = true;
76
+ break;
77
+ case "secure":
78
+ secure = true;
79
+ break;
80
+ case "samesite":
81
+ sameSite = normaliseSameSite(attrValue);
82
+ break;
83
+ case "path":
84
+ path = attrValue;
85
+ break;
86
+ case "domain":
87
+ domain = attrValue.toLowerCase();
88
+ break;
89
+ case "max-age":
90
+ maxAge = parseMaxAge(attrValue);
91
+ break;
92
+ case "expires":
93
+ expires = attrValue;
94
+ break;
95
+ }
96
+ }
97
+ return {
98
+ httpOnly,
99
+ secure,
100
+ sameSite,
101
+ path,
102
+ domain,
103
+ maxAge,
104
+ expires
105
+ };
106
+ }
107
+ __name(parseCookieAttributes, "parseCookieAttributes");
108
+ function splitAttribute(attribute) {
109
+ const attrEquals = attribute.indexOf("=");
110
+ if (attrEquals < 0) return [
111
+ attribute.trim().toLowerCase(),
112
+ ""
113
+ ];
114
+ return [
115
+ attribute.slice(0, attrEquals).trim().toLowerCase(),
116
+ attribute.slice(attrEquals + 1).trim()
117
+ ];
118
+ }
119
+ __name(splitAttribute, "splitAttribute");
120
+ function normaliseSameSite(value) {
121
+ const normalised = value.toLowerCase();
122
+ if (normalised === "strict" || normalised === "lax" || normalised === "none") {
123
+ return normalised;
124
+ }
125
+ return void 0;
126
+ }
127
+ __name(normaliseSameSite, "normaliseSameSite");
128
+ function parseMaxAge(value) {
129
+ const parsed = Number.parseInt(value, 10);
130
+ return Number.isFinite(parsed) ? parsed : void 0;
131
+ }
132
+ __name(parseMaxAge, "parseMaxAge");
133
+ function dedupeSetCookieHeaders(cookies) {
134
+ const lastIndexByKey = /* @__PURE__ */ new Map();
135
+ for (let index = 0; index < cookies.length; index += 1) {
136
+ const raw = cookies[index];
137
+ if (raw === void 0) continue;
138
+ const parsed = parseSetCookieHeader(raw);
139
+ if (parsed.name.length === 0) continue;
140
+ lastIndexByKey.set(buildDedupKey(parsed.name, parsed.domain), index);
141
+ }
142
+ const winnerIndexes = Array.from(lastIndexByKey.values()).sort((a, b) => a - b);
143
+ const winners = [];
144
+ for (const index of winnerIndexes) {
145
+ const raw = cookies[index];
146
+ if (raw !== void 0) winners.push(raw);
147
+ }
148
+ return winners;
149
+ }
150
+ __name(dedupeSetCookieHeaders, "dedupeSetCookieHeaders");
151
+ function getSetCookieHeaders(headers) {
152
+ if (typeof headers.getSetCookie === "function") {
153
+ return headers.getSetCookie();
154
+ }
155
+ const combined = headers.get("set-cookie");
156
+ if (combined === null || combined.length === 0) return [];
157
+ return splitLegacySetCookie(combined);
158
+ }
159
+ __name(getSetCookieHeaders, "getSetCookieHeaders");
160
+ function buildDedupKey(name, domain) {
161
+ return `${name}|${domain ?? ""}`;
162
+ }
163
+ __name(buildDedupKey, "buildDedupKey");
164
+ function containsHeaderSmugglingBytes(raw) {
165
+ for (let i = 0; i < raw.length; i += 1) {
166
+ const code = raw.charCodeAt(i);
167
+ if (code === 10 || code === 13) return true;
168
+ }
169
+ return false;
170
+ }
171
+ __name(containsHeaderSmugglingBytes, "containsHeaderSmugglingBytes");
172
+ function emptyParsedCookie() {
173
+ return {
174
+ name: "",
175
+ value: "",
176
+ httpOnly: false,
177
+ secure: false,
178
+ sameSite: void 0,
179
+ path: void 0,
180
+ domain: void 0,
181
+ maxAge: void 0,
182
+ expires: void 0,
183
+ rawAttributes: []
184
+ };
185
+ }
186
+ __name(emptyParsedCookie, "emptyParsedCookie");
187
+ function splitLegacySetCookie(combined) {
188
+ if (combined.length > MAX_SET_COOKIE_LENGTH * MAX_SET_COOKIE_COUNT) return [];
189
+ const result = [];
190
+ let cursor = 0;
191
+ for (let index = 0; index < combined.length; index += 1) {
192
+ if (combined.charCodeAt(index) !== 44) continue;
193
+ if (looksLikeCookieStart(combined, index + 1)) {
194
+ result.push(combined.slice(cursor, index).trim());
195
+ cursor = index + 1;
196
+ }
197
+ }
198
+ result.push(combined.slice(cursor).trim());
199
+ return result.filter((entry) => entry.length > 0);
200
+ }
201
+ __name(splitLegacySetCookie, "splitLegacySetCookie");
202
+ function looksLikeCookieStart(candidate, startIndex) {
203
+ let index = startIndex;
204
+ while (index < candidate.length) {
205
+ const code = candidate.charCodeAt(index);
206
+ if (code !== 32 && code !== 9) break;
207
+ index += 1;
208
+ }
209
+ let tokenLength = 0;
210
+ while (
211
+ // Stryker disable next-line ConditionalExpression,EqualityOperator,ArithmeticOperator: the token is always `set()` before this scan, so index+tokenLength is always within bounds; the boundary/`true`/`-` variants are indistinguishable
212
+ index + tokenLength < candidate.length && isCookieNameChar(candidate.charCodeAt(index + tokenLength))
213
+ ) {
214
+ tokenLength += 1;
215
+ }
216
+ if (tokenLength === 0) return false;
217
+ return candidate.charCodeAt(index + tokenLength) === 61;
218
+ }
219
+ __name(looksLikeCookieStart, "looksLikeCookieStart");
220
+ function isCookieNameChar(code) {
221
+ if (code >= 48 && code <= 57) return true;
222
+ if (code >= 65 && code <= 90) return true;
223
+ if (code >= 97 && code <= 122) return true;
224
+ switch (code) {
225
+ case 33:
226
+ case 35:
227
+ case 36:
228
+ case 37:
229
+ case 38:
230
+ case 39:
231
+ case 42:
232
+ case 43:
233
+ case 45:
234
+ case 46:
235
+ case 94:
236
+ case 95:
237
+ case 96:
238
+ case 124:
239
+ case 126:
240
+ return true;
241
+ default:
242
+ return false;
243
+ }
244
+ }
245
+ __name(isCookieNameChar, "isCookieNameChar");
246
+
247
+ // src/nextjs/helpers/jwt.ts
248
+ function decodeJwtToken(token) {
249
+ const parts = token.split(".");
250
+ if (parts.length !== 3) return emptyDecoded();
251
+ const headerSegment = parts[0] ?? "";
252
+ const payloadSegment = parts[1] ?? "";
253
+ if (headerSegment.length === 0 || payloadSegment.length === 0) return emptyDecoded();
254
+ const header = safeJsonParse(base64UrlDecodeToString(headerSegment));
255
+ const payload = safeJsonParse(base64UrlDecodeToString(payloadSegment));
256
+ if (payload === void 0) return emptyDecoded();
257
+ return buildDecodedToken(header, payload);
258
+ }
259
+ __name(decodeJwtToken, "decodeJwtToken");
260
+ async function verifyJwtToken(token, secret) {
261
+ if (secret === void 0 || secret === null) {
262
+ return decodeJwtToken(token);
263
+ }
264
+ if (secret.length === 0) {
265
+ return emptyDecoded();
266
+ }
267
+ const parts = token.split(".");
268
+ if (parts.length !== 3) return emptyDecoded();
269
+ const headerSegment = parts[0] ?? "";
270
+ const payloadSegment = parts[1] ?? "";
271
+ const signatureSegment = parts[2] ?? "";
272
+ if (headerSegment.length === 0 || payloadSegment.length === 0 || signatureSegment.length === 0) {
273
+ return emptyDecoded();
274
+ }
275
+ const header = safeJsonParse(base64UrlDecodeToString(headerSegment));
276
+ if (header === void 0 || header.alg !== "HS256") return emptyDecoded();
277
+ const payload = safeJsonParse(base64UrlDecodeToString(payloadSegment));
278
+ if (payload === void 0) return emptyDecoded();
279
+ const signatureBytes = base64UrlDecodeToBytes(signatureSegment);
280
+ if (signatureBytes === void 0) return emptyDecoded();
281
+ const signatureValid = await verifyHs256Signature(headerSegment, payloadSegment, signatureBytes, secret);
282
+ if (!signatureValid) return emptyDecoded();
283
+ return buildDecodedToken(header, payload);
284
+ }
285
+ __name(verifyJwtToken, "verifyJwtToken");
286
+ async function verifyHs256Signature(headerSegment, payloadSegment, signatureBytes, secret) {
287
+ const signingInput = asciiBytes(`${headerSegment}.${payloadSegment}`);
288
+ const secretBytes = utf8Bytes(secret);
289
+ try {
290
+ const keyMaterial = await globalThis.crypto.subtle.importKey(
291
+ "raw",
292
+ toArrayBuffer(secretBytes),
293
+ {
294
+ name: "HMAC",
295
+ hash: "SHA-256"
296
+ },
297
+ // Stryker disable next-line BooleanLiteral: the importKey `extractable` flag does not affect verify results
298
+ false,
299
+ [
300
+ "verify"
301
+ ]
302
+ );
303
+ return await globalThis.crypto.subtle.verify("HMAC", keyMaterial, toArrayBuffer(signatureBytes), toArrayBuffer(signingInput));
304
+ } catch {
305
+ return false;
306
+ }
307
+ }
308
+ __name(verifyHs256Signature, "verifyHs256Signature");
309
+ function isTokenExpired(token) {
310
+ if (token.exp === void 0) return true;
311
+ const nowSeconds = Math.floor(Date.now() / 1e3);
312
+ return token.exp <= nowSeconds;
313
+ }
314
+ __name(isTokenExpired, "isTokenExpired");
315
+ function getUserRole(token) {
316
+ return token.role ?? "";
317
+ }
318
+ __name(getUserRole, "getUserRole");
319
+ function getUserId(token) {
320
+ return token.sub ?? "";
321
+ }
322
+ __name(getUserId, "getUserId");
323
+ function getTenantId(token) {
324
+ return token.tenantId;
325
+ }
326
+ __name(getTenantId, "getTenantId");
327
+ function buildDecodedToken(header, payload) {
328
+ const exp = asNumber(pickClaim(payload, "exp"));
329
+ const iat = asNumber(pickClaim(payload, "iat"));
330
+ const sub = asString(pickClaim(payload, "sub"));
331
+ const role = asString(pickClaim(payload, "role"));
332
+ const tenantId = asString(pickClaim(payload, "tenantId"));
333
+ const nowSeconds = Math.floor(Date.now() / 1e3);
334
+ const isValid = exp !== void 0 && exp > nowSeconds;
335
+ return {
336
+ isValid,
337
+ header,
338
+ payload,
339
+ sub,
340
+ role,
341
+ tenantId,
342
+ exp,
343
+ iat
344
+ };
345
+ }
346
+ __name(buildDecodedToken, "buildDecodedToken");
347
+ function pickClaim(payload, key) {
348
+ return Object.prototype.hasOwnProperty.call(payload, key) ? payload[key] : void 0;
349
+ }
350
+ __name(pickClaim, "pickClaim");
351
+ function toArrayBuffer(bytes) {
352
+ const copy = new Uint8Array(bytes.byteLength);
353
+ copy.set(bytes);
354
+ return copy.buffer;
355
+ }
356
+ __name(toArrayBuffer, "toArrayBuffer");
357
+ function emptyDecoded() {
358
+ return {
359
+ isValid: false,
360
+ header: void 0,
361
+ payload: {},
362
+ sub: void 0,
363
+ role: void 0,
364
+ tenantId: void 0,
365
+ exp: void 0,
366
+ iat: void 0
367
+ };
368
+ }
369
+ __name(emptyDecoded, "emptyDecoded");
370
+ function safeJsonParse(raw) {
371
+ if (raw === void 0) return void 0;
372
+ try {
373
+ const parsed = JSON.parse(raw);
374
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
375
+ return void 0;
376
+ }
377
+ return parsed;
378
+ } catch {
379
+ return void 0;
380
+ }
381
+ }
382
+ __name(safeJsonParse, "safeJsonParse");
383
+ function asNumber(value) {
384
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
385
+ }
386
+ __name(asNumber, "asNumber");
387
+ function asString(value) {
388
+ return typeof value === "string" ? value : void 0;
389
+ }
390
+ __name(asString, "asString");
391
+ function base64UrlDecodeToString(segment) {
392
+ const bytes = base64UrlDecodeToBytes(segment);
393
+ if (bytes === void 0) return void 0;
394
+ try {
395
+ return new TextDecoder("utf-8", {
396
+ fatal: true
397
+ }).decode(bytes);
398
+ } catch {
399
+ return void 0;
400
+ }
401
+ }
402
+ __name(base64UrlDecodeToString, "base64UrlDecodeToString");
403
+ function base64UrlDecodeToBytes(segment) {
404
+ if (!/^[A-Za-z0-9_-]*$/.test(segment)) return void 0;
405
+ const padded = segment.replace(/-/g, "+").replace(/_/g, "/");
406
+ const padding = (4 - padded.length % 4) % 4;
407
+ const base64 = padded + "=".repeat(padding);
408
+ try {
409
+ const binary = atob(base64);
410
+ const out = new Uint8Array(binary.length);
411
+ for (let i = 0; i < binary.length; i += 1) {
412
+ out[i] = binary.charCodeAt(i);
413
+ }
414
+ return out;
415
+ } catch {
416
+ return void 0;
417
+ }
418
+ }
419
+ __name(base64UrlDecodeToBytes, "base64UrlDecodeToBytes");
420
+ function asciiBytes(input) {
421
+ const out = new Uint8Array(input.length);
422
+ for (let i = 0; i < input.length; i += 1) {
423
+ const code = input.charCodeAt(i);
424
+ if (code > 127) {
425
+ throw new TypeError(`asciiBytes: non-ASCII character at index ${i}`);
426
+ }
427
+ out[i] = code;
428
+ }
429
+ return out;
430
+ }
431
+ __name(asciiBytes, "asciiBytes");
432
+ function utf8Bytes(input) {
433
+ return new TextEncoder().encode(input);
434
+ }
435
+ __name(utf8Bytes, "utf8Bytes");
436
+
437
+ // src/nextjs/internal/constants.ts
438
+ var DEFAULT_MAX_REFRESH_ATTEMPTS = 2;
439
+ var REFRESH_ATTEMPT_PARAM = "_r";
440
+ var REASON_PARAM = "reason";
441
+ var REASON_EXPIRED = "expired";
442
+ var IDENTITY_HEADERS_BASELINE = [
443
+ "x-user-id",
444
+ "x-user-role",
445
+ "x-tenant-id",
446
+ "x-tenant-domain"
447
+ ];
448
+
449
+ // src/nextjs/helpers/routeHandlerUtils.ts
450
+ function serializeClearCookie(name, path) {
451
+ return `${name}=; Path=${path}; Max-Age=0; HttpOnly; Secure; SameSite=Strict`;
452
+ }
453
+ __name(serializeClearCookie, "serializeClearCookie");
454
+ function isSafeSameOriginPath(candidate) {
455
+ return typeof candidate === "string" && // Stryker disable next-line EqualityOperator,ConditionalExpression: redundant non-empty check: `candidate.startsWith('/')` below already implies length > 0, so `> 0`/`>= 0`/`true` are indistinguishable
456
+ candidate.length > 0 && candidate.startsWith("/") && !candidate.startsWith("//") && !/[\\\r\n\0]/.test(candidate);
457
+ }
458
+ __name(isSafeSameOriginPath, "isSafeSameOriginPath");
459
+ function isSafeUpstreamPath(candidate) {
460
+ if (typeof candidate !== "string") return false;
461
+ if (!candidate.startsWith("/")) return false;
462
+ if (candidate.includes("..")) return false;
463
+ return !/[?#\\\r\n\0]/.test(candidate);
464
+ }
465
+ __name(isSafeUpstreamPath, "isSafeUpstreamPath");
466
+ function assertSafeCookieName(value, factoryName, label) {
467
+ if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(value)) {
468
+ throw new Error(`${factoryName}: invalid cookie name "${value}" for ${label}.`);
469
+ }
470
+ }
471
+ __name(assertSafeCookieName, "assertSafeCookieName");
472
+ function assertSafeCookiePath(value, factoryName, label) {
473
+ if (!/^\/[\x20-\x3A\x3C-\x7E]*$/.test(value)) {
474
+ throw new Error(`${factoryName}: invalid cookie path "${value}" for ${label}.`);
475
+ }
476
+ }
477
+ __name(assertSafeCookiePath, "assertSafeCookiePath");
478
+ function trimTrailingSlash(value) {
479
+ return value.endsWith("/") ? value.slice(0, -1) : value;
480
+ }
481
+ __name(trimTrailingSlash, "trimTrailingSlash");
482
+
483
+ // src/nextjs/internal/configValidation.ts
484
+ function validateConfig(config) {
485
+ if (!isSafeSameOriginPath(config.loginPath)) {
486
+ throw new Error(`createAuthProxy: loginPath "${config.loginPath}" must be a same-origin pathname starting with "/" (not "//") and must not contain CR/LF/NUL/backslash characters.`);
487
+ }
488
+ for (const route of config.protectedRoutes) {
489
+ validateProtectedRoutePattern(route.pattern);
490
+ if (route.redirectPath !== void 0 && !isSafeSameOriginPath(route.redirectPath)) {
491
+ throw new Error(`createAuthProxy: redirectPath "${route.redirectPath}" in pattern "${route.pattern}" must be a same-origin pathname starting with "/" (not "//") and must not contain CR/LF/NUL/backslash characters.`);
492
+ }
493
+ }
494
+ }
495
+ __name(validateConfig, "validateConfig");
496
+ function validateProtectedRoutePattern(pattern) {
497
+ const segments = pattern.split("/").filter((segment) => segment.length > 0);
498
+ for (let i = 0; i < segments.length; i += 1) {
499
+ const segment = segments[i] ?? "";
500
+ const isGlob = segment === "*" || segment.endsWith("*");
501
+ if (!isGlob) continue;
502
+ const isLast = i === segments.length - 1;
503
+ if (!isLast) {
504
+ throw new Error(`createAuthProxy: protected route pattern "${pattern}" contains a wildcard in a non-trailing position. Wildcards are only permitted as the last segment.`);
505
+ }
506
+ if (i === 0) {
507
+ throw new Error(`createAuthProxy: protected route pattern "${pattern}" begins with a catch-all wildcard, which would promote every route to protected status. Use a concrete prefix segment.`);
508
+ }
509
+ }
510
+ }
511
+ __name(validateProtectedRoutePattern, "validateProtectedRoutePattern");
512
+ function resolveConfig(config) {
513
+ return {
514
+ ...config,
515
+ maxRefreshAttempts: config.maxRefreshAttempts ?? DEFAULT_MAX_REFRESH_ATTEMPTS
516
+ };
517
+ }
518
+ __name(resolveConfig, "resolveConfig");
519
+ function warnOnInsecureConfiguration(config) {
520
+ if (config.jwtSecret !== void 0 && config.jwtSecret.length > 0) return;
521
+ if (isProductionEnv()) {
522
+ throw new Error("createAuthProxy: jwtSecret is required in production. Without it the proxy runs in decode-only mode where RBAC and status-blocking trust unverified tokens \u2014 a crafted token with a future `exp` can impersonate any role. Provide `jwtSecret` or move signature verification to an upstream gateway and explicitly opt out by running outside of a production environment.");
523
+ }
524
+ if (typeof console === "undefined" || typeof console.warn !== "function") return;
525
+ console.warn("[@bymax-one/nest-auth] createAuthProxy: jwtSecret is not configured. The proxy is running in decode-only mode \u2014 JWT signatures are NOT verified. Every RBAC and status-blocking decision trusts the raw token contents, and forged tokens with a future `exp` can impersonate any role. Ensure an upstream gateway verifies signatures before requests reach downstream server components that read the injected identity headers. In production this condition throws instead of warning.");
526
+ }
527
+ __name(warnOnInsecureConfiguration, "warnOnInsecureConfiguration");
528
+ function isProductionEnv() {
529
+ return process.env["NODE_ENV"] === "production";
530
+ }
531
+ __name(isProductionEnv, "isProductionEnv");
532
+
533
+ // src/nextjs/internal/proxyUtils.ts
534
+ function readRefreshAttemptCounter(request, maxAllowed) {
535
+ const raw = request.nextUrl.searchParams.get(REFRESH_ATTEMPT_PARAM);
536
+ if (raw === null) return 0;
537
+ const parsed = Number.parseInt(raw, 10);
538
+ if (!Number.isFinite(parsed) || parsed < 0) return 0;
539
+ return Math.min(parsed, maxAllowed);
540
+ }
541
+ __name(readRefreshAttemptCounter, "readRefreshAttemptCounter");
542
+ function isReasonExpired(request) {
543
+ return request.nextUrl.searchParams.get(REASON_PARAM) === REASON_EXPIRED;
544
+ }
545
+ __name(isReasonExpired, "isReasonExpired");
546
+ function safeRelativePath(candidate, fallback) {
547
+ return isSafeSameOriginPath(candidate) ? candidate : fallback;
548
+ }
549
+ __name(safeRelativePath, "safeRelativePath");
550
+ function buildRefreshDestination(pathname, searchParams, nextCounter) {
551
+ const cleaned = new URLSearchParams(searchParams);
552
+ cleaned.delete(REFRESH_ATTEMPT_PARAM);
553
+ cleaned.delete(REASON_PARAM);
554
+ cleaned.set(REFRESH_ATTEMPT_PARAM, String(nextCounter));
555
+ const query = cleaned.toString();
556
+ return query.length > 0 ? `${pathname}?${query}` : pathname;
557
+ }
558
+ __name(buildRefreshDestination, "buildRefreshDestination");
559
+ function buildSanitizedRequestHeaders(request, config) {
560
+ const headers = new Headers(request.headers);
561
+ for (const name of IDENTITY_HEADERS_BASELINE) {
562
+ headers.delete(name);
563
+ }
564
+ headers.delete(config.userHeaders.userId);
565
+ headers.delete(config.userHeaders.role);
566
+ headers.delete(config.userHeaders.tenantId);
567
+ headers.delete(config.userHeaders.tenantDomain);
568
+ return headers;
569
+ }
570
+ __name(buildSanitizedRequestHeaders, "buildSanitizedRequestHeaders");
571
+ function setOrDeleteHeader(headers, name, value) {
572
+ if (value === void 0 || value.length === 0) {
573
+ headers.delete(name);
574
+ return;
575
+ }
576
+ headers.set(name, sanitizeHeaderValue(value));
577
+ }
578
+ __name(setOrDeleteHeader, "setOrDeleteHeader");
579
+ function sanitizeHeaderValue(value) {
580
+ return value.replace(/[\r\n\0]/g, "");
581
+ }
582
+ __name(sanitizeHeaderValue, "sanitizeHeaderValue");
583
+ function asString2(value) {
584
+ return typeof value === "string" ? value : void 0;
585
+ }
586
+ __name(asString2, "asString");
587
+
588
+ // src/nextjs/internal/routeClassifier.ts
589
+ function classifyRoute(pathname, config) {
590
+ if (pathname.startsWith("/api/auth/")) {
591
+ return {
592
+ kind: "api",
593
+ matched: void 0
594
+ };
595
+ }
596
+ for (const route of config.protectedRoutes) {
597
+ if (matchesRoutePattern(pathname, route.pattern)) {
598
+ return {
599
+ kind: "protected",
600
+ matched: route
601
+ };
602
+ }
603
+ }
604
+ for (const route of config.publicRoutes) {
605
+ if (matchesPublicRoute(pathname, route)) {
606
+ return {
607
+ kind: "public",
608
+ matched: void 0
609
+ };
610
+ }
611
+ }
612
+ return {
613
+ kind: "unmatched",
614
+ matched: void 0
615
+ };
616
+ }
617
+ __name(classifyRoute, "classifyRoute");
618
+ function matchesPublicRoute(pathname, route) {
619
+ if (pathname === route) return true;
620
+ if (route.endsWith("/")) return pathname.startsWith(route);
621
+ return pathname.startsWith(`${route}/`);
622
+ }
623
+ __name(matchesPublicRoute, "matchesPublicRoute");
624
+ function matchesRoutePattern(pathname, pattern) {
625
+ if (pattern === pathname) return true;
626
+ const patternSegments = pattern.split("/").filter((segment) => segment.length > 0);
627
+ const pathSegments = pathname.split("/").filter((segment) => segment.length > 0);
628
+ for (let i = 0; i < patternSegments.length; i += 1) {
629
+ const patternSegment = patternSegments[i] ?? "";
630
+ const isTrailingGlob = (
631
+ // Stryker disable next-line ConditionalExpression,StringLiteral: `patternSegment === '*'` is subsumed by `patternSegment.endsWith('*')`, so dropping it or comparing against '' cannot change the match
632
+ i === patternSegments.length - 1 && (patternSegment === "*" || patternSegment.endsWith("*"))
633
+ );
634
+ if (isTrailingGlob) {
635
+ return true;
636
+ }
637
+ if (i >= pathSegments.length) {
638
+ return false;
639
+ }
640
+ const pathSegment = pathSegments[i] ?? "";
641
+ if (patternSegment.startsWith(":")) {
642
+ continue;
643
+ }
644
+ if (patternSegment !== pathSegment) return false;
645
+ }
646
+ return pathSegments.length === patternSegments.length;
647
+ }
648
+ __name(matchesRoutePattern, "matchesRoutePattern");
649
+ function normalizePath(pathname) {
650
+ try {
651
+ return new URL(pathname, "http://placeholder.invalid").pathname;
652
+ } catch {
653
+ return "/";
654
+ }
655
+ }
656
+ __name(normalizePath, "normalizePath");
657
+
658
+ // src/nextjs/internal/proxyHandlers.ts
659
+ function handlePublicRoute(request, pathname, tokenState, config, sanitizedHeaders) {
660
+ const refreshAttempts = readRefreshAttemptCounter(request, config.maxRefreshAttempts);
661
+ const shouldBreakForReason = isReasonExpired(request);
662
+ const shouldBreakForCounter = refreshAttempts >= config.maxRefreshAttempts;
663
+ if (tokenState.authenticated) {
664
+ return handleAuthenticatedOnPublic(request, pathname, tokenState, config, sanitizedHeaders);
665
+ }
666
+ const hasSessionCookie = request.cookies.get(config.cookieNames.hasSession)?.value;
667
+ const hasSession = hasSessionCookie !== void 0 && hasSessionCookie.length > 0;
668
+ if (shouldBreakForCounter || shouldBreakForReason) {
669
+ return NextResponse.next({
670
+ request: {
671
+ headers: sanitizedHeaders
672
+ }
673
+ });
674
+ }
675
+ if (hasSession) {
676
+ const destination = buildRefreshDestination(pathname, request.nextUrl.searchParams, refreshAttempts + 1);
677
+ const silentRefreshUrl = new URL(buildSilentRefreshUrl(request, destination));
678
+ return NextResponse.redirect(silentRefreshUrl);
679
+ }
680
+ return NextResponse.next({
681
+ request: {
682
+ headers: sanitizedHeaders
683
+ }
684
+ });
685
+ }
686
+ __name(handlePublicRoute, "handlePublicRoute");
687
+ function handleAuthenticatedOnPublic(request, pathname, tokenState, config, sanitizedHeaders) {
688
+ const role = tokenState.token?.role ?? "";
689
+ const reasonPresent = request.nextUrl.searchParams.has(REASON_PARAM);
690
+ const isRedirectIfAuth = config.publicRoutesRedirectIfAuthenticated.some((route) => matchesPublicRoute(pathname, route));
691
+ if (isRedirectIfAuth && !reasonPresent) {
692
+ const destination = safeRelativePath(config.getDefaultDashboard(role), "/");
693
+ return NextResponse.redirect(new URL(destination, request.nextUrl.origin));
694
+ }
695
+ return NextResponse.next({
696
+ request: {
697
+ headers: sanitizedHeaders
698
+ }
699
+ });
700
+ }
701
+ __name(handleAuthenticatedOnPublic, "handleAuthenticatedOnPublic");
702
+ function handleProtectedRoute(request, pathname, tokenState, matched, config, sanitizedHeaders) {
703
+ if (!tokenState.authenticated) {
704
+ return handleUnauthenticatedOnProtected(request, pathname, tokenState, config);
705
+ }
706
+ const token = tokenState.token;
707
+ const role = token?.role ?? "";
708
+ const status = asString2(token?.payload["status"]);
709
+ if (typeof status === "string" && status.length > 0) {
710
+ const statusLower = status.toLocaleLowerCase("en-US");
711
+ const matchedStatus = config.blockedUserStatuses.find((entry) => entry.toLocaleLowerCase("en-US") === statusLower);
712
+ if (matchedStatus !== void 0) {
713
+ return redirectToLogin(request, config, matchedStatus.toLocaleLowerCase("en-US"));
714
+ }
715
+ }
716
+ if (!matched.allowedRoles.includes(role)) {
717
+ const fallback = safeRelativePath(config.getDefaultDashboard(role), "/");
718
+ const destination = matched.redirectPath ?? fallback;
719
+ const safeDestination = safeRelativePath(destination, fallback);
720
+ const url = new URL(safeDestination, request.nextUrl.origin);
721
+ url.searchParams.set("error", "forbidden");
722
+ return NextResponse.redirect(url);
723
+ }
724
+ return buildAuthorisedResponse(request, token, role, config, sanitizedHeaders);
725
+ }
726
+ __name(handleProtectedRoute, "handleProtectedRoute");
727
+ function handleUnauthenticatedOnProtected(request, pathname, tokenState, config) {
728
+ const refreshAttempts = readRefreshAttemptCounter(request, config.maxRefreshAttempts);
729
+ const shouldBreakForReason = isReasonExpired(request);
730
+ const shouldBreakForCounter = refreshAttempts >= config.maxRefreshAttempts;
731
+ const hasSessionCookie = request.cookies.get(config.cookieNames.hasSession)?.value;
732
+ const hasSession = hasSessionCookie !== void 0 && hasSessionCookie.length > 0;
733
+ if (!tokenState.hasCookie && !hasSession) {
734
+ return redirectToLogin(request, config);
735
+ }
736
+ if (shouldBreakForCounter || shouldBreakForReason) {
737
+ return redirectToLogin(request, config, REASON_EXPIRED);
738
+ }
739
+ if (hasSession) {
740
+ const destination = buildRefreshDestination(pathname, request.nextUrl.searchParams, refreshAttempts + 1);
741
+ const silentRefreshUrl = new URL(buildSilentRefreshUrl(request, destination));
742
+ return NextResponse.redirect(silentRefreshUrl);
743
+ }
744
+ return redirectToLogin(request, config);
745
+ }
746
+ __name(handleUnauthenticatedOnProtected, "handleUnauthenticatedOnProtected");
747
+ function buildAuthorisedResponse(request, token, role, config, sanitizedHeaders) {
748
+ const forwardedHeaders = new Headers(sanitizedHeaders);
749
+ setOrDeleteHeader(forwardedHeaders, config.userHeaders.userId, token?.sub);
750
+ setOrDeleteHeader(forwardedHeaders, config.userHeaders.role, role);
751
+ setOrDeleteHeader(forwardedHeaders, config.userHeaders.tenantId, token?.tenantId);
752
+ setOrDeleteHeader(forwardedHeaders, config.userHeaders.tenantDomain, asString2(token?.payload["tenantDomain"]));
753
+ const responseInit = {
754
+ request: {
755
+ headers: forwardedHeaders
756
+ }
757
+ };
758
+ if (!request.nextUrl.searchParams.has(REFRESH_ATTEMPT_PARAM)) {
759
+ return NextResponse.next(responseInit);
760
+ }
761
+ const cleanUrl = new URL(request.nextUrl);
762
+ cleanUrl.searchParams.delete(REFRESH_ATTEMPT_PARAM);
763
+ return NextResponse.rewrite(cleanUrl, responseInit);
764
+ }
765
+ __name(buildAuthorisedResponse, "buildAuthorisedResponse");
766
+ function redirectToLogin(request, config, reason) {
767
+ const loginPath = safeRelativePath(config.loginPath, "/");
768
+ const url = new URL(loginPath, request.nextUrl.origin);
769
+ if (reason !== void 0 && reason.length > 0) {
770
+ url.searchParams.set(REASON_PARAM, reason);
771
+ }
772
+ return NextResponse.redirect(url);
773
+ }
774
+ __name(redirectToLogin, "redirectToLogin");
775
+
776
+ // src/nextjs/internal/tokenState.ts
777
+ async function readTokenState(request, config) {
778
+ const raw = request.cookies.get(config.cookieNames.access)?.value;
779
+ if (raw === void 0 || raw.length === 0) {
780
+ return {
781
+ token: void 0,
782
+ hasCookie: false,
783
+ authenticated: false,
784
+ signatureVerified: false
785
+ };
786
+ }
787
+ const hasSecret = config.jwtSecret !== void 0 && config.jwtSecret.length > 0;
788
+ const decoded = hasSecret ? await verifyJwtToken(raw, config.jwtSecret) : decodeJwtToken(raw);
789
+ return {
790
+ token: decoded,
791
+ hasCookie: true,
792
+ authenticated: decoded.isValid,
793
+ signatureVerified: hasSecret && decoded.isValid
794
+ };
795
+ }
796
+ __name(readTokenState, "readTokenState");
797
+
798
+ // src/nextjs/createAuthProxy.ts
799
+ function createAuthProxy(config) {
800
+ validateConfig(config);
801
+ const resolved = resolveConfig(config);
802
+ warnOnInsecureConfiguration(resolved);
803
+ return {
804
+ proxy: /* @__PURE__ */ __name((request) => runProxy(request, resolved), "proxy"),
805
+ config: resolved
806
+ };
807
+ }
808
+ __name(createAuthProxy, "createAuthProxy");
809
+ async function runProxy(request, resolved) {
810
+ const pathname = normalizePath(request.nextUrl.pathname);
811
+ const classification = classifyRoute(pathname, resolved);
812
+ if (classification.kind === "api") {
813
+ return NextResponse.next();
814
+ }
815
+ const tokenState = await readTokenState(request, resolved);
816
+ const sanitizedHeaders = buildSanitizedRequestHeaders(request, resolved);
817
+ if (isBackgroundRequest(request) && !tokenState.authenticated) {
818
+ return new NextResponse(null, {
819
+ status: 401,
820
+ headers: {
821
+ "Cache-Control": "no-store, no-cache"
822
+ }
823
+ });
824
+ }
825
+ if (classification.kind === "protected") {
826
+ return handleProtectedRoute(request, pathname, tokenState, classification.matched, resolved, sanitizedHeaders);
827
+ }
828
+ return handlePublicRoute(request, pathname, tokenState, resolved, sanitizedHeaders);
829
+ }
830
+ __name(runProxy, "runProxy");
831
+ var DEFAULT_REFRESH_PATH = `/auth/${AUTH_DASHBOARD_ROUTES.refresh}`;
832
+ function buildRefreshUrl(apiBase, refreshPath) {
833
+ return `${trimTrailingSlash(apiBase)}${refreshPath ?? DEFAULT_REFRESH_PATH}`;
834
+ }
835
+ __name(buildRefreshUrl, "buildRefreshUrl");
836
+ function assertValidApiBase(apiBase, factoryName) {
837
+ if (typeof apiBase !== "string" || apiBase.length === 0) {
838
+ throw new Error(`${factoryName}: apiBase must be a non-empty string.`);
839
+ }
840
+ if (!apiBase.startsWith("http://") && !apiBase.startsWith("https://")) {
841
+ throw new Error(`${factoryName}: apiBase "${apiBase}" must be an absolute URL starting with http:// or https://.`);
842
+ }
843
+ }
844
+ __name(assertValidApiBase, "assertValidApiBase");
845
+ function assertValidUpstreamPath(path, factoryName, label) {
846
+ if (path === void 0) return;
847
+ if (!isSafeUpstreamPath(path)) {
848
+ throw new Error(`${factoryName}: ${label} "${path}" must be a same-origin pathname starting with "/" and must not contain ".." or URL control characters.`);
849
+ }
850
+ }
851
+ __name(assertValidUpstreamPath, "assertValidUpstreamPath");
852
+
853
+ // src/nextjs/createSilentRefreshHandler.ts
854
+ var DEFAULT_REFRESH_COOKIE_PATH = "/api/auth";
855
+ function createSilentRefreshHandler(config) {
856
+ if (!isSafeSameOriginPath(config.loginPath)) {
857
+ throw new Error(`createSilentRefreshHandler: loginPath "${config.loginPath}" must be a same-origin pathname starting with "/" (not "//") and must not contain CR/LF/NUL/backslash characters.`);
858
+ }
859
+ assertValidApiBase(config.apiBase, "createSilentRefreshHandler");
860
+ assertValidUpstreamPath(config.refreshPath, "createSilentRefreshHandler", "refreshPath");
861
+ assertSafeCookieName(config.cookieNames.access, "createSilentRefreshHandler", "cookieNames.access");
862
+ assertSafeCookieName(config.cookieNames.refresh, "createSilentRefreshHandler", "cookieNames.refresh");
863
+ assertSafeCookieName(config.cookieNames.hasSession, "createSilentRefreshHandler", "cookieNames.hasSession");
864
+ const refreshCookiePath = config.refreshCookiePath ?? DEFAULT_REFRESH_COOKIE_PATH;
865
+ assertSafeCookiePath(refreshCookiePath, "createSilentRefreshHandler", "refreshCookiePath");
866
+ const refreshUrl = buildRefreshUrl(config.apiBase, config.refreshPath);
867
+ return /* @__PURE__ */ __name(async function silentRefreshHandler(request) {
868
+ const origin = request.nextUrl.origin;
869
+ const rawDestination = request.nextUrl.searchParams.get("redirect");
870
+ const destination = resolveSafeDestination(rawDestination, origin, config.loginPath);
871
+ let upstream;
872
+ try {
873
+ upstream = await fetch(refreshUrl, {
874
+ method: "POST",
875
+ headers: {
876
+ cookie: request.headers.get("cookie") ?? "",
877
+ accept: "application/json"
878
+ },
879
+ // Do not follow redirects automatically — the upstream is
880
+ // expected to respond with the new cookies on 2xx or an
881
+ // auth error on 4xx/5xx; a redirect would indicate
882
+ // misconfiguration and must not be silently followed. Do
883
+ // not change this to `'follow'` without updating the
884
+ // opaque-redirect guard below.
885
+ redirect: "manual"
886
+ });
887
+ } catch {
888
+ return buildLogoutRedirect(origin, config);
889
+ }
890
+ if (upstream.type === "opaqueredirect") {
891
+ return buildLogoutRedirect(origin, config);
892
+ }
893
+ if (!upstream.ok) {
894
+ return buildLogoutRedirect(origin, config);
895
+ }
896
+ const rawSetCookies = getSetCookieHeaders(upstream.headers);
897
+ if (rawSetCookies.length === 0) {
898
+ return buildLogoutRedirect(origin, config);
899
+ }
900
+ return buildSuccessRedirect(origin, destination, rawSetCookies);
901
+ }, "silentRefreshHandler");
902
+ }
903
+ __name(createSilentRefreshHandler, "createSilentRefreshHandler");
904
+ function resolveSafeDestination(raw, origin, loginPath) {
905
+ if (raw === null || raw.length === 0) return loginPath;
906
+ if (!raw.startsWith("/")) return loginPath;
907
+ if (raw.startsWith("//")) return loginPath;
908
+ if (/[\\\r\n\0]/.test(raw)) return loginPath;
909
+ let resolved;
910
+ try {
911
+ resolved = new URL(raw, origin);
912
+ } catch {
913
+ return loginPath;
914
+ }
915
+ if (resolved.origin !== origin) return loginPath;
916
+ return `${resolved.pathname}${resolved.search}${resolved.hash}`;
917
+ }
918
+ __name(resolveSafeDestination, "resolveSafeDestination");
919
+ function buildSuccessRedirect(origin, destination, rawSetCookies) {
920
+ const destinationUrl = new URL(destination, origin);
921
+ const response = NextResponse.redirect(destinationUrl);
922
+ response.headers.set("Cache-Control", "no-store, no-cache");
923
+ const deduped = dedupeSetCookieHeaders(rawSetCookies);
924
+ for (const cookie of deduped) {
925
+ response.headers.append("set-cookie", cookie);
926
+ }
927
+ return response;
928
+ }
929
+ __name(buildSuccessRedirect, "buildSuccessRedirect");
930
+ function buildLogoutRedirect(origin, config) {
931
+ const loginUrl = new URL(config.loginPath, origin);
932
+ loginUrl.searchParams.set("reason", "expired");
933
+ const response = NextResponse.redirect(loginUrl);
934
+ response.headers.set("Cache-Control", "no-store, no-cache");
935
+ const clearCookies = [
936
+ serializeClearCookie(config.cookieNames.access, "/"),
937
+ serializeClearCookie(config.cookieNames.refresh, config.refreshCookiePath ?? DEFAULT_REFRESH_COOKIE_PATH),
938
+ serializeClearCookie(config.cookieNames.hasSession, "/")
939
+ ];
940
+ for (const cookie of clearCookies) {
941
+ response.headers.append("set-cookie", cookie);
942
+ }
943
+ return response;
944
+ }
945
+ __name(buildLogoutRedirect, "buildLogoutRedirect");
946
+ var SILENT_REFRESH_ROUTE = AUTH_PROXY_ROUTES.silentRefresh;
947
+ function createClientRefreshHandler(config) {
948
+ assertValidApiBase(config.apiBase, "createClientRefreshHandler");
949
+ const refreshUrl = buildRefreshUrl(config.apiBase, config.refreshPath);
950
+ return /* @__PURE__ */ __name(async function clientRefreshHandler(request) {
951
+ if (request.method !== "POST") {
952
+ return new Response(null, {
953
+ status: 405,
954
+ headers: {
955
+ Allow: "POST",
956
+ "Cache-Control": "no-store, no-cache"
957
+ }
958
+ });
959
+ }
960
+ let upstream;
961
+ try {
962
+ upstream = await fetch(refreshUrl, {
963
+ method: "POST",
964
+ headers: {
965
+ cookie: request.headers.get("cookie") ?? "",
966
+ accept: "application/json"
967
+ },
968
+ // Manual — a 3xx from the upstream should never be followed
969
+ // silently. See NEST-177 for the rationale.
970
+ redirect: "manual"
971
+ });
972
+ } catch {
973
+ return buildUnauthorisedResponse();
974
+ }
975
+ if (upstream.type === "opaqueredirect" || !upstream.ok) {
976
+ return buildUnauthorisedResponse();
977
+ }
978
+ const rawSetCookies = getSetCookieHeaders(upstream.headers);
979
+ if (rawSetCookies.length === 0) {
980
+ return buildUnauthorisedResponse();
981
+ }
982
+ const responseHeaders = new Headers({
983
+ "Cache-Control": "no-store, no-cache"
984
+ });
985
+ for (const cookie of dedupeSetCookieHeaders(rawSetCookies)) {
986
+ responseHeaders.append("set-cookie", cookie);
987
+ }
988
+ return new Response(null, {
989
+ status: 200,
990
+ headers: responseHeaders
991
+ });
992
+ }, "clientRefreshHandler");
993
+ }
994
+ __name(createClientRefreshHandler, "createClientRefreshHandler");
995
+ function buildUnauthorisedResponse() {
996
+ return new Response(null, {
997
+ status: 401,
998
+ headers: {
999
+ "Cache-Control": "no-store, no-cache"
1000
+ }
1001
+ });
1002
+ }
1003
+ __name(buildUnauthorisedResponse, "buildUnauthorisedResponse");
1004
+ var CLIENT_REFRESH_ROUTE = AUTH_PROXY_ROUTES.clientRefresh;
1005
+ var DEFAULT_LOGOUT_PATH = `/auth/${AUTH_DASHBOARD_ROUTES.logout}`;
1006
+ var DEFAULT_REFRESH_COOKIE_PATH2 = "/api/auth";
1007
+ function createLogoutHandler(config) {
1008
+ const refreshCookiePath = validateLogoutConfig(config);
1009
+ const logoutUrl = `${trimTrailingSlash(config.apiBase)}${config.logoutPath ?? DEFAULT_LOGOUT_PATH}`;
1010
+ return /* @__PURE__ */ __name(async function logoutHandler(request) {
1011
+ if (request.method !== "POST") {
1012
+ return new Response(null, {
1013
+ status: 405,
1014
+ headers: {
1015
+ Allow: "POST",
1016
+ "Cache-Control": "no-store, no-cache"
1017
+ }
1018
+ });
1019
+ }
1020
+ const upstreamHeaders = {
1021
+ cookie: request.headers.get("cookie") ?? "",
1022
+ accept: "application/json"
1023
+ };
1024
+ const incomingAuth = request.headers.get("authorization");
1025
+ if (incomingAuth) upstreamHeaders.authorization = incomingAuth;
1026
+ try {
1027
+ await fetch(logoutUrl, {
1028
+ method: "POST",
1029
+ headers: upstreamHeaders,
1030
+ redirect: "manual"
1031
+ });
1032
+ } catch {
1033
+ }
1034
+ return buildLogoutResponse(request, config, refreshCookiePath);
1035
+ }, "logoutHandler");
1036
+ }
1037
+ __name(createLogoutHandler, "createLogoutHandler");
1038
+ function validateLogoutConfig(config) {
1039
+ assertValidApiBase(config.apiBase, "createLogoutHandler");
1040
+ assertValidUpstreamPath(config.logoutPath, "createLogoutHandler", "logoutPath");
1041
+ assertSafeCookieName(config.cookieNames.access, "createLogoutHandler", "cookieNames.access");
1042
+ assertSafeCookieName(config.cookieNames.refresh, "createLogoutHandler", "cookieNames.refresh");
1043
+ assertSafeCookieName(config.cookieNames.hasSession, "createLogoutHandler", "cookieNames.hasSession");
1044
+ const refreshCookiePath = config.refreshCookiePath ?? DEFAULT_REFRESH_COOKIE_PATH2;
1045
+ assertSafeCookiePath(refreshCookiePath, "createLogoutHandler", "refreshCookiePath");
1046
+ if (config.mode === "redirect" && !isSafeSameOriginPath(config.loginPath)) {
1047
+ throw new Error(`createLogoutHandler: loginPath "${config.loginPath}" must be a same-origin pathname starting with "/" (not "//") and must not contain CR/LF/NUL/backslash characters.`);
1048
+ }
1049
+ return refreshCookiePath;
1050
+ }
1051
+ __name(validateLogoutConfig, "validateLogoutConfig");
1052
+ function buildLogoutResponse(request, config, refreshCookiePath) {
1053
+ if (config.mode === "redirect") {
1054
+ const loginUrl = new URL(config.loginPath, request.nextUrl.origin);
1055
+ const response2 = NextResponse.redirect(loginUrl);
1056
+ attachClearCookies(response2, config, refreshCookiePath);
1057
+ response2.headers.set("Cache-Control", "no-store, no-cache");
1058
+ return response2;
1059
+ }
1060
+ const response = new Response(null, {
1061
+ status: 200,
1062
+ headers: {
1063
+ "Cache-Control": "no-store, no-cache"
1064
+ }
1065
+ });
1066
+ attachClearCookies(response, config, refreshCookiePath);
1067
+ return response;
1068
+ }
1069
+ __name(buildLogoutResponse, "buildLogoutResponse");
1070
+ function attachClearCookies(response, config, refreshCookiePath) {
1071
+ const clearCookies = [
1072
+ serializeClearCookie(config.cookieNames.access, "/"),
1073
+ serializeClearCookie(config.cookieNames.refresh, refreshCookiePath),
1074
+ serializeClearCookie(config.cookieNames.hasSession, "/")
1075
+ ];
1076
+ for (const cookie of clearCookies) {
1077
+ response.headers.append("set-cookie", cookie);
1078
+ }
1079
+ }
1080
+ __name(attachClearCookies, "attachClearCookies");
1081
+ var LOGOUT_ROUTE = AUTH_PROXY_ROUTES.logout;
1082
+
1083
+ export { CLIENT_REFRESH_ROUTE, LOGOUT_ROUTE, SILENT_REFRESH_ROUTE, buildSilentRefreshUrl, createAuthProxy, createClientRefreshHandler, createLogoutHandler, createSilentRefreshHandler, decodeJwtToken, dedupeSetCookieHeaders, getSetCookieHeaders, getTenantId, getUserId, getUserRole, isBackgroundRequest, isTokenExpired, parseSetCookieHeader, resolveSafeDestination, verifyJwtToken };