@bymax-one/nest-auth 1.4.22 → 1.5.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.
@@ -1,20 +1,127 @@
1
- import { AUTH_DASHBOARD_ROUTES, AUTH_PROXY_ROUTES } from '@bymax-one/nest-auth/shared';
2
1
  import 'server-only';
2
+ import { cookies } from 'next/headers';
3
+ import { cache } from 'react';
4
+ import { AUTH_DASHBOARD_ROUTES, AUTH_PROXY_ROUTES, trimSlashes, fillRoute, AUTH_ROUTES, AuthClientError } from '@bymax-one/nest-auth/shared';
3
5
  import { NextResponse } from 'next/server';
4
6
 
5
- var __defProp = Object.defineProperty;
6
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
-
8
7
  // src/nextjs/helpers/isBackgroundRequest.ts
9
8
  function isBackgroundRequest(request) {
10
9
  const { headers } = request;
11
10
  return isNonEmptyHeader(headers.get("rsc")) || isNonEmptyHeader(headers.get("next-router-prefetch")) || isNonEmptyHeader(headers.get("next-router-state-tree"));
12
11
  }
13
- __name(isBackgroundRequest, "isBackgroundRequest");
14
12
  function isNonEmptyHeader(value) {
15
13
  return value !== null && value.length > 0;
16
14
  }
17
- __name(isNonEmptyHeader, "isNonEmptyHeader");
15
+
16
+ // src/nextjs/helpers/routeHandlerUtils.ts
17
+ var SAFE_FETCH_SITES = /* @__PURE__ */ new Set(["same-origin", "none"]);
18
+ function isCrossSiteRequest(request) {
19
+ const fetchSite = request.headers.get("sec-fetch-site");
20
+ return fetchSite !== null && !SAFE_FETCH_SITES.has(fetchSite);
21
+ }
22
+ function serializeClearCookie(name, path, domain) {
23
+ const scope = domain === void 0 ? "" : `; Domain=${domain}`;
24
+ return `${name}=; Path=${path}${scope}; Max-Age=0; HttpOnly; Secure; SameSite=Strict`;
25
+ }
26
+ function isSafeSameOriginPath(candidate) {
27
+ 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
28
+ candidate.length > 0 && candidate.startsWith("/") && !candidate.startsWith("//") && // eslint-disable-next-line no-control-regex -- rejecting control characters is the point
29
+ !/[\\\u0000-\u001f\u007f]/.test(candidate);
30
+ }
31
+ function isSafeUpstreamPath(candidate) {
32
+ if (typeof candidate !== "string") return false;
33
+ if (!candidate.startsWith("/")) return false;
34
+ if (candidate.includes("..")) return false;
35
+ return !/[?#\\\r\n\0]/.test(candidate);
36
+ }
37
+ function assertSafeCookieName(value, factoryName, label) {
38
+ if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(value)) {
39
+ throw new Error(`${factoryName}: invalid cookie name "${value}" for ${label}.`);
40
+ }
41
+ }
42
+ function assertSafeCookiePath(value, factoryName, label) {
43
+ if (!/^\/[\x20-\x3A\x3C-\x7E]*$/.test(value)) {
44
+ throw new Error(`${factoryName}: invalid cookie path "${value}" for ${label}.`);
45
+ }
46
+ }
47
+ function assertSafeCookieDomain(value, factoryName, label) {
48
+ if (!/^\.?[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)*$/.test(
49
+ value
50
+ )) {
51
+ throw new Error(`${factoryName}: invalid cookie domain "${value}" for ${label}.`);
52
+ }
53
+ }
54
+ function trimTrailingSlash(value) {
55
+ return value.endsWith("/") ? value.slice(0, -1) : value;
56
+ }
57
+
58
+ // src/nextjs/helpers/buildRefreshUrl.ts
59
+ var DEFAULT_REFRESH_PATH = `/auth/${AUTH_DASHBOARD_ROUTES.refresh}`;
60
+ function buildRefreshUrl(apiBase, refreshPath) {
61
+ return `${trimTrailingSlash(apiBase)}${refreshPath ?? DEFAULT_REFRESH_PATH}`;
62
+ }
63
+ function assertValidApiBase(apiBase, factoryName) {
64
+ if (typeof apiBase !== "string" || apiBase.length === 0) {
65
+ throw new Error(`${factoryName}: apiBase must be a non-empty string.`);
66
+ }
67
+ if (!apiBase.startsWith("http://") && !apiBase.startsWith("https://")) {
68
+ throw new Error(
69
+ `${factoryName}: apiBase "${apiBase}" must be an absolute URL starting with http:// or https://.`
70
+ );
71
+ }
72
+ }
73
+ function assertValidUpstreamPath(path, factoryName, label) {
74
+ if (path === void 0) return;
75
+ if (!isSafeUpstreamPath(path)) {
76
+ throw new Error(
77
+ `${factoryName}: ${label} "${path}" must be a same-origin pathname starting with "/" and must not contain ".." or URL control characters.`
78
+ );
79
+ }
80
+ }
81
+
82
+ // src/nextjs/helpers/workspaceAccess.ts
83
+ var NOT_USABLE = /* @__PURE__ */ new Set([403, 404, 409]);
84
+ var DEFAULT_TIMEOUT_MS = 5e3;
85
+ var STATUSES = /* @__PURE__ */ new Set([
86
+ "active",
87
+ "pending_deletion",
88
+ "suspended",
89
+ "deleted"
90
+ ]);
91
+ function isAccess(value) {
92
+ if (typeof value !== "object" || value === null) return false;
93
+ const { workspace, role } = value;
94
+ if (typeof role !== "string" || typeof workspace !== "object" || workspace === null) return false;
95
+ const { id, name, status, createdAt, deletionScheduledAt } = workspace;
96
+ return typeof id === "string" && typeof name === "string" && STATUSES.has(status) && typeof createdAt === "string" && (deletionScheduledAt === null || typeof deletionScheduledAt === "string");
97
+ }
98
+ function createWorkspaceAccessReader(config) {
99
+ assertValidApiBase(config.apiBase, "createWorkspaceAccessReader");
100
+ const base = `${trimSlashes(config.apiBase)}/${trimSlashes(config.routePrefix ?? "auth")}`;
101
+ const send = config.fetch ?? fetch;
102
+ return cache(async (workspaceId) => {
103
+ if (typeof workspaceId !== "string" || ["", ".", ".."].includes(workspaceId)) return null;
104
+ const url = `${base}/${fillRoute(AUTH_ROUTES.workspaces.access, { workspaceId })}`;
105
+ const response = await send(url, {
106
+ method: "GET",
107
+ headers: { accept: "application/json", cookie: (await cookies()).toString() },
108
+ cache: "no-store",
109
+ signal: AbortSignal.timeout(config.timeoutMs ?? DEFAULT_TIMEOUT_MS)
110
+ });
111
+ if (NOT_USABLE.has(response.status)) return null;
112
+ if (!response.ok) {
113
+ throw new AuthClientError(
114
+ `Workspace access read failed with status ${response.status}`,
115
+ response.status
116
+ );
117
+ }
118
+ const body = await response.json().catch(() => void 0);
119
+ if (!isAccess(body)) {
120
+ throw new AuthClientError("Workspace access answer has an unexpected shape", response.status);
121
+ }
122
+ return body;
123
+ });
124
+ }
18
125
  function buildSilentRefreshUrl(request, redirectTo) {
19
126
  const requestUrl = new URL(request.url);
20
127
  if (requestUrl.protocol !== "http:" && requestUrl.protocol !== "https:") {
@@ -25,12 +132,10 @@ function buildSilentRefreshUrl(request, redirectTo) {
25
132
  silentRefreshUrl.searchParams.set("redirect", destination);
26
133
  return silentRefreshUrl.toString();
27
134
  }
28
- __name(buildSilentRefreshUrl, "buildSilentRefreshUrl");
29
135
  function buildSilentRefreshPath(request, redirectTo) {
30
136
  const url = new URL(buildSilentRefreshUrl(request, redirectTo));
31
137
  return `${url.pathname}${url.search}`;
32
138
  }
33
- __name(buildSilentRefreshPath, "buildSilentRefreshPath");
34
139
  function resolveDestination(request, requestUrl, redirectTo) {
35
140
  if (typeof redirectTo === "string" && redirectTo.length > 0) {
36
141
  return redirectTo;
@@ -42,7 +147,6 @@ function resolveDestination(request, requestUrl, redirectTo) {
42
147
  }
43
148
  return `${requestUrl.pathname}${requestUrl.search}`;
44
149
  }
45
- __name(resolveDestination, "resolveDestination");
46
150
 
47
151
  // src/nextjs/helpers/dedupeSetCookieHeaders.ts
48
152
  var MAX_SET_COOKIE_LENGTH = 8192;
@@ -57,14 +161,8 @@ function parseSetCookieHeader(raw) {
57
161
  const name = firstEquals >= 0 ? nameValueSegment.slice(0, firstEquals).trim() : "";
58
162
  const value = firstEquals >= 0 ? nameValueSegment.slice(firstEquals + 1) : "";
59
163
  const attributes = parseCookieAttributes(attributeSegments);
60
- return {
61
- name,
62
- value,
63
- ...attributes,
64
- rawAttributes: attributeSegments
65
- };
164
+ return { name, value, ...attributes, rawAttributes: attributeSegments };
66
165
  }
67
- __name(parseSetCookieHeader, "parseSetCookieHeader");
68
166
  function parseCookieAttributes(attributeSegments) {
69
167
  let httpOnly = false;
70
168
  let secure = false;
@@ -100,29 +198,16 @@ function parseCookieAttributes(attributeSegments) {
100
198
  break;
101
199
  }
102
200
  }
103
- return {
104
- httpOnly,
105
- secure,
106
- sameSite,
107
- path,
108
- domain,
109
- maxAge,
110
- expires
111
- };
201
+ return { httpOnly, secure, sameSite, path, domain, maxAge, expires };
112
202
  }
113
- __name(parseCookieAttributes, "parseCookieAttributes");
114
203
  function splitAttribute(attribute) {
115
204
  const attrEquals = attribute.indexOf("=");
116
- if (attrEquals < 0) return [
117
- attribute.trim().toLowerCase(),
118
- ""
119
- ];
205
+ if (attrEquals < 0) return [attribute.trim().toLowerCase(), ""];
120
206
  return [
121
207
  attribute.slice(0, attrEquals).trim().toLowerCase(),
122
208
  attribute.slice(attrEquals + 1).trim()
123
209
  ];
124
210
  }
125
- __name(splitAttribute, "splitAttribute");
126
211
  function normaliseSameSite(value) {
127
212
  const normalised = value.toLowerCase();
128
213
  if (normalised === "strict" || normalised === "lax" || normalised === "none") {
@@ -130,16 +215,14 @@ function normaliseSameSite(value) {
130
215
  }
131
216
  return void 0;
132
217
  }
133
- __name(normaliseSameSite, "normaliseSameSite");
134
218
  function parseMaxAge(value) {
135
219
  const parsed = Number.parseInt(value, 10);
136
220
  return Number.isFinite(parsed) ? parsed : void 0;
137
221
  }
138
- __name(parseMaxAge, "parseMaxAge");
139
- function dedupeSetCookieHeaders(cookies) {
222
+ function dedupeSetCookieHeaders(cookies2) {
140
223
  const lastIndexByKey = /* @__PURE__ */ new Map();
141
- for (let index = 0; index < cookies.length; index += 1) {
142
- const raw = cookies[index];
224
+ for (let index = 0; index < cookies2.length; index += 1) {
225
+ const raw = cookies2[index];
143
226
  if (raw === void 0) continue;
144
227
  const parsed = parseSetCookieHeader(raw);
145
228
  if (parsed.name.length === 0) continue;
@@ -148,12 +231,11 @@ function dedupeSetCookieHeaders(cookies) {
148
231
  const winnerIndexes = Array.from(lastIndexByKey.values()).sort((a, b) => a - b);
149
232
  const winners = [];
150
233
  for (const index of winnerIndexes) {
151
- const raw = cookies[index];
234
+ const raw = cookies2[index];
152
235
  if (raw !== void 0) winners.push(raw);
153
236
  }
154
237
  return winners;
155
238
  }
156
- __name(dedupeSetCookieHeaders, "dedupeSetCookieHeaders");
157
239
  function getSetCookieHeaders(headers) {
158
240
  if (typeof headers.getSetCookie === "function") {
159
241
  return headers.getSetCookie();
@@ -162,11 +244,9 @@ function getSetCookieHeaders(headers) {
162
244
  if (combined === null || combined.length === 0) return [];
163
245
  return splitLegacySetCookie(combined);
164
246
  }
165
- __name(getSetCookieHeaders, "getSetCookieHeaders");
166
247
  function buildDedupKey(name, domain) {
167
248
  return `${name}|${domain ?? ""}`;
168
249
  }
169
- __name(buildDedupKey, "buildDedupKey");
170
250
  function containsHeaderSmugglingBytes(raw) {
171
251
  for (let i = 0; i < raw.length; i += 1) {
172
252
  const code = raw.charCodeAt(i);
@@ -174,7 +254,6 @@ function containsHeaderSmugglingBytes(raw) {
174
254
  }
175
255
  return false;
176
256
  }
177
- __name(containsHeaderSmugglingBytes, "containsHeaderSmugglingBytes");
178
257
  function emptyParsedCookie() {
179
258
  return {
180
259
  name: "",
@@ -189,7 +268,6 @@ function emptyParsedCookie() {
189
268
  rawAttributes: []
190
269
  };
191
270
  }
192
- __name(emptyParsedCookie, "emptyParsedCookie");
193
271
  function splitLegacySetCookie(combined) {
194
272
  if (combined.length > MAX_SET_COOKIE_LENGTH * MAX_SET_COOKIE_COUNT) return [];
195
273
  const result = [];
@@ -204,7 +282,6 @@ function splitLegacySetCookie(combined) {
204
282
  result.push(combined.slice(cursor).trim());
205
283
  return result.filter((entry) => entry.length > 0);
206
284
  }
207
- __name(splitLegacySetCookie, "splitLegacySetCookie");
208
285
  function looksLikeCookieStart(candidate, startIndex) {
209
286
  let index = startIndex;
210
287
  while (index < candidate.length) {
@@ -222,33 +299,45 @@ function looksLikeCookieStart(candidate, startIndex) {
222
299
  if (tokenLength === 0) return false;
223
300
  return candidate.charCodeAt(index + tokenLength) === 61;
224
301
  }
225
- __name(looksLikeCookieStart, "looksLikeCookieStart");
226
302
  function isCookieNameChar(code) {
227
303
  if (code >= 48 && code <= 57) return true;
228
304
  if (code >= 65 && code <= 90) return true;
229
305
  if (code >= 97 && code <= 122) return true;
230
306
  switch (code) {
231
307
  case 33:
308
+ // !
232
309
  case 35:
310
+ // #
233
311
  case 36:
312
+ // $
234
313
  case 37:
314
+ // %
235
315
  case 38:
316
+ // &
236
317
  case 39:
318
+ // '
237
319
  case 42:
320
+ // *
238
321
  case 43:
322
+ // +
239
323
  case 45:
324
+ // -
240
325
  case 46:
326
+ // .
241
327
  case 94:
328
+ // ^
242
329
  case 95:
330
+ // _
243
331
  case 96:
332
+ // `
244
333
  case 124:
334
+ // |
245
335
  case 126:
246
336
  return true;
247
337
  default:
248
338
  return false;
249
339
  }
250
340
  }
251
- __name(isCookieNameChar, "isCookieNameChar");
252
341
  function decodeJwtToken(token) {
253
342
  const parts = token.split(".");
254
343
  if (parts.length !== 3) return emptyDecoded();
@@ -260,7 +349,6 @@ function decodeJwtToken(token) {
260
349
  if (payload === void 0) return emptyDecoded();
261
350
  return buildDecodedToken(header, payload, false);
262
351
  }
263
- __name(decodeJwtToken, "decodeJwtToken");
264
352
  async function verifyJwtToken(token, secret) {
265
353
  if (secret === void 0 || secret === null) return emptyDecoded();
266
354
  if (secret.length === 0) return emptyDecoded();
@@ -278,11 +366,15 @@ async function verifyJwtToken(token, secret) {
278
366
  if (payload === void 0) return emptyDecoded();
279
367
  const signatureBytes = base64UrlDecodeToBytes(signatureSegment);
280
368
  if (signatureBytes === void 0) return emptyDecoded();
281
- const signatureValid = await verifyHs256Signature(headerSegment, payloadSegment, signatureBytes, secret);
369
+ const signatureValid = await verifyHs256Signature(
370
+ headerSegment,
371
+ payloadSegment,
372
+ signatureBytes,
373
+ secret
374
+ );
282
375
  if (!signatureValid) return emptyDecoded();
283
376
  return buildDecodedToken(header, payload, true);
284
377
  }
285
- __name(verifyJwtToken, "verifyJwtToken");
286
378
  async function verifyHs256Signature(headerSegment, payloadSegment, signatureBytes, secret) {
287
379
  const signingInput = asciiBytes(`${headerSegment}.${payloadSegment}`);
288
380
  const secretBytes = utf8Bytes(secret);
@@ -290,40 +382,35 @@ async function verifyHs256Signature(headerSegment, payloadSegment, signatureByte
290
382
  const keyMaterial = await globalThis.crypto.subtle.importKey(
291
383
  "raw",
292
384
  toArrayBuffer(secretBytes),
293
- {
294
- name: "HMAC",
295
- hash: "SHA-256"
296
- },
385
+ { name: "HMAC", hash: "SHA-256" },
297
386
  // Stryker disable next-line BooleanLiteral: the importKey `extractable` flag does not affect verify results
298
387
  false,
299
- [
300
- "verify"
301
- ]
388
+ ["verify"]
389
+ );
390
+ return await globalThis.crypto.subtle.verify(
391
+ "HMAC",
392
+ keyMaterial,
393
+ toArrayBuffer(signatureBytes),
394
+ toArrayBuffer(signingInput)
302
395
  );
303
- return await globalThis.crypto.subtle.verify("HMAC", keyMaterial, toArrayBuffer(signatureBytes), toArrayBuffer(signingInput));
304
396
  } catch {
305
397
  return false;
306
398
  }
307
399
  }
308
- __name(verifyHs256Signature, "verifyHs256Signature");
309
400
  function isTokenExpired(token) {
310
401
  if (token.exp === void 0) return true;
311
402
  const nowSeconds = Math.floor(Date.now() / 1e3);
312
403
  return token.exp <= nowSeconds;
313
404
  }
314
- __name(isTokenExpired, "isTokenExpired");
315
405
  function getUserRole(token) {
316
406
  return token.role ?? "";
317
407
  }
318
- __name(getUserRole, "getUserRole");
319
408
  function getUserId(token) {
320
409
  return token.sub ?? "";
321
410
  }
322
- __name(getUserId, "getUserId");
323
411
  function getTenantId(token) {
324
412
  return token.tenantId;
325
413
  }
326
- __name(getTenantId, "getTenantId");
327
414
  function buildDecodedToken(header, payload, signatureVerified) {
328
415
  const exp = asNumber(pickClaim(payload, "exp"));
329
416
  const iat = asNumber(pickClaim(payload, "iat"));
@@ -344,17 +431,17 @@ function buildDecodedToken(header, payload, signatureVerified) {
344
431
  iat
345
432
  };
346
433
  }
347
- __name(buildDecodedToken, "buildDecodedToken");
348
434
  function pickClaim(payload, key) {
349
- return Object.prototype.hasOwnProperty.call(payload, key) ? payload[key] : void 0;
435
+ return Object.prototype.hasOwnProperty.call(payload, key) ? (
436
+ // eslint-disable-next-line security/detect-object-injection -- key is a compile-time constant from the call sites above.
437
+ payload[key]
438
+ ) : void 0;
350
439
  }
351
- __name(pickClaim, "pickClaim");
352
440
  function toArrayBuffer(bytes) {
353
441
  const copy = new Uint8Array(bytes.byteLength);
354
442
  copy.set(bytes);
355
443
  return copy.buffer;
356
444
  }
357
- __name(toArrayBuffer, "toArrayBuffer");
358
445
  function emptyDecoded() {
359
446
  return {
360
447
  isValid: false,
@@ -368,7 +455,6 @@ function emptyDecoded() {
368
455
  iat: void 0
369
456
  };
370
457
  }
371
- __name(emptyDecoded, "emptyDecoded");
372
458
  function safeJsonParse(raw) {
373
459
  if (raw === void 0) return void 0;
374
460
  try {
@@ -381,27 +467,21 @@ function safeJsonParse(raw) {
381
467
  return void 0;
382
468
  }
383
469
  }
384
- __name(safeJsonParse, "safeJsonParse");
385
470
  function asNumber(value) {
386
471
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
387
472
  }
388
- __name(asNumber, "asNumber");
389
473
  function asString(value) {
390
474
  return typeof value === "string" ? value : void 0;
391
475
  }
392
- __name(asString, "asString");
393
476
  function base64UrlDecodeToString(segment) {
394
477
  const bytes = base64UrlDecodeToBytes(segment);
395
478
  if (bytes === void 0) return void 0;
396
479
  try {
397
- return new TextDecoder("utf-8", {
398
- fatal: true
399
- }).decode(bytes);
480
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
400
481
  } catch {
401
482
  return void 0;
402
483
  }
403
484
  }
404
- __name(base64UrlDecodeToString, "base64UrlDecodeToString");
405
485
  function base64UrlDecodeToBytes(segment) {
406
486
  if (!/^[A-Za-z0-9_-]*$/.test(segment)) return void 0;
407
487
  const padded = segment.replace(/-/g, "+").replace(/_/g, "/");
@@ -418,7 +498,6 @@ function base64UrlDecodeToBytes(segment) {
418
498
  return void 0;
419
499
  }
420
500
  }
421
- __name(base64UrlDecodeToBytes, "base64UrlDecodeToBytes");
422
501
  function asciiBytes(input) {
423
502
  const out = new Uint8Array(input.length);
424
503
  for (let i = 0; i < input.length; i += 1) {
@@ -430,11 +509,9 @@ function asciiBytes(input) {
430
509
  }
431
510
  return out;
432
511
  }
433
- __name(asciiBytes, "asciiBytes");
434
512
  function utf8Bytes(input) {
435
513
  return new TextEncoder().encode(input);
436
514
  }
437
- __name(utf8Bytes, "utf8Bytes");
438
515
 
439
516
  // src/nextjs/internal/constants.ts
440
517
  var DEFAULT_MAX_REFRESH_ATTEMPTS = 2;
@@ -445,74 +522,41 @@ var IDENTITY_HEADERS_BASELINE = [
445
522
  "x-user-id",
446
523
  "x-user-role",
447
524
  "x-tenant-id",
448
- "x-tenant-domain"
525
+ "x-tenant-domain",
526
+ // The workspace a request acts in comes from the route, never from a header the proxy could
527
+ // vouch for: the proxy decodes a token, which carries no workspace. Stripped so a layout that
528
+ // reads this name cannot take a browser-supplied value for an authenticated one.
529
+ "x-workspace-id"
449
530
  ];
450
531
  var NO_STORE_CACHE_CONTROL = "no-store, no-cache";
451
532
 
452
- // src/nextjs/helpers/routeHandlerUtils.ts
453
- var SAFE_FETCH_SITES = /* @__PURE__ */ new Set([
454
- "same-origin",
455
- "none"
456
- ]);
457
- function isCrossSiteRequest(request) {
458
- const fetchSite = request.headers.get("sec-fetch-site");
459
- return fetchSite !== null && !SAFE_FETCH_SITES.has(fetchSite);
460
- }
461
- __name(isCrossSiteRequest, "isCrossSiteRequest");
462
- function serializeClearCookie(name, path, domain) {
463
- const scope = domain === void 0 ? "" : `; Domain=${domain}`;
464
- return `${name}=; Path=${path}${scope}; Max-Age=0; HttpOnly; Secure; SameSite=Strict`;
465
- }
466
- __name(serializeClearCookie, "serializeClearCookie");
467
- function isSafeSameOriginPath(candidate) {
468
- 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
469
- candidate.length > 0 && candidate.startsWith("/") && !candidate.startsWith("//") && // eslint-disable-next-line no-control-regex -- rejecting control characters is the point
470
- !/[\\\u0000-\u001f\u007f]/.test(candidate);
471
- }
472
- __name(isSafeSameOriginPath, "isSafeSameOriginPath");
473
- function isSafeUpstreamPath(candidate) {
474
- if (typeof candidate !== "string") return false;
475
- if (!candidate.startsWith("/")) return false;
476
- if (candidate.includes("..")) return false;
477
- return !/[?#\\\r\n\0]/.test(candidate);
478
- }
479
- __name(isSafeUpstreamPath, "isSafeUpstreamPath");
480
- function assertSafeCookieName(value, factoryName, label) {
481
- if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(value)) {
482
- throw new Error(`${factoryName}: invalid cookie name "${value}" for ${label}.`);
483
- }
484
- }
485
- __name(assertSafeCookieName, "assertSafeCookieName");
486
- function assertSafeCookiePath(value, factoryName, label) {
487
- if (!/^\/[\x20-\x3A\x3C-\x7E]*$/.test(value)) {
488
- throw new Error(`${factoryName}: invalid cookie path "${value}" for ${label}.`);
489
- }
490
- }
491
- __name(assertSafeCookiePath, "assertSafeCookiePath");
492
- function assertSafeCookieDomain(value, factoryName, label) {
493
- if (!/^\.?[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)*$/.test(value)) {
494
- throw new Error(`${factoryName}: invalid cookie domain "${value}" for ${label}.`);
495
- }
496
- }
497
- __name(assertSafeCookieDomain, "assertSafeCookieDomain");
498
- function trimTrailingSlash(value) {
499
- return value.endsWith("/") ? value.slice(0, -1) : value;
500
- }
501
- __name(trimTrailingSlash, "trimTrailingSlash");
502
-
503
533
  // src/nextjs/internal/configValidation.ts
504
534
  function validateConfig(config) {
505
535
  if (!isSafeSameOriginPath(config.loginPath)) {
506
- 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.`);
536
+ throw new Error(
537
+ `createAuthProxy: loginPath "${config.loginPath}" must be a same-origin pathname starting with "/" (not "//") and must not contain CR/LF/NUL/backslash characters.`
538
+ );
507
539
  }
540
+ validateLastWorkspaceCookie(config);
508
541
  for (const route of config.protectedRoutes) {
509
542
  validateProtectedRoutePattern(route.pattern);
510
543
  if (route.redirectPath !== void 0 && !isSafeSameOriginPath(route.redirectPath)) {
511
- 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.`);
544
+ throw new Error(
545
+ `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.`
546
+ );
512
547
  }
513
548
  }
514
549
  }
515
- __name(validateConfig, "validateConfig");
550
+ function validateLastWorkspaceCookie(config) {
551
+ const name = config.lastWorkspaceCookie;
552
+ if (name === void 0) return;
553
+ assertSafeCookieName(name, "createAuthProxy", "lastWorkspaceCookie");
554
+ if (Object.values(config.cookieNames).includes(name)) {
555
+ throw new Error(
556
+ `createAuthProxy: lastWorkspaceCookie "${name}" must differ from cookieNames.access, cookieNames.refresh and cookieNames.hasSession.`
557
+ );
558
+ }
559
+ }
516
560
  function validateProtectedRoutePattern(pattern) {
517
561
  const segments = pattern.split("/").filter((segment) => segment.length > 0);
518
562
  for (let i = 0; i < segments.length; i += 1) {
@@ -521,26 +565,29 @@ function validateProtectedRoutePattern(pattern) {
521
565
  if (!isGlob) continue;
522
566
  const isLast = i === segments.length - 1;
523
567
  if (!isLast) {
524
- throw new Error(`createAuthProxy: protected route pattern "${pattern}" contains a wildcard in a non-trailing position. Wildcards are only permitted as the last segment.`);
568
+ throw new Error(
569
+ `createAuthProxy: protected route pattern "${pattern}" contains a wildcard in a non-trailing position. Wildcards are only permitted as the last segment.`
570
+ );
525
571
  }
526
572
  if (i === 0) {
527
- 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.`);
573
+ throw new Error(
574
+ `createAuthProxy: protected route pattern "${pattern}" begins with a catch-all wildcard, which would promote every route to protected status. Use a concrete prefix segment.`
575
+ );
528
576
  }
529
577
  }
530
578
  }
531
- __name(validateProtectedRoutePattern, "validateProtectedRoutePattern");
532
579
  function resolveConfig(config) {
533
580
  return {
534
581
  ...config,
535
582
  maxRefreshAttempts: config.maxRefreshAttempts ?? DEFAULT_MAX_REFRESH_ATTEMPTS
536
583
  };
537
584
  }
538
- __name(resolveConfig, "resolveConfig");
539
585
  function assertJwtSecretConfigured(config) {
540
586
  if (config.jwtSecret !== void 0 && config.jwtSecret.length > 0) return;
541
- throw new Error("createAuthProxy: jwtSecret is required. Without it no JWT signature can be verified, so route gating, role checks, status blocking and the identity headers injected into server components would all trust unverified token contents \u2014 a crafted token with a future `exp` can impersonate any role. Provide `jwtSecret`; supply it even when an upstream gateway also verifies signatures.");
587
+ throw new Error(
588
+ "createAuthProxy: jwtSecret is required. Without it no JWT signature can be verified, so route gating, role checks, status blocking and the identity headers injected into server components would all trust unverified token contents \u2014 a crafted token with a future `exp` can impersonate any role. Provide `jwtSecret`; supply it even when an upstream gateway also verifies signatures."
589
+ );
542
590
  }
543
- __name(assertJwtSecretConfigured, "assertJwtSecretConfigured");
544
591
  var FORBIDDEN_IN_PATH = /[\u0000-\u001f\u007f]/;
545
592
  function toSameOriginPath(path) {
546
593
  if (!path.startsWith("/")) return "/";
@@ -548,32 +595,18 @@ function toSameOriginPath(path) {
548
595
  if (FORBIDDEN_IN_PATH.test(path)) return "/";
549
596
  return path;
550
597
  }
551
- __name(toSameOriginPath, "toSameOriginPath");
552
598
  function redirectToPath(path) {
553
- return new NextResponse(null, {
554
- status: 307,
555
- headers: {
556
- location: toSameOriginPath(path)
557
- }
558
- });
599
+ return new NextResponse(null, { status: 307, headers: { location: toSameOriginPath(path) } });
559
600
  }
560
- __name(redirectToPath, "redirectToPath");
561
601
  function redirectToPathOnOrigin(path, origin) {
562
602
  const url = new URL(toSameOriginPath(path), origin);
563
- return new NextResponse(null, {
564
- status: 307,
565
- headers: {
566
- location: url.toString()
567
- }
568
- });
603
+ return new NextResponse(null, { status: 307, headers: { location: url.toString() } });
569
604
  }
570
- __name(redirectToPathOnOrigin, "redirectToPathOnOrigin");
571
605
  function withQueryParam(path, key, value) {
572
606
  const parsed = new URL(toSameOriginPath(path), "https://placeholder.invalid");
573
607
  parsed.searchParams.set(key, value);
574
608
  return `${parsed.pathname}${parsed.search}${parsed.hash}`;
575
609
  }
576
- __name(withQueryParam, "withQueryParam");
577
610
 
578
611
  // src/nextjs/internal/proxyUtils.ts
579
612
  function readRefreshAttemptCounter(request, maxAllowed) {
@@ -583,15 +616,12 @@ function readRefreshAttemptCounter(request, maxAllowed) {
583
616
  if (!Number.isFinite(parsed) || parsed < 0) return 0;
584
617
  return Math.min(parsed, maxAllowed);
585
618
  }
586
- __name(readRefreshAttemptCounter, "readRefreshAttemptCounter");
587
619
  function isReasonExpired(request) {
588
620
  return request.nextUrl.searchParams.get(REASON_PARAM) === REASON_EXPIRED;
589
621
  }
590
- __name(isReasonExpired, "isReasonExpired");
591
622
  function safeRelativePath(candidate, fallback) {
592
623
  return isSafeSameOriginPath(candidate) ? candidate : fallback;
593
624
  }
594
- __name(safeRelativePath, "safeRelativePath");
595
625
  function buildRefreshDestination(pathname, searchParams, nextCounter) {
596
626
  const cleaned = new URLSearchParams(searchParams);
597
627
  cleaned.delete(REFRESH_ATTEMPT_PARAM);
@@ -600,7 +630,6 @@ function buildRefreshDestination(pathname, searchParams, nextCounter) {
600
630
  const query = cleaned.toString();
601
631
  return query.length > 0 ? `${pathname}?${query}` : pathname;
602
632
  }
603
- __name(buildRefreshDestination, "buildRefreshDestination");
604
633
  function buildSanitizedRequestHeaders(request, config) {
605
634
  const headers = new Headers(request.headers);
606
635
  for (const name of IDENTITY_HEADERS_BASELINE) {
@@ -612,7 +641,6 @@ function buildSanitizedRequestHeaders(request, config) {
612
641
  headers.delete(config.userHeaders.tenantDomain);
613
642
  return headers;
614
643
  }
615
- __name(buildSanitizedRequestHeaders, "buildSanitizedRequestHeaders");
616
644
  function setOrDeleteHeader(headers, name, value) {
617
645
  if (value === void 0 || value.length === 0) {
618
646
  headers.delete(name);
@@ -620,52 +648,35 @@ function setOrDeleteHeader(headers, name, value) {
620
648
  }
621
649
  headers.set(name, sanitizeHeaderValue(value));
622
650
  }
623
- __name(setOrDeleteHeader, "setOrDeleteHeader");
624
651
  function sanitizeHeaderValue(value) {
625
652
  return value.replace(/[\r\n\0]/g, "");
626
653
  }
627
- __name(sanitizeHeaderValue, "sanitizeHeaderValue");
628
654
  function asString2(value) {
629
655
  return typeof value === "string" ? value : void 0;
630
656
  }
631
- __name(asString2, "asString");
632
657
 
633
658
  // src/nextjs/internal/routeClassifier.ts
634
659
  function classifyRoute(pathname, config) {
635
660
  if (pathname.startsWith("/api/auth/")) {
636
- return {
637
- kind: "api",
638
- matched: void 0
639
- };
661
+ return { kind: "api", matched: void 0 };
640
662
  }
641
663
  for (const route of config.protectedRoutes) {
642
664
  if (matchesRoutePattern(pathname, route.pattern)) {
643
- return {
644
- kind: "protected",
645
- matched: route
646
- };
665
+ return { kind: "protected", matched: route };
647
666
  }
648
667
  }
649
668
  for (const route of config.publicRoutes) {
650
669
  if (matchesPublicRoute(pathname, route)) {
651
- return {
652
- kind: "public",
653
- matched: void 0
654
- };
670
+ return { kind: "public", matched: void 0 };
655
671
  }
656
672
  }
657
- return {
658
- kind: "unmatched",
659
- matched: void 0
660
- };
673
+ return { kind: "unmatched", matched: void 0 };
661
674
  }
662
- __name(classifyRoute, "classifyRoute");
663
675
  function matchesPublicRoute(pathname, route) {
664
676
  if (pathname === route) return true;
665
677
  if (route.endsWith("/")) return pathname.startsWith(route);
666
678
  return pathname.startsWith(`${route}/`);
667
679
  }
668
- __name(matchesPublicRoute, "matchesPublicRoute");
669
680
  function matchesRoutePattern(pathname, pattern) {
670
681
  if (pattern === pathname) return true;
671
682
  const patternSegments = pattern.split("/").filter((segment) => segment.length > 0);
@@ -690,7 +701,6 @@ function matchesRoutePattern(pathname, pattern) {
690
701
  }
691
702
  return pathSegments.length === patternSegments.length;
692
703
  }
693
- __name(matchesRoutePattern, "matchesRoutePattern");
694
704
  function normalizePath(pathname) {
695
705
  try {
696
706
  return new URL(pathname, "http://placeholder.invalid").pathname;
@@ -698,7 +708,19 @@ function normalizePath(pathname) {
698
708
  return "/";
699
709
  }
700
710
  }
701
- __name(normalizePath, "normalizePath");
711
+
712
+ // src/nextjs/internal/workspaceHint.ts
713
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
714
+ function dashboardHint(request, config) {
715
+ const name = config.lastWorkspaceCookie;
716
+ if (name === void 0) return {};
717
+ const value = request.cookies.get(name)?.value;
718
+ return value !== void 0 && UUID.test(value) ? { lastActiveWorkspaceId: value } : {};
719
+ }
720
+ function landingPath(request, config, role) {
721
+ const hint = dashboardHint(request, config);
722
+ return safeRelativePath(config.getDefaultDashboard(role, hint), "/");
723
+ }
702
724
 
703
725
  // src/nextjs/internal/proxyHandlers.ts
704
726
  function handlePublicRoute(request, pathname, tokenState, config, sanitizedHeaders) {
@@ -711,38 +733,33 @@ function handlePublicRoute(request, pathname, tokenState, config, sanitizedHeade
711
733
  const hasSessionCookie = request.cookies.get(config.cookieNames.hasSession)?.value;
712
734
  const hasSession = hasSessionCookie !== void 0 && hasSessionCookie.length > 0;
713
735
  if (shouldBreakForCounter || shouldBreakForReason) {
714
- return NextResponse.next({
715
- request: {
716
- headers: sanitizedHeaders
717
- }
718
- });
736
+ return NextResponse.next({ request: { headers: sanitizedHeaders } });
719
737
  }
720
738
  if (hasSession) {
721
- const destination = buildRefreshDestination(pathname, request.nextUrl.searchParams, refreshAttempts + 1);
722
- return redirectToPathOnOrigin(buildSilentRefreshPath(request, destination), request.nextUrl.origin);
739
+ const destination = buildRefreshDestination(
740
+ pathname,
741
+ request.nextUrl.searchParams,
742
+ refreshAttempts + 1
743
+ );
744
+ return redirectToPathOnOrigin(
745
+ buildSilentRefreshPath(request, destination),
746
+ request.nextUrl.origin
747
+ );
723
748
  }
724
- return NextResponse.next({
725
- request: {
726
- headers: sanitizedHeaders
727
- }
728
- });
749
+ return NextResponse.next({ request: { headers: sanitizedHeaders } });
729
750
  }
730
- __name(handlePublicRoute, "handlePublicRoute");
731
751
  function handleAuthenticatedOnPublic(request, pathname, tokenState, config, sanitizedHeaders) {
732
752
  const role = tokenState.token?.role ?? "";
733
753
  const reasonPresent = request.nextUrl.searchParams.has(REASON_PARAM);
734
- const isRedirectIfAuth = config.publicRoutesRedirectIfAuthenticated.some((route) => matchesPublicRoute(pathname, route));
754
+ const isRedirectIfAuth = config.publicRoutesRedirectIfAuthenticated.some(
755
+ (route) => matchesPublicRoute(pathname, route)
756
+ );
735
757
  if (isRedirectIfAuth && !reasonPresent) {
736
- const destination = safeRelativePath(config.getDefaultDashboard(role), "/");
758
+ const destination = landingPath(request, config, role);
737
759
  return redirectToPathOnOrigin(destination, request.nextUrl.origin);
738
760
  }
739
- return NextResponse.next({
740
- request: {
741
- headers: sanitizedHeaders
742
- }
743
- });
761
+ return NextResponse.next({ request: { headers: sanitizedHeaders } });
744
762
  }
745
- __name(handleAuthenticatedOnPublic, "handleAuthenticatedOnPublic");
746
763
  function handleProtectedRoute(request, pathname, tokenState, matched, config, sanitizedHeaders) {
747
764
  if (!tokenState.authenticated) {
748
765
  return handleUnauthenticatedOnProtected(request, pathname, tokenState, config);
@@ -752,20 +769,24 @@ function handleProtectedRoute(request, pathname, tokenState, matched, config, sa
752
769
  const status = asString2(token?.payload["status"]);
753
770
  if (typeof status === "string" && status.length > 0) {
754
771
  const statusLower = status.toLocaleLowerCase("en-US");
755
- const matchedStatus = config.blockedUserStatuses.find((entry) => entry.toLocaleLowerCase("en-US") === statusLower);
772
+ const matchedStatus = config.blockedUserStatuses.find(
773
+ (entry) => entry.toLocaleLowerCase("en-US") === statusLower
774
+ );
756
775
  if (matchedStatus !== void 0) {
757
776
  return refuseBackground(request) ?? redirectToLogin(request, config, matchedStatus.toLocaleLowerCase("en-US"));
758
777
  }
759
778
  }
760
779
  if (!matched.allowedRoles.includes(role)) {
761
- const fallback = safeRelativePath(config.getDefaultDashboard(role), "/");
780
+ const fallback = landingPath(request, config, role);
762
781
  const destination = matched.redirectPath ?? fallback;
763
782
  const safeDestination = safeRelativePath(destination, fallback);
764
- return refuseBackground(request) ?? redirectToPathOnOrigin(withQueryParam(safeDestination, "error", "forbidden"), request.nextUrl.origin);
783
+ return refuseBackground(request) ?? redirectToPathOnOrigin(
784
+ withQueryParam(safeDestination, "error", "forbidden"),
785
+ request.nextUrl.origin
786
+ );
765
787
  }
766
788
  return buildAuthorisedResponse(request, token, role, config, sanitizedHeaders);
767
789
  }
768
- __name(handleProtectedRoute, "handleProtectedRoute");
769
790
  function handleUnauthenticatedOnProtected(request, pathname, tokenState, config) {
770
791
  const refreshAttempts = readRefreshAttemptCounter(request, config.maxRefreshAttempts);
771
792
  const shouldBreakForReason = isReasonExpired(request);
@@ -779,23 +800,29 @@ function handleUnauthenticatedOnProtected(request, pathname, tokenState, config)
779
800
  return redirectToLogin(request, config, REASON_EXPIRED);
780
801
  }
781
802
  if (hasSession) {
782
- const destination = buildRefreshDestination(pathname, request.nextUrl.searchParams, refreshAttempts + 1);
783
- return redirectToPathOnOrigin(buildSilentRefreshPath(request, destination), request.nextUrl.origin);
803
+ const destination = buildRefreshDestination(
804
+ pathname,
805
+ request.nextUrl.searchParams,
806
+ refreshAttempts + 1
807
+ );
808
+ return redirectToPathOnOrigin(
809
+ buildSilentRefreshPath(request, destination),
810
+ request.nextUrl.origin
811
+ );
784
812
  }
785
813
  return redirectToLogin(request, config);
786
814
  }
787
- __name(handleUnauthenticatedOnProtected, "handleUnauthenticatedOnProtected");
788
815
  function buildAuthorisedResponse(request, token, role, config, sanitizedHeaders) {
789
816
  const forwardedHeaders = new Headers(sanitizedHeaders);
790
817
  setOrDeleteHeader(forwardedHeaders, config.userHeaders.userId, token?.sub);
791
818
  setOrDeleteHeader(forwardedHeaders, config.userHeaders.role, role);
792
819
  setOrDeleteHeader(forwardedHeaders, config.userHeaders.tenantId, token?.tenantId);
793
- setOrDeleteHeader(forwardedHeaders, config.userHeaders.tenantDomain, asString2(token?.payload["tenantDomain"]));
794
- const responseInit = {
795
- request: {
796
- headers: forwardedHeaders
797
- }
798
- };
820
+ setOrDeleteHeader(
821
+ forwardedHeaders,
822
+ config.userHeaders.tenantDomain,
823
+ asString2(token?.payload["tenantDomain"])
824
+ );
825
+ const responseInit = { request: { headers: forwardedHeaders } };
799
826
  if (!request.nextUrl.searchParams.has(REFRESH_ATTEMPT_PARAM)) {
800
827
  return NextResponse.next(responseInit);
801
828
  }
@@ -803,29 +830,21 @@ function buildAuthorisedResponse(request, token, role, config, sanitizedHeaders)
803
830
  cleanUrl.searchParams.delete(REFRESH_ATTEMPT_PARAM);
804
831
  return NextResponse.rewrite(cleanUrl, responseInit);
805
832
  }
806
- __name(buildAuthorisedResponse, "buildAuthorisedResponse");
807
833
  function refuseBackground(request) {
808
834
  if (!isBackgroundRequest(request)) return null;
809
835
  return new NextResponse(null, {
810
836
  status: 403,
811
- headers: {
812
- "Cache-Control": NO_STORE_CACHE_CONTROL
813
- }
837
+ headers: { "Cache-Control": NO_STORE_CACHE_CONTROL }
814
838
  });
815
839
  }
816
- __name(refuseBackground, "refuseBackground");
817
840
  function redirectToLogin(request, config, reason) {
818
841
  const loginPath = safeRelativePath(config.loginPath, "/");
819
842
  const destination = reason !== void 0 && reason.length > 0 ? withQueryParam(loginPath, REASON_PARAM, reason) : loginPath;
820
843
  return redirectToPathOnOrigin(destination, request.nextUrl.origin);
821
844
  }
822
- __name(redirectToLogin, "redirectToLogin");
823
845
 
824
846
  // src/nextjs/internal/tokenState.ts
825
- var ACCESS_TOKEN_TYPES = [
826
- "dashboard",
827
- "platform"
828
- ];
847
+ var ACCESS_TOKEN_TYPES = ["dashboard", "platform"];
829
848
  async function readTokenState(request, config) {
830
849
  const raw = request.cookies.get(config.cookieNames.access)?.value;
831
850
  if (raw === void 0 || raw.length === 0) {
@@ -850,89 +869,74 @@ async function readTokenState(request, config) {
850
869
  signatureVerified: decoded.signatureVerified
851
870
  };
852
871
  }
853
- __name(readTokenState, "readTokenState");
854
872
  function isAccessToken(decoded) {
855
873
  return ACCESS_TOKEN_TYPES.includes(decoded.payload["type"]);
856
874
  }
857
- __name(isAccessToken, "isAccessToken");
858
875
 
859
876
  // src/nextjs/createAuthProxy.ts
860
877
  function createAuthProxy(config) {
861
878
  validateConfig(config);
862
879
  const resolved = resolveConfig(config);
863
880
  assertJwtSecretConfigured(resolved);
864
- return {
865
- proxy: /* @__PURE__ */ __name((request) => runProxy(request, resolved), "proxy"),
866
- config: resolved
867
- };
881
+ return { proxy: (request) => runProxy(request, resolved), config: resolved };
868
882
  }
869
- __name(createAuthProxy, "createAuthProxy");
870
883
  async function runProxy(request, resolved) {
871
884
  const pathname = normalizePath(request.nextUrl.pathname);
872
885
  const classification = classifyRoute(pathname, resolved);
873
886
  const sanitizedHeaders = buildSanitizedRequestHeaders(request, resolved);
874
887
  if (classification.kind === "api") {
875
- return NextResponse.next({
876
- request: {
877
- headers: sanitizedHeaders
878
- }
879
- });
888
+ return NextResponse.next({ request: { headers: sanitizedHeaders } });
880
889
  }
881
890
  const tokenState = await readTokenState(request, resolved);
882
891
  if (isBackgroundRequest(request) && !tokenState.authenticated) {
883
892
  return new NextResponse(null, {
884
893
  status: 401,
885
- headers: {
886
- "Cache-Control": NO_STORE_CACHE_CONTROL
887
- }
894
+ headers: { "Cache-Control": NO_STORE_CACHE_CONTROL }
888
895
  });
889
896
  }
890
897
  if (classification.kind === "protected") {
891
- return handleProtectedRoute(request, pathname, tokenState, classification.matched, resolved, sanitizedHeaders);
898
+ return handleProtectedRoute(
899
+ request,
900
+ pathname,
901
+ tokenState,
902
+ classification.matched,
903
+ resolved,
904
+ sanitizedHeaders
905
+ );
892
906
  }
893
907
  return handlePublicRoute(request, pathname, tokenState, resolved, sanitizedHeaders);
894
908
  }
895
- __name(runProxy, "runProxy");
896
- var DEFAULT_REFRESH_PATH = `/auth/${AUTH_DASHBOARD_ROUTES.refresh}`;
897
- function buildRefreshUrl(apiBase, refreshPath) {
898
- return `${trimTrailingSlash(apiBase)}${refreshPath ?? DEFAULT_REFRESH_PATH}`;
899
- }
900
- __name(buildRefreshUrl, "buildRefreshUrl");
901
- function assertValidApiBase(apiBase, factoryName) {
902
- if (typeof apiBase !== "string" || apiBase.length === 0) {
903
- throw new Error(`${factoryName}: apiBase must be a non-empty string.`);
904
- }
905
- if (!apiBase.startsWith("http://") && !apiBase.startsWith("https://")) {
906
- throw new Error(`${factoryName}: apiBase "${apiBase}" must be an absolute URL starting with http:// or https://.`);
907
- }
908
- }
909
- __name(assertValidApiBase, "assertValidApiBase");
910
- function assertValidUpstreamPath(path, factoryName, label) {
911
- if (path === void 0) return;
912
- if (!isSafeUpstreamPath(path)) {
913
- throw new Error(`${factoryName}: ${label} "${path}" must be a same-origin pathname starting with "/" and must not contain ".." or URL control characters.`);
914
- }
915
- }
916
- __name(assertValidUpstreamPath, "assertValidUpstreamPath");
917
-
918
- // src/nextjs/createSilentRefreshHandler.ts
919
909
  var DEFAULT_REFRESH_COOKIE_PATH = "/api/auth";
920
910
  function createSilentRefreshHandler(config) {
921
911
  if (!isSafeSameOriginPath(config.loginPath)) {
922
- 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.`);
912
+ throw new Error(
913
+ `createSilentRefreshHandler: loginPath "${config.loginPath}" must be a same-origin pathname starting with "/" (not "//") and must not contain CR/LF/NUL/backslash characters.`
914
+ );
923
915
  }
924
916
  assertValidApiBase(config.apiBase, "createSilentRefreshHandler");
925
917
  assertValidUpstreamPath(config.refreshPath, "createSilentRefreshHandler", "refreshPath");
926
- assertSafeCookieName(config.cookieNames.access, "createSilentRefreshHandler", "cookieNames.access");
927
- assertSafeCookieName(config.cookieNames.refresh, "createSilentRefreshHandler", "cookieNames.refresh");
928
- assertSafeCookieName(config.cookieNames.hasSession, "createSilentRefreshHandler", "cookieNames.hasSession");
918
+ assertSafeCookieName(
919
+ config.cookieNames.access,
920
+ "createSilentRefreshHandler",
921
+ "cookieNames.access"
922
+ );
923
+ assertSafeCookieName(
924
+ config.cookieNames.refresh,
925
+ "createSilentRefreshHandler",
926
+ "cookieNames.refresh"
927
+ );
928
+ assertSafeCookieName(
929
+ config.cookieNames.hasSession,
930
+ "createSilentRefreshHandler",
931
+ "cookieNames.hasSession"
932
+ );
929
933
  const refreshCookiePath = config.refreshCookiePath ?? DEFAULT_REFRESH_COOKIE_PATH;
930
934
  assertSafeCookiePath(refreshCookiePath, "createSilentRefreshHandler", "refreshCookiePath");
931
935
  if (config.cookieDomain !== void 0) {
932
936
  assertSafeCookieDomain(config.cookieDomain, "createSilentRefreshHandler", "cookieDomain");
933
937
  }
934
938
  const refreshUrl = buildRefreshUrl(config.apiBase, config.refreshPath);
935
- return /* @__PURE__ */ __name(async function silentRefreshHandler(request) {
939
+ return async function silentRefreshHandler(request) {
936
940
  if (isCrossSiteRequest(request)) {
937
941
  return buildLoginRedirect(config);
938
942
  }
@@ -969,9 +973,8 @@ function createSilentRefreshHandler(config) {
969
973
  return buildLogoutRedirect(config);
970
974
  }
971
975
  return buildSuccessRedirect(destination, rawSetCookies);
972
- }, "silentRefreshHandler");
976
+ };
973
977
  }
974
- __name(createSilentRefreshHandler, "createSilentRefreshHandler");
975
978
  function resolveSafeDestination(raw, origin, loginPath) {
976
979
  if (raw === null || raw.length === 0) return loginPath;
977
980
  if (!raw.startsWith("/")) return loginPath;
@@ -986,7 +989,6 @@ function resolveSafeDestination(raw, origin, loginPath) {
986
989
  if (resolved.origin !== origin) return loginPath;
987
990
  return `${resolved.pathname}${resolved.search}${resolved.hash}`;
988
991
  }
989
- __name(resolveSafeDestination, "resolveSafeDestination");
990
992
  function buildSuccessRedirect(destination, rawSetCookies) {
991
993
  const response = redirectToPath(destination);
992
994
  response.headers.set("Cache-Control", "no-store, no-cache");
@@ -996,12 +998,15 @@ function buildSuccessRedirect(destination, rawSetCookies) {
996
998
  }
997
999
  return response;
998
1000
  }
999
- __name(buildSuccessRedirect, "buildSuccessRedirect");
1000
1001
  function buildLogoutRedirect(config) {
1001
1002
  const response = buildLoginRedirect(config);
1002
1003
  const clearCookies = [
1003
1004
  serializeClearCookie(config.cookieNames.access, "/", config.cookieDomain),
1004
- serializeClearCookie(config.cookieNames.refresh, config.refreshCookiePath ?? DEFAULT_REFRESH_COOKIE_PATH, config.cookieDomain),
1005
+ serializeClearCookie(
1006
+ config.cookieNames.refresh,
1007
+ config.refreshCookiePath ?? DEFAULT_REFRESH_COOKIE_PATH,
1008
+ config.cookieDomain
1009
+ ),
1005
1010
  serializeClearCookie(config.cookieNames.hasSession, "/", config.cookieDomain)
1006
1011
  ];
1007
1012
  for (const cookie of clearCookies) {
@@ -1009,34 +1014,24 @@ function buildLogoutRedirect(config) {
1009
1014
  }
1010
1015
  return response;
1011
1016
  }
1012
- __name(buildLogoutRedirect, "buildLogoutRedirect");
1013
1017
  function buildLoginRedirect(config) {
1014
1018
  const response = redirectToPath(withQueryParam(config.loginPath, "reason", "expired"));
1015
1019
  response.headers.set("Cache-Control", "no-store, no-cache");
1016
1020
  return response;
1017
1021
  }
1018
- __name(buildLoginRedirect, "buildLoginRedirect");
1019
1022
  var SILENT_REFRESH_ROUTE = AUTH_PROXY_ROUTES.silentRefresh;
1020
1023
  function createClientRefreshHandler(config) {
1021
1024
  assertValidApiBase(config.apiBase, "createClientRefreshHandler");
1022
1025
  const refreshUrl = buildRefreshUrl(config.apiBase, config.refreshPath);
1023
- return /* @__PURE__ */ __name(async function clientRefreshHandler(request) {
1026
+ return async function clientRefreshHandler(request) {
1024
1027
  if (request.method !== "POST") {
1025
1028
  return new Response(null, {
1026
1029
  status: 405,
1027
- headers: {
1028
- Allow: "POST",
1029
- "Cache-Control": "no-store, no-cache"
1030
- }
1030
+ headers: { Allow: "POST", "Cache-Control": "no-store, no-cache" }
1031
1031
  });
1032
1032
  }
1033
1033
  if (isCrossSiteRequest(request)) {
1034
- return new Response(null, {
1035
- status: 403,
1036
- headers: {
1037
- "Cache-Control": "no-store, no-cache"
1038
- }
1039
- });
1034
+ return new Response(null, { status: 403, headers: { "Cache-Control": "no-store, no-cache" } });
1040
1035
  }
1041
1036
  let upstream;
1042
1037
  try {
@@ -1060,28 +1055,19 @@ function createClientRefreshHandler(config) {
1060
1055
  if (rawSetCookies.length === 0) {
1061
1056
  return buildUnauthorisedResponse();
1062
1057
  }
1063
- const responseHeaders = new Headers({
1064
- "Cache-Control": "no-store, no-cache"
1065
- });
1058
+ const responseHeaders = new Headers({ "Cache-Control": "no-store, no-cache" });
1066
1059
  for (const cookie of dedupeSetCookieHeaders(rawSetCookies)) {
1067
1060
  responseHeaders.append("set-cookie", cookie);
1068
1061
  }
1069
- return new Response(null, {
1070
- status: 200,
1071
- headers: responseHeaders
1072
- });
1073
- }, "clientRefreshHandler");
1062
+ return new Response(null, { status: 200, headers: responseHeaders });
1063
+ };
1074
1064
  }
1075
- __name(createClientRefreshHandler, "createClientRefreshHandler");
1076
1065
  function buildUnauthorisedResponse() {
1077
1066
  return new Response(null, {
1078
1067
  status: 401,
1079
- headers: {
1080
- "Cache-Control": "no-store, no-cache"
1081
- }
1068
+ headers: { "Cache-Control": "no-store, no-cache" }
1082
1069
  });
1083
1070
  }
1084
- __name(buildUnauthorisedResponse, "buildUnauthorisedResponse");
1085
1071
  var CLIENT_REFRESH_ROUTE = AUTH_PROXY_ROUTES.clientRefresh;
1086
1072
  var DEFAULT_LOGOUT_PATH = `/auth/${AUTH_DASHBOARD_ROUTES.logout}`;
1087
1073
  var SERVER_ERROR_STATUS = 500;
@@ -1091,23 +1077,15 @@ var DEFAULT_REFRESH_COOKIE_PATH2 = "/api/auth";
1091
1077
  function createLogoutHandler(config) {
1092
1078
  const refreshCookiePath = validateLogoutConfig(config);
1093
1079
  const logoutUrl = `${trimTrailingSlash(config.apiBase)}${config.logoutPath ?? DEFAULT_LOGOUT_PATH}`;
1094
- return /* @__PURE__ */ __name(async function logoutHandler(request) {
1080
+ return async function logoutHandler(request) {
1095
1081
  if (request.method !== "POST") {
1096
1082
  return new Response(null, {
1097
1083
  status: 405,
1098
- headers: {
1099
- Allow: "POST",
1100
- "Cache-Control": "no-store, no-cache"
1101
- }
1084
+ headers: { Allow: "POST", "Cache-Control": "no-store, no-cache" }
1102
1085
  });
1103
1086
  }
1104
1087
  if (isCrossSiteRequest(request)) {
1105
- return new Response(null, {
1106
- status: 403,
1107
- headers: {
1108
- "Cache-Control": "no-store, no-cache"
1109
- }
1110
- });
1088
+ return new Response(null, { status: 403, headers: { "Cache-Control": "no-store, no-cache" } });
1111
1089
  }
1112
1090
  const upstreamHeaders = {
1113
1091
  cookie: request.headers.get("cookie") ?? "",
@@ -1129,37 +1107,35 @@ function createLogoutHandler(config) {
1129
1107
  return failedLogoutResponse(upstream.status, upstream.headers.get("retry-after"));
1130
1108
  }
1131
1109
  return buildLogoutResponse(config, refreshCookiePath);
1132
- }, "logoutHandler");
1110
+ };
1133
1111
  }
1134
- __name(createLogoutHandler, "createLogoutHandler");
1135
1112
  function validateLogoutConfig(config) {
1136
1113
  assertValidApiBase(config.apiBase, "createLogoutHandler");
1137
1114
  assertValidUpstreamPath(config.logoutPath, "createLogoutHandler", "logoutPath");
1138
1115
  assertSafeCookieName(config.cookieNames.access, "createLogoutHandler", "cookieNames.access");
1139
1116
  assertSafeCookieName(config.cookieNames.refresh, "createLogoutHandler", "cookieNames.refresh");
1140
- assertSafeCookieName(config.cookieNames.hasSession, "createLogoutHandler", "cookieNames.hasSession");
1117
+ assertSafeCookieName(
1118
+ config.cookieNames.hasSession,
1119
+ "createLogoutHandler",
1120
+ "cookieNames.hasSession"
1121
+ );
1141
1122
  const refreshCookiePath = config.refreshCookiePath ?? DEFAULT_REFRESH_COOKIE_PATH2;
1142
1123
  assertSafeCookiePath(refreshCookiePath, "createLogoutHandler", "refreshCookiePath");
1143
1124
  if (config.cookieDomain !== void 0) {
1144
1125
  assertSafeCookieDomain(config.cookieDomain, "createLogoutHandler", "cookieDomain");
1145
1126
  }
1146
1127
  if (config.mode === "redirect" && !isSafeSameOriginPath(config.loginPath)) {
1147
- 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.`);
1128
+ throw new Error(
1129
+ `createLogoutHandler: loginPath "${config.loginPath}" must be a same-origin pathname starting with "/" (not "//") and must not contain CR/LF/NUL/backslash characters.`
1130
+ );
1148
1131
  }
1149
1132
  return refreshCookiePath;
1150
1133
  }
1151
- __name(validateLogoutConfig, "validateLogoutConfig");
1152
1134
  function failedLogoutResponse(status, retryAfter = null) {
1153
- const headers = new Headers({
1154
- "Cache-Control": "no-store, no-cache"
1155
- });
1135
+ const headers = new Headers({ "Cache-Control": "no-store, no-cache" });
1156
1136
  if (retryAfter !== null) headers.set("Retry-After", retryAfter);
1157
- return new Response(null, {
1158
- status,
1159
- headers
1160
- });
1137
+ return new Response(null, { status, headers });
1161
1138
  }
1162
- __name(failedLogoutResponse, "failedLogoutResponse");
1163
1139
  function buildLogoutResponse(config, refreshCookiePath) {
1164
1140
  if (config.mode === "redirect") {
1165
1141
  const response2 = redirectToPath(config.loginPath);
@@ -1169,14 +1145,11 @@ function buildLogoutResponse(config, refreshCookiePath) {
1169
1145
  }
1170
1146
  const response = new Response(null, {
1171
1147
  status: 200,
1172
- headers: {
1173
- "Cache-Control": "no-store, no-cache"
1174
- }
1148
+ headers: { "Cache-Control": "no-store, no-cache" }
1175
1149
  });
1176
1150
  attachClearCookies(response, config, refreshCookiePath);
1177
1151
  return response;
1178
1152
  }
1179
- __name(buildLogoutResponse, "buildLogoutResponse");
1180
1153
  function attachClearCookies(response, config, refreshCookiePath) {
1181
1154
  const clearCookies = [
1182
1155
  serializeClearCookie(config.cookieNames.access, "/", config.cookieDomain),
@@ -1187,7 +1160,6 @@ function attachClearCookies(response, config, refreshCookiePath) {
1187
1160
  response.headers.append("set-cookie", cookie);
1188
1161
  }
1189
1162
  }
1190
- __name(attachClearCookies, "attachClearCookies");
1191
1163
  var LOGOUT_ROUTE = AUTH_PROXY_ROUTES.logout;
1192
1164
 
1193
- 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 };
1165
+ export { CLIENT_REFRESH_ROUTE, LOGOUT_ROUTE, SILENT_REFRESH_ROUTE, buildSilentRefreshUrl, createAuthProxy, createClientRefreshHandler, createLogoutHandler, createSilentRefreshHandler, createWorkspaceAccessReader, decodeJwtToken, dedupeSetCookieHeaders, getSetCookieHeaders, getTenantId, getUserId, getUserRole, isBackgroundRequest, isTokenExpired, parseSetCookieHeader, resolveSafeDestination, verifyJwtToken };