@bymax-one/nest-auth 1.0.10 → 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>
@@ -25,7 +25,8 @@
25
25
  <a href="https://github.com/bymaxone/nest-auth">GitHub</a> ·
26
26
  <a href="https://github.com/bymaxone/nest-auth/issues">Issues</a> ·
27
27
  <a href="#-quick-start">Quick Start</a> ·
28
- <a href="#-subpath-exports">API Reference</a>
28
+ <a href="#-subpath-exports">API Reference</a> ·
29
+ <a href="https://github.com/bymaxone/nest-auth-example">Example App</a>
29
30
  </p>
30
31
 
31
32
  ---
@@ -69,6 +70,12 @@ pnpm add @bymax-one/nest-auth
69
70
  - ✅ **HttpOnly Cookies** — Secure, SameSite, path-scoped refresh tokens by default
70
71
  - ✅ **Timing-Safe Comparisons** — All secret comparisons use `crypto.timingSafeEqual`
71
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
72
79
 
73
80
  ### 🏢 Multi-Tenant & Platform
74
81
 
@@ -111,6 +118,9 @@ server client
111
118
 
112
119
  ---
113
120
 
121
+ > [!TIP]
122
+ > Prefer to learn from a working app? See the [nest-auth-example](https://github.com/bymaxone/nest-auth-example) — a full NestJS + Next.js project wired with this library.
123
+
114
124
  ## 🚀 Quick Start
115
125
 
116
126
  ### 1. Install
@@ -137,9 +147,15 @@ pnpm add @nestjs/common @nestjs/core @nestjs/jwt @nestjs/throttler @nestjs/webso
137
147
  pnpm add react
138
148
 
139
149
  # Next.js subpath (optional)
140
- pnpm add next react
150
+ pnpm add next react server-only
141
151
  ```
142
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
+
143
159
  > [!IMPORTANT]
144
160
  > Requires `@nestjs/throttler >= 6.0.0` for `AUTH_THROTTLE_CONFIGS` decorators to be honored.
145
161
 
@@ -216,6 +232,10 @@ export class PrismaUserRepository implements IUserRepository {
216
232
  await this.prisma.user.update({ where: { id }, data: { emailVerified: verified } })
217
233
  }
218
234
 
235
+ async updateEmail(id: string, email: string): Promise<void> {
236
+ await this.prisma.user.update({ where: { id }, data: { email: email.toLowerCase() } })
237
+ }
238
+
219
239
  async findByOAuthId(
220
240
  provider: string,
221
241
  providerId: string,
@@ -266,7 +286,8 @@ import type { IEmailProvider, InviteData, SessionInfo } from '@bymax-one/nest-au
266
286
  import { Resend } from 'resend'
267
287
 
268
288
  const escapeHtml = (s: string): string =>
269
- s.replace(/&/g, '&amp;')
289
+ s
290
+ .replace(/&/g, '&amp;')
270
291
  .replace(/</g, '&lt;')
271
292
  .replace(/>/g, '&gt;')
272
293
  .replace(/"/g, '&quot;')
@@ -344,11 +365,7 @@ export class ResendEmailProvider implements IEmailProvider {
344
365
  })
345
366
  }
346
367
 
347
- async sendInvitation(
348
- email: string,
349
- inviteData: InviteData,
350
- _locale?: string
351
- ): Promise<void> {
368
+ async sendInvitation(email: string, inviteData: InviteData, _locale?: string): Promise<void> {
352
369
  const url = `${this.appUrl}/accept-invite?token=${encodeURIComponent(inviteData.inviteToken)}`
353
370
  await this.client.emails.send({
354
371
  from: this.from,
@@ -370,9 +387,7 @@ Wire it via `extraProviders` alongside the user repository:
370
387
  ```typescript
371
388
  import { BYMAX_AUTH_EMAIL_PROVIDER } from '@bymax-one/nest-auth'
372
389
 
373
- extraProviders: [
374
- { provide: BYMAX_AUTH_EMAIL_PROVIDER, useClass: ResendEmailProvider }
375
- ]
390
+ extraProviders: [{ provide: BYMAX_AUTH_EMAIL_PROVIDER, useClass: ResendEmailProvider }]
376
391
  ```
377
392
 
378
393
  ### 4. Register the Module
@@ -399,6 +414,10 @@ import {
399
414
  refreshExpiresInDays: 7
400
415
  },
401
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'
402
421
  roles: {
403
422
  hierarchy: {
404
423
  admin: ['manager', 'user'],
@@ -430,13 +449,11 @@ export class AppModule {}
430
449
  ```typescript
431
450
  // users.controller.ts
432
451
  import { Controller, Get, UseGuards } from '@nestjs/common'
433
- import {
434
- JwtAuthGuard,
435
- RolesGuard,
436
- Roles,
437
- CurrentUser,
438
- DashboardJwtPayload
439
- } 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'
440
457
 
441
458
  @Controller('users')
442
459
  @UseGuards(JwtAuthGuard, RolesGuard)
@@ -467,8 +484,10 @@ import { AuthProvider } from '@bymax-one/nest-auth/react'
467
484
  import { createAuthClient } from '@bymax-one/nest-auth/client'
468
485
 
469
486
  const authClient = createAuthClient({
470
- // Same-origin calls go through the Next.js proxy routes under
471
- // `/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'
472
491
  })
473
492
 
474
493
  export function Providers({ children }: { children: React.ReactNode }) {
@@ -490,7 +509,9 @@ export function Profile() {
490
509
  const { logout } = useAuth()
491
510
 
492
511
  if (status === 'loading') return <div>Loading…</div>
493
- 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>
494
515
 
495
516
  return (
496
517
  <div>
@@ -523,7 +544,7 @@ export const { proxy } = createAuthProxy({
523
544
  loginPath: '/auth/login',
524
545
  getDefaultDashboard: (role) => (role === 'admin' ? '/dashboard/admin' : '/dashboard'),
525
546
  apiBase: process.env.API_BASE_URL!,
526
- jwtSecret: process.env.JWT_SECRET,
547
+ jwtSecret: process.env.JWT_SECRET!,
527
548
  cookieNames: {
528
549
  access: 'access_token',
529
550
  refresh: 'refresh_token',
@@ -583,29 +604,155 @@ export const POST = createLogoutHandler({
583
604
 
584
605
  ---
585
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
+
586
638
  ## ⚙️ Configuration
587
639
 
588
640
  All options are configurable via `registerAsync()`. Here are the key configuration groups:
589
641
 
590
- | Group | Key Options | Default |
591
- | ----------------- | --------------------------------------------------------------------------- | ------------------------- |
592
- | **jwt** | `secret` (required), `accessExpiresIn`, `refreshExpiresInDays`, `algorithm` | `15m`, `7d`, `HS256` |
593
- | **password** | `costFactor`, `blockSize`, `parallelization` | scrypt N=2¹⁵, r=8, p=1 |
594
- | **tokenDelivery** | `'cookie'` \| `'bearer'` \| `'both'` | `'cookie'` |
595
- | **cookies** | `accessTokenName`, `refreshTokenName`, `sessionSignalName`, `refreshCookiePath`, `resolveDomains` | — (see cookie section) |
596
- | **mfa** | `encryptionKey`, `issuer`, `totpWindow`, `recoveryCodeCount` | — |
597
- | **sessions** | `enabled`, `defaultMaxSessions`, `maxSessionsResolver`, `evictionStrategy` | `false`, `5`, —, `'fifo'` |
598
- | **bruteForce** | `maxAttempts`, `windowSeconds` | `5`, `900` |
599
- | **passwordReset** | `method` (`'token'` \| `'otp'`), `otpLength`, `otpTtlSeconds` | `'token'` |
600
- | **platform** | `enabled` | `false` |
601
- | **invitations** | `enabled`, `tokenTtlSeconds` | `false` |
602
- | **roles** | `hierarchy` (required), `platformHierarchy` | — |
603
- | **oauth** | `google: { clientId, clientSecret, callbackUrl }` | — |
604
- | **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 |
605
660
 
606
661
  > [!NOTE]
607
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.
608
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
+
609
756
  ---
610
757
 
611
758
  ## 🏗️ Architecture
@@ -634,13 +781,13 @@ The package runs **inside** your NestJS application as a dynamic module — not
634
781
 
635
782
  ### Design Principles
636
783
 
637
- | Principle | Description |
638
- | -------------------------- | ------------------------------------------------------------------------------------------------------- |
639
- | **🔌 Interface-Driven** | Define contracts, inject implementations — works with Prisma, TypeORM, Drizzle, or any SQL ORM |
640
- | **🔒 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 |
641
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 |
642
- | **🌳 Tree-Shakeable** | `sideEffects: false`, subpath exports, ESM + CJS dual output |
643
- | **⚡ 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 |
644
791
 
645
792
  ---
646
793
 
@@ -695,17 +842,22 @@ When integrating `@bymax-one/nest-auth` in production, verify each of the follow
695
842
 
696
843
  ## 🛡️ Security Table
697
844
 
698
- | Layer | Implementation |
699
- | ----------------- | -------------------------------------------------- |
700
- | Password Hashing | `node:crypto` scrypt (N=2¹⁵, r=8, p=1, keyLen=64) |
701
- | MFA Encryption | AES-256-GCM with 12-byte random IV per call |
702
- | TOTP | HMAC-SHA1 per RFC 4226/6238, ±1 step window |
703
- | Token Generation | `crypto.randomBytes(32)` — 256 bits of entropy |
704
- | Secret Comparison | `crypto.timingSafeEqual` (constant-time) |
705
- | JWT | HS256 via `@nestjs/jwt`, JTI blacklist via Redis |
706
- | Cookies | HttpOnly, Secure, SameSite=Strict, path-scoped |
707
- | Brute-Force | Redis atomic counters per HMAC(email, jwt.secret) |
708
- | 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 |
709
861
 
710
862
  > [!IMPORTANT]
711
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.
@@ -731,9 +883,9 @@ When integrating `@bymax-one/nest-auth` in production, verify each of the follow
731
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**.
732
884
 
733
885
  - ✅ **100% line coverage** — statements, branches, functions, and lines, enforced as a release gate across unit + e2e
734
- - ✅ **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
735
- - ✅ **1,980 tests** — unit and end-to-end, spanning all five subpaths
736
- - ✅ **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
737
889
 
738
890
  ```bash
739
891
  pnpm test # unit suite
@@ -752,36 +904,46 @@ pnpm mutation # Stryker mutation testing
752
904
 
753
905
  Conditionally registered controllers (mfa, sessions, platform, invitations, oauth, password-reset) only mount their endpoints when the corresponding feature is enabled in `BymaxAuthModule.registerAsync()`.
754
906
 
755
- | Method | Path | Auth / Guard | Description |
756
- | ------ | ----------------------------- | ------------------------------------------- | ---------------------------------------------------------- |
757
- | POST | `/register` | Public | Register a new dashboard user and issue tokens |
758
- | POST | `/login` | Public | Authenticate with email/password (may return MFA challenge) |
759
- | POST | `/logout` | `JwtAuthGuard` | Revoke tokens and clear session |
760
- | POST | `/refresh` | Public (refresh cookie) | Rotate refresh token, issue new access token |
761
- | GET | `/me` | `JwtAuthGuard` | Current dashboard user payload |
762
- | POST | `/verify-email` | Public | Verify email with OTP |
763
- | POST | `/resend-verification` | Public | Resend email-verification OTP |
764
- | POST | `/password/forgot-password` | Public | Request password reset (token or OTP) |
765
- | POST | `/password/reset-password` | Public | Submit new password with reset token |
766
- | POST | `/password/verify-otp` | Public | Verify password-reset OTP |
767
- | POST | `/password/resend-otp` | Public | Resend password-reset OTP |
768
- | POST | `/mfa/setup` | `JwtAuthGuard` | Generate TOTP secret and recovery codes |
769
- | POST | `/mfa/verify-enable` | `JwtAuthGuard` | Confirm setup and enable MFA |
770
- | POST | `/mfa/challenge` | Public + `@SkipMfa()` | Submit TOTP/recovery code after login |
771
- | POST | `/mfa/disable` | `JwtAuthGuard` | Disable MFA for the current user |
772
- | GET | `/sessions` | `JwtAuthGuard`, `UserStatusGuard` | List active sessions for the current user |
773
- | DELETE | `/sessions/all` | `JwtAuthGuard`, `UserStatusGuard` | Revoke all sessions |
774
- | DELETE | `/sessions/:id` | `JwtAuthGuard`, `UserStatusGuard` | Revoke a specific session |
775
- | POST | `/invitations` | `JwtAuthGuard` | Create a tenant invitation |
776
- | POST | `/invitations/accept` | Public | Accept an invitation and create the user |
777
- | POST | `/platform/login` | Public | Platform admin login (separate token context) |
778
- | POST | `/platform/mfa/challenge` | Public | Platform admin MFA challenge |
779
- | GET | `/platform/me` | `JwtPlatformGuard` | Current platform admin payload |
780
- | POST | `/platform/logout` | `JwtPlatformGuard` | Revoke platform tokens |
781
- | POST | `/platform/refresh` | Public (platform refresh cookie) | Rotate platform refresh token |
782
- | DELETE | `/platform/sessions` | `JwtPlatformGuard` | Revoke all platform sessions |
783
- | GET | `/oauth/:provider` | Public + `@SkipMfa()` | Initiate OAuth authorization redirect |
784
- | 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.
785
947
 
786
948
  ### Server Guards
787
949
 
@@ -797,6 +959,30 @@ Conditionally registered controllers (mfa, sessions, platform, invitations, oaut
797
959
  > [!NOTE]
798
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.
799
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
+
800
986
  ### Server Decorators
801
987
 
802
988
  | Decorator | Usage |
@@ -826,26 +1012,6 @@ Conditionally registered controllers (mfa, sessions, platform, invitations, oaut
826
1012
 
827
1013
  ---
828
1014
 
829
- ## 🗺️ Roadmap
830
-
831
- 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.
832
-
833
- | Area | Item | Status |
834
- | --------------------------- | ----------------------------------------------------------------------------------------------------------------------- | --------- |
835
- | OAuth providers | First-class `oauth.plugins` array so consumers can drop in GitHub / Microsoft / Apple plugins without forking the core | Planned |
836
- | Error-message i18n | `BymaxAuthModule.forRoot({ messages })` override for `AUTH_ERROR_MESSAGES` (defaults stay Portuguese; English preset) | Planned |
837
- | Refresh-token families | Family-level revocation: detect grace-window reuse as a stolen-token signal and invalidate the entire session family | Planned |
838
- | Passwordless / magic link | `MagicLinkService` + email-delivered single-use link, reusing the existing `generateSecureToken` + `IEmailProvider` API | Exploring |
839
- | Passkeys / WebAuthn | Optional WebAuthn primitive as an MFA method (and eventually a first-factor), behind a peer-dep-gated module | Exploring |
840
- | Per-tenant configuration | Per-tenant overrides for session limits, MFA enforcement, and password policy resolved at request time | Exploring |
841
- | Absolute session lifetime | Hard cap on refresh chains so a session rotated every 6 days does not live forever | Planned |
842
- | Pluggable password policy | `IPasswordPolicy` interface for disallow-lists, complexity classes, and per-tenant rules | Planned |
843
- | Custom token delivery modes | `ITokenDelivery` for non-cookie / non-bearer transports (custom headers, WebSocket handshakes, split client types) | Exploring |
844
-
845
- > Track progress and discuss proposals on the [issues board](https://github.com/bymaxone/nest-auth/issues).
846
-
847
- ---
848
-
849
1015
  ## 🤝 Contributing
850
1016
 
851
1017
  Contributions are welcome! Please read our contributing guidelines before submitting a pull request.