@ilman00/authkit 2.0.0 → 2.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 +491 -0
- package/package.json +7 -2
package/Readme.md
ADDED
|
@@ -0,0 +1,491 @@
|
|
|
1
|
+
# @ilman00/authkit
|
|
2
|
+
|
|
3
|
+
Plug-and-play authentication for Express.js apps. Abstracts JWT auth, email verification, password reset, and RBAC into a few lines — without locking you into any database.
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/@ilman00/authkit)
|
|
6
|
+
[](./LICENSE)
|
|
7
|
+
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
## Features
|
|
11
|
+
|
|
12
|
+
- JWT access + refresh tokens (stateful or stateless)
|
|
13
|
+
- Refresh token rotation
|
|
14
|
+
- Email verification
|
|
15
|
+
- Forgot / reset password
|
|
16
|
+
- Change password (invalidates all sessions)
|
|
17
|
+
- Logout / logout from all devices
|
|
18
|
+
- Role-based access control (RBAC)
|
|
19
|
+
- Database-agnostic via the **Adapter Pattern**
|
|
20
|
+
- Fully typed with TypeScript
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
## Install
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
npm install @ilman00/authkit
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
> `express` is a peer dependency — install it separately if you haven't already.
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
## Quick Start
|
|
35
|
+
|
|
36
|
+
```typescript
|
|
37
|
+
import express from "express";
|
|
38
|
+
import {
|
|
39
|
+
init,
|
|
40
|
+
registerHandler,
|
|
41
|
+
loginHandler,
|
|
42
|
+
refreshHandler,
|
|
43
|
+
logoutHandler,
|
|
44
|
+
logoutAllHandler,
|
|
45
|
+
verifyEmailHandler,
|
|
46
|
+
forgotPasswordHandler,
|
|
47
|
+
resetPasswordHandler,
|
|
48
|
+
resendVerificationHandler,
|
|
49
|
+
changePasswordHandler,
|
|
50
|
+
protect,
|
|
51
|
+
} from "@ilman00/authkit";
|
|
52
|
+
|
|
53
|
+
const app = express();
|
|
54
|
+
app.use(express.json());
|
|
55
|
+
|
|
56
|
+
init({
|
|
57
|
+
secret: process.env.JWT_SECRET!,
|
|
58
|
+
adapter: {
|
|
59
|
+
findUserByEmail: (email) => db.findUserByEmail(email),
|
|
60
|
+
findUserById: (id) => db.findUserById(id),
|
|
61
|
+
createUser: (data) => db.createUser(data),
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
app.post("/register", registerHandler);
|
|
66
|
+
app.post("/login", loginHandler);
|
|
67
|
+
app.get("/profile", protect(), (req, res) => res.json(req.user));
|
|
68
|
+
|
|
69
|
+
app.listen(3000);
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
---
|
|
73
|
+
|
|
74
|
+
## Table of Contents
|
|
75
|
+
|
|
76
|
+
- [Configuration](#configuration)
|
|
77
|
+
- [Adapter Pattern](#adapter-pattern)
|
|
78
|
+
- [Routes](#routes)
|
|
79
|
+
- [RBAC](#rbac)
|
|
80
|
+
- [Email Features](#email-features)
|
|
81
|
+
- [Stateful Refresh Tokens](#stateful-refresh-tokens)
|
|
82
|
+
- [Adapters](#adapters)
|
|
83
|
+
- [MySQL2](#mysql2)
|
|
84
|
+
- [Prisma](#prisma)
|
|
85
|
+
- [Mongoose](#mongoose)
|
|
86
|
+
- [Token Expiry Reference](#token-expiry-reference)
|
|
87
|
+
- [Error Reference](#error-reference)
|
|
88
|
+
- [Version History](#version-history)
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## Configuration
|
|
93
|
+
|
|
94
|
+
Pass a config object to `init()` once at app startup — before registering any routes.
|
|
95
|
+
|
|
96
|
+
```typescript
|
|
97
|
+
init({
|
|
98
|
+
secret: process.env.JWT_SECRET!, // required
|
|
99
|
+
accessTokenExpiry: "15m", // default: '15m'
|
|
100
|
+
refreshTokenExpiry: "7d", // default: '7d'
|
|
101
|
+
verificationUrl: "https://myapp.com", // default: 'http://localhost:3000'
|
|
102
|
+
emailSender: async (to, subject, html) => { /* nodemailer etc. */ },
|
|
103
|
+
adapter: { /* see Adapter Pattern */ },
|
|
104
|
+
});
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
| Option | Type | Required | Description |
|
|
108
|
+
|---|---|---|---|
|
|
109
|
+
| `secret` | `string` | ✅ | JWT signing secret |
|
|
110
|
+
| `adapter` | `AuthAdapter` | ✅ | Database adapter object |
|
|
111
|
+
| `accessTokenExpiry` | `string` | — | Default `'15m'` |
|
|
112
|
+
| `refreshTokenExpiry` | `string` | — | Default `'7d'` |
|
|
113
|
+
| `verificationUrl` | `string` | — | Base URL for email links. Package appends `/verify-email?token=` and `/reset-password?token=` |
|
|
114
|
+
| `emailSender` | `function` | — | Required to use any email features |
|
|
115
|
+
|
|
116
|
+
---
|
|
117
|
+
|
|
118
|
+
## Adapter Pattern
|
|
119
|
+
|
|
120
|
+
The package never imports a database library. You provide an adapter object with methods that match your database. The package calls them internally.
|
|
121
|
+
|
|
122
|
+
### Required methods — all clients
|
|
123
|
+
|
|
124
|
+
```typescript
|
|
125
|
+
adapter: {
|
|
126
|
+
findUserByEmail: (email: string) => Promise<AuthUser | null>;
|
|
127
|
+
findUserById: (id: string) => Promise<AuthUser | null>;
|
|
128
|
+
createUser: (data: Partial<AuthUser>) => Promise<AuthUser>;
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
### Optional methods — email features
|
|
133
|
+
|
|
134
|
+
Required when `emailSender` is configured.
|
|
135
|
+
|
|
136
|
+
```typescript
|
|
137
|
+
updateUser: (id: string, data: Partial<AuthUser>) => Promise<AuthUser>;
|
|
138
|
+
saveVerificationToken: (payload: VerificationToken) => Promise<void>;
|
|
139
|
+
findVerificationToken: (token: string) => Promise<VerificationToken | null>;
|
|
140
|
+
deleteVerificationToken: (token: string) => Promise<void>;
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
### Optional methods — stateful refresh tokens
|
|
144
|
+
|
|
145
|
+
Opt in to DB-backed refresh tokens by providing all three. If omitted, the package falls back to stateless JWT verification.
|
|
146
|
+
|
|
147
|
+
```typescript
|
|
148
|
+
saveRefreshToken: (payload: RefreshToken) => Promise<void>;
|
|
149
|
+
findRefreshToken: (token: string) => Promise<RefreshToken | null>;
|
|
150
|
+
deleteRefreshToken: (token: string) => Promise<void>;
|
|
151
|
+
deleteAllRefreshTokens: (userId: string) => Promise<void>; // needed for logout-all and change-password
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
The returned `AuthUser` must have `id`, `email`, and `password` (hashed). All other fields are optional.
|
|
155
|
+
|
|
156
|
+
---
|
|
157
|
+
|
|
158
|
+
## Routes
|
|
159
|
+
|
|
160
|
+
Register these handlers on your Express app:
|
|
161
|
+
|
|
162
|
+
```typescript
|
|
163
|
+
// Auth
|
|
164
|
+
app.post("/register", registerHandler);
|
|
165
|
+
app.post("/login", loginHandler);
|
|
166
|
+
app.post("/refresh", refreshHandler);
|
|
167
|
+
app.post("/logout", protect(), logoutHandler); // body: { refreshToken }
|
|
168
|
+
app.post("/logout-all", protect(), logoutAllHandler);
|
|
169
|
+
|
|
170
|
+
// Email
|
|
171
|
+
app.post("/verify-email", verifyEmailHandler); // body: { token }
|
|
172
|
+
app.post("/resend-verification", resendVerificationHandler); // body: { email }
|
|
173
|
+
app.post("/forgot-password", forgotPasswordHandler); // body: { email }
|
|
174
|
+
app.post("/reset-password", resetPasswordHandler); // body: { token, newPassword }
|
|
175
|
+
app.post("/change-password", protect(), changePasswordHandler); // body: { currentPassword, newPassword }
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
### Request / Response reference
|
|
179
|
+
|
|
180
|
+
#### `POST /register`
|
|
181
|
+
```json
|
|
182
|
+
// Request
|
|
183
|
+
{ "email": "user@example.com", "password": "secret", "role": "user", "name": "John" }
|
|
184
|
+
|
|
185
|
+
// Response 201
|
|
186
|
+
{ "message": "User registered successfully" }
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
#### `POST /login`
|
|
190
|
+
```json
|
|
191
|
+
// Request
|
|
192
|
+
{ "email": "user@example.com", "password": "secret" }
|
|
193
|
+
|
|
194
|
+
// Response 200
|
|
195
|
+
{ "accessToken": "eyJ...", "refreshToken": "eyJ..." }
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
#### `POST /refresh`
|
|
199
|
+
```json
|
|
200
|
+
// Request
|
|
201
|
+
{ "refreshToken": "eyJ..." }
|
|
202
|
+
|
|
203
|
+
// Response 200 — old refresh token is invalidated, new pair issued
|
|
204
|
+
{ "accessToken": "eyJ...", "refreshToken": "eyJ..." }
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
#### `POST /logout`
|
|
208
|
+
```json
|
|
209
|
+
// Request (Authorization: Bearer <accessToken>)
|
|
210
|
+
{ "refreshToken": "eyJ..." }
|
|
211
|
+
|
|
212
|
+
// Response 200
|
|
213
|
+
{ "message": "Logged out successfully" }
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
#### `POST /change-password`
|
|
217
|
+
```json
|
|
218
|
+
// Request (Authorization: Bearer <accessToken>)
|
|
219
|
+
{ "currentPassword": "old", "newPassword": "new" }
|
|
220
|
+
|
|
221
|
+
// Response 200 — all refresh tokens invalidated
|
|
222
|
+
{ "message": "Password changed successfully" }
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
---
|
|
226
|
+
|
|
227
|
+
## RBAC
|
|
228
|
+
|
|
229
|
+
`protect()` is a factory function. Call it with no arguments for any authenticated user, or pass roles to restrict access.
|
|
230
|
+
|
|
231
|
+
```typescript
|
|
232
|
+
app.get("/profile", protect(), handler); // any authenticated user
|
|
233
|
+
app.get("/admin", protect("admin"), handler); // admin only
|
|
234
|
+
app.get("/reports", protect("admin", "manager"), handler); // either role
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
Role is set at registration via `req.body.role` and embedded in the JWT. On each request `protect()` re-fetches the user from the DB via `adapter.findUserById` — so role changes take effect immediately.
|
|
238
|
+
|
|
239
|
+
| Scenario | Status |
|
|
240
|
+
|---|---|
|
|
241
|
+
| No token | 401 |
|
|
242
|
+
| Invalid / expired token | 401 |
|
|
243
|
+
| User no longer in DB | 401 |
|
|
244
|
+
| Valid token, wrong role | 403 |
|
|
245
|
+
| Valid token, correct role | `next()` |
|
|
246
|
+
|
|
247
|
+
The authenticated user is available as `req.user` inside your handler.
|
|
248
|
+
|
|
249
|
+
---
|
|
250
|
+
|
|
251
|
+
## Email Features
|
|
252
|
+
|
|
253
|
+
Enable email features by providing `emailSender` in config and the four optional adapter methods.
|
|
254
|
+
|
|
255
|
+
```typescript
|
|
256
|
+
import nodemailer from "nodemailer";
|
|
257
|
+
|
|
258
|
+
const transporter = nodemailer.createTransport({ /* SMTP config */ });
|
|
259
|
+
|
|
260
|
+
init({
|
|
261
|
+
secret: process.env.JWT_SECRET!,
|
|
262
|
+
verificationUrl: "https://myapp.com",
|
|
263
|
+
|
|
264
|
+
emailSender: async (to, subject, html) => {
|
|
265
|
+
await transporter.sendMail({ from: "no-reply@myapp.com", to, subject, html });
|
|
266
|
+
},
|
|
267
|
+
|
|
268
|
+
adapter: {
|
|
269
|
+
// ... required methods
|
|
270
|
+
updateUser: ...,
|
|
271
|
+
saveVerificationToken: ...,
|
|
272
|
+
findVerificationToken: ...,
|
|
273
|
+
deleteVerificationToken: ...,
|
|
274
|
+
},
|
|
275
|
+
});
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
The package sends HTML emails with links in the format:
|
|
279
|
+
- Verification: `{verificationUrl}/verify-email?token=xxx`
|
|
280
|
+
- Password reset: `{verificationUrl}/reset-password?token=xxx`
|
|
281
|
+
|
|
282
|
+
> **Mobile apps:** pass a deep link as `verificationUrl` (e.g. `myapp://`) and handle the token in your app.
|
|
283
|
+
|
|
284
|
+
Clients without `emailSender` are unaffected — email features are fully opt-in.
|
|
285
|
+
|
|
286
|
+
---
|
|
287
|
+
|
|
288
|
+
## Stateful Refresh Tokens
|
|
289
|
+
|
|
290
|
+
By default the package is stateless — refresh tokens are verified by JWT signature only. To enable revocation, logout, and rotation, add the three refresh adapter methods:
|
|
291
|
+
|
|
292
|
+
```typescript
|
|
293
|
+
adapter: {
|
|
294
|
+
// ... other methods
|
|
295
|
+
saveRefreshToken: async (p) => { /* insert token row */ },
|
|
296
|
+
findRefreshToken: async (token) => { /* find token row */ },
|
|
297
|
+
deleteRefreshToken: async (token) => { /* delete token row */ },
|
|
298
|
+
deleteAllRefreshTokens: async (userId) => { /* delete all rows for user */ },
|
|
299
|
+
}
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
When these methods are present:
|
|
303
|
+
- Login saves the refresh token to the DB
|
|
304
|
+
- `/refresh` validates against the DB, deletes the old token, and saves the new one
|
|
305
|
+
- `/logout` deletes the specific token
|
|
306
|
+
- `/logout-all` and `/change-password` delete all tokens for the user
|
|
307
|
+
|
|
308
|
+
---
|
|
309
|
+
|
|
310
|
+
## Adapters
|
|
311
|
+
|
|
312
|
+
### MySQL2
|
|
313
|
+
|
|
314
|
+
```typescript
|
|
315
|
+
import { createPool } from "mysql2/promise";
|
|
316
|
+
import { v4 as uuidv4 } from "uuid";
|
|
317
|
+
|
|
318
|
+
const pool = createPool({ host, user, password, database });
|
|
319
|
+
|
|
320
|
+
init({
|
|
321
|
+
secret: process.env.JWT_SECRET!,
|
|
322
|
+
verificationUrl: "https://myapp.com",
|
|
323
|
+
emailSender: async (to, subject, html) => { /* ... */ },
|
|
324
|
+
adapter: {
|
|
325
|
+
findUserByEmail: async (email) => {
|
|
326
|
+
const [rows] = await pool.query("SELECT * FROM users WHERE email = ?", [email]);
|
|
327
|
+
return (rows as any[])[0] ?? null;
|
|
328
|
+
},
|
|
329
|
+
findUserById: async (id) => {
|
|
330
|
+
const [rows] = await pool.query("SELECT * FROM users WHERE id = ?", [id]);
|
|
331
|
+
return (rows as any[])[0] ?? null;
|
|
332
|
+
},
|
|
333
|
+
createUser: async (data) => {
|
|
334
|
+
const id = uuidv4();
|
|
335
|
+
await pool.query(
|
|
336
|
+
"INSERT INTO users (id, email, password, role, isVerified) VALUES (?, ?, ?, ?, ?)",
|
|
337
|
+
[id, data.email, data.password, data.role ?? "user", false]
|
|
338
|
+
);
|
|
339
|
+
const [rows] = await pool.query("SELECT * FROM users WHERE id = ?", [id]);
|
|
340
|
+
return (rows as any[])[0];
|
|
341
|
+
},
|
|
342
|
+
updateUser: async (id, data) => {
|
|
343
|
+
const fields = Object.keys(data).map(k => `${k} = ?`).join(", ");
|
|
344
|
+
await pool.query(`UPDATE users SET ${fields} WHERE id = ?`, [...Object.values(data), id]);
|
|
345
|
+
const [rows] = await pool.query("SELECT * FROM users WHERE id = ?", [id]);
|
|
346
|
+
return (rows as any[])[0];
|
|
347
|
+
},
|
|
348
|
+
saveVerificationToken: async (p) => {
|
|
349
|
+
await pool.query(
|
|
350
|
+
"INSERT INTO tokens (token, userId, type, expiresAt) VALUES (?, ?, ?, ?)",
|
|
351
|
+
[p.token, p.userId, p.type, p.expiresAt]
|
|
352
|
+
);
|
|
353
|
+
},
|
|
354
|
+
findVerificationToken: async (token) => {
|
|
355
|
+
const [rows] = await pool.query("SELECT * FROM tokens WHERE token = ?", [token]);
|
|
356
|
+
return (rows as any[])[0] ?? null;
|
|
357
|
+
},
|
|
358
|
+
deleteVerificationToken: async (token) => {
|
|
359
|
+
await pool.query("DELETE FROM tokens WHERE token = ?", [token]);
|
|
360
|
+
},
|
|
361
|
+
saveRefreshToken: async (p) => {
|
|
362
|
+
await pool.query(
|
|
363
|
+
"INSERT INTO refresh_tokens (token, userId, expiresAt) VALUES (?, ?, ?)",
|
|
364
|
+
[p.token, p.userId, p.expiresAt]
|
|
365
|
+
);
|
|
366
|
+
},
|
|
367
|
+
findRefreshToken: async (token) => {
|
|
368
|
+
const [rows] = await pool.query("SELECT * FROM refresh_tokens WHERE token = ?", [token]);
|
|
369
|
+
return (rows as any[])[0] ?? null;
|
|
370
|
+
},
|
|
371
|
+
deleteRefreshToken: async (token) => {
|
|
372
|
+
await pool.query("DELETE FROM refresh_tokens WHERE token = ?", [token]);
|
|
373
|
+
},
|
|
374
|
+
deleteAllRefreshTokens: async (userId) => {
|
|
375
|
+
await pool.query("DELETE FROM refresh_tokens WHERE userId = ?", [userId]);
|
|
376
|
+
},
|
|
377
|
+
},
|
|
378
|
+
});
|
|
379
|
+
```
|
|
380
|
+
|
|
381
|
+
#### Required tables
|
|
382
|
+
|
|
383
|
+
```sql
|
|
384
|
+
CREATE TABLE users (
|
|
385
|
+
id VARCHAR(36) PRIMARY KEY,
|
|
386
|
+
email VARCHAR(255) UNIQUE NOT NULL,
|
|
387
|
+
password VARCHAR(255) NOT NULL,
|
|
388
|
+
role VARCHAR(50) DEFAULT 'user',
|
|
389
|
+
isVerified BOOLEAN DEFAULT false
|
|
390
|
+
);
|
|
391
|
+
|
|
392
|
+
CREATE TABLE tokens (
|
|
393
|
+
token VARCHAR(128) PRIMARY KEY,
|
|
394
|
+
userId VARCHAR(36) NOT NULL,
|
|
395
|
+
type ENUM('email_verification', 'password_reset') NOT NULL,
|
|
396
|
+
expiresAt DATETIME NOT NULL,
|
|
397
|
+
FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE
|
|
398
|
+
);
|
|
399
|
+
|
|
400
|
+
CREATE TABLE refresh_tokens (
|
|
401
|
+
token VARCHAR(512) PRIMARY KEY,
|
|
402
|
+
userId VARCHAR(36) NOT NULL,
|
|
403
|
+
expiresAt DATETIME NOT NULL,
|
|
404
|
+
FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE
|
|
405
|
+
);
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
---
|
|
409
|
+
|
|
410
|
+
### Prisma
|
|
411
|
+
|
|
412
|
+
```typescript
|
|
413
|
+
init({
|
|
414
|
+
secret: process.env.JWT_SECRET!,
|
|
415
|
+
verificationUrl: "https://myapp.com",
|
|
416
|
+
emailSender: async (to, subject, html) => { /* ... */ },
|
|
417
|
+
adapter: {
|
|
418
|
+
findUserByEmail: (email) => prisma.user.findUnique({ where: { email } }),
|
|
419
|
+
findUserById: (id) => prisma.user.findUnique({ where: { id } }),
|
|
420
|
+
createUser: (data) => prisma.user.create({ data }),
|
|
421
|
+
updateUser: (id, data) => prisma.user.update({ where: { id }, data }),
|
|
422
|
+
saveVerificationToken: (p) => prisma.token.create({ data: p }).then(() => {}),
|
|
423
|
+
findVerificationToken: (token) => prisma.token.findUnique({ where: { token } }),
|
|
424
|
+
deleteVerificationToken: (token) => prisma.token.delete({ where: { token } }).then(() => {}),
|
|
425
|
+
saveRefreshToken: (p) => prisma.refreshToken.create({ data: p }).then(() => {}),
|
|
426
|
+
findRefreshToken: (token) => prisma.refreshToken.findUnique({ where: { token } }),
|
|
427
|
+
deleteRefreshToken: (token) => prisma.refreshToken.delete({ where: { token } }).then(() => {}),
|
|
428
|
+
deleteAllRefreshTokens: (userId) => prisma.refreshToken.deleteMany({ where: { userId } }).then(() => {}),
|
|
429
|
+
},
|
|
430
|
+
});
|
|
431
|
+
```
|
|
432
|
+
|
|
433
|
+
---
|
|
434
|
+
|
|
435
|
+
### Mongoose
|
|
436
|
+
|
|
437
|
+
```typescript
|
|
438
|
+
init({
|
|
439
|
+
secret: process.env.JWT_SECRET!,
|
|
440
|
+
adapter: {
|
|
441
|
+
findUserByEmail: (email) => UserModel.findOne({ email }).lean(),
|
|
442
|
+
findUserById: (id) => UserModel.findById(id).lean(),
|
|
443
|
+
createUser: (data) => UserModel.create(data),
|
|
444
|
+
// add optional methods as needed
|
|
445
|
+
},
|
|
446
|
+
});
|
|
447
|
+
```
|
|
448
|
+
|
|
449
|
+
---
|
|
450
|
+
|
|
451
|
+
## Token Expiry Reference
|
|
452
|
+
|
|
453
|
+
| Token | Default Expiry | Configurable |
|
|
454
|
+
|---|---|---|
|
|
455
|
+
| Access token | 15 minutes | Yes — `accessTokenExpiry` |
|
|
456
|
+
| Refresh token | 7 days | Yes — `refreshTokenExpiry` |
|
|
457
|
+
| Email verification | 24 hours | No |
|
|
458
|
+
| Password reset | 15 minutes | No |
|
|
459
|
+
|
|
460
|
+
---
|
|
461
|
+
|
|
462
|
+
## Error Reference
|
|
463
|
+
|
|
464
|
+
All handlers return JSON errors in the format `{ "message": "..." }`.
|
|
465
|
+
|
|
466
|
+
| Scenario | Status |
|
|
467
|
+
|---|---|
|
|
468
|
+
| Validation error (missing fields) | 400 |
|
|
469
|
+
| Invalid credentials | 400 |
|
|
470
|
+
| Unauthorized (no/invalid token) | 401 |
|
|
471
|
+
| Forbidden (wrong role) | 403 |
|
|
472
|
+
| Misconfigured adapter/emailSender | 500 |
|
|
473
|
+
|
|
474
|
+
`forgotPasswordHandler` and `resendVerificationHandler` always return `200` regardless of whether the email exists — to prevent user enumeration.
|
|
475
|
+
|
|
476
|
+
---
|
|
477
|
+
|
|
478
|
+
## Version History
|
|
479
|
+
|
|
480
|
+
| Version | Changes |
|
|
481
|
+
|---|---|
|
|
482
|
+
| `1.0.0` | Initial release — register, login, protect middleware |
|
|
483
|
+
| `2.0.0` | **Breaking** — `protect` changed to factory function. Custom fields via `[key: string]: unknown` on `AuthUser` |
|
|
484
|
+
| `2.1.0` | Email verification, forgot/reset password. Optional adapter methods. `emailSender` + `verificationUrl` config |
|
|
485
|
+
| `2.2.0` | Stateful refresh tokens with rotation. `refreshHandler`, `logoutHandler`, `logoutAllHandler`, `changePasswordHandler`, `resendVerificationHandler` |
|
|
486
|
+
|
|
487
|
+
---
|
|
488
|
+
|
|
489
|
+
## License
|
|
490
|
+
|
|
491
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ilman00/authkit",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.1.0",
|
|
4
4
|
"description": "Plug and play auth for Express apps",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -9,7 +9,9 @@
|
|
|
9
9
|
],
|
|
10
10
|
"scripts": {
|
|
11
11
|
"build": "tsc",
|
|
12
|
-
"dev": "tsc --watch"
|
|
12
|
+
"dev": "tsc --watch",
|
|
13
|
+
"test": "jest",
|
|
14
|
+
"test:watch": "jest --watch"
|
|
13
15
|
},
|
|
14
16
|
"peerDependencies": {
|
|
15
17
|
"express": "^4.x || ^5.x"
|
|
@@ -22,7 +24,10 @@
|
|
|
22
24
|
"devDependencies": {
|
|
23
25
|
"@types/bcryptjs": "^2.4.6",
|
|
24
26
|
"@types/express": "^4.17.21",
|
|
27
|
+
"@types/jest": "^30.0.0",
|
|
25
28
|
"@types/jsonwebtoken": "^9.0.0",
|
|
29
|
+
"jest": "^30.4.2",
|
|
30
|
+
"ts-jest": "^29.4.9",
|
|
26
31
|
"typescript": "^5.0.0"
|
|
27
32
|
},
|
|
28
33
|
"keywords": [
|