@bymax-one/nest-auth 1.0.11 → 1.1.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,4 +1,5 @@
1
1
  import { AUTH_DASHBOARD_ROUTES, AUTH_PROXY_ROUTES } from '@bymax-one/nest-auth/shared';
2
+ import 'server-only';
2
3
  import { NextResponse } from 'next/server';
3
4
 
4
5
  var __defProp = Object.defineProperty;
@@ -25,6 +26,11 @@ function buildSilentRefreshUrl(request, redirectTo) {
25
26
  return silentRefreshUrl.toString();
26
27
  }
27
28
  __name(buildSilentRefreshUrl, "buildSilentRefreshUrl");
29
+ function buildSilentRefreshPath(request, redirectTo) {
30
+ const url = new URL(buildSilentRefreshUrl(request, redirectTo));
31
+ return `${url.pathname}${url.search}`;
32
+ }
33
+ __name(buildSilentRefreshPath, "buildSilentRefreshPath");
28
34
  function resolveDestination(request, requestUrl, redirectTo) {
29
35
  if (typeof redirectTo === "string" && redirectTo.length > 0) {
30
36
  return redirectTo;
@@ -243,8 +249,6 @@ function isCookieNameChar(code) {
243
249
  }
244
250
  }
245
251
  __name(isCookieNameChar, "isCookieNameChar");
246
-
247
- // src/nextjs/helpers/jwt.ts
248
252
  function decodeJwtToken(token) {
249
253
  const parts = token.split(".");
250
254
  if (parts.length !== 3) return emptyDecoded();
@@ -254,14 +258,11 @@ function decodeJwtToken(token) {
254
258
  const header = safeJsonParse(base64UrlDecodeToString(headerSegment));
255
259
  const payload = safeJsonParse(base64UrlDecodeToString(payloadSegment));
256
260
  if (payload === void 0) return emptyDecoded();
257
- return buildDecodedToken(header, payload);
261
+ return buildDecodedToken(header, payload, false);
258
262
  }
259
263
  __name(decodeJwtToken, "decodeJwtToken");
260
264
  async function verifyJwtToken(token, secret) {
261
- if (secret === void 0 || secret === null) {
262
- return decodeJwtToken(token);
263
- }
264
- if (secret.length === 0) {
265
+ if (secret === void 0 || secret === null || secret.length === 0) {
265
266
  return emptyDecoded();
266
267
  }
267
268
  const parts = token.split(".");
@@ -280,7 +281,7 @@ async function verifyJwtToken(token, secret) {
280
281
  if (signatureBytes === void 0) return emptyDecoded();
281
282
  const signatureValid = await verifyHs256Signature(headerSegment, payloadSegment, signatureBytes, secret);
282
283
  if (!signatureValid) return emptyDecoded();
283
- return buildDecodedToken(header, payload);
284
+ return buildDecodedToken(header, payload, true);
284
285
  }
285
286
  __name(verifyJwtToken, "verifyJwtToken");
286
287
  async function verifyHs256Signature(headerSegment, payloadSegment, signatureBytes, secret) {
@@ -324,7 +325,7 @@ function getTenantId(token) {
324
325
  return token.tenantId;
325
326
  }
326
327
  __name(getTenantId, "getTenantId");
327
- function buildDecodedToken(header, payload) {
328
+ function buildDecodedToken(header, payload, signatureVerified) {
328
329
  const exp = asNumber(pickClaim(payload, "exp"));
329
330
  const iat = asNumber(pickClaim(payload, "iat"));
330
331
  const sub = asString(pickClaim(payload, "sub"));
@@ -334,6 +335,7 @@ function buildDecodedToken(header, payload) {
334
335
  const isValid = exp !== void 0 && exp > nowSeconds;
335
336
  return {
336
337
  isValid,
338
+ signatureVerified,
337
339
  header,
338
340
  payload,
339
341
  sub,
@@ -357,6 +359,7 @@ __name(toArrayBuffer, "toArrayBuffer");
357
359
  function emptyDecoded() {
358
360
  return {
359
361
  isValid: false,
362
+ signatureVerified: false,
360
363
  header: void 0,
361
364
  payload: {},
362
365
  sub: void 0,
@@ -445,15 +448,27 @@ var IDENTITY_HEADERS_BASELINE = [
445
448
  "x-tenant-id",
446
449
  "x-tenant-domain"
447
450
  ];
451
+ var NO_STORE_CACHE_CONTROL = "no-store, no-cache";
448
452
 
449
453
  // src/nextjs/helpers/routeHandlerUtils.ts
450
- function serializeClearCookie(name, path) {
451
- return `${name}=; Path=${path}; Max-Age=0; HttpOnly; Secure; SameSite=Strict`;
454
+ var SAFE_FETCH_SITES = /* @__PURE__ */ new Set([
455
+ "same-origin",
456
+ "none"
457
+ ]);
458
+ function isCrossSiteRequest(request) {
459
+ const fetchSite = request.headers.get("sec-fetch-site");
460
+ return fetchSite !== null && !SAFE_FETCH_SITES.has(fetchSite);
461
+ }
462
+ __name(isCrossSiteRequest, "isCrossSiteRequest");
463
+ function serializeClearCookie(name, path, domain) {
464
+ const scope = domain === void 0 ? "" : `; Domain=${domain}`;
465
+ return `${name}=; Path=${path}${scope}; Max-Age=0; HttpOnly; Secure; SameSite=Strict`;
452
466
  }
453
467
  __name(serializeClearCookie, "serializeClearCookie");
454
468
  function isSafeSameOriginPath(candidate) {
455
469
  return typeof candidate === "string" && // Stryker disable next-line EqualityOperator,ConditionalExpression: redundant non-empty check: `candidate.startsWith('/')` below already implies length > 0, so `> 0`/`>= 0`/`true` are indistinguishable
456
- candidate.length > 0 && candidate.startsWith("/") && !candidate.startsWith("//") && !/[\\\r\n\0]/.test(candidate);
470
+ candidate.length > 0 && candidate.startsWith("/") && !candidate.startsWith("//") && // eslint-disable-next-line no-control-regex -- rejecting control characters is the point
471
+ !/[\\\u0000-\u001f\u007f]/.test(candidate);
457
472
  }
458
473
  __name(isSafeSameOriginPath, "isSafeSameOriginPath");
459
474
  function isSafeUpstreamPath(candidate) {
@@ -475,6 +490,12 @@ function assertSafeCookiePath(value, factoryName, label) {
475
490
  }
476
491
  }
477
492
  __name(assertSafeCookiePath, "assertSafeCookiePath");
493
+ function assertSafeCookieDomain(value, factoryName, label) {
494
+ 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)) {
495
+ throw new Error(`${factoryName}: invalid cookie domain "${value}" for ${label}.`);
496
+ }
497
+ }
498
+ __name(assertSafeCookieDomain, "assertSafeCookieDomain");
478
499
  function trimTrailingSlash(value) {
479
500
  return value.endsWith("/") ? value.slice(0, -1) : value;
480
501
  }
@@ -529,6 +550,39 @@ function isProductionEnv() {
529
550
  return process.env["NODE_ENV"] === "production";
530
551
  }
531
552
  __name(isProductionEnv, "isProductionEnv");
553
+ var FORBIDDEN_IN_PATH = /[\u0000-\u001f\u007f]/;
554
+ function toSameOriginPath(path) {
555
+ if (!path.startsWith("/")) return "/";
556
+ if (path.startsWith("//") || path.startsWith("/\\")) return "/";
557
+ if (FORBIDDEN_IN_PATH.test(path)) return "/";
558
+ return path;
559
+ }
560
+ __name(toSameOriginPath, "toSameOriginPath");
561
+ function redirectToPath(path) {
562
+ return new NextResponse(null, {
563
+ status: 307,
564
+ headers: {
565
+ location: toSameOriginPath(path)
566
+ }
567
+ });
568
+ }
569
+ __name(redirectToPath, "redirectToPath");
570
+ function redirectToPathOnOrigin(path, origin) {
571
+ const url = new URL(toSameOriginPath(path), origin);
572
+ return new NextResponse(null, {
573
+ status: 307,
574
+ headers: {
575
+ location: url.toString()
576
+ }
577
+ });
578
+ }
579
+ __name(redirectToPathOnOrigin, "redirectToPathOnOrigin");
580
+ function withQueryParam(path, key, value) {
581
+ const parsed = new URL(toSameOriginPath(path), "https://placeholder.invalid");
582
+ parsed.searchParams.set(key, value);
583
+ return `${parsed.pathname}${parsed.search}${parsed.hash}`;
584
+ }
585
+ __name(withQueryParam, "withQueryParam");
532
586
 
533
587
  // src/nextjs/internal/proxyUtils.ts
534
588
  function readRefreshAttemptCounter(request, maxAllowed) {
@@ -674,8 +728,7 @@ function handlePublicRoute(request, pathname, tokenState, config, sanitizedHeade
674
728
  }
675
729
  if (hasSession) {
676
730
  const destination = buildRefreshDestination(pathname, request.nextUrl.searchParams, refreshAttempts + 1);
677
- const silentRefreshUrl = new URL(buildSilentRefreshUrl(request, destination));
678
- return NextResponse.redirect(silentRefreshUrl);
731
+ return redirectToPathOnOrigin(buildSilentRefreshPath(request, destination), request.nextUrl.origin);
679
732
  }
680
733
  return NextResponse.next({
681
734
  request: {
@@ -690,7 +743,7 @@ function handleAuthenticatedOnPublic(request, pathname, tokenState, config, sani
690
743
  const isRedirectIfAuth = config.publicRoutesRedirectIfAuthenticated.some((route) => matchesPublicRoute(pathname, route));
691
744
  if (isRedirectIfAuth && !reasonPresent) {
692
745
  const destination = safeRelativePath(config.getDefaultDashboard(role), "/");
693
- return NextResponse.redirect(new URL(destination, request.nextUrl.origin));
746
+ return redirectToPathOnOrigin(destination, request.nextUrl.origin);
694
747
  }
695
748
  return NextResponse.next({
696
749
  request: {
@@ -710,16 +763,14 @@ function handleProtectedRoute(request, pathname, tokenState, matched, config, sa
710
763
  const statusLower = status.toLocaleLowerCase("en-US");
711
764
  const matchedStatus = config.blockedUserStatuses.find((entry) => entry.toLocaleLowerCase("en-US") === statusLower);
712
765
  if (matchedStatus !== void 0) {
713
- return redirectToLogin(request, config, matchedStatus.toLocaleLowerCase("en-US"));
766
+ return refuseBackground(request) ?? redirectToLogin(request, config, matchedStatus.toLocaleLowerCase("en-US"));
714
767
  }
715
768
  }
716
769
  if (!matched.allowedRoles.includes(role)) {
717
770
  const fallback = safeRelativePath(config.getDefaultDashboard(role), "/");
718
771
  const destination = matched.redirectPath ?? fallback;
719
772
  const safeDestination = safeRelativePath(destination, fallback);
720
- const url = new URL(safeDestination, request.nextUrl.origin);
721
- url.searchParams.set("error", "forbidden");
722
- return NextResponse.redirect(url);
773
+ return refuseBackground(request) ?? redirectToPathOnOrigin(withQueryParam(safeDestination, "error", "forbidden"), request.nextUrl.origin);
723
774
  }
724
775
  return buildAuthorisedResponse(request, token, role, config, sanitizedHeaders);
725
776
  }
@@ -738,8 +789,7 @@ function handleUnauthenticatedOnProtected(request, pathname, tokenState, config)
738
789
  }
739
790
  if (hasSession) {
740
791
  const destination = buildRefreshDestination(pathname, request.nextUrl.searchParams, refreshAttempts + 1);
741
- const silentRefreshUrl = new URL(buildSilentRefreshUrl(request, destination));
742
- return NextResponse.redirect(silentRefreshUrl);
792
+ return redirectToPathOnOrigin(buildSilentRefreshPath(request, destination), request.nextUrl.origin);
743
793
  }
744
794
  return redirectToLogin(request, config);
745
795
  }
@@ -763,17 +813,28 @@ function buildAuthorisedResponse(request, token, role, config, sanitizedHeaders)
763
813
  return NextResponse.rewrite(cleanUrl, responseInit);
764
814
  }
765
815
  __name(buildAuthorisedResponse, "buildAuthorisedResponse");
816
+ function refuseBackground(request) {
817
+ if (!isBackgroundRequest(request)) return null;
818
+ return new NextResponse(null, {
819
+ status: 403,
820
+ headers: {
821
+ "Cache-Control": NO_STORE_CACHE_CONTROL
822
+ }
823
+ });
824
+ }
825
+ __name(refuseBackground, "refuseBackground");
766
826
  function redirectToLogin(request, config, reason) {
767
827
  const loginPath = safeRelativePath(config.loginPath, "/");
768
- const url = new URL(loginPath, request.nextUrl.origin);
769
- if (reason !== void 0 && reason.length > 0) {
770
- url.searchParams.set(REASON_PARAM, reason);
771
- }
772
- return NextResponse.redirect(url);
828
+ const destination = reason !== void 0 && reason.length > 0 ? withQueryParam(loginPath, REASON_PARAM, reason) : loginPath;
829
+ return redirectToPathOnOrigin(destination, request.nextUrl.origin);
773
830
  }
774
831
  __name(redirectToLogin, "redirectToLogin");
775
832
 
776
833
  // src/nextjs/internal/tokenState.ts
834
+ var ACCESS_TOKEN_TYPES = [
835
+ "dashboard",
836
+ "platform"
837
+ ];
777
838
  async function readTokenState(request, config) {
778
839
  const raw = request.cookies.get(config.cookieNames.access)?.value;
779
840
  if (raw === void 0 || raw.length === 0) {
@@ -786,14 +847,24 @@ async function readTokenState(request, config) {
786
847
  }
787
848
  const hasSecret = config.jwtSecret !== void 0 && config.jwtSecret.length > 0;
788
849
  const decoded = hasSecret ? await verifyJwtToken(raw, config.jwtSecret) : decodeJwtToken(raw);
850
+ const isSession = decoded.isValid && isAccessToken(decoded);
789
851
  return {
790
852
  token: decoded,
791
853
  hasCookie: true,
792
- authenticated: decoded.isValid,
793
- signatureVerified: hasSecret && decoded.isValid
854
+ authenticated: isSession,
855
+ // Passed through, not conjoined with `isSession`. The name says "a signature was checked",
856
+ // and folding expiry and token-type into it made the same identifier mean one thing on
857
+ // `DecodedToken` and a stricter thing here — the kind of collision that is only ever
858
+ // discovered by someone trusting the looser reading. `authenticated` above is where the
859
+ // conjunction belongs, and it is the field every decision in this proxy actually reads.
860
+ signatureVerified: decoded.signatureVerified
794
861
  };
795
862
  }
796
863
  __name(readTokenState, "readTokenState");
864
+ function isAccessToken(decoded) {
865
+ return ACCESS_TOKEN_TYPES.includes(decoded.payload["type"]);
866
+ }
867
+ __name(isAccessToken, "isAccessToken");
797
868
 
798
869
  // src/nextjs/createAuthProxy.ts
799
870
  function createAuthProxy(config) {
@@ -809,16 +880,20 @@ __name(createAuthProxy, "createAuthProxy");
809
880
  async function runProxy(request, resolved) {
810
881
  const pathname = normalizePath(request.nextUrl.pathname);
811
882
  const classification = classifyRoute(pathname, resolved);
883
+ const sanitizedHeaders = buildSanitizedRequestHeaders(request, resolved);
812
884
  if (classification.kind === "api") {
813
- return NextResponse.next();
885
+ return NextResponse.next({
886
+ request: {
887
+ headers: sanitizedHeaders
888
+ }
889
+ });
814
890
  }
815
891
  const tokenState = await readTokenState(request, resolved);
816
- const sanitizedHeaders = buildSanitizedRequestHeaders(request, resolved);
817
892
  if (isBackgroundRequest(request) && !tokenState.authenticated) {
818
893
  return new NextResponse(null, {
819
894
  status: 401,
820
895
  headers: {
821
- "Cache-Control": "no-store, no-cache"
896
+ "Cache-Control": NO_STORE_CACHE_CONTROL
822
897
  }
823
898
  });
824
899
  }
@@ -863,8 +938,19 @@ function createSilentRefreshHandler(config) {
863
938
  assertSafeCookieName(config.cookieNames.hasSession, "createSilentRefreshHandler", "cookieNames.hasSession");
864
939
  const refreshCookiePath = config.refreshCookiePath ?? DEFAULT_REFRESH_COOKIE_PATH;
865
940
  assertSafeCookiePath(refreshCookiePath, "createSilentRefreshHandler", "refreshCookiePath");
941
+ if (config.cookieDomain !== void 0) {
942
+ assertSafeCookieDomain(config.cookieDomain, "createSilentRefreshHandler", "cookieDomain");
943
+ }
866
944
  const refreshUrl = buildRefreshUrl(config.apiBase, config.refreshPath);
867
945
  return /* @__PURE__ */ __name(async function silentRefreshHandler(request) {
946
+ if (isCrossSiteRequest(request)) {
947
+ return new NextResponse(null, {
948
+ status: 403,
949
+ headers: {
950
+ "Cache-Control": "no-store, no-cache"
951
+ }
952
+ });
953
+ }
868
954
  const origin = request.nextUrl.origin;
869
955
  const rawDestination = request.nextUrl.searchParams.get("redirect");
870
956
  const destination = resolveSafeDestination(rawDestination, origin, config.loginPath);
@@ -885,19 +971,19 @@ function createSilentRefreshHandler(config) {
885
971
  redirect: "manual"
886
972
  });
887
973
  } catch {
888
- return buildLogoutRedirect(origin, config);
974
+ return buildLogoutRedirect(config);
889
975
  }
890
976
  if (upstream.type === "opaqueredirect") {
891
- return buildLogoutRedirect(origin, config);
977
+ return buildLogoutRedirect(config);
892
978
  }
893
979
  if (!upstream.ok) {
894
- return buildLogoutRedirect(origin, config);
980
+ return buildLogoutRedirect(config);
895
981
  }
896
982
  const rawSetCookies = getSetCookieHeaders(upstream.headers);
897
983
  if (rawSetCookies.length === 0) {
898
- return buildLogoutRedirect(origin, config);
984
+ return buildLogoutRedirect(config);
899
985
  }
900
- return buildSuccessRedirect(origin, destination, rawSetCookies);
986
+ return buildSuccessRedirect(destination, rawSetCookies);
901
987
  }, "silentRefreshHandler");
902
988
  }
903
989
  __name(createSilentRefreshHandler, "createSilentRefreshHandler");
@@ -916,9 +1002,8 @@ function resolveSafeDestination(raw, origin, loginPath) {
916
1002
  return `${resolved.pathname}${resolved.search}${resolved.hash}`;
917
1003
  }
918
1004
  __name(resolveSafeDestination, "resolveSafeDestination");
919
- function buildSuccessRedirect(origin, destination, rawSetCookies) {
920
- const destinationUrl = new URL(destination, origin);
921
- const response = NextResponse.redirect(destinationUrl);
1005
+ function buildSuccessRedirect(destination, rawSetCookies) {
1006
+ const response = redirectToPath(destination);
922
1007
  response.headers.set("Cache-Control", "no-store, no-cache");
923
1008
  const deduped = dedupeSetCookieHeaders(rawSetCookies);
924
1009
  for (const cookie of deduped) {
@@ -927,15 +1012,13 @@ function buildSuccessRedirect(origin, destination, rawSetCookies) {
927
1012
  return response;
928
1013
  }
929
1014
  __name(buildSuccessRedirect, "buildSuccessRedirect");
930
- function buildLogoutRedirect(origin, config) {
931
- const loginUrl = new URL(config.loginPath, origin);
932
- loginUrl.searchParams.set("reason", "expired");
933
- const response = NextResponse.redirect(loginUrl);
1015
+ function buildLogoutRedirect(config) {
1016
+ const response = redirectToPath(withQueryParam(config.loginPath, "reason", "expired"));
934
1017
  response.headers.set("Cache-Control", "no-store, no-cache");
935
1018
  const clearCookies = [
936
- serializeClearCookie(config.cookieNames.access, "/"),
937
- serializeClearCookie(config.cookieNames.refresh, config.refreshCookiePath ?? DEFAULT_REFRESH_COOKIE_PATH),
938
- serializeClearCookie(config.cookieNames.hasSession, "/")
1019
+ serializeClearCookie(config.cookieNames.access, "/", config.cookieDomain),
1020
+ serializeClearCookie(config.cookieNames.refresh, config.refreshCookiePath ?? DEFAULT_REFRESH_COOKIE_PATH, config.cookieDomain),
1021
+ serializeClearCookie(config.cookieNames.hasSession, "/", config.cookieDomain)
939
1022
  ];
940
1023
  for (const cookie of clearCookies) {
941
1024
  response.headers.append("set-cookie", cookie);
@@ -957,6 +1040,14 @@ function createClientRefreshHandler(config) {
957
1040
  }
958
1041
  });
959
1042
  }
1043
+ if (isCrossSiteRequest(request)) {
1044
+ return new Response(null, {
1045
+ status: 403,
1046
+ headers: {
1047
+ "Cache-Control": "no-store, no-cache"
1048
+ }
1049
+ });
1050
+ }
960
1051
  let upstream;
961
1052
  try {
962
1053
  upstream = await fetch(refreshUrl, {
@@ -1017,6 +1108,14 @@ function createLogoutHandler(config) {
1017
1108
  }
1018
1109
  });
1019
1110
  }
1111
+ if (isCrossSiteRequest(request)) {
1112
+ return new Response(null, {
1113
+ status: 403,
1114
+ headers: {
1115
+ "Cache-Control": "no-store, no-cache"
1116
+ }
1117
+ });
1118
+ }
1020
1119
  const upstreamHeaders = {
1021
1120
  cookie: request.headers.get("cookie") ?? "",
1022
1121
  accept: "application/json"
@@ -1043,6 +1142,9 @@ function validateLogoutConfig(config) {
1043
1142
  assertSafeCookieName(config.cookieNames.hasSession, "createLogoutHandler", "cookieNames.hasSession");
1044
1143
  const refreshCookiePath = config.refreshCookiePath ?? DEFAULT_REFRESH_COOKIE_PATH2;
1045
1144
  assertSafeCookiePath(refreshCookiePath, "createLogoutHandler", "refreshCookiePath");
1145
+ if (config.cookieDomain !== void 0) {
1146
+ assertSafeCookieDomain(config.cookieDomain, "createLogoutHandler", "cookieDomain");
1147
+ }
1046
1148
  if (config.mode === "redirect" && !isSafeSameOriginPath(config.loginPath)) {
1047
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.`);
1048
1150
  }
@@ -1051,8 +1153,7 @@ function validateLogoutConfig(config) {
1051
1153
  __name(validateLogoutConfig, "validateLogoutConfig");
1052
1154
  function buildLogoutResponse(request, config, refreshCookiePath) {
1053
1155
  if (config.mode === "redirect") {
1054
- const loginUrl = new URL(config.loginPath, request.nextUrl.origin);
1055
- const response2 = NextResponse.redirect(loginUrl);
1156
+ const response2 = redirectToPath(config.loginPath);
1056
1157
  attachClearCookies(response2, config, refreshCookiePath);
1057
1158
  response2.headers.set("Cache-Control", "no-store, no-cache");
1058
1159
  return response2;
@@ -1069,9 +1170,9 @@ function buildLogoutResponse(request, config, refreshCookiePath) {
1069
1170
  __name(buildLogoutResponse, "buildLogoutResponse");
1070
1171
  function attachClearCookies(response, config, refreshCookiePath) {
1071
1172
  const clearCookies = [
1072
- serializeClearCookie(config.cookieNames.access, "/"),
1073
- serializeClearCookie(config.cookieNames.refresh, refreshCookiePath),
1074
- serializeClearCookie(config.cookieNames.hasSession, "/")
1173
+ serializeClearCookie(config.cookieNames.access, "/", config.cookieDomain),
1174
+ serializeClearCookie(config.cookieNames.refresh, refreshCookiePath, config.cookieDomain),
1175
+ serializeClearCookie(config.cookieNames.hasSession, "/", config.cookieDomain)
1075
1176
  ];
1076
1177
  for (const cookie of clearCookies) {
1077
1178
  response.headers.append("set-cookie", cookie);
@@ -82,42 +82,38 @@ function AuthProvider({ children, client, onSessionExpired, revalidateInterval =
82
82
  return;
83
83
  }
84
84
  }, []);
85
- const revalidate = React.useCallback(
86
- async (isInitial) => {
87
- try {
88
- const user = await clientRef.current.getMe();
89
- syncedDispatch({
90
- type: "SET_USER",
91
- payload: {
92
- user,
93
- timestamp: /* @__PURE__ */ new Date()
94
- }
95
- });
96
- } catch (error) {
97
- const wasAuthenticated = statusRef.current === "authenticated";
98
- if (isSessionExpiredError(error)) {
99
- if (!isInitial && wasAuthenticated) {
100
- try {
101
- onSessionExpiredRef.current?.();
102
- } catch (callbackError) {
103
- console.warn("[nest-auth] onSessionExpired callback threw:", callbackError);
104
- }
85
+ const revalidate = React.useCallback(async (isInitial) => {
86
+ try {
87
+ const user = await clientRef.current.getMe();
88
+ syncedDispatch({
89
+ type: "SET_USER",
90
+ payload: {
91
+ user,
92
+ timestamp: /* @__PURE__ */ new Date()
93
+ }
94
+ });
95
+ } catch (error) {
96
+ const wasAuthenticated = statusRef.current === "authenticated";
97
+ if (isSessionExpiredError(error)) {
98
+ if (!isInitial && wasAuthenticated) {
99
+ try {
100
+ onSessionExpiredRef.current?.();
101
+ } catch (callbackError) {
102
+ console.warn("[nest-auth] onSessionExpired callback threw:", callbackError);
105
103
  }
106
- syncedDispatch({
107
- type: "CLEAR_SESSION"
108
- });
109
- return;
110
104
  }
111
105
  syncedDispatch({
112
- type: "SET_ERROR"
106
+ type: "CLEAR_SESSION"
113
107
  });
108
+ return;
114
109
  }
115
- },
116
- // Stryker disable next-line ArrayDeclaration: deps hold only the stable `syncedDispatch`, so emptying the array does not change effect/memo behavior
117
- [
118
- syncedDispatch
119
- ]
120
- );
110
+ syncedDispatch({
111
+ type: "SET_ERROR"
112
+ });
113
+ }
114
+ }, [
115
+ syncedDispatch
116
+ ]);
121
117
  React.useEffect(() => {
122
118
  void revalidate(true);
123
119
  }, [
@@ -137,71 +133,63 @@ function AuthProvider({ children, client, onSessionExpired, revalidateInterval =
137
133
  revalidate,
138
134
  revalidateInterval
139
135
  ]);
140
- const login = React.useCallback(
141
- async (email, password, options) => {
142
- const tenantId = options?.tenantId ?? DEFAULT_TENANT_ID;
143
- syncedDispatch({
144
- type: "SET_LOADING"
136
+ const login = React.useCallback(async (email, password, options) => {
137
+ const tenantId = options?.tenantId ?? DEFAULT_TENANT_ID;
138
+ syncedDispatch({
139
+ type: "SET_LOADING"
140
+ });
141
+ try {
142
+ const result = await clientRef.current.login({
143
+ email,
144
+ password,
145
+ tenantId
145
146
  });
146
- try {
147
- const result = await clientRef.current.login({
148
- email,
149
- password,
150
- tenantId
151
- });
152
- if ("mfaRequired" in result) {
153
- syncedDispatch({
154
- type: "CLEAR_SESSION"
155
- });
156
- return result;
157
- }
147
+ if ("mfaRequired" in result) {
158
148
  syncedDispatch({
159
- type: "SET_USER",
160
- payload: {
161
- user: result.user,
162
- timestamp: /* @__PURE__ */ new Date()
163
- }
149
+ type: "CLEAR_SESSION"
164
150
  });
165
151
  return result;
166
- } catch (error) {
167
- syncedDispatch({
168
- type: "SET_ERROR"
169
- });
170
- throw error;
171
152
  }
172
- },
173
- // Stryker disable next-line ArrayDeclaration: deps hold only the stable `syncedDispatch`, so emptying the array does not change memoization
174
- [
175
- syncedDispatch
176
- ]
177
- );
178
- const register = React.useCallback(
179
- async (data) => {
180
153
  syncedDispatch({
181
- type: "SET_LOADING"
154
+ type: "SET_USER",
155
+ payload: {
156
+ user: result.user,
157
+ timestamp: /* @__PURE__ */ new Date()
158
+ }
182
159
  });
183
- try {
184
- const result = await clientRef.current.register(data);
185
- syncedDispatch({
186
- type: "SET_USER",
187
- payload: {
188
- user: result.user,
189
- timestamp: /* @__PURE__ */ new Date()
190
- }
191
- });
192
- return result;
193
- } catch (error) {
194
- syncedDispatch({
195
- type: "SET_ERROR"
196
- });
197
- throw error;
198
- }
199
- },
200
- // Stryker disable next-line ArrayDeclaration: deps hold only the stable `syncedDispatch`, so emptying the array does not change memoization
201
- [
202
- syncedDispatch
203
- ]
204
- );
160
+ return result;
161
+ } catch (error) {
162
+ syncedDispatch({
163
+ type: "SET_ERROR"
164
+ });
165
+ throw error;
166
+ }
167
+ }, [
168
+ syncedDispatch
169
+ ]);
170
+ const register = React.useCallback(async (data) => {
171
+ syncedDispatch({
172
+ type: "SET_LOADING"
173
+ });
174
+ try {
175
+ const result = await clientRef.current.register(data);
176
+ syncedDispatch({
177
+ type: "SET_USER",
178
+ payload: {
179
+ user: result.user,
180
+ timestamp: /* @__PURE__ */ new Date()
181
+ }
182
+ });
183
+ return result;
184
+ } catch (error) {
185
+ syncedDispatch({
186
+ type: "SET_ERROR"
187
+ });
188
+ throw error;
189
+ }
190
+ }, [
191
+ syncedDispatch
192
+ ]);
205
193
  const logout = React.useCallback(async () => {
206
194
  try {
207
195
  await clientRef.current.logout();