@bymax-one/nest-auth 1.0.11 → 1.1.1

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.
@@ -174,22 +174,34 @@ function createAuthFetch(config = {}) {
174
174
  }, "authFetch");
175
175
  }
176
176
  __name(createAuthFetch, "createAuthFetch");
177
+ function trimSlashes(value, leading) {
178
+ let start = 0;
179
+ let end = value.length;
180
+ if (leading) {
181
+ while (start < end && value[start] === "/") start += 1;
182
+ }
183
+ while (end > start && value[end - 1] === "/") end -= 1;
184
+ return value.slice(start, end);
185
+ }
186
+ __name(trimSlashes, "trimSlashes");
177
187
  function normalizeBaseUrl(baseUrl) {
178
- return baseUrl.replace(/\/+$/, "");
188
+ return trimSlashes(baseUrl, false);
179
189
  }
180
190
  __name(normalizeBaseUrl, "normalizeBaseUrl");
181
191
  function normalizeRoutePrefix(prefix) {
182
- return prefix.replace(/^\/+|\/+$/g, "");
192
+ return trimSlashes(prefix, true);
183
193
  }
184
194
  __name(normalizeRoutePrefix, "normalizeRoutePrefix");
185
195
  function jsonBody(value) {
186
196
  return JSON.stringify(value);
187
197
  }
188
198
  __name(jsonBody, "jsonBody");
189
- function extractErrorBody(text) {
199
+ function extractErrorBody(text, response) {
190
200
  if (text.length === 0) return void 0;
191
201
  try {
192
202
  const parsed = JSON.parse(text);
203
+ const fromEnvelope = readErrorEnvelope(parsed, response);
204
+ if (fromEnvelope !== void 0) return fromEnvelope;
193
205
  return isAuthErrorBody(parsed) ? parsed : void 0;
194
206
  } catch {
195
207
  return void 0;
@@ -197,7 +209,7 @@ function extractErrorBody(text) {
197
209
  }
198
210
  __name(extractErrorBody, "extractErrorBody");
199
211
  function throwAuthError(response, text) {
200
- const body = extractErrorBody(text);
212
+ const body = extractErrorBody(text, response);
201
213
  const message = body?.message ?? `Request failed with status ${response.status}`;
202
214
  throw new shared.AuthClientError(message, response.status, body);
203
215
  }
@@ -228,6 +240,31 @@ async function expectNoContent(response) {
228
240
  );
229
241
  }
230
242
  __name(expectNoContent, "expectNoContent");
243
+ var UNKNOWN_STATUS_TEXT = "Error";
244
+ function readErrorEnvelope(value, response) {
245
+ const envelope = value?.error;
246
+ if (typeof envelope !== "object" || envelope === null) return void 0;
247
+ const candidate = envelope;
248
+ const code = candidate["code"];
249
+ const message = candidate["message"];
250
+ if (typeof code !== "string" || typeof message !== "string") return void 0;
251
+ const details = candidate["details"];
252
+ return {
253
+ message,
254
+ error: response.statusText.length > 0 ? response.statusText : UNKNOWN_STATUS_TEXT,
255
+ statusCode: response.status,
256
+ code,
257
+ // A non-object `details` is not something the server emits; treat
258
+ // it as absent rather than propagating an unusable value under a
259
+ // type that promises a record.
260
+ // Stryker disable ConditionalExpression: equivalent — `typeof null` is `'object'`, so
261
+ // dropping the null check casts `null` to the record type and yields the very `null` the
262
+ // other branch returns. Block form because the mutant sits two lines below a wrapped
263
+ // comment, where the per-line directive points at the comment's own continuation.
264
+ details: typeof details === "object" && details !== null ? details : null
265
+ };
266
+ }
267
+ __name(readErrorEnvelope, "readErrorEnvelope");
231
268
  function isAuthErrorBody(value) {
232
269
  if (typeof value !== "object" || value === null) return false;
233
270
  const candidate = value;
@@ -245,7 +282,14 @@ function createAuthClient(config) {
245
282
  const baseUrl = normalizeBaseUrl(config.baseUrl);
246
283
  const routePrefix = normalizeRoutePrefix(config.routePrefix ?? "auth");
247
284
  const authFetch = config.authFetch ?? createAuthFetch({
248
- baseUrl,
285
+ // Deliberately NO `baseUrl`. This client composes the full URL itself in `url()` below,
286
+ // and `createAuthFetch` prepends its own `baseUrl` to any input that is not absolute —
287
+ // so passing it here applied the base TWICE. With the documented same-origin setting
288
+ // (`baseUrl: '/api'`, used by the README and by AuthProvider's own example) every call
289
+ // went to `/api/api/auth/*` and 404'd: login, register, logout, refresh and getMe, all
290
+ // of them. An absolute base hid it, because the second prepend is skipped for anything
291
+ // matching `^https?://` — which is why every test in this file, all of which use an
292
+ // absolute base AND inject a stub `authFetch`, stayed green.
249
293
  routePrefix,
250
294
  // Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — createAuthFetch coalesces each option with `??`/falsy checks downstream
251
295
  ...config.refreshEndpoint !== void 0 ? {
@@ -173,22 +173,34 @@ function createAuthFetch(config = {}) {
173
173
  }, "authFetch");
174
174
  }
175
175
  __name(createAuthFetch, "createAuthFetch");
176
+ function trimSlashes(value, leading) {
177
+ let start = 0;
178
+ let end = value.length;
179
+ if (leading) {
180
+ while (start < end && value[start] === "/") start += 1;
181
+ }
182
+ while (end > start && value[end - 1] === "/") end -= 1;
183
+ return value.slice(start, end);
184
+ }
185
+ __name(trimSlashes, "trimSlashes");
176
186
  function normalizeBaseUrl(baseUrl) {
177
- return baseUrl.replace(/\/+$/, "");
187
+ return trimSlashes(baseUrl, false);
178
188
  }
179
189
  __name(normalizeBaseUrl, "normalizeBaseUrl");
180
190
  function normalizeRoutePrefix(prefix) {
181
- return prefix.replace(/^\/+|\/+$/g, "");
191
+ return trimSlashes(prefix, true);
182
192
  }
183
193
  __name(normalizeRoutePrefix, "normalizeRoutePrefix");
184
194
  function jsonBody(value) {
185
195
  return JSON.stringify(value);
186
196
  }
187
197
  __name(jsonBody, "jsonBody");
188
- function extractErrorBody(text) {
198
+ function extractErrorBody(text, response) {
189
199
  if (text.length === 0) return void 0;
190
200
  try {
191
201
  const parsed = JSON.parse(text);
202
+ const fromEnvelope = readErrorEnvelope(parsed, response);
203
+ if (fromEnvelope !== void 0) return fromEnvelope;
192
204
  return isAuthErrorBody(parsed) ? parsed : void 0;
193
205
  } catch {
194
206
  return void 0;
@@ -196,7 +208,7 @@ function extractErrorBody(text) {
196
208
  }
197
209
  __name(extractErrorBody, "extractErrorBody");
198
210
  function throwAuthError(response, text) {
199
- const body = extractErrorBody(text);
211
+ const body = extractErrorBody(text, response);
200
212
  const message = body?.message ?? `Request failed with status ${response.status}`;
201
213
  throw new AuthClientError(message, response.status, body);
202
214
  }
@@ -227,6 +239,31 @@ async function expectNoContent(response) {
227
239
  );
228
240
  }
229
241
  __name(expectNoContent, "expectNoContent");
242
+ var UNKNOWN_STATUS_TEXT = "Error";
243
+ function readErrorEnvelope(value, response) {
244
+ const envelope = value?.error;
245
+ if (typeof envelope !== "object" || envelope === null) return void 0;
246
+ const candidate = envelope;
247
+ const code = candidate["code"];
248
+ const message = candidate["message"];
249
+ if (typeof code !== "string" || typeof message !== "string") return void 0;
250
+ const details = candidate["details"];
251
+ return {
252
+ message,
253
+ error: response.statusText.length > 0 ? response.statusText : UNKNOWN_STATUS_TEXT,
254
+ statusCode: response.status,
255
+ code,
256
+ // A non-object `details` is not something the server emits; treat
257
+ // it as absent rather than propagating an unusable value under a
258
+ // type that promises a record.
259
+ // Stryker disable ConditionalExpression: equivalent — `typeof null` is `'object'`, so
260
+ // dropping the null check casts `null` to the record type and yields the very `null` the
261
+ // other branch returns. Block form because the mutant sits two lines below a wrapped
262
+ // comment, where the per-line directive points at the comment's own continuation.
263
+ details: typeof details === "object" && details !== null ? details : null
264
+ };
265
+ }
266
+ __name(readErrorEnvelope, "readErrorEnvelope");
230
267
  function isAuthErrorBody(value) {
231
268
  if (typeof value !== "object" || value === null) return false;
232
269
  const candidate = value;
@@ -244,7 +281,14 @@ function createAuthClient(config) {
244
281
  const baseUrl = normalizeBaseUrl(config.baseUrl);
245
282
  const routePrefix = normalizeRoutePrefix(config.routePrefix ?? "auth");
246
283
  const authFetch = config.authFetch ?? createAuthFetch({
247
- baseUrl,
284
+ // Deliberately NO `baseUrl`. This client composes the full URL itself in `url()` below,
285
+ // and `createAuthFetch` prepends its own `baseUrl` to any input that is not absolute —
286
+ // so passing it here applied the base TWICE. With the documented same-origin setting
287
+ // (`baseUrl: '/api'`, used by the README and by AuthProvider's own example) every call
288
+ // went to `/api/api/auth/*` and 404'd: login, register, logout, refresh and getMe, all
289
+ // of them. An absolute base hid it, because the second prepend is skipped for anything
290
+ // matching `^https?://` — which is why every test in this file, all of which use an
291
+ // absolute base AND inject a stub `authFetch`, stayed green.
248
292
  routePrefix,
249
293
  // Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — createAuthFetch coalesces each option with `??`/falsy checks downstream
250
294
  ...config.refreshEndpoint !== void 0 ? {
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var shared = require('@bymax-one/nest-auth/shared');
4
+ require('server-only');
4
5
  var server = require('next/server');
5
6
 
6
7
  var __defProp = Object.defineProperty;
@@ -27,6 +28,11 @@ function buildSilentRefreshUrl(request, redirectTo) {
27
28
  return silentRefreshUrl.toString();
28
29
  }
29
30
  __name(buildSilentRefreshUrl, "buildSilentRefreshUrl");
31
+ function buildSilentRefreshPath(request, redirectTo) {
32
+ const url = new URL(buildSilentRefreshUrl(request, redirectTo));
33
+ return `${url.pathname}${url.search}`;
34
+ }
35
+ __name(buildSilentRefreshPath, "buildSilentRefreshPath");
30
36
  function resolveDestination(request, requestUrl, redirectTo) {
31
37
  if (typeof redirectTo === "string" && redirectTo.length > 0) {
32
38
  return redirectTo;
@@ -245,8 +251,6 @@ function isCookieNameChar(code) {
245
251
  }
246
252
  }
247
253
  __name(isCookieNameChar, "isCookieNameChar");
248
-
249
- // src/nextjs/helpers/jwt.ts
250
254
  function decodeJwtToken(token) {
251
255
  const parts = token.split(".");
252
256
  if (parts.length !== 3) return emptyDecoded();
@@ -256,14 +260,11 @@ function decodeJwtToken(token) {
256
260
  const header = safeJsonParse(base64UrlDecodeToString(headerSegment));
257
261
  const payload = safeJsonParse(base64UrlDecodeToString(payloadSegment));
258
262
  if (payload === void 0) return emptyDecoded();
259
- return buildDecodedToken(header, payload);
263
+ return buildDecodedToken(header, payload, false);
260
264
  }
261
265
  __name(decodeJwtToken, "decodeJwtToken");
262
266
  async function verifyJwtToken(token, secret) {
263
- if (secret === void 0 || secret === null) {
264
- return decodeJwtToken(token);
265
- }
266
- if (secret.length === 0) {
267
+ if (secret === void 0 || secret === null || secret.length === 0) {
267
268
  return emptyDecoded();
268
269
  }
269
270
  const parts = token.split(".");
@@ -282,7 +283,7 @@ async function verifyJwtToken(token, secret) {
282
283
  if (signatureBytes === void 0) return emptyDecoded();
283
284
  const signatureValid = await verifyHs256Signature(headerSegment, payloadSegment, signatureBytes, secret);
284
285
  if (!signatureValid) return emptyDecoded();
285
- return buildDecodedToken(header, payload);
286
+ return buildDecodedToken(header, payload, true);
286
287
  }
287
288
  __name(verifyJwtToken, "verifyJwtToken");
288
289
  async function verifyHs256Signature(headerSegment, payloadSegment, signatureBytes, secret) {
@@ -326,7 +327,7 @@ function getTenantId(token) {
326
327
  return token.tenantId;
327
328
  }
328
329
  __name(getTenantId, "getTenantId");
329
- function buildDecodedToken(header, payload) {
330
+ function buildDecodedToken(header, payload, signatureVerified) {
330
331
  const exp = asNumber(pickClaim(payload, "exp"));
331
332
  const iat = asNumber(pickClaim(payload, "iat"));
332
333
  const sub = asString(pickClaim(payload, "sub"));
@@ -336,6 +337,7 @@ function buildDecodedToken(header, payload) {
336
337
  const isValid = exp !== void 0 && exp > nowSeconds;
337
338
  return {
338
339
  isValid,
340
+ signatureVerified,
339
341
  header,
340
342
  payload,
341
343
  sub,
@@ -359,6 +361,7 @@ __name(toArrayBuffer, "toArrayBuffer");
359
361
  function emptyDecoded() {
360
362
  return {
361
363
  isValid: false,
364
+ signatureVerified: false,
362
365
  header: void 0,
363
366
  payload: {},
364
367
  sub: void 0,
@@ -447,15 +450,27 @@ var IDENTITY_HEADERS_BASELINE = [
447
450
  "x-tenant-id",
448
451
  "x-tenant-domain"
449
452
  ];
453
+ var NO_STORE_CACHE_CONTROL = "no-store, no-cache";
450
454
 
451
455
  // src/nextjs/helpers/routeHandlerUtils.ts
452
- function serializeClearCookie(name, path) {
453
- return `${name}=; Path=${path}; Max-Age=0; HttpOnly; Secure; SameSite=Strict`;
456
+ var SAFE_FETCH_SITES = /* @__PURE__ */ new Set([
457
+ "same-origin",
458
+ "none"
459
+ ]);
460
+ function isCrossSiteRequest(request) {
461
+ const fetchSite = request.headers.get("sec-fetch-site");
462
+ return fetchSite !== null && !SAFE_FETCH_SITES.has(fetchSite);
463
+ }
464
+ __name(isCrossSiteRequest, "isCrossSiteRequest");
465
+ function serializeClearCookie(name, path, domain) {
466
+ const scope = domain === void 0 ? "" : `; Domain=${domain}`;
467
+ return `${name}=; Path=${path}${scope}; Max-Age=0; HttpOnly; Secure; SameSite=Strict`;
454
468
  }
455
469
  __name(serializeClearCookie, "serializeClearCookie");
456
470
  function isSafeSameOriginPath(candidate) {
457
471
  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
458
- candidate.length > 0 && candidate.startsWith("/") && !candidate.startsWith("//") && !/[\\\r\n\0]/.test(candidate);
472
+ candidate.length > 0 && candidate.startsWith("/") && !candidate.startsWith("//") && // eslint-disable-next-line no-control-regex -- rejecting control characters is the point
473
+ !/[\\\u0000-\u001f\u007f]/.test(candidate);
459
474
  }
460
475
  __name(isSafeSameOriginPath, "isSafeSameOriginPath");
461
476
  function isSafeUpstreamPath(candidate) {
@@ -477,6 +492,12 @@ function assertSafeCookiePath(value, factoryName, label) {
477
492
  }
478
493
  }
479
494
  __name(assertSafeCookiePath, "assertSafeCookiePath");
495
+ function assertSafeCookieDomain(value, factoryName, label) {
496
+ 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)) {
497
+ throw new Error(`${factoryName}: invalid cookie domain "${value}" for ${label}.`);
498
+ }
499
+ }
500
+ __name(assertSafeCookieDomain, "assertSafeCookieDomain");
480
501
  function trimTrailingSlash(value) {
481
502
  return value.endsWith("/") ? value.slice(0, -1) : value;
482
503
  }
@@ -531,6 +552,39 @@ function isProductionEnv() {
531
552
  return process.env["NODE_ENV"] === "production";
532
553
  }
533
554
  __name(isProductionEnv, "isProductionEnv");
555
+ var FORBIDDEN_IN_PATH = /[\u0000-\u001f\u007f]/;
556
+ function toSameOriginPath(path) {
557
+ if (!path.startsWith("/")) return "/";
558
+ if (path.startsWith("//") || path.startsWith("/\\")) return "/";
559
+ if (FORBIDDEN_IN_PATH.test(path)) return "/";
560
+ return path;
561
+ }
562
+ __name(toSameOriginPath, "toSameOriginPath");
563
+ function redirectToPath(path) {
564
+ return new server.NextResponse(null, {
565
+ status: 307,
566
+ headers: {
567
+ location: toSameOriginPath(path)
568
+ }
569
+ });
570
+ }
571
+ __name(redirectToPath, "redirectToPath");
572
+ function redirectToPathOnOrigin(path, origin) {
573
+ const url = new URL(toSameOriginPath(path), origin);
574
+ return new server.NextResponse(null, {
575
+ status: 307,
576
+ headers: {
577
+ location: url.toString()
578
+ }
579
+ });
580
+ }
581
+ __name(redirectToPathOnOrigin, "redirectToPathOnOrigin");
582
+ function withQueryParam(path, key, value) {
583
+ const parsed = new URL(toSameOriginPath(path), "https://placeholder.invalid");
584
+ parsed.searchParams.set(key, value);
585
+ return `${parsed.pathname}${parsed.search}${parsed.hash}`;
586
+ }
587
+ __name(withQueryParam, "withQueryParam");
534
588
 
535
589
  // src/nextjs/internal/proxyUtils.ts
536
590
  function readRefreshAttemptCounter(request, maxAllowed) {
@@ -676,8 +730,7 @@ function handlePublicRoute(request, pathname, tokenState, config, sanitizedHeade
676
730
  }
677
731
  if (hasSession) {
678
732
  const destination = buildRefreshDestination(pathname, request.nextUrl.searchParams, refreshAttempts + 1);
679
- const silentRefreshUrl = new URL(buildSilentRefreshUrl(request, destination));
680
- return server.NextResponse.redirect(silentRefreshUrl);
733
+ return redirectToPathOnOrigin(buildSilentRefreshPath(request, destination), request.nextUrl.origin);
681
734
  }
682
735
  return server.NextResponse.next({
683
736
  request: {
@@ -692,7 +745,7 @@ function handleAuthenticatedOnPublic(request, pathname, tokenState, config, sani
692
745
  const isRedirectIfAuth = config.publicRoutesRedirectIfAuthenticated.some((route) => matchesPublicRoute(pathname, route));
693
746
  if (isRedirectIfAuth && !reasonPresent) {
694
747
  const destination = safeRelativePath(config.getDefaultDashboard(role), "/");
695
- return server.NextResponse.redirect(new URL(destination, request.nextUrl.origin));
748
+ return redirectToPathOnOrigin(destination, request.nextUrl.origin);
696
749
  }
697
750
  return server.NextResponse.next({
698
751
  request: {
@@ -712,16 +765,14 @@ function handleProtectedRoute(request, pathname, tokenState, matched, config, sa
712
765
  const statusLower = status.toLocaleLowerCase("en-US");
713
766
  const matchedStatus = config.blockedUserStatuses.find((entry) => entry.toLocaleLowerCase("en-US") === statusLower);
714
767
  if (matchedStatus !== void 0) {
715
- return redirectToLogin(request, config, matchedStatus.toLocaleLowerCase("en-US"));
768
+ return refuseBackground(request) ?? redirectToLogin(request, config, matchedStatus.toLocaleLowerCase("en-US"));
716
769
  }
717
770
  }
718
771
  if (!matched.allowedRoles.includes(role)) {
719
772
  const fallback = safeRelativePath(config.getDefaultDashboard(role), "/");
720
773
  const destination = matched.redirectPath ?? fallback;
721
774
  const safeDestination = safeRelativePath(destination, fallback);
722
- const url = new URL(safeDestination, request.nextUrl.origin);
723
- url.searchParams.set("error", "forbidden");
724
- return server.NextResponse.redirect(url);
775
+ return refuseBackground(request) ?? redirectToPathOnOrigin(withQueryParam(safeDestination, "error", "forbidden"), request.nextUrl.origin);
725
776
  }
726
777
  return buildAuthorisedResponse(request, token, role, config, sanitizedHeaders);
727
778
  }
@@ -740,8 +791,7 @@ function handleUnauthenticatedOnProtected(request, pathname, tokenState, config)
740
791
  }
741
792
  if (hasSession) {
742
793
  const destination = buildRefreshDestination(pathname, request.nextUrl.searchParams, refreshAttempts + 1);
743
- const silentRefreshUrl = new URL(buildSilentRefreshUrl(request, destination));
744
- return server.NextResponse.redirect(silentRefreshUrl);
794
+ return redirectToPathOnOrigin(buildSilentRefreshPath(request, destination), request.nextUrl.origin);
745
795
  }
746
796
  return redirectToLogin(request, config);
747
797
  }
@@ -765,17 +815,28 @@ function buildAuthorisedResponse(request, token, role, config, sanitizedHeaders)
765
815
  return server.NextResponse.rewrite(cleanUrl, responseInit);
766
816
  }
767
817
  __name(buildAuthorisedResponse, "buildAuthorisedResponse");
818
+ function refuseBackground(request) {
819
+ if (!isBackgroundRequest(request)) return null;
820
+ return new server.NextResponse(null, {
821
+ status: 403,
822
+ headers: {
823
+ "Cache-Control": NO_STORE_CACHE_CONTROL
824
+ }
825
+ });
826
+ }
827
+ __name(refuseBackground, "refuseBackground");
768
828
  function redirectToLogin(request, config, reason) {
769
829
  const loginPath = safeRelativePath(config.loginPath, "/");
770
- const url = new URL(loginPath, request.nextUrl.origin);
771
- if (reason !== void 0 && reason.length > 0) {
772
- url.searchParams.set(REASON_PARAM, reason);
773
- }
774
- return server.NextResponse.redirect(url);
830
+ const destination = reason !== void 0 && reason.length > 0 ? withQueryParam(loginPath, REASON_PARAM, reason) : loginPath;
831
+ return redirectToPathOnOrigin(destination, request.nextUrl.origin);
775
832
  }
776
833
  __name(redirectToLogin, "redirectToLogin");
777
834
 
778
835
  // src/nextjs/internal/tokenState.ts
836
+ var ACCESS_TOKEN_TYPES = [
837
+ "dashboard",
838
+ "platform"
839
+ ];
779
840
  async function readTokenState(request, config) {
780
841
  const raw = request.cookies.get(config.cookieNames.access)?.value;
781
842
  if (raw === void 0 || raw.length === 0) {
@@ -788,14 +849,24 @@ async function readTokenState(request, config) {
788
849
  }
789
850
  const hasSecret = config.jwtSecret !== void 0 && config.jwtSecret.length > 0;
790
851
  const decoded = hasSecret ? await verifyJwtToken(raw, config.jwtSecret) : decodeJwtToken(raw);
852
+ const isSession = decoded.isValid && isAccessToken(decoded);
791
853
  return {
792
854
  token: decoded,
793
855
  hasCookie: true,
794
- authenticated: decoded.isValid,
795
- signatureVerified: hasSecret && decoded.isValid
856
+ authenticated: isSession,
857
+ // Passed through, not conjoined with `isSession`. The name says "a signature was checked",
858
+ // and folding expiry and token-type into it made the same identifier mean one thing on
859
+ // `DecodedToken` and a stricter thing here — the kind of collision that is only ever
860
+ // discovered by someone trusting the looser reading. `authenticated` above is where the
861
+ // conjunction belongs, and it is the field every decision in this proxy actually reads.
862
+ signatureVerified: decoded.signatureVerified
796
863
  };
797
864
  }
798
865
  __name(readTokenState, "readTokenState");
866
+ function isAccessToken(decoded) {
867
+ return ACCESS_TOKEN_TYPES.includes(decoded.payload["type"]);
868
+ }
869
+ __name(isAccessToken, "isAccessToken");
799
870
 
800
871
  // src/nextjs/createAuthProxy.ts
801
872
  function createAuthProxy(config) {
@@ -811,16 +882,20 @@ __name(createAuthProxy, "createAuthProxy");
811
882
  async function runProxy(request, resolved) {
812
883
  const pathname = normalizePath(request.nextUrl.pathname);
813
884
  const classification = classifyRoute(pathname, resolved);
885
+ const sanitizedHeaders = buildSanitizedRequestHeaders(request, resolved);
814
886
  if (classification.kind === "api") {
815
- return server.NextResponse.next();
887
+ return server.NextResponse.next({
888
+ request: {
889
+ headers: sanitizedHeaders
890
+ }
891
+ });
816
892
  }
817
893
  const tokenState = await readTokenState(request, resolved);
818
- const sanitizedHeaders = buildSanitizedRequestHeaders(request, resolved);
819
894
  if (isBackgroundRequest(request) && !tokenState.authenticated) {
820
895
  return new server.NextResponse(null, {
821
896
  status: 401,
822
897
  headers: {
823
- "Cache-Control": "no-store, no-cache"
898
+ "Cache-Control": NO_STORE_CACHE_CONTROL
824
899
  }
825
900
  });
826
901
  }
@@ -865,8 +940,19 @@ function createSilentRefreshHandler(config) {
865
940
  assertSafeCookieName(config.cookieNames.hasSession, "createSilentRefreshHandler", "cookieNames.hasSession");
866
941
  const refreshCookiePath = config.refreshCookiePath ?? DEFAULT_REFRESH_COOKIE_PATH;
867
942
  assertSafeCookiePath(refreshCookiePath, "createSilentRefreshHandler", "refreshCookiePath");
943
+ if (config.cookieDomain !== void 0) {
944
+ assertSafeCookieDomain(config.cookieDomain, "createSilentRefreshHandler", "cookieDomain");
945
+ }
868
946
  const refreshUrl = buildRefreshUrl(config.apiBase, config.refreshPath);
869
947
  return /* @__PURE__ */ __name(async function silentRefreshHandler(request) {
948
+ if (isCrossSiteRequest(request)) {
949
+ return new server.NextResponse(null, {
950
+ status: 403,
951
+ headers: {
952
+ "Cache-Control": "no-store, no-cache"
953
+ }
954
+ });
955
+ }
870
956
  const origin = request.nextUrl.origin;
871
957
  const rawDestination = request.nextUrl.searchParams.get("redirect");
872
958
  const destination = resolveSafeDestination(rawDestination, origin, config.loginPath);
@@ -887,19 +973,19 @@ function createSilentRefreshHandler(config) {
887
973
  redirect: "manual"
888
974
  });
889
975
  } catch {
890
- return buildLogoutRedirect(origin, config);
976
+ return buildLogoutRedirect(config);
891
977
  }
892
978
  if (upstream.type === "opaqueredirect") {
893
- return buildLogoutRedirect(origin, config);
979
+ return buildLogoutRedirect(config);
894
980
  }
895
981
  if (!upstream.ok) {
896
- return buildLogoutRedirect(origin, config);
982
+ return buildLogoutRedirect(config);
897
983
  }
898
984
  const rawSetCookies = getSetCookieHeaders(upstream.headers);
899
985
  if (rawSetCookies.length === 0) {
900
- return buildLogoutRedirect(origin, config);
986
+ return buildLogoutRedirect(config);
901
987
  }
902
- return buildSuccessRedirect(origin, destination, rawSetCookies);
988
+ return buildSuccessRedirect(destination, rawSetCookies);
903
989
  }, "silentRefreshHandler");
904
990
  }
905
991
  __name(createSilentRefreshHandler, "createSilentRefreshHandler");
@@ -918,9 +1004,8 @@ function resolveSafeDestination(raw, origin, loginPath) {
918
1004
  return `${resolved.pathname}${resolved.search}${resolved.hash}`;
919
1005
  }
920
1006
  __name(resolveSafeDestination, "resolveSafeDestination");
921
- function buildSuccessRedirect(origin, destination, rawSetCookies) {
922
- const destinationUrl = new URL(destination, origin);
923
- const response = server.NextResponse.redirect(destinationUrl);
1007
+ function buildSuccessRedirect(destination, rawSetCookies) {
1008
+ const response = redirectToPath(destination);
924
1009
  response.headers.set("Cache-Control", "no-store, no-cache");
925
1010
  const deduped = dedupeSetCookieHeaders(rawSetCookies);
926
1011
  for (const cookie of deduped) {
@@ -929,15 +1014,13 @@ function buildSuccessRedirect(origin, destination, rawSetCookies) {
929
1014
  return response;
930
1015
  }
931
1016
  __name(buildSuccessRedirect, "buildSuccessRedirect");
932
- function buildLogoutRedirect(origin, config) {
933
- const loginUrl = new URL(config.loginPath, origin);
934
- loginUrl.searchParams.set("reason", "expired");
935
- const response = server.NextResponse.redirect(loginUrl);
1017
+ function buildLogoutRedirect(config) {
1018
+ const response = redirectToPath(withQueryParam(config.loginPath, "reason", "expired"));
936
1019
  response.headers.set("Cache-Control", "no-store, no-cache");
937
1020
  const clearCookies = [
938
- serializeClearCookie(config.cookieNames.access, "/"),
939
- serializeClearCookie(config.cookieNames.refresh, config.refreshCookiePath ?? DEFAULT_REFRESH_COOKIE_PATH),
940
- serializeClearCookie(config.cookieNames.hasSession, "/")
1021
+ serializeClearCookie(config.cookieNames.access, "/", config.cookieDomain),
1022
+ serializeClearCookie(config.cookieNames.refresh, config.refreshCookiePath ?? DEFAULT_REFRESH_COOKIE_PATH, config.cookieDomain),
1023
+ serializeClearCookie(config.cookieNames.hasSession, "/", config.cookieDomain)
941
1024
  ];
942
1025
  for (const cookie of clearCookies) {
943
1026
  response.headers.append("set-cookie", cookie);
@@ -959,6 +1042,14 @@ function createClientRefreshHandler(config) {
959
1042
  }
960
1043
  });
961
1044
  }
1045
+ if (isCrossSiteRequest(request)) {
1046
+ return new Response(null, {
1047
+ status: 403,
1048
+ headers: {
1049
+ "Cache-Control": "no-store, no-cache"
1050
+ }
1051
+ });
1052
+ }
962
1053
  let upstream;
963
1054
  try {
964
1055
  upstream = await fetch(refreshUrl, {
@@ -1019,6 +1110,14 @@ function createLogoutHandler(config) {
1019
1110
  }
1020
1111
  });
1021
1112
  }
1113
+ if (isCrossSiteRequest(request)) {
1114
+ return new Response(null, {
1115
+ status: 403,
1116
+ headers: {
1117
+ "Cache-Control": "no-store, no-cache"
1118
+ }
1119
+ });
1120
+ }
1022
1121
  const upstreamHeaders = {
1023
1122
  cookie: request.headers.get("cookie") ?? "",
1024
1123
  accept: "application/json"
@@ -1045,6 +1144,9 @@ function validateLogoutConfig(config) {
1045
1144
  assertSafeCookieName(config.cookieNames.hasSession, "createLogoutHandler", "cookieNames.hasSession");
1046
1145
  const refreshCookiePath = config.refreshCookiePath ?? DEFAULT_REFRESH_COOKIE_PATH2;
1047
1146
  assertSafeCookiePath(refreshCookiePath, "createLogoutHandler", "refreshCookiePath");
1147
+ if (config.cookieDomain !== void 0) {
1148
+ assertSafeCookieDomain(config.cookieDomain, "createLogoutHandler", "cookieDomain");
1149
+ }
1048
1150
  if (config.mode === "redirect" && !isSafeSameOriginPath(config.loginPath)) {
1049
1151
  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.`);
1050
1152
  }
@@ -1053,8 +1155,7 @@ function validateLogoutConfig(config) {
1053
1155
  __name(validateLogoutConfig, "validateLogoutConfig");
1054
1156
  function buildLogoutResponse(request, config, refreshCookiePath) {
1055
1157
  if (config.mode === "redirect") {
1056
- const loginUrl = new URL(config.loginPath, request.nextUrl.origin);
1057
- const response2 = server.NextResponse.redirect(loginUrl);
1158
+ const response2 = redirectToPath(config.loginPath);
1058
1159
  attachClearCookies(response2, config, refreshCookiePath);
1059
1160
  response2.headers.set("Cache-Control", "no-store, no-cache");
1060
1161
  return response2;
@@ -1071,9 +1172,9 @@ function buildLogoutResponse(request, config, refreshCookiePath) {
1071
1172
  __name(buildLogoutResponse, "buildLogoutResponse");
1072
1173
  function attachClearCookies(response, config, refreshCookiePath) {
1073
1174
  const clearCookies = [
1074
- serializeClearCookie(config.cookieNames.access, "/"),
1075
- serializeClearCookie(config.cookieNames.refresh, refreshCookiePath),
1076
- serializeClearCookie(config.cookieNames.hasSession, "/")
1175
+ serializeClearCookie(config.cookieNames.access, "/", config.cookieDomain),
1176
+ serializeClearCookie(config.cookieNames.refresh, refreshCookiePath, config.cookieDomain),
1177
+ serializeClearCookie(config.cookieNames.hasSession, "/", config.cookieDomain)
1077
1178
  ];
1078
1179
  for (const cookie of clearCookies) {
1079
1180
  response.headers.append("set-cookie", cookie);