@bymax-one/nest-auth 1.0.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/CHANGELOG.md +369 -0
- package/LICENSE +21 -0
- package/README.md +886 -0
- package/dist/client/index.cjs +347 -0
- package/dist/client/index.d.cts +301 -0
- package/dist/client/index.d.ts +301 -0
- package/dist/client/index.mjs +341 -0
- package/dist/nextjs/index.cjs +1103 -0
- package/dist/nextjs/index.d.cts +1025 -0
- package/dist/nextjs/index.d.ts +1025 -0
- package/dist/nextjs/index.mjs +1083 -0
- package/dist/react/index.cjs +304 -0
- package/dist/react/index.d.cts +342 -0
- package/dist/react/index.d.ts +342 -0
- package/dist/react/index.mjs +295 -0
- package/dist/server/index.cjs +8039 -0
- package/dist/server/index.d.cts +5092 -0
- package/dist/server/index.d.ts +5092 -0
- package/dist/server/index.mjs +7996 -0
- package/dist/shared/index.cjs +240 -0
- package/dist/shared/index.d.cts +736 -0
- package/dist/shared/index.d.ts +736 -0
- package/dist/shared/index.mjs +223 -0
- package/package.json +195 -0
package/README.md
ADDED
|
@@ -0,0 +1,886 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="https://img.shields.io/badge/%40bymax--one-nest--auth-000000?style=for-the-badge&logo=nestjs&logoColor=E0234E" alt="@bymax-one/nest-auth" />
|
|
3
|
+
</p>
|
|
4
|
+
|
|
5
|
+
<h1 align="center">@bymax-one/nest-auth</h1>
|
|
6
|
+
|
|
7
|
+
<p align="center">
|
|
8
|
+
<strong>Full-stack authentication for NestJS, React & Next.js</strong><br />
|
|
9
|
+
<sub>JWT · MFA · OAuth · Sessions · Multi-Tenant · Zero External Crypto Dependencies</sub>
|
|
10
|
+
</p>
|
|
11
|
+
|
|
12
|
+
<p align="center">
|
|
13
|
+
<a href="https://www.npmjs.com/package/@bymax-one/nest-auth"><img src="https://img.shields.io/npm/v/@bymax-one/nest-auth?style=flat-square&colorA=000000&colorB=000000" alt="npm version" /></a>
|
|
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
|
+
<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
|
+
<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>
|
|
18
|
+
<a href="https://github.com/bymaxone/nest-auth/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/@bymax-one/nest-auth?style=flat-square&colorA=000000&colorB=000000" alt="license" /></a>
|
|
19
|
+
<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>
|
|
20
|
+
<a href="https://nodejs.org/"><img src="https://img.shields.io/badge/Node.js-24%2B-339933?style=flat-square&logo=node.js&logoColor=white" alt="Node.js" /></a>
|
|
21
|
+
</p>
|
|
22
|
+
|
|
23
|
+
<p align="center">
|
|
24
|
+
<a href="https://github.com/bymaxone/nest-auth">GitHub</a> ·
|
|
25
|
+
<a href="https://github.com/bymaxone/nest-auth/issues">Issues</a> ·
|
|
26
|
+
<a href="#-quick-start">Quick Start</a> ·
|
|
27
|
+
<a href="#-subpath-exports">API Reference</a>
|
|
28
|
+
</p>
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## ✨ Overview
|
|
33
|
+
|
|
34
|
+
`@bymax-one/nest-auth` is a **complete authentication and authorization solution** shipped as a single npm package with **5 subpath exports** — covering everything from NestJS backend guards to React hooks and Next.js route handlers.
|
|
35
|
+
|
|
36
|
+
Instead of wiring together dozens of packages for JWT, MFA, OAuth, sessions, password reset, and brute-force protection, you install one library and get a production-ready auth system that works across your entire stack.
|
|
37
|
+
|
|
38
|
+
### Why nest-auth?
|
|
39
|
+
|
|
40
|
+
- **🎯 One package, full stack** — Backend module, shared types, fetch client, React hooks, and Next.js integration all in a single `pnpm add`. Types and constants are shared automatically between server and client — no manual synchronization.
|
|
41
|
+
- **🔌 Your database, your rules** — The library defines TypeScript interfaces (`IUserRepository`, `IEmailProvider`). You implement them with your ORM of choice (Prisma, TypeORM, Drizzle). No vendor lock-in, no hidden database dependencies.
|
|
42
|
+
- **🔒 Native crypto only** — All security-critical code (password hashing, MFA encryption, TOTP, token generation) runs on `node:crypto` — zero third-party crypto packages, so the most sensitive code paths carry no third-party supply-chain risk.
|
|
43
|
+
- **⚡ Pay for what you use** — Features like MFA, sessions, OAuth, and platform admin are opt-in. When not configured, their controllers and services are never registered — zero overhead in your NestJS container.
|
|
44
|
+
- **🏢 Multi-tenant ready** — Every operation is scoped by `tenantId`. Built for SaaS from day one, not bolted on as an afterthought.
|
|
45
|
+
|
|
46
|
+
```
|
|
47
|
+
pnpm add @bymax-one/nest-auth
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
---
|
|
51
|
+
|
|
52
|
+
## 🔥 Features
|
|
53
|
+
|
|
54
|
+
### 🔐 Core Authentication
|
|
55
|
+
|
|
56
|
+
- ✅ **Registration & Login** — Email/password with configurable validation
|
|
57
|
+
- ✅ **JWT Access + Refresh Tokens** — Automatic rotation with grace window for concurrent requests
|
|
58
|
+
- ✅ **Multi-Factor Authentication** — TOTP with QR code URI, recovery codes, and challenge flow
|
|
59
|
+
- ✅ **OAuth 2.0** — Google out of the box, extensible via plugin interface
|
|
60
|
+
- ✅ **Password Reset** — Token-based or OTP, configurable per deployment
|
|
61
|
+
- ✅ **Email Verification** — OTP-based with configurable TTL
|
|
62
|
+
|
|
63
|
+
### 🛡️ Security
|
|
64
|
+
|
|
65
|
+
- ✅ **Zero External Crypto** — All cryptography via native `node:crypto` (scrypt, AES-256-GCM, HMAC-SHA1, TOTP)
|
|
66
|
+
- ✅ **Brute-Force Protection** — Configurable rate limiting per email + tenant
|
|
67
|
+
- ✅ **Session Management** — Track active sessions with FIFO eviction and new-session alerts
|
|
68
|
+
- ✅ **HttpOnly Cookies** — Secure, SameSite, path-scoped refresh tokens by default
|
|
69
|
+
- ✅ **Timing-Safe Comparisons** — All secret comparisons use `crypto.timingSafeEqual`
|
|
70
|
+
- ✅ **JWT Revocation** — Instant access token revocation via Redis JTI blacklist
|
|
71
|
+
|
|
72
|
+
### 🏢 Multi-Tenant & Platform
|
|
73
|
+
|
|
74
|
+
- ✅ **Tenant Isolation** — All operations scoped by `tenantId` with configurable resolver
|
|
75
|
+
- ✅ **Platform Admin Auth** — Separate token context and role hierarchy for super-admins
|
|
76
|
+
- ✅ **User Invitations** — Invite users with role assignment and configurable expiration
|
|
77
|
+
- ✅ **Role-Based Access Control** — Hierarchical roles with `@Roles()` decorator
|
|
78
|
+
|
|
79
|
+
### 🧩 Developer Experience
|
|
80
|
+
|
|
81
|
+
- ✅ **Full-Stack TypeScript** — Strict types shared across server and client
|
|
82
|
+
- ✅ **5 Subpath Exports** — Import only what you need, tree-shakeable
|
|
83
|
+
- ✅ **Dynamic Module** — Configure everything via `registerAsync()`, sensible defaults included
|
|
84
|
+
- ✅ **Interface-Driven** — Bring your own database and email provider
|
|
85
|
+
- ✅ **No Passport Required** — Guards validate JWT natively via `@nestjs/jwt`
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## 📦 Subpath Exports
|
|
90
|
+
|
|
91
|
+
One package, five entry points — import only what your app needs:
|
|
92
|
+
|
|
93
|
+
| Subpath | Import | Purpose | Dependencies |
|
|
94
|
+
| ----------- | ----------------------------- | ------------------------------------------- | :----------------: |
|
|
95
|
+
| **Server** | `@bymax-one/nest-auth` | NestJS module, guards, decorators, services | NestJS 11, ioredis |
|
|
96
|
+
| **Shared** | `@bymax-one/nest-auth/shared` | Types, constants, error codes | None |
|
|
97
|
+
| **Client** | `@bymax-one/nest-auth/client` | Fetch-based auth client | None |
|
|
98
|
+
| **React** | `@bymax-one/nest-auth/react` | Hooks & AuthProvider | React 19 |
|
|
99
|
+
| **Next.js** | `@bymax-one/nest-auth/nextjs` | Proxy, route handlers, JWT helpers | Next.js 16 |
|
|
100
|
+
|
|
101
|
+
```
|
|
102
|
+
shared (zero deps)
|
|
103
|
+
↗ ↖
|
|
104
|
+
server client
|
|
105
|
+
↑
|
|
106
|
+
react
|
|
107
|
+
↑
|
|
108
|
+
nextjs
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
---
|
|
112
|
+
|
|
113
|
+
## 🚀 Quick Start
|
|
114
|
+
|
|
115
|
+
### 1. Install
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
# Using pnpm (recommended)
|
|
119
|
+
pnpm add @bymax-one/nest-auth
|
|
120
|
+
|
|
121
|
+
# Using npm
|
|
122
|
+
npm install @bymax-one/nest-auth
|
|
123
|
+
|
|
124
|
+
# Using yarn
|
|
125
|
+
yarn add @bymax-one/nest-auth
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
> [!IMPORTANT]
|
|
129
|
+
> You must also install the required **peer dependencies** for the subpaths you use:
|
|
130
|
+
|
|
131
|
+
```bash
|
|
132
|
+
# Server subpath (required)
|
|
133
|
+
pnpm add @nestjs/common @nestjs/core @nestjs/jwt @nestjs/throttler @nestjs/websockets ioredis class-validator class-transformer reflect-metadata
|
|
134
|
+
|
|
135
|
+
# React subpath (optional)
|
|
136
|
+
pnpm add react
|
|
137
|
+
|
|
138
|
+
# Next.js subpath (optional)
|
|
139
|
+
pnpm add next react
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
> [!IMPORTANT]
|
|
143
|
+
> Requires `@nestjs/throttler >= 6.0.0` for `AUTH_THROTTLE_CONFIGS` decorators to be honored.
|
|
144
|
+
|
|
145
|
+
### 2. Implement the Repository Interface
|
|
146
|
+
|
|
147
|
+
The package defines **what** it needs — your app provides **how**. The consumer maps the abstract `AuthUser` fields onto its own database schema (column names, indexes, soft-delete columns are entirely up to you). The only invariant is that `passwordHash` MUST be persisted exactly as supplied by the library — it is the output of `node:crypto` scrypt and re-hashing or transforming it will break login.
|
|
148
|
+
|
|
149
|
+
```typescript
|
|
150
|
+
// user.repository.ts
|
|
151
|
+
import { Injectable } from '@nestjs/common'
|
|
152
|
+
import type {
|
|
153
|
+
AuthUser,
|
|
154
|
+
CreateUserData,
|
|
155
|
+
CreateWithOAuthData,
|
|
156
|
+
IUserRepository,
|
|
157
|
+
UpdateMfaData
|
|
158
|
+
} from '@bymax-one/nest-auth'
|
|
159
|
+
import { PrismaService } from './prisma.service'
|
|
160
|
+
|
|
161
|
+
@Injectable()
|
|
162
|
+
export class PrismaUserRepository implements IUserRepository {
|
|
163
|
+
constructor(private readonly prisma: PrismaService) {}
|
|
164
|
+
|
|
165
|
+
async findById(id: string, tenantId?: string): Promise<AuthUser | null> {
|
|
166
|
+
const where = tenantId ? { id, tenantId } : { id }
|
|
167
|
+
return this.prisma.user.findFirst({ where })
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async findByEmail(email: string, tenantId: string): Promise<AuthUser | null> {
|
|
171
|
+
return this.prisma.user.findUnique({
|
|
172
|
+
where: { email_tenantId: { email: email.toLowerCase(), tenantId } }
|
|
173
|
+
})
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async create(data: CreateUserData): Promise<AuthUser> {
|
|
177
|
+
return this.prisma.user.create({
|
|
178
|
+
data: {
|
|
179
|
+
email: data.email.toLowerCase(),
|
|
180
|
+
name: data.name,
|
|
181
|
+
passwordHash: data.passwordHash,
|
|
182
|
+
role: data.role ?? 'user',
|
|
183
|
+
status: data.status ?? 'pending',
|
|
184
|
+
tenantId: data.tenantId,
|
|
185
|
+
emailVerified: data.emailVerified ?? false,
|
|
186
|
+
mfaEnabled: false
|
|
187
|
+
}
|
|
188
|
+
})
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
async updatePassword(id: string, passwordHash: string): Promise<void> {
|
|
192
|
+
await this.prisma.user.update({ where: { id }, data: { passwordHash } })
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async updateMfa(id: string, data: UpdateMfaData): Promise<void> {
|
|
196
|
+
await this.prisma.user.update({
|
|
197
|
+
where: { id },
|
|
198
|
+
data: {
|
|
199
|
+
mfaEnabled: data.mfaEnabled,
|
|
200
|
+
mfaSecret: data.mfaSecret,
|
|
201
|
+
mfaRecoveryCodes: data.mfaRecoveryCodes ?? []
|
|
202
|
+
}
|
|
203
|
+
})
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async updateLastLogin(id: string): Promise<void> {
|
|
207
|
+
await this.prisma.user.update({ where: { id }, data: { lastLoginAt: new Date() } })
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async updateStatus(id: string, status: string): Promise<void> {
|
|
211
|
+
await this.prisma.user.update({ where: { id }, data: { status } })
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async updateEmailVerified(id: string, verified: boolean): Promise<void> {
|
|
215
|
+
await this.prisma.user.update({ where: { id }, data: { emailVerified: verified } })
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
async findByOAuthId(
|
|
219
|
+
provider: string,
|
|
220
|
+
providerId: string,
|
|
221
|
+
tenantId: string
|
|
222
|
+
): Promise<AuthUser | null> {
|
|
223
|
+
return this.prisma.user.findFirst({
|
|
224
|
+
where: { oauthProvider: provider, oauthProviderId: providerId, tenantId }
|
|
225
|
+
})
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async linkOAuth(userId: string, provider: string, providerId: string): Promise<void> {
|
|
229
|
+
await this.prisma.user.update({
|
|
230
|
+
where: { id: userId },
|
|
231
|
+
data: { oauthProvider: provider, oauthProviderId: providerId }
|
|
232
|
+
})
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async createWithOAuth(data: CreateWithOAuthData): Promise<AuthUser> {
|
|
236
|
+
return this.prisma.user.create({
|
|
237
|
+
data: {
|
|
238
|
+
email: data.email.toLowerCase(),
|
|
239
|
+
name: data.name,
|
|
240
|
+
passwordHash: null,
|
|
241
|
+
role: data.role ?? 'user',
|
|
242
|
+
status: data.status ?? 'active',
|
|
243
|
+
tenantId: data.tenantId,
|
|
244
|
+
emailVerified: data.emailVerified ?? true,
|
|
245
|
+
oauthProvider: data.oauthProvider,
|
|
246
|
+
oauthProviderId: data.oauthProviderId,
|
|
247
|
+
mfaEnabled: false
|
|
248
|
+
}
|
|
249
|
+
})
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
### 3. Implement the Email Provider Interface
|
|
255
|
+
|
|
256
|
+
Email delivery is fully delegated to the consumer — the library never imports a mailer SDK. Implement `IEmailProvider` with your transport of choice (Resend, SendGrid, SES, Nodemailer) and bind it to the `BYMAX_AUTH_EMAIL_PROVIDER` token.
|
|
257
|
+
|
|
258
|
+
> [!WARNING]
|
|
259
|
+
> Any user-supplied value (display name, tenant name, inviter name) interpolated into HTML email bodies MUST be escaped to prevent stored XSS in notification content. Tokens and OTPs are library-generated and safe, but `inviterName`, `tenantName`, device strings, and any consumer-supplied placeholder are attacker-controllable.
|
|
260
|
+
|
|
261
|
+
```typescript
|
|
262
|
+
// email.provider.ts
|
|
263
|
+
import { Injectable } from '@nestjs/common'
|
|
264
|
+
import type { IEmailProvider, InviteData, SessionInfo } from '@bymax-one/nest-auth'
|
|
265
|
+
import { Resend } from 'resend'
|
|
266
|
+
|
|
267
|
+
const escapeHtml = (s: string): string =>
|
|
268
|
+
s.replace(/&/g, '&')
|
|
269
|
+
.replace(/</g, '<')
|
|
270
|
+
.replace(/>/g, '>')
|
|
271
|
+
.replace(/"/g, '"')
|
|
272
|
+
.replace(/'/g, ''')
|
|
273
|
+
|
|
274
|
+
@Injectable()
|
|
275
|
+
export class ResendEmailProvider implements IEmailProvider {
|
|
276
|
+
private readonly client = new Resend(process.env.RESEND_API_KEY!)
|
|
277
|
+
private readonly from = 'no-reply@example.com'
|
|
278
|
+
private readonly appUrl = process.env.APP_URL!
|
|
279
|
+
|
|
280
|
+
async sendPasswordResetToken(email: string, token: string, _locale?: string): Promise<void> {
|
|
281
|
+
const url = `${this.appUrl}/reset-password?token=${encodeURIComponent(token)}`
|
|
282
|
+
await this.client.emails.send({
|
|
283
|
+
from: this.from,
|
|
284
|
+
to: email,
|
|
285
|
+
subject: 'Reset your password',
|
|
286
|
+
html: `<p>Click <a href="${url}">here</a> to reset your password.</p>`
|
|
287
|
+
})
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
async sendPasswordResetOtp(email: string, otp: string, _locale?: string): Promise<void> {
|
|
291
|
+
await this.client.emails.send({
|
|
292
|
+
from: this.from,
|
|
293
|
+
to: email,
|
|
294
|
+
subject: 'Your password reset code',
|
|
295
|
+
html: `<p>Your code is <strong>${otp}</strong>. It expires in 10 minutes.</p>`
|
|
296
|
+
})
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
async sendEmailVerificationOtp(email: string, otp: string, _locale?: string): Promise<void> {
|
|
300
|
+
await this.client.emails.send({
|
|
301
|
+
from: this.from,
|
|
302
|
+
to: email,
|
|
303
|
+
subject: 'Verify your email',
|
|
304
|
+
html: `<p>Your verification code is <strong>${otp}</strong>.</p>`
|
|
305
|
+
})
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
async sendMfaEnabledNotification(email: string, _locale?: string): Promise<void> {
|
|
309
|
+
await this.client.emails.send({
|
|
310
|
+
from: this.from,
|
|
311
|
+
to: email,
|
|
312
|
+
subject: 'MFA enabled on your account',
|
|
313
|
+
html: '<p>Two-factor authentication has been enabled. If this was not you, contact support immediately.</p>'
|
|
314
|
+
})
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
async sendMfaDisabledNotification(email: string, _locale?: string): Promise<void> {
|
|
318
|
+
await this.client.emails.send({
|
|
319
|
+
from: this.from,
|
|
320
|
+
to: email,
|
|
321
|
+
subject: 'MFA disabled on your account',
|
|
322
|
+
html: '<p>Two-factor authentication has been disabled. If this was not you, contact support immediately.</p>'
|
|
323
|
+
})
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
async sendNewSessionAlert(
|
|
327
|
+
email: string,
|
|
328
|
+
sessionInfo: SessionInfo,
|
|
329
|
+
_locale?: string
|
|
330
|
+
): Promise<void> {
|
|
331
|
+
await this.client.emails.send({
|
|
332
|
+
from: this.from,
|
|
333
|
+
to: email,
|
|
334
|
+
subject: 'New sign-in to your account',
|
|
335
|
+
html: `
|
|
336
|
+
<p>New session detected:</p>
|
|
337
|
+
<ul>
|
|
338
|
+
<li>Device: ${escapeHtml(sessionInfo.device)}</li>
|
|
339
|
+
<li>IP: ${escapeHtml(sessionInfo.ip)}</li>
|
|
340
|
+
<li>Session: ${escapeHtml(sessionInfo.sessionHash)}</li>
|
|
341
|
+
</ul>
|
|
342
|
+
`
|
|
343
|
+
})
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
async sendInvitation(
|
|
347
|
+
email: string,
|
|
348
|
+
inviteData: InviteData,
|
|
349
|
+
_locale?: string
|
|
350
|
+
): Promise<void> {
|
|
351
|
+
const url = `${this.appUrl}/accept-invite?token=${encodeURIComponent(inviteData.inviteToken)}`
|
|
352
|
+
await this.client.emails.send({
|
|
353
|
+
from: this.from,
|
|
354
|
+
to: email,
|
|
355
|
+
subject: `You have been invited to ${inviteData.tenantName}`,
|
|
356
|
+
html: `
|
|
357
|
+
<p><strong>${escapeHtml(inviteData.inviterName)}</strong> invited you to join
|
|
358
|
+
<strong>${escapeHtml(inviteData.tenantName)}</strong>.</p>
|
|
359
|
+
<p><a href="${url}">Accept invitation</a></p>
|
|
360
|
+
<p>This link expires on ${inviteData.expiresAt.toUTCString()}.</p>
|
|
361
|
+
`
|
|
362
|
+
})
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
Wire it via `extraProviders` alongside the user repository:
|
|
368
|
+
|
|
369
|
+
```typescript
|
|
370
|
+
import { BYMAX_AUTH_EMAIL_PROVIDER } from '@bymax-one/nest-auth'
|
|
371
|
+
|
|
372
|
+
extraProviders: [
|
|
373
|
+
{ provide: BYMAX_AUTH_EMAIL_PROVIDER, useClass: ResendEmailProvider }
|
|
374
|
+
]
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
### 4. Register the Module
|
|
378
|
+
|
|
379
|
+
The user repository and Redis client are provided via NestJS dependency injection tokens — not as direct config fields. This follows the [NestJS custom providers pattern](https://docs.nestjs.com/fundamentals/custom-providers) and ensures the DI container manages all dependencies correctly.
|
|
380
|
+
|
|
381
|
+
```typescript
|
|
382
|
+
// app.module.ts
|
|
383
|
+
import { Module } from '@nestjs/common'
|
|
384
|
+
import {
|
|
385
|
+
BymaxAuthModule,
|
|
386
|
+
BYMAX_AUTH_USER_REPOSITORY,
|
|
387
|
+
BYMAX_AUTH_REDIS_CLIENT
|
|
388
|
+
} from '@bymax-one/nest-auth'
|
|
389
|
+
|
|
390
|
+
@Module({
|
|
391
|
+
imports: [
|
|
392
|
+
BymaxAuthModule.registerAsync({
|
|
393
|
+
imports: [ConfigModule, DatabaseModule, RedisModule],
|
|
394
|
+
useFactory: (config: ConfigService) => ({
|
|
395
|
+
jwt: {
|
|
396
|
+
secret: config.get('JWT_SECRET'), // min 32 chars, high entropy
|
|
397
|
+
accessExpiresIn: '15m',
|
|
398
|
+
refreshExpiresInDays: 7
|
|
399
|
+
},
|
|
400
|
+
tokenDelivery: 'cookie', // 'cookie' | 'bearer' | 'both'
|
|
401
|
+
roles: {
|
|
402
|
+
hierarchy: {
|
|
403
|
+
admin: ['manager', 'user'],
|
|
404
|
+
manager: ['user'],
|
|
405
|
+
user: []
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
}),
|
|
409
|
+
inject: [ConfigService],
|
|
410
|
+
extraProviders: [
|
|
411
|
+
{
|
|
412
|
+
provide: BYMAX_AUTH_USER_REPOSITORY,
|
|
413
|
+
useClass: PrismaUserRepository
|
|
414
|
+
},
|
|
415
|
+
{
|
|
416
|
+
provide: BYMAX_AUTH_REDIS_CLIENT,
|
|
417
|
+
useFactory: (redis: RedisService) => redis.client,
|
|
418
|
+
inject: [RedisService]
|
|
419
|
+
}
|
|
420
|
+
]
|
|
421
|
+
})
|
|
422
|
+
]
|
|
423
|
+
})
|
|
424
|
+
export class AppModule {}
|
|
425
|
+
```
|
|
426
|
+
|
|
427
|
+
### 5. Protect Routes
|
|
428
|
+
|
|
429
|
+
```typescript
|
|
430
|
+
// users.controller.ts
|
|
431
|
+
import { Controller, Get, UseGuards } from '@nestjs/common'
|
|
432
|
+
import {
|
|
433
|
+
JwtAuthGuard,
|
|
434
|
+
RolesGuard,
|
|
435
|
+
Roles,
|
|
436
|
+
CurrentUser,
|
|
437
|
+
DashboardJwtPayload
|
|
438
|
+
} from '@bymax-one/nest-auth'
|
|
439
|
+
|
|
440
|
+
@Controller('users')
|
|
441
|
+
@UseGuards(JwtAuthGuard, RolesGuard)
|
|
442
|
+
export class UsersController {
|
|
443
|
+
@Get('me')
|
|
444
|
+
getProfile(@CurrentUser() user: DashboardJwtPayload) {
|
|
445
|
+
return { id: user.sub, role: user.role, tenantId: user.tenantId }
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
@Get()
|
|
449
|
+
@Roles('admin')
|
|
450
|
+
listUsers() {
|
|
451
|
+
// Only accessible by admins (and above in hierarchy)
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
```
|
|
455
|
+
|
|
456
|
+
### 6. Frontend Integration (React)
|
|
457
|
+
|
|
458
|
+
Build an `AuthClient` once with `createAuthClient`, then hand it to
|
|
459
|
+
`AuthProvider`. Hooks (`useSession`, `useAuth`, `useAuthStatus`) read
|
|
460
|
+
the context populated by the provider.
|
|
461
|
+
|
|
462
|
+
```tsx
|
|
463
|
+
// app/providers.tsx
|
|
464
|
+
'use client'
|
|
465
|
+
import { AuthProvider } from '@bymax-one/nest-auth/react'
|
|
466
|
+
import { createAuthClient } from '@bymax-one/nest-auth/client'
|
|
467
|
+
|
|
468
|
+
const authClient = createAuthClient({
|
|
469
|
+
// Same-origin calls go through the Next.js proxy routes under
|
|
470
|
+
// `/api/auth/*`. Set `baseUrl` only when calling a cross-origin API.
|
|
471
|
+
})
|
|
472
|
+
|
|
473
|
+
export function Providers({ children }: { children: React.ReactNode }) {
|
|
474
|
+
return (
|
|
475
|
+
<AuthProvider client={authClient} onSessionExpired={() => (location.href = '/login')}>
|
|
476
|
+
{children}
|
|
477
|
+
</AuthProvider>
|
|
478
|
+
)
|
|
479
|
+
}
|
|
480
|
+
```
|
|
481
|
+
|
|
482
|
+
```tsx
|
|
483
|
+
// app/(dashboard)/profile.tsx
|
|
484
|
+
'use client'
|
|
485
|
+
import { useAuth, useSession } from '@bymax-one/nest-auth/react'
|
|
486
|
+
|
|
487
|
+
export function Profile() {
|
|
488
|
+
const { user, status } = useSession()
|
|
489
|
+
const { logout } = useAuth()
|
|
490
|
+
|
|
491
|
+
if (status === 'loading') return <div>Loading…</div>
|
|
492
|
+
if (status === 'unauthenticated') return <div>Please log in</div>
|
|
493
|
+
|
|
494
|
+
return (
|
|
495
|
+
<div>
|
|
496
|
+
<p>Welcome, {user.name}!</p>
|
|
497
|
+
<button onClick={() => logout()}>Sign out</button>
|
|
498
|
+
</div>
|
|
499
|
+
)
|
|
500
|
+
}
|
|
501
|
+
```
|
|
502
|
+
|
|
503
|
+
### 7. Frontend Integration (Next.js 16)
|
|
504
|
+
|
|
505
|
+
Mount the Edge-Runtime auth proxy at the project root and expose the
|
|
506
|
+
three `/api/auth/*` route handlers. The proxy handles anti-redirect-
|
|
507
|
+
loop protection, RBAC, status blocking, and background-request
|
|
508
|
+
detection; the route handlers bridge the browser to your NestJS
|
|
509
|
+
backend.
|
|
510
|
+
|
|
511
|
+
```typescript
|
|
512
|
+
// proxy.ts — Next.js 16 Edge middleware
|
|
513
|
+
import { createAuthProxy } from '@bymax-one/nest-auth/nextjs'
|
|
514
|
+
|
|
515
|
+
export const { proxy } = createAuthProxy({
|
|
516
|
+
publicRoutes: ['/', '/auth/login', '/auth/register'],
|
|
517
|
+
publicRoutesRedirectIfAuthenticated: ['/auth/login', '/auth/register'],
|
|
518
|
+
protectedRoutes: [
|
|
519
|
+
{ pattern: '/dashboard/:path*', allowedRoles: ['admin', 'member'] },
|
|
520
|
+
{ pattern: '/admin/:path*', allowedRoles: ['admin'] }
|
|
521
|
+
],
|
|
522
|
+
loginPath: '/auth/login',
|
|
523
|
+
getDefaultDashboard: (role) => (role === 'admin' ? '/dashboard/admin' : '/dashboard'),
|
|
524
|
+
apiBase: process.env.API_BASE_URL!,
|
|
525
|
+
jwtSecret: process.env.JWT_SECRET,
|
|
526
|
+
cookieNames: {
|
|
527
|
+
access: 'access_token',
|
|
528
|
+
refresh: 'refresh_token',
|
|
529
|
+
hasSession: 'has_session'
|
|
530
|
+
},
|
|
531
|
+
userHeaders: {
|
|
532
|
+
userId: 'x-user-id',
|
|
533
|
+
role: 'x-user-role',
|
|
534
|
+
tenantId: 'x-tenant-id',
|
|
535
|
+
tenantDomain: 'x-tenant-domain'
|
|
536
|
+
},
|
|
537
|
+
blockedUserStatuses: ['BANNED', 'INACTIVE', 'EXPIRED']
|
|
538
|
+
})
|
|
539
|
+
|
|
540
|
+
export const config = {
|
|
541
|
+
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)']
|
|
542
|
+
}
|
|
543
|
+
```
|
|
544
|
+
|
|
545
|
+
```typescript
|
|
546
|
+
// app/api/auth/silent-refresh/route.ts
|
|
547
|
+
import { createSilentRefreshHandler } from '@bymax-one/nest-auth/nextjs'
|
|
548
|
+
|
|
549
|
+
export const GET = createSilentRefreshHandler({
|
|
550
|
+
apiBase: process.env.API_BASE_URL!,
|
|
551
|
+
loginPath: '/auth/login',
|
|
552
|
+
cookieNames: {
|
|
553
|
+
access: 'access_token',
|
|
554
|
+
refresh: 'refresh_token',
|
|
555
|
+
hasSession: 'has_session'
|
|
556
|
+
}
|
|
557
|
+
})
|
|
558
|
+
```
|
|
559
|
+
|
|
560
|
+
```typescript
|
|
561
|
+
// app/api/auth/client-refresh/route.ts
|
|
562
|
+
import { createClientRefreshHandler } from '@bymax-one/nest-auth/nextjs'
|
|
563
|
+
|
|
564
|
+
export const POST = createClientRefreshHandler({ apiBase: process.env.API_BASE_URL! })
|
|
565
|
+
```
|
|
566
|
+
|
|
567
|
+
```typescript
|
|
568
|
+
// app/api/auth/logout/route.ts
|
|
569
|
+
import { createLogoutHandler } from '@bymax-one/nest-auth/nextjs'
|
|
570
|
+
|
|
571
|
+
export const POST = createLogoutHandler({
|
|
572
|
+
apiBase: process.env.API_BASE_URL!,
|
|
573
|
+
mode: 'redirect',
|
|
574
|
+
loginPath: '/auth/login',
|
|
575
|
+
cookieNames: {
|
|
576
|
+
access: 'access_token',
|
|
577
|
+
refresh: 'refresh_token',
|
|
578
|
+
hasSession: 'has_session'
|
|
579
|
+
}
|
|
580
|
+
})
|
|
581
|
+
```
|
|
582
|
+
|
|
583
|
+
---
|
|
584
|
+
|
|
585
|
+
## ⚙️ Configuration
|
|
586
|
+
|
|
587
|
+
All options are configurable via `registerAsync()`. Here are the key configuration groups:
|
|
588
|
+
|
|
589
|
+
| Group | Key Options | Default |
|
|
590
|
+
| ----------------- | --------------------------------------------------------------------------- | ------------------------- |
|
|
591
|
+
| **jwt** | `secret` (required), `accessExpiresIn`, `refreshExpiresInDays`, `algorithm` | `15m`, `7d`, `HS256` |
|
|
592
|
+
| **password** | `costFactor`, `blockSize`, `parallelization` | scrypt N=2¹⁵, r=8, p=1 |
|
|
593
|
+
| **tokenDelivery** | `'cookie'` \| `'bearer'` \| `'both'` | `'cookie'` |
|
|
594
|
+
| **cookies** | `accessTokenName`, `refreshTokenName`, `sessionSignalName`, `refreshCookiePath`, `resolveDomains` | — (see cookie section) |
|
|
595
|
+
| **mfa** | `encryptionKey`, `issuer`, `totpWindow`, `recoveryCodeCount` | — |
|
|
596
|
+
| **sessions** | `enabled`, `defaultMaxSessions`, `maxSessionsResolver`, `evictionStrategy` | `false`, `5`, —, `'fifo'` |
|
|
597
|
+
| **bruteForce** | `maxAttempts`, `windowSeconds` | `5`, `900` |
|
|
598
|
+
| **passwordReset** | `method` (`'token'` \| `'otp'`), `otpLength`, `otpTtlSeconds` | `'token'` |
|
|
599
|
+
| **platform** | `enabled` | `false` |
|
|
600
|
+
| **invitations** | `enabled`, `tokenTtlSeconds` | `false` |
|
|
601
|
+
| **roles** | `hierarchy` (required), `platformHierarchy` | — |
|
|
602
|
+
| **oauth** | `google: { clientId, clientSecret, callbackUrl }` | — |
|
|
603
|
+
| **controllers** | Toggle individual controllers on/off | All enabled |
|
|
604
|
+
|
|
605
|
+
> [!NOTE]
|
|
606
|
+
> When a feature is not configured (e.g., `mfa`, `sessions`, `platform`), its controllers and services are **not registered** in the NestJS container — zero overhead.
|
|
607
|
+
|
|
608
|
+
---
|
|
609
|
+
|
|
610
|
+
## 🏗️ Architecture
|
|
611
|
+
|
|
612
|
+
The package runs **inside** your NestJS application as a dynamic module — not as a separate service:
|
|
613
|
+
|
|
614
|
+
```
|
|
615
|
+
┌─────────────────────────────────────────────┐
|
|
616
|
+
│ Your NestJS Application │
|
|
617
|
+
│ │
|
|
618
|
+
│ ┌───────────────────────────────────────┐ │
|
|
619
|
+
│ │ @bymax-one/nest-auth │ │
|
|
620
|
+
│ │ │ │
|
|
621
|
+
│ │ Controllers ←→ Services ←→ Redis │ │
|
|
622
|
+
│ │ Guards ←→ Crypto (node:crypto) │ │
|
|
623
|
+
│ │ Decorators ←→ Token Manager (JWT) │ │
|
|
624
|
+
│ └──────────┬────────────┬───────────────┘ │
|
|
625
|
+
│ │ │ │
|
|
626
|
+
│ ┌───────▼──┐ ┌──────▼───────┐ │
|
|
627
|
+
│ │ IUser │ │ IEmail │ │
|
|
628
|
+
│ │ Repo │ │ Provider │ │
|
|
629
|
+
│ │ (yours) │ │ (yours) │ │
|
|
630
|
+
│ └──────────┘ └──────────────┘ │
|
|
631
|
+
└─────────────────────────────────────────────┘
|
|
632
|
+
```
|
|
633
|
+
|
|
634
|
+
### Design Principles
|
|
635
|
+
|
|
636
|
+
| Principle | Description |
|
|
637
|
+
| -------------------------- | ------------------------------------------------------------------------------------------------------- |
|
|
638
|
+
| **🔌 Interface-Driven** | Define contracts, inject implementations — works with Prisma, TypeORM, Drizzle, or any SQL ORM |
|
|
639
|
+
| **🔒 Secure by Default** | scrypt hashing, HttpOnly cookies, JWT blacklisting, brute-force protection — all enabled out of the box |
|
|
640
|
+
| **🪶 Zero Runtime Deps** | `"dependencies": {}` — adds no runtime deps of its own; crypto is native `node:crypto`. Required peers (NestJS, ioredis…) come from your app |
|
|
641
|
+
| **🌳 Tree-Shakeable** | `sideEffects: false`, subpath exports, ESM + CJS dual output |
|
|
642
|
+
| **⚡ Conditional Loading** | Unconfigured features don't register — no wasted memory or startup time |
|
|
643
|
+
|
|
644
|
+
---
|
|
645
|
+
|
|
646
|
+
## 🔐 Security Model
|
|
647
|
+
|
|
648
|
+
The security architecture follows established standards and industry best practices.
|
|
649
|
+
|
|
650
|
+
### JWT Token Type Discrimination
|
|
651
|
+
|
|
652
|
+
Every token carries a `type` claim that guards validate before accepting:
|
|
653
|
+
|
|
654
|
+
| Token type | Issued when | Accepted by |
|
|
655
|
+
| ----------------- | ----------------------------------------- | ---------------------- |
|
|
656
|
+
| `'dashboard'` | Successful login or MFA challenge | `JwtAuthGuard` |
|
|
657
|
+
| `'platform'` | Platform admin login or MFA challenge | `JwtPlatformGuard` |
|
|
658
|
+
| `'mfa_challenge'` | Login with MFA enabled (pre-verification) | MFA challenge endpoint |
|
|
659
|
+
|
|
660
|
+
This prevents **token type confusion attacks** — a class of vulnerability documented by [OWASP](https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/06-Session_Management_Testing/10-Testing_JSON_Web_Tokens) where a token issued for one purpose is accepted by another. The same pattern is used by AWS Cognito (`token_use` claim) and recommended by [Curity's JWT best practices guide](https://curity.io/resources/learn/jwt-best-practices/).
|
|
661
|
+
|
|
662
|
+
`JwtPlatformGuard` returns `PLATFORM_AUTH_REQUIRED` (not the generic `TOKEN_INVALID`) when a dashboard token is submitted to a platform route — so clients can distinguish wrong-context from expired/invalid errors.
|
|
663
|
+
|
|
664
|
+
### Separate Auth Contexts for Multi-Tenant SaaS
|
|
665
|
+
|
|
666
|
+
Platform admins and tenant users are fully isolated stacks — separate repositories, JWT payloads, guards, and routes. A platform admin token cannot access tenant routes, and a tenant token cannot access platform routes, regardless of role. This aligns with the architecture recommended by AWS, Logto, and WorkOS for multi-tenant SaaS platforms.
|
|
667
|
+
|
|
668
|
+
The `tenantId` is always extracted from the validated JWT — never from the request body — preventing tenant spoofing at the architecture level.
|
|
669
|
+
|
|
670
|
+
### Token Revocation via Redis JTI Blacklist
|
|
671
|
+
|
|
672
|
+
Access tokens are short-lived (default 15 minutes) and immediately revocable via a Redis JTI blacklist. Refresh tokens rotate on every use with a configurable grace window to handle concurrent requests. This is the industry-standard hybrid approach used by Auth0, Okta, and SuperTokens — combining short lifetimes for low-latency revocation with rotating refresh tokens for session continuity.
|
|
673
|
+
|
|
674
|
+
### Password Hashing
|
|
675
|
+
|
|
676
|
+
Passwords are hashed with **scrypt** via `node:crypto`, which is memory-hard and resistant to GPU-based brute-force attacks. All secret comparisons use `crypto.timingSafeEqual` for constant-time evaluation — [a requirement explicitly documented](https://nodejs.org/api/crypto.html#cryptotimingsafeequala-b) in the Node.js crypto documentation.
|
|
677
|
+
|
|
678
|
+
### No External Cryptographic Dependencies
|
|
679
|
+
|
|
680
|
+
All security-critical operations use the OpenSSL-backed `node:crypto` module — no bcrypt, argon2, otpauth, uuid, or nanoid packages. This eliminates the supply chain attack surface for the most sensitive code paths.
|
|
681
|
+
|
|
682
|
+
### Security Checklist
|
|
683
|
+
|
|
684
|
+
When integrating `@bymax-one/nest-auth` in production, verify each of the following:
|
|
685
|
+
|
|
686
|
+
- `cookies.resolveDomains` MUST validate against an allowlist of configured domains
|
|
687
|
+
- MFA recovery without TOTP requires admin intervention (no self-service)
|
|
688
|
+
- `@MaxLength(128)` on password DTOs prevents algorithmic-DoS via oversized scrypt inputs
|
|
689
|
+
- JWT algorithm pinning to HS256 prevents algorithm-confusion attacks
|
|
690
|
+
- Constant-time comparisons via `crypto.timingSafeEqual` for all secret comparisons
|
|
691
|
+
- HttpOnly cookies; `Secure` enforced in production; `SameSite=Strict` for refresh tokens
|
|
692
|
+
|
|
693
|
+
---
|
|
694
|
+
|
|
695
|
+
## 🛡️ Security Table
|
|
696
|
+
|
|
697
|
+
| Layer | Implementation |
|
|
698
|
+
| ----------------- | -------------------------------------------------- |
|
|
699
|
+
| Password Hashing | `node:crypto` scrypt (N=2¹⁵, r=8, p=1, keyLen=64) |
|
|
700
|
+
| MFA Encryption | AES-256-GCM with 12-byte random IV per call |
|
|
701
|
+
| TOTP | HMAC-SHA1 per RFC 4226/6238, ±1 step window |
|
|
702
|
+
| Token Generation | `crypto.randomBytes(32)` — 256 bits of entropy |
|
|
703
|
+
| Secret Comparison | `crypto.timingSafeEqual` (constant-time) |
|
|
704
|
+
| JWT | HS256 via `@nestjs/jwt`, JTI blacklist via Redis |
|
|
705
|
+
| Cookies | HttpOnly, Secure, SameSite=Strict, path-scoped |
|
|
706
|
+
| Brute-Force | Redis atomic counters per HMAC(email, jwt.secret) |
|
|
707
|
+
| CSRF (OAuth) | 64-char hex state nonce, single-use via `getdel()` |
|
|
708
|
+
|
|
709
|
+
> [!IMPORTANT]
|
|
710
|
+
> This package uses **zero external cryptographic dependencies**. All operations use Node.js native `node:crypto`, eliminating supply chain attack vectors for critical security code.
|
|
711
|
+
|
|
712
|
+
---
|
|
713
|
+
|
|
714
|
+
## 🧱 Tech Stack
|
|
715
|
+
|
|
716
|
+
<p>
|
|
717
|
+
<img src="https://img.shields.io/badge/NestJS-11-E0234E?style=flat-square&logo=nestjs&logoColor=white" alt="NestJS" />
|
|
718
|
+
<img src="https://img.shields.io/badge/TypeScript-strict-3178C6?style=flat-square&logo=typescript&logoColor=white" alt="TypeScript" />
|
|
719
|
+
<img src="https://img.shields.io/badge/React-19-61DAFB?style=flat-square&logo=react&logoColor=black" alt="React" />
|
|
720
|
+
<img src="https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white" alt="Next.js" />
|
|
721
|
+
<img src="https://img.shields.io/badge/Node.js-24%2B-339933?style=flat-square&logo=node.js&logoColor=white" alt="Node.js" />
|
|
722
|
+
<img src="https://img.shields.io/badge/Redis-7%2B-DC382D?style=flat-square&logo=redis&logoColor=white" alt="Redis" />
|
|
723
|
+
<img src="https://img.shields.io/badge/Jest-29-C21325?style=flat-square&logo=jest&logoColor=white" alt="Jest" />
|
|
724
|
+
</p>
|
|
725
|
+
|
|
726
|
+
---
|
|
727
|
+
|
|
728
|
+
## 🧪 Testing & Quality
|
|
729
|
+
|
|
730
|
+
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**.
|
|
731
|
+
|
|
732
|
+
- ✅ **100% line coverage** — statements, branches, functions, and lines, enforced as a release gate across unit + e2e
|
|
733
|
+
- ✅ **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
|
|
734
|
+
- ✅ **1,980 tests** — unit and end-to-end, spanning all five subpaths
|
|
735
|
+
- ✅ **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
|
|
736
|
+
|
|
737
|
+
```bash
|
|
738
|
+
pnpm test # unit suite
|
|
739
|
+
pnpm test:cov:all # unit + e2e, 100% coverage gate
|
|
740
|
+
pnpm mutation # Stryker mutation testing
|
|
741
|
+
```
|
|
742
|
+
|
|
743
|
+
> [!NOTE]
|
|
744
|
+
> Line coverage proves a line _executed_ under test; mutation testing proves a test _would fail_ if that line were wrong. The full methodology and per-area breakdown are in [docs/mutation_testing_results.md](./docs/mutation_testing_results.md).
|
|
745
|
+
|
|
746
|
+
---
|
|
747
|
+
|
|
748
|
+
## 📖 API Reference
|
|
749
|
+
|
|
750
|
+
### HTTP Endpoints
|
|
751
|
+
|
|
752
|
+
Conditionally registered controllers (mfa, sessions, platform, invitations, oauth, password-reset) only mount their endpoints when the corresponding feature is enabled in `BymaxAuthModule.registerAsync()`.
|
|
753
|
+
|
|
754
|
+
| Method | Path | Auth / Guard | Description |
|
|
755
|
+
| ------ | ----------------------------- | ------------------------------------------- | ---------------------------------------------------------- |
|
|
756
|
+
| POST | `/register` | Public | Register a new dashboard user and issue tokens |
|
|
757
|
+
| POST | `/login` | Public | Authenticate with email/password (may return MFA challenge) |
|
|
758
|
+
| POST | `/logout` | `JwtAuthGuard` | Revoke tokens and clear session |
|
|
759
|
+
| POST | `/refresh` | Public (refresh cookie) | Rotate refresh token, issue new access token |
|
|
760
|
+
| GET | `/me` | `JwtAuthGuard` | Current dashboard user payload |
|
|
761
|
+
| POST | `/verify-email` | Public | Verify email with OTP |
|
|
762
|
+
| POST | `/resend-verification` | Public | Resend email-verification OTP |
|
|
763
|
+
| POST | `/password/forgot-password` | Public | Request password reset (token or OTP) |
|
|
764
|
+
| POST | `/password/reset-password` | Public | Submit new password with reset token |
|
|
765
|
+
| POST | `/password/verify-otp` | Public | Verify password-reset OTP |
|
|
766
|
+
| POST | `/password/resend-otp` | Public | Resend password-reset OTP |
|
|
767
|
+
| POST | `/mfa/setup` | `JwtAuthGuard` | Generate TOTP secret and recovery codes |
|
|
768
|
+
| POST | `/mfa/verify-enable` | `JwtAuthGuard` | Confirm setup and enable MFA |
|
|
769
|
+
| POST | `/mfa/challenge` | Public + `@SkipMfa()` | Submit TOTP/recovery code after login |
|
|
770
|
+
| POST | `/mfa/disable` | `JwtAuthGuard` | Disable MFA for the current user |
|
|
771
|
+
| GET | `/sessions` | `JwtAuthGuard`, `UserStatusGuard` | List active sessions for the current user |
|
|
772
|
+
| DELETE | `/sessions/all` | `JwtAuthGuard`, `UserStatusGuard` | Revoke all sessions |
|
|
773
|
+
| DELETE | `/sessions/:id` | `JwtAuthGuard`, `UserStatusGuard` | Revoke a specific session |
|
|
774
|
+
| POST | `/invitations` | `JwtAuthGuard` | Create a tenant invitation |
|
|
775
|
+
| POST | `/invitations/accept` | Public | Accept an invitation and create the user |
|
|
776
|
+
| POST | `/platform/login` | Public | Platform admin login (separate token context) |
|
|
777
|
+
| POST | `/platform/mfa/challenge` | Public | Platform admin MFA challenge |
|
|
778
|
+
| GET | `/platform/me` | `JwtPlatformGuard` | Current platform admin payload |
|
|
779
|
+
| POST | `/platform/logout` | `JwtPlatformGuard` | Revoke platform tokens |
|
|
780
|
+
| POST | `/platform/refresh` | Public (platform refresh cookie) | Rotate platform refresh token |
|
|
781
|
+
| DELETE | `/platform/sessions` | `JwtPlatformGuard` | Revoke all platform sessions |
|
|
782
|
+
| GET | `/oauth/:provider` | Public + `@SkipMfa()` | Initiate OAuth authorization redirect |
|
|
783
|
+
| GET | `/oauth/:provider/callback` | Public + `@SkipMfa()` | Handle OAuth callback, exchange code, issue tokens |
|
|
784
|
+
|
|
785
|
+
### Server Guards
|
|
786
|
+
|
|
787
|
+
| Guard | Decorator | Purpose |
|
|
788
|
+
| -------------------- | ------------------------------- | ----------------------------------------------------------- |
|
|
789
|
+
| `JwtAuthGuard` | — | Validates JWT from cookie or `Authorization: Bearer` header |
|
|
790
|
+
| `RolesGuard` | `@Roles('admin')` | Hierarchical role check |
|
|
791
|
+
| `UserStatusGuard` | — | Blocks inactive/banned users (Redis-cached status) |
|
|
792
|
+
| `MfaRequiredGuard` | `@SkipMfa()` | Enforces MFA verification on protected routes |
|
|
793
|
+
| `JwtPlatformGuard` | — | Platform admin JWT validation (Bearer only) |
|
|
794
|
+
| `PlatformRolesGuard` | `@PlatformRoles('super_admin')` | Platform role hierarchy enforcement |
|
|
795
|
+
|
|
796
|
+
> [!NOTE]
|
|
797
|
+
> 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.
|
|
798
|
+
|
|
799
|
+
### Server Decorators
|
|
800
|
+
|
|
801
|
+
| Decorator | Usage |
|
|
802
|
+
| -------------------------- | ---------------------------------------------------------------------------- |
|
|
803
|
+
| `@CurrentUser()` | Extract JWT payload from request: `@CurrentUser() user: DashboardJwtPayload` |
|
|
804
|
+
| `@Roles(...roles)` | Set required roles: `@Roles('admin', 'manager')` |
|
|
805
|
+
| `@PlatformRoles(...roles)` | Set required platform roles: `@PlatformRoles('super_admin')` |
|
|
806
|
+
| `@Public()` | Mark route as public (skip JWT guard) |
|
|
807
|
+
| `@SkipMfa()` | Skip MFA verification for this route |
|
|
808
|
+
|
|
809
|
+
### React Hooks
|
|
810
|
+
|
|
811
|
+
| Hook | Returns |
|
|
812
|
+
| ----------------- | -------------------------------------------------------------------------------------------------------- |
|
|
813
|
+
| `useSession()` | `{ user, status, isLoading, refresh(), lastValidation }` — current session state and revalidation helper |
|
|
814
|
+
| `useAuth()` | `{ login(), logout(), register(), forgotPassword(), resetPassword() }` — auth actions |
|
|
815
|
+
| `useAuthStatus()` | `{ isAuthenticated, isLoading }` — derived state |
|
|
816
|
+
|
|
817
|
+
### Next.js Factories
|
|
818
|
+
|
|
819
|
+
| Factory | Type | Purpose |
|
|
820
|
+
| ------------------------------ | ------------ | ------------------------------- |
|
|
821
|
+
| `createAuthProxy()` | Proxy config | Auth-aware proxy for `proxy.ts` |
|
|
822
|
+
| `createSilentRefreshHandler()` | GET handler | iframe-based token refresh |
|
|
823
|
+
| `createClientRefreshHandler()` | POST handler | Client-triggered token refresh |
|
|
824
|
+
| `createLogoutHandler()` | POST handler | Clear tokens and session |
|
|
825
|
+
|
|
826
|
+
---
|
|
827
|
+
|
|
828
|
+
## 🗺️ Roadmap
|
|
829
|
+
|
|
830
|
+
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.
|
|
831
|
+
|
|
832
|
+
| Area | Item | Status |
|
|
833
|
+
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------- | --------- |
|
|
834
|
+
| OAuth providers | First-class `oauth.plugins` array so consumers can drop in GitHub / Microsoft / Apple plugins without forking the core | Planned |
|
|
835
|
+
| Error-message i18n | `BymaxAuthModule.forRoot({ messages })` override for `AUTH_ERROR_MESSAGES` (defaults stay Portuguese; English preset) | Planned |
|
|
836
|
+
| Refresh-token families | Family-level revocation: detect grace-window reuse as a stolen-token signal and invalidate the entire session family | Planned |
|
|
837
|
+
| Passwordless / magic link | `MagicLinkService` + email-delivered single-use link, reusing the existing `generateSecureToken` + `IEmailProvider` API | Exploring |
|
|
838
|
+
| Passkeys / WebAuthn | Optional WebAuthn primitive as an MFA method (and eventually a first-factor), behind a peer-dep-gated module | Exploring |
|
|
839
|
+
| Per-tenant configuration | Per-tenant overrides for session limits, MFA enforcement, and password policy resolved at request time | Exploring |
|
|
840
|
+
| Absolute session lifetime | Hard cap on refresh chains so a session rotated every 6 days does not live forever | Planned |
|
|
841
|
+
| Pluggable password policy | `IPasswordPolicy` interface for disallow-lists, complexity classes, and per-tenant rules | Planned |
|
|
842
|
+
| Custom token delivery modes | `ITokenDelivery` for non-cookie / non-bearer transports (custom headers, WebSocket handshakes, split client types) | Exploring |
|
|
843
|
+
|
|
844
|
+
> Track progress and discuss proposals on the [issues board](https://github.com/bymaxone/nest-auth/issues).
|
|
845
|
+
|
|
846
|
+
---
|
|
847
|
+
|
|
848
|
+
## 🤝 Contributing
|
|
849
|
+
|
|
850
|
+
Contributions are welcome! Please read our contributing guidelines before submitting a pull request.
|
|
851
|
+
|
|
852
|
+
```bash
|
|
853
|
+
# Clone the repository
|
|
854
|
+
git clone https://github.com/bymaxone/nest-auth.git
|
|
855
|
+
cd nest-auth
|
|
856
|
+
|
|
857
|
+
# Install dependencies
|
|
858
|
+
pnpm install
|
|
859
|
+
|
|
860
|
+
# Run tests
|
|
861
|
+
pnpm test
|
|
862
|
+
|
|
863
|
+
# Build
|
|
864
|
+
pnpm build
|
|
865
|
+
|
|
866
|
+
# Type check
|
|
867
|
+
pnpm typecheck
|
|
868
|
+
```
|
|
869
|
+
|
|
870
|
+
---
|
|
871
|
+
|
|
872
|
+
## 🔒 Security Policy
|
|
873
|
+
|
|
874
|
+
If you discover a security vulnerability, please **do not** open a public issue. Instead, email us at **security@bymax.one** with details. We take security seriously and will respond promptly.
|
|
875
|
+
|
|
876
|
+
---
|
|
877
|
+
|
|
878
|
+
## 📄 License
|
|
879
|
+
|
|
880
|
+
[MIT](./LICENSE) © [Bymax One](https://github.com/bymaxone)
|
|
881
|
+
|
|
882
|
+
---
|
|
883
|
+
|
|
884
|
+
<p align="center">
|
|
885
|
+
<sub>Built with ❤️ by <a href="https://github.com/bymaxone">Bymax One</a></sub>
|
|
886
|
+
</p>
|