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