@bymax-one/nest-auth 1.5.2 → 1.5.4

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.
@@ -2,6 +2,14 @@
2
2
 
3
3
  var shared = require('@bymax-one/nest-auth/shared');
4
4
 
5
+ // src/client/createAuthFetch.ts
6
+
7
+ // src/shared/utils/timer-delay.ts
8
+ var MAX_TIMER_DELAY_MS = 2147483647;
9
+ function isTimerDelay(value) {
10
+ return typeof value === "number" && value >= 0 && value <= MAX_TIMER_DELAY_MS;
11
+ }
12
+
5
13
  // src/client/createAuthFetch.ts
6
14
  var DEFAULT_HEADERS = Object.freeze({
7
15
  "Content-Type": "application/json"
@@ -135,6 +143,15 @@ async function performRefresh(endpoint, credentials) {
135
143
  return { ok: false, reason: "unreachable", status: null };
136
144
  }
137
145
  }
146
+ function requestTimeoutOf(timeout) {
147
+ const timeoutMs = timeout ?? 3e4;
148
+ if (!isTimerDelay(timeoutMs)) {
149
+ throw new TypeError(
150
+ `createAuthFetch: timeout must be a number of milliseconds from 0 to ${MAX_TIMER_DELAY_MS}.`
151
+ );
152
+ }
153
+ return timeoutMs;
154
+ }
138
155
  function createAuthFetch(config = {}) {
139
156
  const baseUrl = config.baseUrl;
140
157
  const refreshEndpoint = config.refreshEndpoint ?? shared.AUTH_PROXY_ROUTES.clientRefresh;
@@ -142,7 +159,7 @@ function createAuthFetch(config = {}) {
142
159
  const defaultHeaders = buildDefaultHeaders(config.defaultHeaders);
143
160
  const onSessionExpired = config.onSessionExpired;
144
161
  const onRefreshFailed = config.onRefreshFailed;
145
- const timeoutMs = config.timeout ?? 3e4;
162
+ const timeoutMs = requestTimeoutOf(config.timeout);
146
163
  const skipRefreshSuffixes = shared.buildAuthRefreshSkipSuffixes(config.routePrefix);
147
164
  const reportCallbackError = (err) => {
148
165
  console.warn("[nest-auth] onRefreshFailed callback threw:", err);
@@ -87,7 +87,8 @@ interface AuthFetchConfig {
87
87
  /**
88
88
  * Per-request timeout in milliseconds.
89
89
  *
90
- * Default: `30_000` (30s). Pass `0` to disable the timeout.
90
+ * Default: `30_000` (30s). Pass `0` to disable the timeout. Anything but a number from `0` to
91
+ * `2147483647` (the largest delay a timer honors) is refused when the wrapper is created.
91
92
  * Disabling is appropriate for long-poll endpoints; for normal
92
93
  * requests keep the default to avoid hanging UIs on slow networks.
93
94
  */
@@ -87,7 +87,8 @@ interface AuthFetchConfig {
87
87
  /**
88
88
  * Per-request timeout in milliseconds.
89
89
  *
90
- * Default: `30_000` (30s). Pass `0` to disable the timeout.
90
+ * Default: `30_000` (30s). Pass `0` to disable the timeout. Anything but a number from `0` to
91
+ * `2147483647` (the largest delay a timer honors) is refused when the wrapper is created.
91
92
  * Disabling is appropriate for long-poll endpoints; for normal
92
93
  * requests keep the default to avoid hanging UIs on slow networks.
93
94
  */
@@ -1,6 +1,14 @@
1
1
  import { AUTH_ERROR_CODES, AUTH_PROXY_ROUTES, buildAuthRefreshSkipSuffixes, AUTH_PASSWORD_ROUTES, AUTH_MFA_ROUTES, AuthClientError, AUTH_DASHBOARD_ROUTES, AUTH_WORKSPACE_ROUTES, trimSlashes, fillRoute } from '@bymax-one/nest-auth/shared';
2
2
  export { AuthClientError } from '@bymax-one/nest-auth/shared';
3
3
 
4
+ // src/client/createAuthFetch.ts
5
+
6
+ // src/shared/utils/timer-delay.ts
7
+ var MAX_TIMER_DELAY_MS = 2147483647;
8
+ function isTimerDelay(value) {
9
+ return typeof value === "number" && value >= 0 && value <= MAX_TIMER_DELAY_MS;
10
+ }
11
+
4
12
  // src/client/createAuthFetch.ts
5
13
  var DEFAULT_HEADERS = Object.freeze({
6
14
  "Content-Type": "application/json"
@@ -134,6 +142,15 @@ async function performRefresh(endpoint, credentials) {
134
142
  return { ok: false, reason: "unreachable", status: null };
135
143
  }
136
144
  }
145
+ function requestTimeoutOf(timeout) {
146
+ const timeoutMs = timeout ?? 3e4;
147
+ if (!isTimerDelay(timeoutMs)) {
148
+ throw new TypeError(
149
+ `createAuthFetch: timeout must be a number of milliseconds from 0 to ${MAX_TIMER_DELAY_MS}.`
150
+ );
151
+ }
152
+ return timeoutMs;
153
+ }
137
154
  function createAuthFetch(config = {}) {
138
155
  const baseUrl = config.baseUrl;
139
156
  const refreshEndpoint = config.refreshEndpoint ?? AUTH_PROXY_ROUTES.clientRefresh;
@@ -141,7 +158,7 @@ function createAuthFetch(config = {}) {
141
158
  const defaultHeaders = buildDefaultHeaders(config.defaultHeaders);
142
159
  const onSessionExpired = config.onSessionExpired;
143
160
  const onRefreshFailed = config.onRefreshFailed;
144
- const timeoutMs = config.timeout ?? 3e4;
161
+ const timeoutMs = requestTimeoutOf(config.timeout);
145
162
  const skipRefreshSuffixes = buildAuthRefreshSkipSuffixes(config.routePrefix);
146
163
  const reportCallbackError = (err) => {
147
164
  console.warn("[nest-auth] onRefreshFailed callback threw:", err);
@@ -351,7 +351,7 @@ function decodeJwtToken(token) {
351
351
  if (payload === void 0) return emptyDecoded();
352
352
  return buildDecodedToken(header, payload, false);
353
353
  }
354
- async function verifyJwtToken(token, secret) {
354
+ async function verifyJwtToken(token, secret, options) {
355
355
  if (secret === void 0 || secret === null) return emptyDecoded();
356
356
  if (secret.length === 0) return emptyDecoded();
357
357
  const parts = token.split(".");
@@ -368,15 +368,32 @@ async function verifyJwtToken(token, secret) {
368
368
  if (payload === void 0) return emptyDecoded();
369
369
  const signatureBytes = base64UrlDecodeToBytes(signatureSegment);
370
370
  if (signatureBytes === void 0) return emptyDecoded();
371
- const signatureValid = await verifyHs256Signature(
372
- headerSegment,
373
- payloadSegment,
374
- signatureBytes,
375
- secret
376
- );
377
- if (!signatureValid) return emptyDecoded();
371
+ const signatureValid = await verifyAgainstSecrets(headerSegment, payloadSegment, signatureBytes, [
372
+ secret,
373
+ ...retiredSecretsOf(options)
374
+ ]);
375
+ if (!signatureValid || !carriesRequiredClaims(payload, options)) return emptyDecoded();
378
376
  return buildDecodedToken(header, payload, true);
379
377
  }
378
+ function retiredSecretsOf(options) {
379
+ const listed = options?.previousSecrets;
380
+ return Array.isArray(listed) ? listed.filter((entry) => typeof entry === "string") : [];
381
+ }
382
+ async function verifyAgainstSecrets(headerSegment, payloadSegment, signatureBytes, secrets) {
383
+ for (const secret of secrets) {
384
+ if (await verifyHs256Signature(headerSegment, payloadSegment, signatureBytes, secret)) {
385
+ return true;
386
+ }
387
+ }
388
+ return false;
389
+ }
390
+ function carriesRequiredClaims(payload, options) {
391
+ const { issuer, audience } = options ?? {};
392
+ if (issuer !== void 0 && issuer !== "" && payload["iss"] !== issuer) return false;
393
+ if (audience === void 0 || audience === "") return true;
394
+ const claim = payload["aud"];
395
+ return Array.isArray(claim) ? claim.includes(audience) : claim === audience;
396
+ }
380
397
  async function verifyHs256Signature(headerSegment, payloadSegment, signatureBytes, secret) {
381
398
  const signingInput = asciiBytes(`${headerSegment}.${payloadSegment}`);
382
399
  const secretBytes = utf8Bytes(secret);
@@ -857,7 +874,11 @@ async function readTokenState(request, config) {
857
874
  signatureVerified: false
858
875
  };
859
876
  }
860
- const decoded = await verifyJwtToken(raw, config.jwtSecret);
877
+ const decoded = await verifyJwtToken(raw, config.jwtSecret, {
878
+ previousSecrets: config.jwtPreviousSecrets,
879
+ issuer: config.jwtIssuer,
880
+ audience: config.jwtAudience
881
+ });
861
882
  const isSession = decoded.isValid && isAccessToken(decoded);
862
883
  return {
863
884
  token: decoded,
@@ -341,10 +341,11 @@ declare function getSetCookieHeaders(headers: HeadersLike): string[];
341
341
  *
342
342
  * Two functions, and a missing secret never selects between them:
343
343
  *
344
- * - {@link verifyJwtToken} performs HS256 signature verification and
345
- * expiry validation. It fails closed: a missing or empty secret
346
- * returns an empty, invalid result rather than a decoded payload.
347
- * This is the production path.
344
+ * - {@link verifyJwtToken} performs HS256 signature verification,
345
+ * expiry validation and, when configured, the issuer and audience
346
+ * checks. It fails closed: a missing or empty secret returns an
347
+ * empty, invalid result rather than a decoded payload. This is the
348
+ * path for a routing decision at the edge.
348
349
  *
349
350
  * - {@link decodeJwtToken} parses the payload without verifying the
350
351
  * signature. It is called explicitly, for non-authoritative claims
@@ -516,15 +517,50 @@ declare function decodeJwtToken(token: string): DecodedToken;
516
517
  * No test can distinguish the two, so the mutants on it carry a
517
518
  * suppression.
518
519
  *
520
+ * **This is a routing check, not an authorization check.** It tells the edge whether a token was
521
+ * minted with the backend's secret, is unexpired and carries the backend's issuer and audience, which
522
+ * is enough to choose between rendering a page and redirecting to sign-in. It cannot see what the
523
+ * backend sees: a logout, a password reset or a revoke-all, the account's current status (a blocked or suspended user), the MFA state, or a workspace
524
+ * membership. A token this function accepts may be one the backend refuses on the next call. Never
525
+ * use its result, or a role read from it, as the access decision for data or an action: the backend
526
+ * must verify every request that reads or changes anything.
527
+ *
519
528
  * @param token - JWS compact serialisation.
520
529
  * @param secret - HS256 shared secret. A missing or empty value
521
530
  * makes every token invalid.
531
+ * @param options - The backend's retired secrets, issuer and audience, so a token is judged as the
532
+ * backend judges it; see {@link VerifyJwtOptions}. Omitted, only the signature and
533
+ * the expiry are checked.
522
534
  * @returns A {@link DecodedToken} where `isValid` reflects BOTH the
523
535
  * signature verification AND the expiry check, and
524
536
  * `signatureVerified` is `true` only when a signature was
525
537
  * actually checked.
526
538
  */
527
- declare function verifyJwtToken(token: string, secret?: string | null): Promise<DecodedToken>;
539
+ declare function verifyJwtToken(token: string, secret?: string | null, options?: VerifyJwtOptions): Promise<DecodedToken>;
540
+ /**
541
+ * What `verifyJwtToken` holds a token to beyond its signature, as the backend holds it.
542
+ *
543
+ * A proxy that ignores one accepts a token the backend refuses (or, for a retired secret, refuses
544
+ * one the backend still accepts).
545
+ */
546
+ interface VerifyJwtOptions {
547
+ /**
548
+ * Secrets the backend still verifies with while a rotation drains (`jwt.previousSecrets`), tried
549
+ * after the current one. An empty entry never verifies anything.
550
+ */
551
+ readonly previousSecrets?: readonly string[] | undefined;
552
+ /**
553
+ * The issuer every token must carry in `iss` (`jwt.issuer`). A token with no `iss`, or any other
554
+ * value, is refused, so omitting the claim is not a way to skip the check. An empty string reads
555
+ * as unconfigured.
556
+ */
557
+ readonly issuer?: string | undefined;
558
+ /**
559
+ * The audience every token must carry in `aud` (`jwt.audience`), as a string or inside an array.
560
+ * A token with none, or without it, is refused. An empty string reads as unconfigured.
561
+ */
562
+ readonly audience?: string | undefined;
563
+ }
528
564
  /**
529
565
  * Returns `true` when the decoded token has no `exp` claim OR the
530
566
  * `exp` claim has already passed relative to the system clock.
@@ -699,6 +735,22 @@ interface AuthProxyConfig {
699
735
  * mode signature verification MUST be performed upstream.
700
736
  */
701
737
  readonly jwtSecret?: string;
738
+ /**
739
+ * Secrets the backend still verifies with while a rotation drains (`jwt.previousSecrets`). The
740
+ * proxy verifies with them after `jwtSecret`, so a session signed before the rotation is not
741
+ * treated as signed out while the backend still accepts it.
742
+ */
743
+ readonly jwtPreviousSecrets?: readonly string[];
744
+ /**
745
+ * The issuer the backend requires (`jwt.issuer`). When set, a token without exactly this `iss`
746
+ * is not authenticated. Leave it unset when the backend sets none.
747
+ */
748
+ readonly jwtIssuer?: string;
749
+ /**
750
+ * The audience the backend requires (`jwt.audience`). When set, a token whose `aud` is not this
751
+ * value, or does not contain it, is not authenticated. Leave it unset when the backend sets none.
752
+ */
753
+ readonly jwtAudience?: string;
702
754
  /**
703
755
  * Maximum number of consecutive silent-refresh redirects the
704
756
  * proxy will chain before giving up and rendering the page
@@ -1227,4 +1279,4 @@ declare function createLogoutHandler(config: LogoutHandlerConfig): LogoutHandler
1227
1279
  declare const LOGOUT_ROUTE: "/api/auth/logout";
1228
1280
 
1229
1281
  export { CLIENT_REFRESH_ROUTE, LOGOUT_ROUTE, SILENT_REFRESH_ROUTE, buildSilentRefreshUrl, createAuthProxy, createClientRefreshHandler, createLogoutHandler, createSilentRefreshHandler, createWorkspaceAccessReader, decodeJwtToken, dedupeSetCookieHeaders, getSetCookieHeaders, getTenantId, getUserId, getUserRole, isBackgroundRequest, isTokenExpired, parseSetCookieHeader, resolveSafeDestination, verifyJwtToken };
1230
- export type { AuthProxyConfig, AuthProxyInstance, ClientRefreshHandler, ClientRefreshHandlerConfig, DashboardHint, DecodedToken, HeadersLike, JwtHeader, LogoutHandler, LogoutHandlerConfig, LogoutHandlerRedirectConfig, LogoutHandlerStatusConfig, ParsedSetCookie, ProtectedRoutePattern, RequestWithHeaders, RequestWithUrl, ResolvedAuthProxyConfig, SilentRefreshHandler, SilentRefreshHandlerConfig, WorkspaceAccessReaderConfig };
1282
+ export type { AuthProxyConfig, AuthProxyInstance, ClientRefreshHandler, ClientRefreshHandlerConfig, DashboardHint, DecodedToken, HeadersLike, JwtHeader, LogoutHandler, LogoutHandlerConfig, LogoutHandlerRedirectConfig, LogoutHandlerStatusConfig, ParsedSetCookie, ProtectedRoutePattern, RequestWithHeaders, RequestWithUrl, ResolvedAuthProxyConfig, SilentRefreshHandler, SilentRefreshHandlerConfig, VerifyJwtOptions, WorkspaceAccessReaderConfig };
@@ -341,10 +341,11 @@ declare function getSetCookieHeaders(headers: HeadersLike): string[];
341
341
  *
342
342
  * Two functions, and a missing secret never selects between them:
343
343
  *
344
- * - {@link verifyJwtToken} performs HS256 signature verification and
345
- * expiry validation. It fails closed: a missing or empty secret
346
- * returns an empty, invalid result rather than a decoded payload.
347
- * This is the production path.
344
+ * - {@link verifyJwtToken} performs HS256 signature verification,
345
+ * expiry validation and, when configured, the issuer and audience
346
+ * checks. It fails closed: a missing or empty secret returns an
347
+ * empty, invalid result rather than a decoded payload. This is the
348
+ * path for a routing decision at the edge.
348
349
  *
349
350
  * - {@link decodeJwtToken} parses the payload without verifying the
350
351
  * signature. It is called explicitly, for non-authoritative claims
@@ -516,15 +517,50 @@ declare function decodeJwtToken(token: string): DecodedToken;
516
517
  * No test can distinguish the two, so the mutants on it carry a
517
518
  * suppression.
518
519
  *
520
+ * **This is a routing check, not an authorization check.** It tells the edge whether a token was
521
+ * minted with the backend's secret, is unexpired and carries the backend's issuer and audience, which
522
+ * is enough to choose between rendering a page and redirecting to sign-in. It cannot see what the
523
+ * backend sees: a logout, a password reset or a revoke-all, the account's current status (a blocked or suspended user), the MFA state, or a workspace
524
+ * membership. A token this function accepts may be one the backend refuses on the next call. Never
525
+ * use its result, or a role read from it, as the access decision for data or an action: the backend
526
+ * must verify every request that reads or changes anything.
527
+ *
519
528
  * @param token - JWS compact serialisation.
520
529
  * @param secret - HS256 shared secret. A missing or empty value
521
530
  * makes every token invalid.
531
+ * @param options - The backend's retired secrets, issuer and audience, so a token is judged as the
532
+ * backend judges it; see {@link VerifyJwtOptions}. Omitted, only the signature and
533
+ * the expiry are checked.
522
534
  * @returns A {@link DecodedToken} where `isValid` reflects BOTH the
523
535
  * signature verification AND the expiry check, and
524
536
  * `signatureVerified` is `true` only when a signature was
525
537
  * actually checked.
526
538
  */
527
- declare function verifyJwtToken(token: string, secret?: string | null): Promise<DecodedToken>;
539
+ declare function verifyJwtToken(token: string, secret?: string | null, options?: VerifyJwtOptions): Promise<DecodedToken>;
540
+ /**
541
+ * What `verifyJwtToken` holds a token to beyond its signature, as the backend holds it.
542
+ *
543
+ * A proxy that ignores one accepts a token the backend refuses (or, for a retired secret, refuses
544
+ * one the backend still accepts).
545
+ */
546
+ interface VerifyJwtOptions {
547
+ /**
548
+ * Secrets the backend still verifies with while a rotation drains (`jwt.previousSecrets`), tried
549
+ * after the current one. An empty entry never verifies anything.
550
+ */
551
+ readonly previousSecrets?: readonly string[] | undefined;
552
+ /**
553
+ * The issuer every token must carry in `iss` (`jwt.issuer`). A token with no `iss`, or any other
554
+ * value, is refused, so omitting the claim is not a way to skip the check. An empty string reads
555
+ * as unconfigured.
556
+ */
557
+ readonly issuer?: string | undefined;
558
+ /**
559
+ * The audience every token must carry in `aud` (`jwt.audience`), as a string or inside an array.
560
+ * A token with none, or without it, is refused. An empty string reads as unconfigured.
561
+ */
562
+ readonly audience?: string | undefined;
563
+ }
528
564
  /**
529
565
  * Returns `true` when the decoded token has no `exp` claim OR the
530
566
  * `exp` claim has already passed relative to the system clock.
@@ -699,6 +735,22 @@ interface AuthProxyConfig {
699
735
  * mode signature verification MUST be performed upstream.
700
736
  */
701
737
  readonly jwtSecret?: string;
738
+ /**
739
+ * Secrets the backend still verifies with while a rotation drains (`jwt.previousSecrets`). The
740
+ * proxy verifies with them after `jwtSecret`, so a session signed before the rotation is not
741
+ * treated as signed out while the backend still accepts it.
742
+ */
743
+ readonly jwtPreviousSecrets?: readonly string[];
744
+ /**
745
+ * The issuer the backend requires (`jwt.issuer`). When set, a token without exactly this `iss`
746
+ * is not authenticated. Leave it unset when the backend sets none.
747
+ */
748
+ readonly jwtIssuer?: string;
749
+ /**
750
+ * The audience the backend requires (`jwt.audience`). When set, a token whose `aud` is not this
751
+ * value, or does not contain it, is not authenticated. Leave it unset when the backend sets none.
752
+ */
753
+ readonly jwtAudience?: string;
702
754
  /**
703
755
  * Maximum number of consecutive silent-refresh redirects the
704
756
  * proxy will chain before giving up and rendering the page
@@ -1227,4 +1279,4 @@ declare function createLogoutHandler(config: LogoutHandlerConfig): LogoutHandler
1227
1279
  declare const LOGOUT_ROUTE: "/api/auth/logout";
1228
1280
 
1229
1281
  export { CLIENT_REFRESH_ROUTE, LOGOUT_ROUTE, SILENT_REFRESH_ROUTE, buildSilentRefreshUrl, createAuthProxy, createClientRefreshHandler, createLogoutHandler, createSilentRefreshHandler, createWorkspaceAccessReader, decodeJwtToken, dedupeSetCookieHeaders, getSetCookieHeaders, getTenantId, getUserId, getUserRole, isBackgroundRequest, isTokenExpired, parseSetCookieHeader, resolveSafeDestination, verifyJwtToken };
1230
- export type { AuthProxyConfig, AuthProxyInstance, ClientRefreshHandler, ClientRefreshHandlerConfig, DashboardHint, DecodedToken, HeadersLike, JwtHeader, LogoutHandler, LogoutHandlerConfig, LogoutHandlerRedirectConfig, LogoutHandlerStatusConfig, ParsedSetCookie, ProtectedRoutePattern, RequestWithHeaders, RequestWithUrl, ResolvedAuthProxyConfig, SilentRefreshHandler, SilentRefreshHandlerConfig, WorkspaceAccessReaderConfig };
1282
+ export type { AuthProxyConfig, AuthProxyInstance, ClientRefreshHandler, ClientRefreshHandlerConfig, DashboardHint, DecodedToken, HeadersLike, JwtHeader, LogoutHandler, LogoutHandlerConfig, LogoutHandlerRedirectConfig, LogoutHandlerStatusConfig, ParsedSetCookie, ProtectedRoutePattern, RequestWithHeaders, RequestWithUrl, ResolvedAuthProxyConfig, SilentRefreshHandler, SilentRefreshHandlerConfig, VerifyJwtOptions, WorkspaceAccessReaderConfig };
@@ -349,7 +349,7 @@ function decodeJwtToken(token) {
349
349
  if (payload === void 0) return emptyDecoded();
350
350
  return buildDecodedToken(header, payload, false);
351
351
  }
352
- async function verifyJwtToken(token, secret) {
352
+ async function verifyJwtToken(token, secret, options) {
353
353
  if (secret === void 0 || secret === null) return emptyDecoded();
354
354
  if (secret.length === 0) return emptyDecoded();
355
355
  const parts = token.split(".");
@@ -366,15 +366,32 @@ async function verifyJwtToken(token, secret) {
366
366
  if (payload === void 0) return emptyDecoded();
367
367
  const signatureBytes = base64UrlDecodeToBytes(signatureSegment);
368
368
  if (signatureBytes === void 0) return emptyDecoded();
369
- const signatureValid = await verifyHs256Signature(
370
- headerSegment,
371
- payloadSegment,
372
- signatureBytes,
373
- secret
374
- );
375
- if (!signatureValid) return emptyDecoded();
369
+ const signatureValid = await verifyAgainstSecrets(headerSegment, payloadSegment, signatureBytes, [
370
+ secret,
371
+ ...retiredSecretsOf(options)
372
+ ]);
373
+ if (!signatureValid || !carriesRequiredClaims(payload, options)) return emptyDecoded();
376
374
  return buildDecodedToken(header, payload, true);
377
375
  }
376
+ function retiredSecretsOf(options) {
377
+ const listed = options?.previousSecrets;
378
+ return Array.isArray(listed) ? listed.filter((entry) => typeof entry === "string") : [];
379
+ }
380
+ async function verifyAgainstSecrets(headerSegment, payloadSegment, signatureBytes, secrets) {
381
+ for (const secret of secrets) {
382
+ if (await verifyHs256Signature(headerSegment, payloadSegment, signatureBytes, secret)) {
383
+ return true;
384
+ }
385
+ }
386
+ return false;
387
+ }
388
+ function carriesRequiredClaims(payload, options) {
389
+ const { issuer, audience } = options ?? {};
390
+ if (issuer !== void 0 && issuer !== "" && payload["iss"] !== issuer) return false;
391
+ if (audience === void 0 || audience === "") return true;
392
+ const claim = payload["aud"];
393
+ return Array.isArray(claim) ? claim.includes(audience) : claim === audience;
394
+ }
378
395
  async function verifyHs256Signature(headerSegment, payloadSegment, signatureBytes, secret) {
379
396
  const signingInput = asciiBytes(`${headerSegment}.${payloadSegment}`);
380
397
  const secretBytes = utf8Bytes(secret);
@@ -855,7 +872,11 @@ async function readTokenState(request, config) {
855
872
  signatureVerified: false
856
873
  };
857
874
  }
858
- const decoded = await verifyJwtToken(raw, config.jwtSecret);
875
+ const decoded = await verifyJwtToken(raw, config.jwtSecret, {
876
+ previousSecrets: config.jwtPreviousSecrets,
877
+ issuer: config.jwtIssuer,
878
+ audience: config.jwtAudience
879
+ });
859
880
  const isSession = decoded.isValid && isAccessToken(decoded);
860
881
  return {
861
882
  token: decoded,
@@ -42,6 +42,20 @@ function authReducer(state, action) {
42
42
  function isSessionExpiredError(error) {
43
43
  return clientErrorStatus(error) === 401;
44
44
  }
45
+ function useRevalidationLoop(revalidate, interval) {
46
+ const period = interval >= 0 && interval <= 2147483647 ? interval : DEFAULT_REVALIDATE_INTERVAL_MS;
47
+ react.useEffect(() => {
48
+ if (period <= 0) {
49
+ return void 0;
50
+ }
51
+ const handle = setInterval(() => {
52
+ void revalidate(false);
53
+ }, period);
54
+ return () => {
55
+ clearInterval(handle);
56
+ };
57
+ }, [revalidate, period]);
58
+ }
45
59
  function AuthProvider({
46
60
  children,
47
61
  client,
@@ -96,7 +110,7 @@ function AuthProvider({
96
110
  syncedDispatch({ type: "CLEAR_SESSION" });
97
111
  return;
98
112
  }
99
- syncedDispatch({ type: "SET_ERROR" });
113
+ if (!wasAuthenticated || isFinalAnswer(error)) syncedDispatch({ type: "SET_ERROR" });
100
114
  }
101
115
  },
102
116
  [syncedDispatch]
@@ -107,17 +121,7 @@ function AuthProvider({
107
121
  sessionGenerationRef.current = {};
108
122
  };
109
123
  }, [revalidate]);
110
- react.useEffect(() => {
111
- if (revalidateInterval <= 0) {
112
- return void 0;
113
- }
114
- const handle = setInterval(() => {
115
- void revalidate(false);
116
- }, revalidateInterval);
117
- return () => {
118
- clearInterval(handle);
119
- };
120
- }, [revalidate, revalidateInterval]);
124
+ useRevalidationLoop(revalidate, revalidateInterval);
121
125
  const login = react.useCallback(
122
126
  async (email, password, options) => {
123
127
  syncedDispatch({ type: "SET_LOADING" });
@@ -44,6 +44,9 @@ interface AuthProviderProps {
44
44
  * Interval (in milliseconds) between automatic revalidations.
45
45
  * Default: {@link DEFAULT_REVALIDATE_INTERVAL_MS} (5 minutes).
46
46
  *
47
+ * A value that is not a number from `0` to `2147483647` (the largest delay a timer honors, so
48
+ * `NaN` and `Infinity` too) is read as the default, never as a 1 ms loop.
49
+ *
47
50
  * Set to `0` to disable the loop entirely — useful for short-lived
48
51
  * flows (sign-up wizards, kiosk screens) where the overhead of a
49
52
  * background poll is not worth the freshness guarantee.
@@ -44,6 +44,9 @@ interface AuthProviderProps {
44
44
  * Interval (in milliseconds) between automatic revalidations.
45
45
  * Default: {@link DEFAULT_REVALIDATE_INTERVAL_MS} (5 minutes).
46
46
  *
47
+ * A value that is not a number from `0` to `2147483647` (the largest delay a timer honors, so
48
+ * `NaN` and `Infinity` too) is read as the default, never as a 1 ms loop.
49
+ *
47
50
  * Set to `0` to disable the loop entirely — useful for short-lived
48
51
  * flows (sign-up wizards, kiosk screens) where the overhead of a
49
52
  * background poll is not worth the freshness guarantee.
@@ -40,6 +40,20 @@ function authReducer(state, action) {
40
40
  function isSessionExpiredError(error) {
41
41
  return clientErrorStatus(error) === 401;
42
42
  }
43
+ function useRevalidationLoop(revalidate, interval) {
44
+ const period = interval >= 0 && interval <= 2147483647 ? interval : DEFAULT_REVALIDATE_INTERVAL_MS;
45
+ useEffect(() => {
46
+ if (period <= 0) {
47
+ return void 0;
48
+ }
49
+ const handle = setInterval(() => {
50
+ void revalidate(false);
51
+ }, period);
52
+ return () => {
53
+ clearInterval(handle);
54
+ };
55
+ }, [revalidate, period]);
56
+ }
43
57
  function AuthProvider({
44
58
  children,
45
59
  client,
@@ -94,7 +108,7 @@ function AuthProvider({
94
108
  syncedDispatch({ type: "CLEAR_SESSION" });
95
109
  return;
96
110
  }
97
- syncedDispatch({ type: "SET_ERROR" });
111
+ if (!wasAuthenticated || isFinalAnswer(error)) syncedDispatch({ type: "SET_ERROR" });
98
112
  }
99
113
  },
100
114
  [syncedDispatch]
@@ -105,17 +119,7 @@ function AuthProvider({
105
119
  sessionGenerationRef.current = {};
106
120
  };
107
121
  }, [revalidate]);
108
- useEffect(() => {
109
- if (revalidateInterval <= 0) {
110
- return void 0;
111
- }
112
- const handle = setInterval(() => {
113
- void revalidate(false);
114
- }, revalidateInterval);
115
- return () => {
116
- clearInterval(handle);
117
- };
118
- }, [revalidate, revalidateInterval]);
122
+ useRevalidationLoop(revalidate, revalidateInterval);
119
123
  const login = useCallback(
120
124
  async (email, password, options) => {
121
125
  syncedDispatch({ type: "SET_LOADING" });