@bymax-one/nest-auth 1.0.11 → 1.1.1
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/CHANGELOG.md +443 -1
- package/README.md +275 -108
- package/dist/client/index.cjs +49 -5
- package/dist/client/index.mjs +49 -5
- package/dist/nextjs/index.cjs +152 -51
- package/dist/nextjs/index.d.cts +164 -58
- package/dist/nextjs/index.d.ts +164 -58
- package/dist/nextjs/index.mjs +152 -51
- package/dist/react/index.cjs +85 -89
- package/dist/react/index.mjs +85 -89
- package/dist/server/index.cjs +6083 -1574
- package/dist/server/index.d.cts +2880 -180
- package/dist/server/index.d.ts +2880 -180
- package/dist/server/index.mjs +6062 -1560
- package/dist/shared/index.cjs +60 -9
- package/dist/shared/index.d.cts +126 -18
- package/dist/shared/index.d.ts +126 -18
- package/dist/shared/index.mjs +60 -9
- package/package.json +112 -43
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-
|
|
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
|
|
289
|
+
s
|
|
290
|
+
.replace(/&/g, '&')
|
|
274
291
|
.replace(/</g, '<')
|
|
275
292
|
.replace(/>/g, '>')
|
|
276
293
|
.replace(/"/g, '"')
|
|
@@ -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
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
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
|
|
475
|
-
//
|
|
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
|
-
|
|
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>
|
|
@@ -517,7 +534,10 @@ backend.
|
|
|
517
534
|
// proxy.ts — Next.js 16 Edge middleware
|
|
518
535
|
import { createAuthProxy } from '@bymax-one/nest-auth/nextjs'
|
|
519
536
|
|
|
520
|
-
|
|
537
|
+
// Next 16 scans this file for a function exported as `proxy` (or as the default), and it
|
|
538
|
+
// does not recognise a destructuring pattern: `export const { proxy } = ...` fails the build
|
|
539
|
+
// with "The file ./proxy.ts must export a function". Bind first, then export.
|
|
540
|
+
const authProxy = createAuthProxy({
|
|
521
541
|
publicRoutes: ['/', '/auth/login', '/auth/register'],
|
|
522
542
|
publicRoutesRedirectIfAuthenticated: ['/auth/login', '/auth/register'],
|
|
523
543
|
protectedRoutes: [
|
|
@@ -527,7 +547,7 @@ export const { proxy } = createAuthProxy({
|
|
|
527
547
|
loginPath: '/auth/login',
|
|
528
548
|
getDefaultDashboard: (role) => (role === 'admin' ? '/dashboard/admin' : '/dashboard'),
|
|
529
549
|
apiBase: process.env.API_BASE_URL!,
|
|
530
|
-
jwtSecret: process.env.JWT_SECRET
|
|
550
|
+
jwtSecret: process.env.JWT_SECRET!,
|
|
531
551
|
cookieNames: {
|
|
532
552
|
access: 'access_token',
|
|
533
553
|
refresh: 'refresh_token',
|
|
@@ -542,6 +562,8 @@ export const { proxy } = createAuthProxy({
|
|
|
542
562
|
blockedUserStatuses: ['BANNED', 'INACTIVE', 'EXPIRED']
|
|
543
563
|
})
|
|
544
564
|
|
|
565
|
+
export const proxy = authProxy.proxy
|
|
566
|
+
|
|
545
567
|
export const config = {
|
|
546
568
|
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)']
|
|
547
569
|
}
|
|
@@ -587,29 +609,155 @@ export const POST = createLogoutHandler({
|
|
|
587
609
|
|
|
588
610
|
---
|
|
589
611
|
|
|
612
|
+
### WebSocket upgrades
|
|
613
|
+
|
|
614
|
+
The browser `WebSocket` API cannot set handshake headers, so a browser client cannot send
|
|
615
|
+
`Authorization: Bearer <token>` at the upgrade. The usual workaround puts the access token in the
|
|
616
|
+
query string, where it lands in access logs, browser history and proxy caches — a long-lived
|
|
617
|
+
credential in plaintext. `WsJwtGuard` refuses it.
|
|
618
|
+
|
|
619
|
+
The supported path is a single-use ticket:
|
|
620
|
+
|
|
621
|
+
```typescript
|
|
622
|
+
// 1. Mint from an authenticated session (POST, cookies or bearer as usual).
|
|
623
|
+
const { ticket, expiresIn } = await fetch('/auth/ws-ticket', {
|
|
624
|
+
method: 'POST',
|
|
625
|
+
credentials: 'include'
|
|
626
|
+
}).then((r) => r.json())
|
|
627
|
+
|
|
628
|
+
// 2. Open the socket with it. The ticket is consumed by the first redemption.
|
|
629
|
+
const socket = new WebSocket(`wss://api.example.com/socket?ticket=${ticket}`)
|
|
630
|
+
```
|
|
631
|
+
|
|
632
|
+
The ticket is opaque, 32 bytes of CSPRNG output, and lives 30 seconds. Only `sha256(ticket)` is
|
|
633
|
+
ever a Redis key, and the stored value is a verified-identity **snapshot** — no `jti`, no
|
|
634
|
+
signature, no expiry of its own — so a redeemed ticket authorizes a socket and cannot be turned
|
|
635
|
+
back into a session. Minting requires an authenticated session in good standing that has already
|
|
636
|
+
satisfied MFA, so a ticket never carries more authority than the request that asked for it.
|
|
637
|
+
|
|
638
|
+
Non-browser clients that can set headers keep using `Authorization: Bearer` at the handshake;
|
|
639
|
+
both channels are accepted, and a ticket wins when both are present.
|
|
640
|
+
|
|
641
|
+
---
|
|
642
|
+
|
|
590
643
|
## ⚙️ Configuration
|
|
591
644
|
|
|
592
645
|
All options are configurable via `registerAsync()`. Here are the key configuration groups:
|
|
593
646
|
|
|
594
|
-
| Group
|
|
595
|
-
|
|
|
596
|
-
| **jwt**
|
|
597
|
-
| **password**
|
|
598
|
-
| **tokenDelivery**
|
|
599
|
-
| **cookies**
|
|
600
|
-
| **mfa**
|
|
601
|
-
| **sessions**
|
|
602
|
-
| **bruteForce**
|
|
603
|
-
| **
|
|
604
|
-
| **
|
|
605
|
-
| **
|
|
606
|
-
| **
|
|
607
|
-
| **
|
|
608
|
-
| **
|
|
647
|
+
| Group | Key Options | Default |
|
|
648
|
+
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- |
|
|
649
|
+
| **jwt** | `secret` (required), `previousSecrets`, `accessExpiresIn`, `refreshExpiresInDays`, `absoluteSessionLifetimeDays`, `algorithm`, `issuer`, `audience` | `15m`, `7d`, off, `HS256`, both off |
|
|
650
|
+
| **password** | `costFactor`, `blockSize`, `parallelization` | scrypt N=2¹⁷, r=8, p=1 |
|
|
651
|
+
| **tokenDelivery** | `'cookie'` \| `'bearer'` \| `'both'` | `'cookie'` |
|
|
652
|
+
| **cookies** | `accessTokenName`, `refreshTokenName`, `sessionSignalName`, `refreshCookiePath`, `sameSite`, `trustedOrigins`, `resolveDomains` | `'lax'`, `[]` (see cookie section) |
|
|
653
|
+
| **mfa** | `encryptionKey`, `previousEncryptionKeys`, `issuer`, `totpWindow`, `recoveryCodeCount` | — |
|
|
654
|
+
| **sessions** | `enabled`, `defaultMaxSessions`, `maxSessionsResolver` | `false`, `5`, — |
|
|
655
|
+
| **bruteForce** | `maxAttempts`, `windowSeconds` | `5`, `900` |
|
|
656
|
+
| **rateLimit** | `enabled`, `clientIpSource` (`'peer'` \| `'trusted-proxy'`) — per-IP limits over Redis | `true`, **required** |
|
|
657
|
+
| **passwordReset** | `method` (`'token'` \| `'otp'`), `otpLength`, `otpTtlSeconds` | `'token'` |
|
|
658
|
+
| **platform** | `enabled` | `false` |
|
|
659
|
+
| **invitations** | `enabled`, `tokenTtlSeconds` | `false` |
|
|
660
|
+
| **roles** | `hierarchy` (required), `platformHierarchy` | — |
|
|
661
|
+
| **oauth** | `google: { clientId, clientSecret, callbackUrl }` | — |
|
|
662
|
+
| **emailVerification** | `required`, `otpTtlSeconds` | `true`, `600` |
|
|
663
|
+
| **password** (screen) | `blocklist` — extra words the default screen refuses, on top of the ones it ships | `[]` |
|
|
664
|
+
| **controllers** | Toggle individual controllers on/off | `auth`, `passwordReset` on; rest opt-in |
|
|
609
665
|
|
|
610
666
|
> [!NOTE]
|
|
611
667
|
> 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
668
|
|
|
669
|
+
> [!IMPORTANT]
|
|
670
|
+
> **`rateLimit.clientIpSource` is required** whenever rate limiting is enabled — there is no
|
|
671
|
+
> default. The option group is a discriminated union, so TypeScript refuses the omission at
|
|
672
|
+
> compile time; the module also refuses to start without it, because the type binds TypeScript
|
|
673
|
+
> and nothing else. Set `'peer'` when the application is
|
|
674
|
+
> directly exposed: the limit keys on the socket address, read from the connection and never
|
|
675
|
+
> from a forwarding header. Set `'trusted-proxy'` when it runs behind a proxy and `trust proxy`
|
|
676
|
+
> is configured for the real hop count: the limit keys on `req.ip`, the forwarded client
|
|
677
|
+
> address. Neither can be the default, because each is a working limiter in one deployment and
|
|
678
|
+
> no limiter at all in the other — `'peer'` behind a proxy puts every client in **one** bucket,
|
|
679
|
+
> so a single caller can rate-limit your whole user base with no credential, and
|
|
680
|
+
> `'trusted-proxy'` without a proxy lets the caller choose their own key. Both look like a
|
|
681
|
+
> working limiter at runtime. Pass `rateLimit.enabled: false` if the limits are enforced at the
|
|
682
|
+
> edge instead.
|
|
683
|
+
|
|
684
|
+
> [!TIP]
|
|
685
|
+
> **Binding tokens to an issuer and an audience.** `jwt.issuer` and `jwt.audience` are off by
|
|
686
|
+
> default. Set either and its value is stamped on every token this backend mints and **required**
|
|
687
|
+
> on every token it verifies — one carrying a different value, or none at all, is rejected.
|
|
688
|
+
> That matters with HS256, where the verifier can also sign: every service holding the secret to
|
|
689
|
+
> check a token can mint one, so audience binding is what stops a token minted for one service
|
|
690
|
+
> being replayed at another that trusts the same secret.
|
|
691
|
+
>
|
|
692
|
+
> Two things to know before switching it on. Both backends of a shared deployment must carry the
|
|
693
|
+
> same pair, or they stop accepting each other's tokens. And enabling it invalidates the access
|
|
694
|
+
> tokens already in flight, since those were minted without the claims — a window of one
|
|
695
|
+
> access-token lifetime, which clients close by refreshing. An empty string reads as unconfigured
|
|
696
|
+
> rather than as "require the empty issuer", so an unset environment variable cannot turn the
|
|
697
|
+
> check on by accident.
|
|
698
|
+
|
|
699
|
+
> **Rotating the signing secret.** `jwt.previousSecrets` lists secrets retired by a rotation,
|
|
700
|
+
> accepted for verification only. Without it, changing `jwt.secret` signs every user out the
|
|
701
|
+
> moment the new configuration rolls out **and** invalidates every stored recovery-code digest —
|
|
702
|
+
> those are keyed by an HMAC derived from the secret, so users lose the codes they printed and
|
|
703
|
+
> filed. With it, both keep working while tokens issued under the old secret drain, and a
|
|
704
|
+
> rotation becomes a rollout. Remove the entry once the longest-lived token signed under it has
|
|
705
|
+
> expired: every entry is a key that still opens the door. `mfa.encryptionKey` rotates the same
|
|
706
|
+
> way, through its own list — see below.
|
|
707
|
+
|
|
708
|
+
> [!TIP]
|
|
709
|
+
> **Rotating the MFA encryption key.** `mfa.previousEncryptionKeys` lists AES-256 keys retired by
|
|
710
|
+
> a rotation of `mfa.encryptionKey`. The stored ciphertext carries no key identifier, so without
|
|
711
|
+
> the list a change of key makes every enrolled user's TOTP secret undecryptable at once, with no
|
|
712
|
+
> way back — their authenticator simply stops matching. With it, a stored secret that opened
|
|
713
|
+
> under a retired key is **re-encrypted under the current one** on the next successful challenge,
|
|
714
|
+
> so the rotation drains on its own instead of requiring the retired key to stay configured
|
|
715
|
+
> forever. Each entry is validated at startup exactly like the current key (base64, exactly 32
|
|
716
|
+
> bytes, and never equal to the current key or to another entry), because a malformed one would
|
|
717
|
+
> otherwise surface at a user's first challenge rather than at boot. Drop the entry once your
|
|
718
|
+
> enrolled users have had time to authenticate at least once.
|
|
719
|
+
|
|
720
|
+
> [!IMPORTANT]
|
|
721
|
+
> **The parameters that carry a control's strength are bounded at startup.** `mfa.totpWindow`
|
|
722
|
+
> must be `0..=10`: the window counts 30-second steps on _either_ side of now, so `2n + 1`
|
|
723
|
+
> codes are valid at once — three at the default of 1, but 121 at 60, which makes a six-digit
|
|
724
|
+
> code a hundred times easier to guess while the configuration still reads as "MFA enabled".
|
|
725
|
+
> `mfa.recoveryCodeCount` must be `1..=50`, because zero enrols an account with no way back
|
|
726
|
+
> if the authenticator is lost. `password.blockSize` must be at least 8 and
|
|
727
|
+
> `password.parallelization` at least 1: scrypt's memory cost is `128 * N * r`, so a smaller
|
|
728
|
+
> block size divides the hardness that `password.costFactor`'s floor exists to guarantee —
|
|
729
|
+
> invisibly, since the bounded parameter is still intact. `rust-auth` enforces the identical
|
|
730
|
+
> ranges.
|
|
731
|
+
|
|
732
|
+
> [!IMPORTANT]
|
|
733
|
+
> `jwt.accessExpiresIn` must not exceed **30 days**, the window the store keeps a bumped token
|
|
734
|
+
> epoch readable. The epoch is what makes a stateless access token revocable: a password reset
|
|
735
|
+
> advances it and every token stamped below it stops verifying — but only while the bumped value
|
|
736
|
+
> is still there. A longer-lived access token would outlive it, the lookup would fall back to
|
|
737
|
+
> `0`, and a token the reset revoked would verify again. Startup refuses the configuration
|
|
738
|
+
> rather than letting it fail open, and rejects an unreadable time span or a non-positive
|
|
739
|
+
> lifetime on the same pass.
|
|
740
|
+
|
|
741
|
+
Two options are deliberately off by default because switching them on changes behaviour for
|
|
742
|
+
sessions and origins that already exist:
|
|
743
|
+
|
|
744
|
+
- `jwt.absoluteSessionLifetimeDays` caps how long one login can be extended by rotation. Without
|
|
745
|
+
it, a client refreshing every fifteen minutes keeps a session alive forever.
|
|
746
|
+
- `cookies.trustedOrigins` is required as soon as `cookies.sameSite: 'none'` is set, and refused
|
|
747
|
+
otherwise — that posture is the only one where the browser sends the session cookie
|
|
748
|
+
cross-site, and it is the only one where the origin check has anything to authorize.
|
|
749
|
+
|
|
750
|
+
The breach check is opt-in for a different reason: it is the only part of the credential path
|
|
751
|
+
that reaches the network, and a library should not start talking to a third party because it was
|
|
752
|
+
upgraded. Wire it explicitly:
|
|
753
|
+
|
|
754
|
+
```typescript
|
|
755
|
+
BymaxAuthModule.registerAsync({
|
|
756
|
+
useFactory: () => ({ ... }),
|
|
757
|
+
extraProviders: [{ provide: BYMAX_AUTH_BREACH_CHECKER, useClass: HibpBreachChecker }]
|
|
758
|
+
})
|
|
759
|
+
```
|
|
760
|
+
|
|
613
761
|
---
|
|
614
762
|
|
|
615
763
|
## 🏗️ Architecture
|
|
@@ -638,13 +786,13 @@ The package runs **inside** your NestJS application as a dynamic module — not
|
|
|
638
786
|
|
|
639
787
|
### Design Principles
|
|
640
788
|
|
|
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
|
|
789
|
+
| Principle | Description |
|
|
790
|
+
| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
791
|
+
| **🔌 Interface-Driven** | Define contracts, inject implementations — works with Prisma, TypeORM, Drizzle, or any SQL ORM |
|
|
792
|
+
| **🔒 Secure by Default** | scrypt hashing, HttpOnly cookies, JWT blacklisting, brute-force protection — all enabled out of the box |
|
|
645
793
|
| **🪶 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
|
|
794
|
+
| **🌳 Tree-Shakeable** | `sideEffects: false`, subpath exports, ESM + CJS dual output |
|
|
795
|
+
| **⚡ Conditional Loading** | Unconfigured features don't register — no wasted memory or startup time |
|
|
648
796
|
|
|
649
797
|
---
|
|
650
798
|
|
|
@@ -699,17 +847,22 @@ When integrating `@bymax-one/nest-auth` in production, verify each of the follow
|
|
|
699
847
|
|
|
700
848
|
## 🛡️ Security Table
|
|
701
849
|
|
|
702
|
-
| Layer
|
|
703
|
-
|
|
|
704
|
-
| Password Hashing
|
|
705
|
-
| MFA Encryption
|
|
706
|
-
| TOTP
|
|
707
|
-
| Token Generation
|
|
708
|
-
| Secret Comparison
|
|
709
|
-
| JWT
|
|
710
|
-
| Cookies
|
|
711
|
-
| Brute-Force
|
|
712
|
-
| CSRF (OAuth)
|
|
850
|
+
| Layer | Implementation |
|
|
851
|
+
| ------------------ | ------------------------------------------------------------------------------------------------------ |
|
|
852
|
+
| Password Hashing | `node:crypto` scrypt (N=2¹⁷, r=8, p=1, keyLen=64) — OWASP's recommended minimum |
|
|
853
|
+
| MFA Encryption | AES-256-GCM with 12-byte random IV per call |
|
|
854
|
+
| TOTP | HMAC-SHA1 per RFC 4226/6238, ±1 step window |
|
|
855
|
+
| Token Generation | `crypto.randomBytes(32)` — 256 bits of entropy |
|
|
856
|
+
| Secret Comparison | `crypto.timingSafeEqual` (constant-time) |
|
|
857
|
+
| JWT | HS256 via `@nestjs/jwt`, JTI blacklist via Redis |
|
|
858
|
+
| Cookies | HttpOnly, Secure, SameSite=Strict, path-scoped |
|
|
859
|
+
| Brute-Force | Redis atomic counters per HMAC(email, jwt.secret) |
|
|
860
|
+
| CSRF (OAuth) | 64-char hex state nonce, single-use via `getdel()` |
|
|
861
|
+
| Refresh Rotation | Single-use tokens with a grace window; a replay past it revokes that login's whole family lineage |
|
|
862
|
+
| Cross-Site Writes | `Origin` / `Sec-Fetch-Site` check on cookie-authenticated writes — the gap `SameSite=None` leaves open |
|
|
863
|
+
| Breached Passwords | Optional Have I Been Pwned range check by k-anonymity; only a 5-char SHA-1 prefix leaves the process |
|
|
864
|
+
| Rate Limiting | Per-IP fixed-window counters in Redis, keyed by `HMAC(ip)` — enforced by the library, not by the host |
|
|
865
|
+
| Session Lifetime | Optional absolute cap on how long one login can be extended by rotation |
|
|
713
866
|
|
|
714
867
|
> [!IMPORTANT]
|
|
715
868
|
> 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 +888,9 @@ When integrating `@bymax-one/nest-auth` in production, verify each of the follow
|
|
|
735
888
|
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
889
|
|
|
737
890
|
- ✅ **100% line coverage** — statements, branches, functions, and lines, enforced as a release gate across unit + e2e
|
|
738
|
-
- ✅ **
|
|
739
|
-
- ✅ **
|
|
740
|
-
- ✅ **
|
|
891
|
+
- ✅ **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
|
|
892
|
+
- ✅ **2,458 tests** — unit and end-to-end, spanning all five subpaths
|
|
893
|
+
- ✅ **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
894
|
|
|
742
895
|
```bash
|
|
743
896
|
pnpm test # unit suite
|
|
@@ -756,36 +909,46 @@ pnpm mutation # Stryker mutation testing
|
|
|
756
909
|
|
|
757
910
|
Conditionally registered controllers (mfa, sessions, platform, invitations, oauth, password-reset) only mount their endpoints when the corresponding feature is enabled in `BymaxAuthModule.registerAsync()`.
|
|
758
911
|
|
|
759
|
-
| Method | Path
|
|
760
|
-
| ------ |
|
|
761
|
-
| POST | `/register`
|
|
762
|
-
| POST | `/login`
|
|
763
|
-
| POST | `/logout`
|
|
764
|
-
| POST | `/refresh`
|
|
765
|
-
| GET | `/me`
|
|
766
|
-
| POST | `/verify-email`
|
|
767
|
-
| POST | `/resend-verification`
|
|
768
|
-
| POST | `/password/forgot-password`
|
|
769
|
-
| POST | `/password/reset-password`
|
|
770
|
-
| POST | `/password/verify-otp`
|
|
771
|
-
| POST | `/password/resend-otp`
|
|
772
|
-
| POST | `/mfa/setup`
|
|
773
|
-
| POST | `/mfa/verify-enable`
|
|
774
|
-
| POST | `/mfa/challenge`
|
|
775
|
-
| POST | `/mfa/disable`
|
|
776
|
-
| GET | `/sessions`
|
|
777
|
-
| DELETE | `/sessions/all`
|
|
778
|
-
| DELETE | `/sessions/:id`
|
|
779
|
-
| POST | `/invitations`
|
|
780
|
-
| POST | `/invitations/accept`
|
|
781
|
-
| POST | `/
|
|
782
|
-
| POST | `/
|
|
783
|
-
|
|
|
784
|
-
| POST | `/platform/
|
|
785
|
-
| POST | `/platform/
|
|
786
|
-
|
|
|
787
|
-
|
|
|
788
|
-
|
|
|
912
|
+
| Method | Path | Auth / Guard | Description |
|
|
913
|
+
| ------ | --------------------------- | ---------------------------------- | ----------------------------------------------------------- |
|
|
914
|
+
| POST | `/register` | Public | Register a new dashboard user and issue tokens |
|
|
915
|
+
| POST | `/login` | Public | Authenticate with email/password (may return MFA challenge) |
|
|
916
|
+
| POST | `/logout` | `JwtAuthGuard` | Revoke tokens and clear session |
|
|
917
|
+
| POST | `/refresh` | Public (refresh cookie) | Rotate refresh token, issue new access token |
|
|
918
|
+
| GET | `/me` | `JwtAuthGuard` | Current dashboard user payload |
|
|
919
|
+
| POST | `/verify-email` | Public | Verify email with OTP |
|
|
920
|
+
| POST | `/resend-verification` | Public | Resend email-verification OTP |
|
|
921
|
+
| POST | `/password/forgot-password` | Public | Request password reset (token or OTP) |
|
|
922
|
+
| POST | `/password/reset-password` | Public | Submit new password with reset token |
|
|
923
|
+
| POST | `/password/verify-otp` | Public | Verify password-reset OTP |
|
|
924
|
+
| POST | `/password/resend-otp` | Public | Resend password-reset OTP |
|
|
925
|
+
| POST | `/mfa/setup` | `JwtAuthGuard` | Generate TOTP secret and recovery codes |
|
|
926
|
+
| POST | `/mfa/verify-enable` | `JwtAuthGuard` | Confirm setup and enable MFA |
|
|
927
|
+
| POST | `/mfa/challenge` | Public + `@SkipMfa()` | Submit TOTP/recovery code after login |
|
|
928
|
+
| POST | `/mfa/disable` | `JwtAuthGuard` | Disable MFA for the current user |
|
|
929
|
+
| GET | `/sessions` | `JwtAuthGuard`, `UserStatusGuard` | List active sessions for the current user |
|
|
930
|
+
| DELETE | `/sessions/all` | `JwtAuthGuard`, `UserStatusGuard` | Revoke all sessions |
|
|
931
|
+
| DELETE | `/sessions/:id` | `JwtAuthGuard`, `UserStatusGuard` | Revoke a specific session |
|
|
932
|
+
| POST | `/invitations` | `JwtAuthGuard`, `UserStatusGuard` | Create a tenant invitation |
|
|
933
|
+
| POST | `/invitations/accept` | Public | Accept an invitation and create the user |
|
|
934
|
+
| POST | `/invitations/revoke` | `JwtAuthGuard`, `UserStatusGuard` | Withdraw a pending invitation |
|
|
935
|
+
| POST | `/email/change` | `JwtAuthGuard`, `UserStatusGuard` | Request an address change (re-proves the current password) |
|
|
936
|
+
| POST | `/email/change/confirm` | Public | Confirm it with the token mailed to the new address |
|
|
937
|
+
| POST | `/platform/login` | Public | Platform admin login (separate token context) |
|
|
938
|
+
| POST | `/platform/mfa/challenge` | Public | Platform admin MFA challenge |
|
|
939
|
+
| GET | `/platform/me` | `JwtPlatformGuard` | Current platform admin payload |
|
|
940
|
+
| POST | `/platform/logout` | `JwtPlatformGuard` | Revoke platform tokens |
|
|
941
|
+
| POST | `/platform/refresh` | Public (platform refresh cookie) | Rotate platform refresh token |
|
|
942
|
+
| DELETE | `/platform/sessions` | `JwtPlatformGuard` | Revoke all platform sessions |
|
|
943
|
+
| POST | `/password/change` | `JwtAuthGuard` + `UserStatusGuard` | Change the password, proving the current one |
|
|
944
|
+
| GET | `/oauth/:provider` | Public + `@SkipMfa()` | Initiate OAuth authorization redirect |
|
|
945
|
+
| GET | `/oauth/:provider/callback` | Public + `@SkipMfa()` | Handle OAuth callback, exchange code, issue tokens |
|
|
946
|
+
|
|
947
|
+
> **The OAuth routes require `cookie-parser`.** `GET /oauth/:provider` plants an HttpOnly
|
|
948
|
+
> `oauth_state` cookie carrying the flow's `state`, and the callback refuses any request that
|
|
949
|
+
> does not send it back — the binding RFC 6749 §10.12 requires, without which an attacker can
|
|
950
|
+
> hand a victim a callback URL and have the victim's browser complete the attacker's login.
|
|
951
|
+
> Mount `app.use(cookieParser())` before the module's routes or every callback answers 401.
|
|
789
952
|
|
|
790
953
|
### Server Guards
|
|
791
954
|
|
|
@@ -801,6 +964,30 @@ Conditionally registered controllers (mfa, sessions, platform, invitations, oaut
|
|
|
801
964
|
> [!NOTE]
|
|
802
965
|
> 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
966
|
|
|
967
|
+
### One error envelope
|
|
968
|
+
|
|
969
|
+
Every failure the module raises answers with the same body, so a client parses `error.code` and
|
|
970
|
+
nothing else:
|
|
971
|
+
|
|
972
|
+
```json
|
|
973
|
+
{ "error": { "code": "auth.invalid_credentials", "message": "…", "details": null } }
|
|
974
|
+
```
|
|
975
|
+
|
|
976
|
+
That includes malformed requests: the controllers mount `createAuthValidationPipe()`, which
|
|
977
|
+
answers `auth.validation` with the offending fields under `error.details` as
|
|
978
|
+
`[{ "field": "email", "message": "…" }]` rather than the framework's own shape.
|
|
979
|
+
|
|
980
|
+
Failures the module did **not** raise are the application's to answer, so nothing is imposed on
|
|
981
|
+
them by default. Register the optional filter to bring them into the same envelope:
|
|
982
|
+
|
|
983
|
+
```typescript
|
|
984
|
+
app.useGlobalFilters(new AuthExceptionFilter())
|
|
985
|
+
```
|
|
986
|
+
|
|
987
|
+
It passes an `AuthException` through untouched, keeps the status any other `HttpException`
|
|
988
|
+
chose, and answers an unhandled throw with `auth.internal` and a generic message — never the
|
|
989
|
+
thrown one.
|
|
990
|
+
|
|
804
991
|
### Server Decorators
|
|
805
992
|
|
|
806
993
|
| Decorator | Usage |
|
|
@@ -830,26 +1017,6 @@ Conditionally registered controllers (mfa, sessions, platform, invitations, oaut
|
|
|
830
1017
|
|
|
831
1018
|
---
|
|
832
1019
|
|
|
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
1020
|
## 🤝 Contributing
|
|
854
1021
|
|
|
855
1022
|
Contributions are welcome! Please read our contributing guidelines before submitting a pull request.
|