@bymax-one/nest-auth 1.5.2 → 1.5.3

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.
@@ -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,