@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.
package/README.md CHANGED
@@ -14,7 +14,7 @@
14
14
  <a href="https://www.npmjs.com/package/@bymax-one/nest-auth"><img src="https://img.shields.io/npm/dm/@bymax-one/nest-auth?style=flat-square&colorA=000000&colorB=000000" alt="npm downloads" /></a>
15
15
  <a href="https://github.com/bymaxone/nest-auth/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/bymaxone/nest-auth/ci.yml?branch=main&style=flat-square&colorA=000000&label=CI" alt="CI status" /></a>
16
16
  <a href="https://github.com/bymaxone/nest-auth/actions/workflows/ci.yml"><img src="https://img.shields.io/badge/coverage-100%25-brightgreen?style=flat-square&colorA=000000" alt="coverage" /></a>
17
- <a href="https://github.com/bymaxone/nest-auth/blob/main/docs/mutation_testing_results.md"><img src="https://img.shields.io/badge/mutation-99.10%25-brightgreen?style=flat-square&colorA=000000" alt="mutation score" /></a>
17
+ <a href="https://github.com/bymaxone/nest-auth/blob/main/docs/mutation_testing_results.md"><img src="https://img.shields.io/badge/mutation-100%25-brightgreen?style=flat-square&colorA=000000" alt="mutation score" /></a>
18
18
  <a href="https://scorecard.dev/viewer/?uri=github.com/bymaxone/nest-auth"><img src="https://api.scorecard.dev/projects/github.com/bymaxone/nest-auth/badge?style=flat-square" alt="OpenSSF Scorecard" /></a>
19
19
  <a href="https://github.com/bymaxone/nest-auth/blob/main/LICENSE"><img src="https://img.shields.io/github/license/bymaxone/nest-auth?style=flat-square&colorA=000000&colorB=000000" alt="license" /></a>
20
20
  <a href="https://www.typescriptlang.org/"><img src="https://img.shields.io/badge/TypeScript-strict-3178C6?style=flat-square&logo=typescript&logoColor=white" alt="TypeScript" /></a>
@@ -70,6 +70,12 @@ pnpm add @bymax-one/nest-auth
70
70
  - ✅ **HttpOnly Cookies** — Secure, SameSite, path-scoped refresh tokens by default
71
71
  - ✅ **Timing-Safe Comparisons** — All secret comparisons use `crypto.timingSafeEqual`
72
72
  - ✅ **JWT Revocation** — Instant access token revocation via Redis JTI blacklist
73
+ - ✅ **Refresh-Token Reuse Detection** — Replaying a consumed token revokes that login's whole lineage, and only that lineage
74
+ - ✅ **Bulk Access-Token Revocation** — A password reset advances a per-user token epoch, invalidating every outstanding access token in one write
75
+ - ✅ **Absolute Session Lifetime** — Optional hard cap on how long one login can be extended by rotation
76
+ - ✅ **Cross-Site Request Refusal** — Cookie-authenticated writes from an untrusted origin are rejected (matters under `SameSite=None`)
77
+ - ✅ **Breached-Password Refusal** — Optional Have I Been Pwned check by k-anonymity range; the password never leaves the process
78
+ - ✅ **Per-IP Rate Limiting** — Enforced by the library over Redis, so the limit holds across instances with no host wiring
73
79
 
74
80
  ### 🏢 Multi-Tenant & Platform
75
81
 
@@ -141,9 +147,15 @@ pnpm add @nestjs/common @nestjs/core @nestjs/jwt @nestjs/throttler @nestjs/webso
141
147
  pnpm add react
142
148
 
143
149
  # Next.js subpath (optional)
144
- pnpm add next react
150
+ pnpm add next react server-only
145
151
  ```
146
152
 
153
+ > [!NOTE]
154
+ > `server-only` is what makes importing the Next.js JWT helper from a Client Component a
155
+ > **build error**. That module receives the HS256 secret, and a secret in a client chunk is a
156
+ > secret published to every visitor — with nothing downstream to notice. It is a marker package
157
+ > with no runtime behaviour, and Next.js's own documentation prescribes it for exactly this.
158
+
147
159
  > [!IMPORTANT]
148
160
  > Requires `@nestjs/throttler >= 6.0.0` for `AUTH_THROTTLE_CONFIGS` decorators to be honored.
149
161
 
@@ -220,6 +232,10 @@ export class PrismaUserRepository implements IUserRepository {
220
232
  await this.prisma.user.update({ where: { id }, data: { emailVerified: verified } })
221
233
  }
222
234
 
235
+ async updateEmail(id: string, email: string): Promise<void> {
236
+ await this.prisma.user.update({ where: { id }, data: { email: email.toLowerCase() } })
237
+ }
238
+
223
239
  async findByOAuthId(
224
240
  provider: string,
225
241
  providerId: string,
@@ -270,7 +286,8 @@ import type { IEmailProvider, InviteData, SessionInfo } from '@bymax-one/nest-au
270
286
  import { Resend } from 'resend'
271
287
 
272
288
  const escapeHtml = (s: string): string =>
273
- s.replace(/&/g, '&amp;')
289
+ s
290
+ .replace(/&/g, '&amp;')
274
291
  .replace(/</g, '&lt;')
275
292
  .replace(/>/g, '&gt;')
276
293
  .replace(/"/g, '&quot;')
@@ -348,11 +365,7 @@ export class ResendEmailProvider implements IEmailProvider {
348
365
  })
349
366
  }
350
367
 
351
- async sendInvitation(
352
- email: string,
353
- inviteData: InviteData,
354
- _locale?: string
355
- ): Promise<void> {
368
+ async sendInvitation(email: string, inviteData: InviteData, _locale?: string): Promise<void> {
356
369
  const url = `${this.appUrl}/accept-invite?token=${encodeURIComponent(inviteData.inviteToken)}`
357
370
  await this.client.emails.send({
358
371
  from: this.from,
@@ -374,9 +387,7 @@ Wire it via `extraProviders` alongside the user repository:
374
387
  ```typescript
375
388
  import { BYMAX_AUTH_EMAIL_PROVIDER } from '@bymax-one/nest-auth'
376
389
 
377
- extraProviders: [
378
- { provide: BYMAX_AUTH_EMAIL_PROVIDER, useClass: ResendEmailProvider }
379
- ]
390
+ extraProviders: [{ provide: BYMAX_AUTH_EMAIL_PROVIDER, useClass: ResendEmailProvider }]
380
391
  ```
381
392
 
382
393
  ### 4. Register the Module
@@ -403,6 +414,10 @@ import {
403
414
  refreshExpiresInDays: 7
404
415
  },
405
416
  tokenDelivery: 'cookie', // 'cookie' | 'bearer' | 'both'
417
+ // Required while the limiter is on, and neither value can be a default:
418
+ // 'peer' behind a proxy reads the proxy's address for every request, and
419
+ // 'trusted-proxy' without one trusts a header the client can forge.
420
+ rateLimit: { clientIpSource: 'trusted-proxy' }, // 'peer' | 'trusted-proxy'
406
421
  roles: {
407
422
  hierarchy: {
408
423
  admin: ['manager', 'user'],
@@ -434,13 +449,11 @@ export class AppModule {}
434
449
  ```typescript
435
450
  // users.controller.ts
436
451
  import { Controller, Get, UseGuards } from '@nestjs/common'
437
- import {
438
- JwtAuthGuard,
439
- RolesGuard,
440
- Roles,
441
- CurrentUser,
442
- DashboardJwtPayload
443
- } from '@bymax-one/nest-auth'
452
+ import { JwtAuthGuard, RolesGuard, Roles, CurrentUser } from '@bymax-one/nest-auth'
453
+ // `import type` is required for a type used in a decorated signature: with
454
+ // `emitDecoratorMetadata` and `isolatedModules`, a value import would be emitted
455
+ // into the metadata and fail to erase (TS1272).
456
+ import type { DashboardJwtPayload } from '@bymax-one/nest-auth'
444
457
 
445
458
  @Controller('users')
446
459
  @UseGuards(JwtAuthGuard, RolesGuard)
@@ -471,8 +484,10 @@ import { AuthProvider } from '@bymax-one/nest-auth/react'
471
484
  import { createAuthClient } from '@bymax-one/nest-auth/client'
472
485
 
473
486
  const authClient = createAuthClient({
474
- // Same-origin calls go through the Next.js proxy routes under
475
- // `/api/auth/*`. Set `baseUrl` only when calling a cross-origin API.
487
+ // Same-origin: a relative base sends every call through the Next.js
488
+ // proxy routes — `'/api'` plus the default `routePrefix` composes
489
+ // `/api/auth/*`. Use an absolute origin for a cross-origin API.
490
+ baseUrl: '/api'
476
491
  })
477
492
 
478
493
  export function Providers({ children }: { children: React.ReactNode }) {
@@ -494,7 +509,9 @@ export function Profile() {
494
509
  const { logout } = useAuth()
495
510
 
496
511
  if (status === 'loading') return <div>Loading…</div>
497
- if (status === 'unauthenticated') return <div>Please log in</div>
512
+ // `status` and `user` are separate fields, so the status check alone does
513
+ // not narrow `user` away from null — test the one you are about to read.
514
+ if (!user) return <div>Please log in</div>
498
515
 
499
516
  return (
500
517
  <div>
@@ -527,7 +544,7 @@ export const { proxy } = createAuthProxy({
527
544
  loginPath: '/auth/login',
528
545
  getDefaultDashboard: (role) => (role === 'admin' ? '/dashboard/admin' : '/dashboard'),
529
546
  apiBase: process.env.API_BASE_URL!,
530
- jwtSecret: process.env.JWT_SECRET,
547
+ jwtSecret: process.env.JWT_SECRET!,
531
548
  cookieNames: {
532
549
  access: 'access_token',
533
550
  refresh: 'refresh_token',
@@ -587,29 +604,155 @@ export const POST = createLogoutHandler({
587
604
 
588
605
  ---
589
606
 
607
+ ### WebSocket upgrades
608
+
609
+ The browser `WebSocket` API cannot set handshake headers, so a browser client cannot send
610
+ `Authorization: Bearer <token>` at the upgrade. The usual workaround puts the access token in the
611
+ query string, where it lands in access logs, browser history and proxy caches — a long-lived
612
+ credential in plaintext. `WsJwtGuard` refuses it.
613
+
614
+ The supported path is a single-use ticket:
615
+
616
+ ```typescript
617
+ // 1. Mint from an authenticated session (POST, cookies or bearer as usual).
618
+ const { ticket, expiresIn } = await fetch('/auth/ws-ticket', {
619
+ method: 'POST',
620
+ credentials: 'include'
621
+ }).then((r) => r.json())
622
+
623
+ // 2. Open the socket with it. The ticket is consumed by the first redemption.
624
+ const socket = new WebSocket(`wss://api.example.com/socket?ticket=${ticket}`)
625
+ ```
626
+
627
+ The ticket is opaque, 32 bytes of CSPRNG output, and lives 30 seconds. Only `sha256(ticket)` is
628
+ ever a Redis key, and the stored value is a verified-identity **snapshot** — no `jti`, no
629
+ signature, no expiry of its own — so a redeemed ticket authorizes a socket and cannot be turned
630
+ back into a session. Minting requires an authenticated session in good standing that has already
631
+ satisfied MFA, so a ticket never carries more authority than the request that asked for it.
632
+
633
+ Non-browser clients that can set headers keep using `Authorization: Bearer` at the handshake;
634
+ both channels are accepted, and a ticket wins when both are present.
635
+
636
+ ---
637
+
590
638
  ## ⚙️ Configuration
591
639
 
592
640
  All options are configurable via `registerAsync()`. Here are the key configuration groups:
593
641
 
594
- | Group | Key Options | Default |
595
- | ----------------- | --------------------------------------------------------------------------- | ------------------------- |
596
- | **jwt** | `secret` (required), `accessExpiresIn`, `refreshExpiresInDays`, `algorithm` | `15m`, `7d`, `HS256` |
597
- | **password** | `costFactor`, `blockSize`, `parallelization` | scrypt N=2¹⁵, r=8, p=1 |
598
- | **tokenDelivery** | `'cookie'` \| `'bearer'` \| `'both'` | `'cookie'` |
599
- | **cookies** | `accessTokenName`, `refreshTokenName`, `sessionSignalName`, `refreshCookiePath`, `resolveDomains` | — (see cookie section) |
600
- | **mfa** | `encryptionKey`, `issuer`, `totpWindow`, `recoveryCodeCount` | — |
601
- | **sessions** | `enabled`, `defaultMaxSessions`, `maxSessionsResolver`, `evictionStrategy` | `false`, `5`, —, `'fifo'` |
602
- | **bruteForce** | `maxAttempts`, `windowSeconds` | `5`, `900` |
603
- | **passwordReset** | `method` (`'token'` \| `'otp'`), `otpLength`, `otpTtlSeconds` | `'token'` |
604
- | **platform** | `enabled` | `false` |
605
- | **invitations** | `enabled`, `tokenTtlSeconds` | `false` |
606
- | **roles** | `hierarchy` (required), `platformHierarchy` | — |
607
- | **oauth** | `google: { clientId, clientSecret, callbackUrl }` | — |
608
- | **controllers** | Toggle individual controllers on/off | All enabled |
642
+ | Group | Key Options | Default |
643
+ | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- |
644
+ | **jwt** | `secret` (required), `previousSecrets`, `accessExpiresIn`, `refreshExpiresInDays`, `absoluteSessionLifetimeDays`, `algorithm`, `issuer`, `audience` | `15m`, `7d`, off, `HS256`, both off |
645
+ | **password** | `costFactor`, `blockSize`, `parallelization` | scrypt N=2¹⁷, r=8, p=1 |
646
+ | **tokenDelivery** | `'cookie'` \| `'bearer'` \| `'both'` | `'cookie'` |
647
+ | **cookies** | `accessTokenName`, `refreshTokenName`, `sessionSignalName`, `refreshCookiePath`, `sameSite`, `trustedOrigins`, `resolveDomains` | `'lax'`, `[]` (see cookie section) |
648
+ | **mfa** | `encryptionKey`, `previousEncryptionKeys`, `issuer`, `totpWindow`, `recoveryCodeCount` | — |
649
+ | **sessions** | `enabled`, `defaultMaxSessions`, `maxSessionsResolver` | `false`, `5`, — |
650
+ | **bruteForce** | `maxAttempts`, `windowSeconds` | `5`, `900` |
651
+ | **rateLimit** | `enabled`, `clientIpSource` (`'peer'` \| `'trusted-proxy'`) — per-IP limits over Redis | `true`, **required** |
652
+ | **passwordReset** | `method` (`'token'` \| `'otp'`), `otpLength`, `otpTtlSeconds` | `'token'` |
653
+ | **platform** | `enabled` | `false` |
654
+ | **invitations** | `enabled`, `tokenTtlSeconds` | `false` |
655
+ | **roles** | `hierarchy` (required), `platformHierarchy` | — |
656
+ | **oauth** | `google: { clientId, clientSecret, callbackUrl }` | — |
657
+ | **emailVerification** | `required`, `otpTtlSeconds` | `true`, `600` |
658
+ | **password** (screen) | `blocklist` — extra words the default screen refuses, on top of the ones it ships | `[]` |
659
+ | **controllers** | Toggle individual controllers on/off | `auth`, `passwordReset` on; rest opt-in |
609
660
 
610
661
  > [!NOTE]
611
662
  > When a feature is not configured (e.g., `mfa`, `sessions`, `platform`), its controllers and services are **not registered** in the NestJS container — zero overhead.
612
663
 
664
+ > [!IMPORTANT]
665
+ > **`rateLimit.clientIpSource` is required** whenever rate limiting is enabled — there is no
666
+ > default. The option group is a discriminated union, so TypeScript refuses the omission at
667
+ > compile time; the module also refuses to start without it, because the type binds TypeScript
668
+ > and nothing else. Set `'peer'` when the application is
669
+ > directly exposed: the limit keys on the socket address, read from the connection and never
670
+ > from a forwarding header. Set `'trusted-proxy'` when it runs behind a proxy and `trust proxy`
671
+ > is configured for the real hop count: the limit keys on `req.ip`, the forwarded client
672
+ > address. Neither can be the default, because each is a working limiter in one deployment and
673
+ > no limiter at all in the other — `'peer'` behind a proxy puts every client in **one** bucket,
674
+ > so a single caller can rate-limit your whole user base with no credential, and
675
+ > `'trusted-proxy'` without a proxy lets the caller choose their own key. Both look like a
676
+ > working limiter at runtime. Pass `rateLimit.enabled: false` if the limits are enforced at the
677
+ > edge instead.
678
+
679
+ > [!TIP]
680
+ > **Binding tokens to an issuer and an audience.** `jwt.issuer` and `jwt.audience` are off by
681
+ > default. Set either and its value is stamped on every token this backend mints and **required**
682
+ > on every token it verifies — one carrying a different value, or none at all, is rejected.
683
+ > That matters with HS256, where the verifier can also sign: every service holding the secret to
684
+ > check a token can mint one, so audience binding is what stops a token minted for one service
685
+ > being replayed at another that trusts the same secret.
686
+ >
687
+ > Two things to know before switching it on. Both backends of a shared deployment must carry the
688
+ > same pair, or they stop accepting each other's tokens. And enabling it invalidates the access
689
+ > tokens already in flight, since those were minted without the claims — a window of one
690
+ > access-token lifetime, which clients close by refreshing. An empty string reads as unconfigured
691
+ > rather than as "require the empty issuer", so an unset environment variable cannot turn the
692
+ > check on by accident.
693
+
694
+ > **Rotating the signing secret.** `jwt.previousSecrets` lists secrets retired by a rotation,
695
+ > accepted for verification only. Without it, changing `jwt.secret` signs every user out the
696
+ > moment the new configuration rolls out **and** invalidates every stored recovery-code digest —
697
+ > those are keyed by an HMAC derived from the secret, so users lose the codes they printed and
698
+ > filed. With it, both keep working while tokens issued under the old secret drain, and a
699
+ > rotation becomes a rollout. Remove the entry once the longest-lived token signed under it has
700
+ > expired: every entry is a key that still opens the door. `mfa.encryptionKey` rotates the same
701
+ > way, through its own list — see below.
702
+
703
+ > [!TIP]
704
+ > **Rotating the MFA encryption key.** `mfa.previousEncryptionKeys` lists AES-256 keys retired by
705
+ > a rotation of `mfa.encryptionKey`. The stored ciphertext carries no key identifier, so without
706
+ > the list a change of key makes every enrolled user's TOTP secret undecryptable at once, with no
707
+ > way back — their authenticator simply stops matching. With it, a stored secret that opened
708
+ > under a retired key is **re-encrypted under the current one** on the next successful challenge,
709
+ > so the rotation drains on its own instead of requiring the retired key to stay configured
710
+ > forever. Each entry is validated at startup exactly like the current key (base64, exactly 32
711
+ > bytes, and never equal to the current key or to another entry), because a malformed one would
712
+ > otherwise surface at a user's first challenge rather than at boot. Drop the entry once your
713
+ > enrolled users have had time to authenticate at least once.
714
+
715
+ > [!IMPORTANT]
716
+ > **The parameters that carry a control's strength are bounded at startup.** `mfa.totpWindow`
717
+ > must be `0..=10`: the window counts 30-second steps on _either_ side of now, so `2n + 1`
718
+ > codes are valid at once — three at the default of 1, but 121 at 60, which makes a six-digit
719
+ > code a hundred times easier to guess while the configuration still reads as "MFA enabled".
720
+ > `mfa.recoveryCodeCount` must be `1..=50`, because zero enrols an account with no way back
721
+ > if the authenticator is lost. `password.blockSize` must be at least 8 and
722
+ > `password.parallelization` at least 1: scrypt's memory cost is `128 * N * r`, so a smaller
723
+ > block size divides the hardness that `password.costFactor`'s floor exists to guarantee —
724
+ > invisibly, since the bounded parameter is still intact. `rust-auth` enforces the identical
725
+ > ranges.
726
+
727
+ > [!IMPORTANT]
728
+ > `jwt.accessExpiresIn` must not exceed **30 days**, the window the store keeps a bumped token
729
+ > epoch readable. The epoch is what makes a stateless access token revocable: a password reset
730
+ > advances it and every token stamped below it stops verifying — but only while the bumped value
731
+ > is still there. A longer-lived access token would outlive it, the lookup would fall back to
732
+ > `0`, and a token the reset revoked would verify again. Startup refuses the configuration
733
+ > rather than letting it fail open, and rejects an unreadable time span or a non-positive
734
+ > lifetime on the same pass.
735
+
736
+ Two options are deliberately off by default because switching them on changes behaviour for
737
+ sessions and origins that already exist:
738
+
739
+ - `jwt.absoluteSessionLifetimeDays` caps how long one login can be extended by rotation. Without
740
+ it, a client refreshing every fifteen minutes keeps a session alive forever.
741
+ - `cookies.trustedOrigins` is required as soon as `cookies.sameSite: 'none'` is set, and refused
742
+ otherwise — that posture is the only one where the browser sends the session cookie
743
+ cross-site, and it is the only one where the origin check has anything to authorize.
744
+
745
+ The breach check is opt-in for a different reason: it is the only part of the credential path
746
+ that reaches the network, and a library should not start talking to a third party because it was
747
+ upgraded. Wire it explicitly:
748
+
749
+ ```typescript
750
+ BymaxAuthModule.registerAsync({
751
+ useFactory: () => ({ ... }),
752
+ extraProviders: [{ provide: BYMAX_AUTH_BREACH_CHECKER, useClass: HibpBreachChecker }]
753
+ })
754
+ ```
755
+
613
756
  ---
614
757
 
615
758
  ## 🏗️ Architecture
@@ -638,13 +781,13 @@ The package runs **inside** your NestJS application as a dynamic module — not
638
781
 
639
782
  ### Design Principles
640
783
 
641
- | Principle | Description |
642
- | -------------------------- | ------------------------------------------------------------------------------------------------------- |
643
- | **🔌 Interface-Driven** | Define contracts, inject implementations — works with Prisma, TypeORM, Drizzle, or any SQL ORM |
644
- | **🔒 Secure by Default** | scrypt hashing, HttpOnly cookies, JWT blacklisting, brute-force protection — all enabled out of the box |
784
+ | Principle | Description |
785
+ | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
786
+ | **🔌 Interface-Driven** | Define contracts, inject implementations — works with Prisma, TypeORM, Drizzle, or any SQL ORM |
787
+ | **🔒 Secure by Default** | scrypt hashing, HttpOnly cookies, JWT blacklisting, brute-force protection — all enabled out of the box |
645
788
  | **🪶 Zero Runtime Deps** | `"dependencies": {}` — adds no runtime deps of its own; crypto is native `node:crypto`. Required peers (NestJS, ioredis…) come from your app |
646
- | **🌳 Tree-Shakeable** | `sideEffects: false`, subpath exports, ESM + CJS dual output |
647
- | **⚡ Conditional Loading** | Unconfigured features don't register — no wasted memory or startup time |
789
+ | **🌳 Tree-Shakeable** | `sideEffects: false`, subpath exports, ESM + CJS dual output |
790
+ | **⚡ Conditional Loading** | Unconfigured features don't register — no wasted memory or startup time |
648
791
 
649
792
  ---
650
793
 
@@ -699,17 +842,22 @@ When integrating `@bymax-one/nest-auth` in production, verify each of the follow
699
842
 
700
843
  ## 🛡️ Security Table
701
844
 
702
- | Layer | Implementation |
703
- | ----------------- | -------------------------------------------------- |
704
- | Password Hashing | `node:crypto` scrypt (N=2¹⁵, r=8, p=1, keyLen=64) |
705
- | MFA Encryption | AES-256-GCM with 12-byte random IV per call |
706
- | TOTP | HMAC-SHA1 per RFC 4226/6238, ±1 step window |
707
- | Token Generation | `crypto.randomBytes(32)` — 256 bits of entropy |
708
- | Secret Comparison | `crypto.timingSafeEqual` (constant-time) |
709
- | JWT | HS256 via `@nestjs/jwt`, JTI blacklist via Redis |
710
- | Cookies | HttpOnly, Secure, SameSite=Strict, path-scoped |
711
- | Brute-Force | Redis atomic counters per HMAC(email, jwt.secret) |
712
- | CSRF (OAuth) | 64-char hex state nonce, single-use via `getdel()` |
845
+ | Layer | Implementation |
846
+ | ------------------ | ------------------------------------------------------------------------------------------------------ |
847
+ | Password Hashing | `node:crypto` scrypt (N=2¹⁷, r=8, p=1, keyLen=64) — OWASP's recommended minimum |
848
+ | MFA Encryption | AES-256-GCM with 12-byte random IV per call |
849
+ | TOTP | HMAC-SHA1 per RFC 4226/6238, ±1 step window |
850
+ | Token Generation | `crypto.randomBytes(32)` — 256 bits of entropy |
851
+ | Secret Comparison | `crypto.timingSafeEqual` (constant-time) |
852
+ | JWT | HS256 via `@nestjs/jwt`, JTI blacklist via Redis |
853
+ | Cookies | HttpOnly, Secure, SameSite=Strict, path-scoped |
854
+ | Brute-Force | Redis atomic counters per HMAC(email, jwt.secret) |
855
+ | CSRF (OAuth) | 64-char hex state nonce, single-use via `getdel()` |
856
+ | Refresh Rotation | Single-use tokens with a grace window; a replay past it revokes that login's whole family lineage |
857
+ | Cross-Site Writes | `Origin` / `Sec-Fetch-Site` check on cookie-authenticated writes — the gap `SameSite=None` leaves open |
858
+ | Breached Passwords | Optional Have I Been Pwned range check by k-anonymity; only a 5-char SHA-1 prefix leaves the process |
859
+ | Rate Limiting | Per-IP fixed-window counters in Redis, keyed by `HMAC(ip)` — enforced by the library, not by the host |
860
+ | Session Lifetime | Optional absolute cap on how long one login can be extended by rotation |
713
861
 
714
862
  > [!IMPORTANT]
715
863
  > This package uses **zero external cryptographic dependencies**. All operations use Node.js native `node:crypto`, eliminating supply chain attack vectors for critical security code.
@@ -735,9 +883,9 @@ When integrating `@bymax-one/nest-auth` in production, verify each of the follow
735
883
  Authentication is critical infrastructure, so the suite is held to a bar beyond "it runs" — every behavior is pinned so that a regression **fails a test**.
736
884
 
737
885
  - ✅ **100% line coverage** — statements, branches, functions, and lines, enforced as a release gate across unit + e2e
738
- - ✅ **99.10% mutation score** — verified with [Stryker](https://stryker-mutator.io/): thousands of small faults are seeded into the source and the suite must catch them
739
- - ✅ **1,980 tests** — unit and end-to-end, spanning all five subpaths
740
- - ✅ **Security paths at 100% mutation** — `crypto/` and `guards/` are fully killed; refresh-cookie `HttpOnly`, session-hash validation, TOTP zero-padding, and response-splitting defenses are each pinned by a dedicated test
886
+ - ✅ **100% mutation score** — verified with [Stryker](https://stryker-mutator.io/): 3,474 seeded faults killed, **no survivors and nothing left uncovered**, against a `break` threshold of 95
887
+ - ✅ **2,458 tests** — unit and end-to-end, spanning all five subpaths
888
+ - ✅ **Every equivalent mutant documented** — the handful that no test can kill (a redundant guard, a dependency array of stable references) carries an inline `// Stryker disable` with the reason it cannot be killed, so the score is an accounting rather than a number
741
889
 
742
890
  ```bash
743
891
  pnpm test # unit suite
@@ -756,36 +904,46 @@ pnpm mutation # Stryker mutation testing
756
904
 
757
905
  Conditionally registered controllers (mfa, sessions, platform, invitations, oauth, password-reset) only mount their endpoints when the corresponding feature is enabled in `BymaxAuthModule.registerAsync()`.
758
906
 
759
- | Method | Path | Auth / Guard | Description |
760
- | ------ | ----------------------------- | ------------------------------------------- | ---------------------------------------------------------- |
761
- | POST | `/register` | Public | Register a new dashboard user and issue tokens |
762
- | POST | `/login` | Public | Authenticate with email/password (may return MFA challenge) |
763
- | POST | `/logout` | `JwtAuthGuard` | Revoke tokens and clear session |
764
- | POST | `/refresh` | Public (refresh cookie) | Rotate refresh token, issue new access token |
765
- | GET | `/me` | `JwtAuthGuard` | Current dashboard user payload |
766
- | POST | `/verify-email` | Public | Verify email with OTP |
767
- | POST | `/resend-verification` | Public | Resend email-verification OTP |
768
- | POST | `/password/forgot-password` | Public | Request password reset (token or OTP) |
769
- | POST | `/password/reset-password` | Public | Submit new password with reset token |
770
- | POST | `/password/verify-otp` | Public | Verify password-reset OTP |
771
- | POST | `/password/resend-otp` | Public | Resend password-reset OTP |
772
- | POST | `/mfa/setup` | `JwtAuthGuard` | Generate TOTP secret and recovery codes |
773
- | POST | `/mfa/verify-enable` | `JwtAuthGuard` | Confirm setup and enable MFA |
774
- | POST | `/mfa/challenge` | Public + `@SkipMfa()` | Submit TOTP/recovery code after login |
775
- | POST | `/mfa/disable` | `JwtAuthGuard` | Disable MFA for the current user |
776
- | GET | `/sessions` | `JwtAuthGuard`, `UserStatusGuard` | List active sessions for the current user |
777
- | DELETE | `/sessions/all` | `JwtAuthGuard`, `UserStatusGuard` | Revoke all sessions |
778
- | DELETE | `/sessions/:id` | `JwtAuthGuard`, `UserStatusGuard` | Revoke a specific session |
779
- | POST | `/invitations` | `JwtAuthGuard` | Create a tenant invitation |
780
- | POST | `/invitations/accept` | Public | Accept an invitation and create the user |
781
- | POST | `/platform/login` | Public | Platform admin login (separate token context) |
782
- | POST | `/platform/mfa/challenge` | Public | Platform admin MFA challenge |
783
- | GET | `/platform/me` | `JwtPlatformGuard` | Current platform admin payload |
784
- | POST | `/platform/logout` | `JwtPlatformGuard` | Revoke platform tokens |
785
- | POST | `/platform/refresh` | Public (platform refresh cookie) | Rotate platform refresh token |
786
- | DELETE | `/platform/sessions` | `JwtPlatformGuard` | Revoke all platform sessions |
787
- | GET | `/oauth/:provider` | Public + `@SkipMfa()` | Initiate OAuth authorization redirect |
788
- | GET | `/oauth/:provider/callback` | Public + `@SkipMfa()` | Handle OAuth callback, exchange code, issue tokens |
907
+ | Method | Path | Auth / Guard | Description |
908
+ | ------ | --------------------------- | ---------------------------------- | ----------------------------------------------------------- |
909
+ | POST | `/register` | Public | Register a new dashboard user and issue tokens |
910
+ | POST | `/login` | Public | Authenticate with email/password (may return MFA challenge) |
911
+ | POST | `/logout` | `JwtAuthGuard` | Revoke tokens and clear session |
912
+ | POST | `/refresh` | Public (refresh cookie) | Rotate refresh token, issue new access token |
913
+ | GET | `/me` | `JwtAuthGuard` | Current dashboard user payload |
914
+ | POST | `/verify-email` | Public | Verify email with OTP |
915
+ | POST | `/resend-verification` | Public | Resend email-verification OTP |
916
+ | POST | `/password/forgot-password` | Public | Request password reset (token or OTP) |
917
+ | POST | `/password/reset-password` | Public | Submit new password with reset token |
918
+ | POST | `/password/verify-otp` | Public | Verify password-reset OTP |
919
+ | POST | `/password/resend-otp` | Public | Resend password-reset OTP |
920
+ | POST | `/mfa/setup` | `JwtAuthGuard` | Generate TOTP secret and recovery codes |
921
+ | POST | `/mfa/verify-enable` | `JwtAuthGuard` | Confirm setup and enable MFA |
922
+ | POST | `/mfa/challenge` | Public + `@SkipMfa()` | Submit TOTP/recovery code after login |
923
+ | POST | `/mfa/disable` | `JwtAuthGuard` | Disable MFA for the current user |
924
+ | GET | `/sessions` | `JwtAuthGuard`, `UserStatusGuard` | List active sessions for the current user |
925
+ | DELETE | `/sessions/all` | `JwtAuthGuard`, `UserStatusGuard` | Revoke all sessions |
926
+ | DELETE | `/sessions/:id` | `JwtAuthGuard`, `UserStatusGuard` | Revoke a specific session |
927
+ | POST | `/invitations` | `JwtAuthGuard`, `UserStatusGuard` | Create a tenant invitation |
928
+ | POST | `/invitations/accept` | Public | Accept an invitation and create the user |
929
+ | POST | `/invitations/revoke` | `JwtAuthGuard`, `UserStatusGuard` | Withdraw a pending invitation |
930
+ | POST | `/email/change` | `JwtAuthGuard`, `UserStatusGuard` | Request an address change (re-proves the current password) |
931
+ | POST | `/email/change/confirm` | Public | Confirm it with the token mailed to the new address |
932
+ | POST | `/platform/login` | Public | Platform admin login (separate token context) |
933
+ | POST | `/platform/mfa/challenge` | Public | Platform admin MFA challenge |
934
+ | GET | `/platform/me` | `JwtPlatformGuard` | Current platform admin payload |
935
+ | POST | `/platform/logout` | `JwtPlatformGuard` | Revoke platform tokens |
936
+ | POST | `/platform/refresh` | Public (platform refresh cookie) | Rotate platform refresh token |
937
+ | DELETE | `/platform/sessions` | `JwtPlatformGuard` | Revoke all platform sessions |
938
+ | POST | `/password/change` | `JwtAuthGuard` + `UserStatusGuard` | Change the password, proving the current one |
939
+ | GET | `/oauth/:provider` | Public + `@SkipMfa()` | Initiate OAuth authorization redirect |
940
+ | GET | `/oauth/:provider/callback` | Public + `@SkipMfa()` | Handle OAuth callback, exchange code, issue tokens |
941
+
942
+ > **The OAuth routes require `cookie-parser`.** `GET /oauth/:provider` plants an HttpOnly
943
+ > `oauth_state` cookie carrying the flow's `state`, and the callback refuses any request that
944
+ > does not send it back — the binding RFC 6749 §10.12 requires, without which an attacker can
945
+ > hand a victim a callback URL and have the victim's browser complete the attacker's login.
946
+ > Mount `app.use(cookieParser())` before the module's routes or every callback answers 401.
789
947
 
790
948
  ### Server Guards
791
949
 
@@ -801,6 +959,30 @@ Conditionally registered controllers (mfa, sessions, platform, invitations, oaut
801
959
  > [!NOTE]
802
960
  > Three additional guards — `SelfOrAdminGuard` (ownership checks), `OptionalAuthGuard` (routes that behave differently for anonymous vs authenticated users), and `WsJwtGuard` (JWT authentication on WebSocket gateways) — are exported from the public `@bymax-one/nest-auth` barrel. Use them exactly like the core guards above.
803
961
 
962
+ ### One error envelope
963
+
964
+ Every failure the module raises answers with the same body, so a client parses `error.code` and
965
+ nothing else:
966
+
967
+ ```json
968
+ { "error": { "code": "auth.invalid_credentials", "message": "…", "details": null } }
969
+ ```
970
+
971
+ That includes malformed requests: the controllers mount `createAuthValidationPipe()`, which
972
+ answers `auth.validation` with the offending fields under `error.details` as
973
+ `[{ "field": "email", "message": "…" }]` rather than the framework's own shape.
974
+
975
+ Failures the module did **not** raise are the application's to answer, so nothing is imposed on
976
+ them by default. Register the optional filter to bring them into the same envelope:
977
+
978
+ ```typescript
979
+ app.useGlobalFilters(new AuthExceptionFilter())
980
+ ```
981
+
982
+ It passes an `AuthException` through untouched, keeps the status any other `HttpException`
983
+ chose, and answers an unhandled throw with `auth.internal` and a generic message — never the
984
+ thrown one.
985
+
804
986
  ### Server Decorators
805
987
 
806
988
  | Decorator | Usage |
@@ -830,26 +1012,6 @@ Conditionally registered controllers (mfa, sessions, platform, invitations, oaut
830
1012
 
831
1013
  ---
832
1014
 
833
- ## 🗺️ Roadmap
834
-
835
- The items below are on deck for future minor / major releases. None are shipping today — the list exists so contributors can see where the library is headed and where help is most useful. Open an issue if you'd like to discuss priorities or propose a design.
836
-
837
- | Area | Item | Status |
838
- | --------------------------- | ----------------------------------------------------------------------------------------------------------------------- | --------- |
839
- | OAuth providers | First-class `oauth.plugins` array so consumers can drop in GitHub / Microsoft / Apple plugins without forking the core | Planned |
840
- | Error-message i18n | `BymaxAuthModule.forRoot({ messages })` override for `AUTH_ERROR_MESSAGES` (defaults stay Portuguese; English preset) | Planned |
841
- | Refresh-token families | Family-level revocation: detect grace-window reuse as a stolen-token signal and invalidate the entire session family | Planned |
842
- | Passwordless / magic link | `MagicLinkService` + email-delivered single-use link, reusing the existing `generateSecureToken` + `IEmailProvider` API | Exploring |
843
- | Passkeys / WebAuthn | Optional WebAuthn primitive as an MFA method (and eventually a first-factor), behind a peer-dep-gated module | Exploring |
844
- | Per-tenant configuration | Per-tenant overrides for session limits, MFA enforcement, and password policy resolved at request time | Exploring |
845
- | Absolute session lifetime | Hard cap on refresh chains so a session rotated every 6 days does not live forever | Planned |
846
- | Pluggable password policy | `IPasswordPolicy` interface for disallow-lists, complexity classes, and per-tenant rules | Planned |
847
- | Custom token delivery modes | `ITokenDelivery` for non-cookie / non-bearer transports (custom headers, WebSocket handshakes, split client types) | Exploring |
848
-
849
- > Track progress and discuss proposals on the [issues board](https://github.com/bymaxone/nest-auth/issues).
850
-
851
- ---
852
-
853
1015
  ## 🤝 Contributing
854
1016
 
855
1017
  Contributions are welcome! Please read our contributing guidelines before submitting a pull request.
@@ -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;