@ilman00/authkit 1.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/dist/config/auth.config.d.ts.map +1 -1
- package/dist/config/auth.config.js +8 -13
- package/dist/config/auth.config.js.map +1 -1
- package/dist/handlers/email.handler.d.ts +6 -0
- package/dist/handlers/email.handler.d.ts.map +1 -0
- package/dist/handlers/email.handler.js +96 -0
- package/dist/handlers/email.handler.js.map +1 -0
- package/dist/index.d.ts +4 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -1
- package/dist/index.js.map +1 -1
- package/dist/middleware/protect.d.ts +1 -1
- package/dist/middleware/protect.d.ts.map +1 -1
- package/dist/middleware/protect.js +27 -21
- package/dist/middleware/protect.js.map +1 -1
- package/dist/services/auth.service.d.ts +1 -0
- package/dist/services/auth.service.d.ts.map +1 -1
- package/dist/services/auth.service.js +19 -2
- package/dist/services/auth.service.js.map +1 -1
- package/dist/services/email.service.d.ts +17 -0
- package/dist/services/email.service.d.ts.map +1 -0
- package/dist/services/email.service.js +58 -0
- package/dist/services/email.service.js.map +1 -0
- package/dist/types/index.d.ts +14 -0
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +18 -5
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
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.config.d.ts","sourceRoot":"","sources":["../../src/config/auth.config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAUtC,wBAAgB,UAAU,CAAC,UAAU,EAAE,UAAU,GAAG,IAAI,
|
|
1
|
+
{"version":3,"file":"auth.config.d.ts","sourceRoot":"","sources":["../../src/config/auth.config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAUtC,wBAAgB,UAAU,CAAC,UAAU,EAAE,UAAU,GAAG,IAAI,CAgBvD;AAED,wBAAgB,SAAS,IAAI,UAAU,CAGtC"}
|
|
@@ -9,30 +9,25 @@ const REQUIRED_ADAPTER_METHODS = [
|
|
|
9
9
|
"createUser",
|
|
10
10
|
];
|
|
11
11
|
function initConfig(userConfig) {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
// Validate adapter
|
|
17
|
-
if (!userConfig.adapter) {
|
|
18
|
-
throw new Error("[my-auth-kit] adapter is required");
|
|
19
|
-
}
|
|
12
|
+
if (!userConfig.secret)
|
|
13
|
+
throw new Error("[authkit] secret is required");
|
|
14
|
+
if (!userConfig.adapter)
|
|
15
|
+
throw new Error("[authkit] adapter is required");
|
|
20
16
|
for (const method of REQUIRED_ADAPTER_METHODS) {
|
|
21
17
|
if (typeof userConfig.adapter[method] !== "function") {
|
|
22
|
-
throw new Error(`[
|
|
18
|
+
throw new Error(`[authkit] adapter missing required method: "${method}"`);
|
|
23
19
|
}
|
|
24
20
|
}
|
|
25
|
-
// Store with defaults
|
|
26
21
|
config = {
|
|
27
22
|
accessTokenExpiry: "15m",
|
|
28
23
|
refreshTokenExpiry: "7d",
|
|
24
|
+
verificationUrl: "http://localhost:3000", // sensible default
|
|
29
25
|
...userConfig,
|
|
30
26
|
};
|
|
31
27
|
}
|
|
32
28
|
function getConfig() {
|
|
33
|
-
if (!config)
|
|
34
|
-
throw new Error("[
|
|
35
|
-
}
|
|
29
|
+
if (!config)
|
|
30
|
+
throw new Error("[authkit] call init() before using auth");
|
|
36
31
|
return config;
|
|
37
32
|
}
|
|
38
33
|
//# sourceMappingURL=auth.config.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.config.js","sourceRoot":"","sources":["../../src/config/auth.config.ts"],"names":[],"mappings":";;AAUA,
|
|
1
|
+
{"version":3,"file":"auth.config.js","sourceRoot":"","sources":["../../src/config/auth.config.ts"],"names":[],"mappings":";;AAUA,gCAgBC;AAED,8BAGC;AA7BD,IAAI,MAAM,GAAsB,IAAI,CAAC;AAErC,MAAM,wBAAwB,GAAG;IAC/B,iBAAiB;IACjB,cAAc;IACd,YAAY;CACJ,CAAC;AAEX,SAAgB,UAAU,CAAC,UAAsB;IAC/C,IAAI,CAAC,UAAU,CAAC,MAAM;QAAG,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;IACzE,IAAI,CAAC,UAAU,CAAC,OAAO;QAAE,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;IAE1E,KAAK,MAAM,MAAM,IAAI,wBAAwB,EAAE,CAAC;QAC9C,IAAI,OAAO,UAAU,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,UAAU,EAAE,CAAC;YACrD,MAAM,IAAI,KAAK,CAAC,+CAA+C,MAAM,GAAG,CAAC,CAAC;QAC5E,CAAC;IACH,CAAC;IAED,MAAM,GAAG;QACP,iBAAiB,EAAG,KAAK;QACzB,kBAAkB,EAAE,IAAI;QACxB,eAAe,EAAK,uBAAuB,EAAG,mBAAmB;QACjE,GAAG,UAAU;KACd,CAAC;AACJ,CAAC;AAED,SAAgB,SAAS;IACvB,IAAI,CAAC,MAAM;QAAE,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;IACxE,OAAO,MAAM,CAAC;AAChB,CAAC"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { Response } from "express";
|
|
2
|
+
import { AuthRequest } from "../types";
|
|
3
|
+
export declare function verifyEmailHandler(req: AuthRequest, res: Response): Promise<void>;
|
|
4
|
+
export declare function forgotPasswordHandler(req: AuthRequest, res: Response): Promise<void>;
|
|
5
|
+
export declare function resetPasswordHandler(req: AuthRequest, res: Response): Promise<void>;
|
|
6
|
+
//# sourceMappingURL=email.handler.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"email.handler.d.ts","sourceRoot":"","sources":["../../src/handlers/email.handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAYvC,wBAAsB,kBAAkB,CACtC,GAAG,EAAE,WAAW,EAChB,GAAG,EAAE,QAAQ,GACZ,OAAO,CAAC,IAAI,CAAC,CA2Bf;AAGD,wBAAsB,qBAAqB,CACzC,GAAG,EAAE,WAAW,EAChB,GAAG,EAAE,QAAQ,GACZ,OAAO,CAAC,IAAI,CAAC,CAiCf;AAGD,wBAAsB,oBAAoB,CACxC,GAAG,EAAE,WAAW,EAChB,GAAG,EAAE,QAAQ,GACZ,OAAO,CAAC,IAAI,CAAC,CA6Bf"}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.verifyEmailHandler = verifyEmailHandler;
|
|
4
|
+
exports.forgotPasswordHandler = forgotPasswordHandler;
|
|
5
|
+
exports.resetPasswordHandler = resetPasswordHandler;
|
|
6
|
+
const errors_1 = require("../utils/errors");
|
|
7
|
+
const email_service_1 = require("../services/email.service");
|
|
8
|
+
const password_service_1 = require("../services/password.service");
|
|
9
|
+
// POST /verify-email { token }
|
|
10
|
+
async function verifyEmailHandler(req, res) {
|
|
11
|
+
try {
|
|
12
|
+
const { adapter } = (0, email_service_1.requireEmailConfig)();
|
|
13
|
+
const { token } = req.body;
|
|
14
|
+
if (!token)
|
|
15
|
+
throw new errors_1.AuthError("Token is required", 400);
|
|
16
|
+
const record = await adapter.findVerificationToken(token);
|
|
17
|
+
if (!record)
|
|
18
|
+
throw new errors_1.AuthError("Invalid or expired token", 400);
|
|
19
|
+
if (record.type !== "email_verification")
|
|
20
|
+
throw new errors_1.AuthError("Invalid token type", 400);
|
|
21
|
+
if (record.expiresAt < new Date())
|
|
22
|
+
throw new errors_1.AuthError("Token has expired", 400);
|
|
23
|
+
await adapter.updateUser(record.userId, { isVerified: true });
|
|
24
|
+
await adapter.deleteVerificationToken(token);
|
|
25
|
+
res.status(200).json({ message: "Email verified successfully" });
|
|
26
|
+
}
|
|
27
|
+
catch (err) {
|
|
28
|
+
if (err instanceof errors_1.AuthError) {
|
|
29
|
+
res.status(err.statusCode).json({ message: err.message });
|
|
30
|
+
}
|
|
31
|
+
else if (err instanceof Error) {
|
|
32
|
+
res.status(400).json({ message: err.message });
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
// POST /forgot-password { email }
|
|
37
|
+
async function forgotPasswordHandler(req, res) {
|
|
38
|
+
try {
|
|
39
|
+
const { adapter } = (0, email_service_1.requireEmailConfig)();
|
|
40
|
+
const { email } = req.body;
|
|
41
|
+
if (!email)
|
|
42
|
+
throw new errors_1.AuthError("Email is required", 400);
|
|
43
|
+
const user = await adapter.findUserByEmail(email);
|
|
44
|
+
// Always respond with 200 — never reveal if email exists or not
|
|
45
|
+
if (!user) {
|
|
46
|
+
res.status(200).json({ message: "If that email exists, a reset link has been sent" });
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const token = (0, email_service_1.generateToken)();
|
|
50
|
+
await adapter.saveVerificationToken({
|
|
51
|
+
token,
|
|
52
|
+
userId: user.id,
|
|
53
|
+
type: "password_reset",
|
|
54
|
+
expiresAt: (0, email_service_1.getExpiryDate)(15), // 15 minutes
|
|
55
|
+
});
|
|
56
|
+
await (0, email_service_1.sendPasswordResetEmail)(user.email, token);
|
|
57
|
+
res.status(200).json({ message: "If that email exists, a reset link has been sent" });
|
|
58
|
+
}
|
|
59
|
+
catch (err) {
|
|
60
|
+
if (err instanceof errors_1.AuthError) {
|
|
61
|
+
res.status(err.statusCode).json({ message: err.message });
|
|
62
|
+
}
|
|
63
|
+
else if (err instanceof Error) {
|
|
64
|
+
res.status(400).json({ message: err.message });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
// POST /reset-password { token, newPassword }
|
|
69
|
+
async function resetPasswordHandler(req, res) {
|
|
70
|
+
try {
|
|
71
|
+
const { adapter } = (0, email_service_1.requireEmailConfig)();
|
|
72
|
+
const { token, newPassword } = req.body;
|
|
73
|
+
if (!token || !newPassword)
|
|
74
|
+
throw new errors_1.AuthError("Token and newPassword are required", 400);
|
|
75
|
+
const record = await adapter.findVerificationToken(token);
|
|
76
|
+
if (!record)
|
|
77
|
+
throw new errors_1.AuthError("Invalid or expired token", 400);
|
|
78
|
+
if (record.type !== "password_reset")
|
|
79
|
+
throw new errors_1.AuthError("Invalid token type", 400);
|
|
80
|
+
if (record.expiresAt < new Date())
|
|
81
|
+
throw new errors_1.AuthError("Token has expired", 400);
|
|
82
|
+
const hashed = await (0, password_service_1.hashPassword)(newPassword);
|
|
83
|
+
await adapter.updateUser(record.userId, { password: hashed });
|
|
84
|
+
await adapter.deleteVerificationToken(token);
|
|
85
|
+
res.status(200).json({ message: "Password reset successfully" });
|
|
86
|
+
}
|
|
87
|
+
catch (err) {
|
|
88
|
+
if (err instanceof errors_1.AuthError) {
|
|
89
|
+
res.status(err.statusCode).json({ message: err.message });
|
|
90
|
+
}
|
|
91
|
+
else if (err instanceof Error) {
|
|
92
|
+
res.status(400).json({ message: err.message });
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
//# sourceMappingURL=email.handler.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"email.handler.js","sourceRoot":"","sources":["../../src/handlers/email.handler.ts"],"names":[],"mappings":";;AAaA,gDA8BC;AAGD,sDAoCC;AAGD,oDAgCC;AAnHD,4CAA4C;AAE5C,6DAKmC;AACnC,mEAA4D;AAE5D,gCAAgC;AACzB,KAAK,UAAU,kBAAkB,CACtC,GAAgB,EAChB,GAAa;IAEb,IAAI,CAAC;QACH,MAAM,EAAE,OAAO,EAAE,GAAG,IAAA,kCAAkB,GAAE,CAAC;QACzC,MAAM,EAAE,KAAK,EAAE,GAAG,GAAG,CAAC,IAAI,CAAC;QAE3B,IAAI,CAAC,KAAK;YAAE,MAAM,IAAI,kBAAS,CAAC,mBAAmB,EAAE,GAAG,CAAC,CAAC;QAE1D,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,qBAAqB,CAAC,KAAK,CAAC,CAAC;QAE1D,IAAI,CAAC,MAAM;YACT,MAAM,IAAI,kBAAS,CAAC,0BAA0B,EAAE,GAAG,CAAC,CAAC;QACvD,IAAI,MAAM,CAAC,IAAI,KAAK,oBAAoB;YACtC,MAAM,IAAI,kBAAS,CAAC,oBAAoB,EAAE,GAAG,CAAC,CAAC;QACjD,IAAI,MAAM,CAAC,SAAS,GAAG,IAAI,IAAI,EAAE;YAC/B,MAAM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ect } from "./middleware/protect";
|
|
3
|
-
import {
|
|
3
|
+
import { verifyEmailHandler, forgotPasswordHandler, resetPasswordHandler } from "./handlers/email.handler";
|
|
4
|
+
import { AuthConfig, AuthAdapter, AuthUser, AuthRequest, VerificationToken } from "./types";
|
|
4
5
|
export declare function init(config: AuthConfig): void;
|
|
5
|
-
export { registerHandler, loginHandler, protect };
|
|
6
|
-
export type { AuthConfig, AuthAdapter, AuthUser, AuthRequest };
|
|
6
|
+
export { registerHandler, loginHandler, protect, verifyEmailHandler, forgotPasswordHandler, resetPasswordHandler, };
|
|
7
|
+
export type { AuthConfig, AuthAdapter, AuthUser, AuthRequest, VerificationToken };
|
|
7
8
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACxE,OAAO,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACxE,OAAO,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAC/C,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACrB,oBAAoB,EACrB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,QAAQ,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAE5F,wBAAgB,IAAI,CAAC,MAAM,EAAE,UAAU,GAAG,IAAI,CAE7C;AAED,OAAO,EACL,eAAe,EACf,YAAY,EACZ,OAAO,EACP,kBAAkB,EAClB,qBAAqB,EACrB,oBAAoB,GACrB,CAAC;AAEF,YAAY,EAAE,UAAU,EAAE,WAAW,EAAE,QAAQ,EAAE,WAAW,EAAE,iBAAiB,EAAE,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.protect = exports.loginHandler = exports.registerHandler = void 0;
|
|
3
|
+
exports.resetPasswordHandler = exports.forgotPasswordHandler = exports.verifyEmailHandler = exports.protect = exports.loginHandler = exports.registerHandler = void 0;
|
|
4
4
|
exports.init = init;
|
|
5
5
|
const auth_config_1 = require("./config/auth.config");
|
|
6
6
|
const auth_handler_1 = require("./handlers/auth.handler");
|
|
@@ -8,6 +8,10 @@ Object.defineProperty(exports, "registerHandler", { enumerable: true, get: funct
|
|
|
8
8
|
Object.defineProperty(exports, "loginHandler", { enumerable: true, get: function () { return auth_handler_1.loginHandler; } });
|
|
9
9
|
const protect_1 = require("./middleware/protect");
|
|
10
10
|
Object.defineProperty(exports, "protect", { enumerable: true, get: function () { return protect_1.protect; } });
|
|
11
|
+
const email_handler_1 = require("./handlers/email.handler");
|
|
12
|
+
Object.defineProperty(exports, "verifyEmailHandler", { enumerable: true, get: function () { return email_handler_1.verifyEmailHandler; } });
|
|
13
|
+
Object.defineProperty(exports, "forgotPasswordHandler", { enumerable: true, get: function () { return email_handler_1.forgotPasswordHandler; } });
|
|
14
|
+
Object.defineProperty(exports, "resetPasswordHandler", { enumerable: true, get: function () { return email_handler_1.resetPasswordHandler; } });
|
|
11
15
|
function init(config) {
|
|
12
16
|
(0, auth_config_1.initConfig)(config);
|
|
13
17
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAUA,oBAEC;AAZD,sDAAkD;AAClD,0DAAwE;AActE,gGAdO,8BAAe,OAcP;AACf,6FAfwB,2BAAY,OAexB;AAdd,kDAA+C;AAe7C,wFAfO,iBAAO,OAeP;AAdT,4DAIkC;AAWhC,mGAdA,kCAAkB,OAcA;AAClB,sGAdA,qCAAqB,OAcA;AACrB,qGAdA,oCAAoB,OAcA;AAVtB,SAAgB,IAAI,CAAC,MAAkB;IACrC,IAAA,wBAAU,EAAC,MAAM,CAAC,CAAC;AACrB,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { Response, NextFunction } from "express";
|
|
2
2
|
import { AuthRequest } from "../types";
|
|
3
|
-
export declare function protect(req: AuthRequest, res: Response, next: NextFunction)
|
|
3
|
+
export declare function protect(...allowedRoles: string[]): (req: AuthRequest, res: Response, next: NextFunction) => Promise<void>;
|
|
4
4
|
//# sourceMappingURL=protect.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"protect.d.ts","sourceRoot":"","sources":["../../src/middleware/protect.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAGjD,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;
|
|
1
|
+
{"version":3,"file":"protect.d.ts","sourceRoot":"","sources":["../../src/middleware/protect.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAGjD,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAIvC,wBAAgB,OAAO,CAAC,GAAG,YAAY,EAAE,MAAM,EAAE,IACjC,KAAK,WAAW,EAAE,KAAK,QAAQ,EAAE,MAAM,YAAY,KAAG,OAAO,CAAC,IAAI,CAAC,CA2BlF"}
|
|
@@ -4,28 +4,34 @@ exports.protect = protect;
|
|
|
4
4
|
const jwt_service_1 = require("../services/jwt.service");
|
|
5
5
|
const auth_config_1 = require("../config/auth.config");
|
|
6
6
|
const errors_1 = require("../utils/errors");
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
7
|
+
// ✅ Now accepts optional roles
|
|
8
|
+
function protect(...allowedRoles) {
|
|
9
|
+
return async (req, res, next) => {
|
|
10
|
+
try {
|
|
11
|
+
const authHeader = req.headers.authorization;
|
|
12
|
+
if (!authHeader?.startsWith("Bearer "))
|
|
13
|
+
throw new errors_1.AuthError("No token provided", 401);
|
|
14
|
+
const token = authHeader.split(" ")[1];
|
|
15
|
+
const decoded = (0, jwt_service_1.verifyToken)(token);
|
|
16
|
+
const { adapter } = (0, auth_config_1.getConfig)();
|
|
17
|
+
const user = await adapter.findUserById(decoded.id);
|
|
18
|
+
if (!user)
|
|
19
|
+
throw new errors_1.AuthError("User no longer exists", 401);
|
|
20
|
+
// ✅ Role check — only runs if roles were specified
|
|
21
|
+
if (allowedRoles.length > 0 && !allowedRoles.includes(user.role ?? "")) {
|
|
22
|
+
throw new errors_1.AuthError("Forbidden: insufficient permissions", 403);
|
|
23
|
+
}
|
|
24
|
+
req.user = user;
|
|
25
|
+
next();
|
|
12
26
|
}
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
next();
|
|
21
|
-
}
|
|
22
|
-
catch (err) {
|
|
23
|
-
if (err instanceof errors_1.AuthError) {
|
|
24
|
-
res.status(err.statusCode).json({ message: err.message });
|
|
27
|
+
catch (err) {
|
|
28
|
+
if (err instanceof errors_1.AuthError) {
|
|
29
|
+
res.status(err.statusCode).json({ message: err.message });
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
res.status(401).json({ message: "Invalid or expired token" });
|
|
33
|
+
}
|
|
25
34
|
}
|
|
26
|
-
|
|
27
|
-
res.status(401).json({ message: "Invalid or expired token" });
|
|
28
|
-
}
|
|
29
|
-
}
|
|
35
|
+
};
|
|
30
36
|
}
|
|
31
37
|
//# sourceMappingURL=protect.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"protect.js","sourceRoot":"","sources":["../../src/middleware/protect.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"protect.js","sourceRoot":"","sources":["../../src/middleware/protect.ts"],"names":[],"mappings":";;AAOA,0BA4BC;AAlCD,yDAAsD;AACtD,uDAAkD;AAElD,4CAA4C;AAE5C,+BAA+B;AAC/B,SAAgB,OAAO,CAAC,GAAG,YAAsB;IAC/C,OAAO,KAAK,EAAE,GAAgB,EAAE,GAAa,EAAE,IAAkB,EAAiB,EAAE;QAClF,IAAI,CAAC;YACH,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,aAAa,CAAC;YAC7C,IAAI,CAAC,UAAU,EAAE,UAAU,CAAC,SAAS,CAAC;gBAAE,MAAM,IAAI,kBAAS,CAAC,mBAAmB,EAAE,GAAG,CAAC,CAAC;YAEtF,MAAM,KAAK,GAAK,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;YACzC,MAAM,OAAO,GAAG,IAAA,yBAAW,EAAC,KAAK,CAAC,CAAC;YAEnC,MAAM,EAAE,OAAO,EAAE,GAAG,IAAA,uBAAS,GAAE,CAAC;YAChC,MAAM,IAAI,GAAG,MAAM,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;YACpD,IAAI,CAAC,IAAI;gBAAE,MAAM,IAAI,kBAAS,CAAC,uBAAuB,EAAE,GAAG,CAAC,CAAC;YAE7D,mDAAmD;YACnD,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,IAAI,EAAE,CAAC,EAAE,CAAC;gBACvE,MAAM,IAAI,kBAAS,CAAC,qCAAqC,EAAE,GAAG,CAAC,CAAC;YAClE,CAAC;YAED,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC;YAChB,IAAI,EAAE,CAAC;QACT,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,GAAG,YAAY,kBAAS,EAAE,CAAC;gBAC7B,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC;YAC5D,CAAC;iBAAM,CAAC;gBACN,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,0BAA0B,EAAE,CAAC,CAAC;YAChE,CAAC;QACH,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.service.d.ts","sourceRoot":"","sources":["../../src/services/auth.service.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"auth.service.d.ts","sourceRoot":"","sources":["../../src/services/auth.service.ts"],"names":[],"mappings":"AASA,wBAAsB,YAAY,CAAC,QAAQ,EAAE;IAC3C,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB,GAAG,OAAO,CAAC,IAAI,CAAC,CAyBhB;AAED,wBAAsB,SAAS,CAC7B,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,CAAC,CASxD"}
|
|
@@ -5,13 +5,30 @@ exports.loginUser = loginUser;
|
|
|
5
5
|
const password_service_1 = require("./password.service");
|
|
6
6
|
const jwt_service_1 = require("./jwt.service");
|
|
7
7
|
const auth_config_1 = require("../config/auth.config");
|
|
8
|
+
const email_service_1 = require("./email.service");
|
|
8
9
|
async function registerUser(userData) {
|
|
9
|
-
const { adapter } = (0, auth_config_1.getConfig)();
|
|
10
|
+
const { adapter, emailSender } = (0, auth_config_1.getConfig)();
|
|
10
11
|
const existing = await adapter.findUserByEmail(userData.email);
|
|
11
12
|
if (existing)
|
|
12
13
|
throw new Error("User already exists");
|
|
13
14
|
const hashed = await (0, password_service_1.hashPassword)(userData.password);
|
|
14
|
-
await adapter.createUser({
|
|
15
|
+
const user = await adapter.createUser({
|
|
16
|
+
...userData,
|
|
17
|
+
password: hashed,
|
|
18
|
+
isVerified: false, // always false on register
|
|
19
|
+
});
|
|
20
|
+
// Only send verification email if emailSender is configured
|
|
21
|
+
// If not — silently skip (backward compatible)
|
|
22
|
+
if (emailSender && adapter.saveVerificationToken) {
|
|
23
|
+
const token = (0, email_service_1.generateToken)();
|
|
24
|
+
await adapter.saveVerificationToken({
|
|
25
|
+
token,
|
|
26
|
+
userId: user.id,
|
|
27
|
+
type: "email_verification",
|
|
28
|
+
expiresAt: (0, email_service_1.getExpiryDate)(24 * 60), // 24 hours
|
|
29
|
+
});
|
|
30
|
+
await (0, email_service_1.sendVerificationEmail)(user.email, token);
|
|
31
|
+
}
|
|
15
32
|
}
|
|
16
33
|
async function loginUser(email, password) {
|
|
17
34
|
const { adapter } = (0, auth_config_1.getConfig)();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../src/services/auth.service.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../src/services/auth.service.ts"],"names":[],"mappings":";;AASA,oCA8BC;AAED,8BAYC;AArDD,yDAAmE;AACnE,+CAAkE;AAClE,uDAAkD;AAClD,mDAIyB;AAElB,KAAK,UAAU,YAAY,CAAC,QAKlC;IACC,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,GAAG,IAAA,uBAAS,GAAE,CAAC;IAE7C,MAAM,QAAQ,GAAG,MAAM,OAA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,MAAM,WAAW,GAAI,IAAA,6BAAe,EAAC,IAAI,CAAC,CAAC;IAC3C,MAAM,YAAY,GAAG,IAAA,8BAAgB,EAAC,IAAI,CAAC,CAAC;IAC5C,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,CAAC;AACvC,CAAC"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { AuthConfig } from "../types";
|
|
2
|
+
type EmailReadyConfig = Omit<AuthConfig, "adapter" | "emailSender"> & {
|
|
3
|
+
emailSender: Required<AuthConfig>["emailSender"];
|
|
4
|
+
adapter: Omit<AuthConfig["adapter"], "updateUser" | "saveVerificationToken" | "findVerificationToken" | "deleteVerificationToken"> & {
|
|
5
|
+
updateUser: Required<AuthConfig["adapter"]>["updateUser"];
|
|
6
|
+
saveVerificationToken: Required<AuthConfig["adapter"]>["saveVerificationToken"];
|
|
7
|
+
findVerificationToken: Required<AuthConfig["adapter"]>["findVerificationToken"];
|
|
8
|
+
deleteVerificationToken: Required<AuthConfig["adapter"]>["deleteVerificationToken"];
|
|
9
|
+
};
|
|
10
|
+
};
|
|
11
|
+
export declare function requireEmailConfig(): EmailReadyConfig;
|
|
12
|
+
export declare function generateToken(): string;
|
|
13
|
+
export declare function getExpiryDate(minutes: number): Date;
|
|
14
|
+
export declare function sendVerificationEmail(to: string, token: string): Promise<void>;
|
|
15
|
+
export declare function sendPasswordResetEmail(to: string, token: string): Promise<void>;
|
|
16
|
+
export {};
|
|
17
|
+
//# sourceMappingURL=email.service.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"email.service.d.ts","sourceRoot":"","sources":["../../src/services/email.service.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAGtC,KAAK,gBAAgB,GAAG,IAAI,CAAC,UAAU,EAAE,SAAS,GAAG,aAAa,CAAC,GAAG;IACpE,WAAW,EAAE,QAAQ,CAAC,UAAU,CAAC,CAAC,aAAa,CAAC,CAAC;IACjD,OAAO,EAAE,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,EACjC,YAAY,GAAG,uBAAuB,GAAG,uBAAuB,GAAG,yBAAyB,CAC7F,GAAG;QACF,UAAU,EAAe,QAAQ,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;QACvE,qBAAqB,EAAI,QAAQ,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,CAAC,uBAAuB,CAAC,CAAC;QAClF,qBAAqB,EAAI,QAAQ,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,CAAC,uBAAuB,CAAC,CAAC;QAClF,uBAAuB,EAAE,QAAQ,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,CAAC,yBAAyB,CAAC,CAAC;KACrF,CAAC;CACH,CAAC;AAEF,wBAAgB,kBAAkB,IAAI,gBAAgB,CAerD;AAGD,wBAAgB,aAAa,IAAI,MAAM,CAEtC;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAEnD;AAID,wBAAsB,qBAAqB,CACzC,EAAE,EAAE,MAAM,EACV,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,IAAI,CAAC,CAaf;AAED,wBAAsB,sBAAsB,CAC1C,EAAE,EAAE,MAAM,EACV,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,IAAI,CAAC,CAaf"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.requireEmailConfig = requireEmailConfig;
|
|
7
|
+
exports.generateToken = generateToken;
|
|
8
|
+
exports.getExpiryDate = getExpiryDate;
|
|
9
|
+
exports.sendVerificationEmail = sendVerificationEmail;
|
|
10
|
+
exports.sendPasswordResetEmail = sendPasswordResetEmail;
|
|
11
|
+
const crypto_1 = __importDefault(require("crypto"));
|
|
12
|
+
const auth_config_1 = require("../config/auth.config");
|
|
13
|
+
const errors_1 = require("../utils/errors");
|
|
14
|
+
function requireEmailConfig() {
|
|
15
|
+
const config = (0, auth_config_1.getConfig)();
|
|
16
|
+
if (!config.emailSender)
|
|
17
|
+
throw new errors_1.AuthError("[authkit] emailSender is required to use email features", 500);
|
|
18
|
+
if (!config.adapter.updateUser)
|
|
19
|
+
throw new errors_1.AuthError("[authkit] adapter.updateUser is required", 500);
|
|
20
|
+
if (!config.adapter.saveVerificationToken)
|
|
21
|
+
throw new errors_1.AuthError("[authkit] adapter.saveVerificationToken is required", 500);
|
|
22
|
+
if (!config.adapter.findVerificationToken)
|
|
23
|
+
throw new errors_1.AuthError("[authkit] adapter.findVerificationToken is required", 500);
|
|
24
|
+
if (!config.adapter.deleteVerificationToken)
|
|
25
|
+
throw new errors_1.AuthError("[authkit] adapter.deleteVerificationToken is required", 500);
|
|
26
|
+
return config; // safe — all fields confirmed above
|
|
27
|
+
}
|
|
28
|
+
// ---- Token helpers -----------------------------------------------
|
|
29
|
+
function generateToken() {
|
|
30
|
+
return crypto_1.default.randomBytes(32).toString("hex");
|
|
31
|
+
}
|
|
32
|
+
function getExpiryDate(minutes) {
|
|
33
|
+
return new Date(Date.now() + minutes * 60 * 1000);
|
|
34
|
+
}
|
|
35
|
+
// ---- Email senders -----------------------------------------------
|
|
36
|
+
async function sendVerificationEmail(to, token) {
|
|
37
|
+
const { emailSender, verificationUrl } = requireEmailConfig();
|
|
38
|
+
const link = `${verificationUrl}/verify-email?token=${token}`;
|
|
39
|
+
const html = `
|
|
40
|
+
<h2>Verify your email</h2>
|
|
41
|
+
<p>Click the link below to verify your email address. This link expires in 24 hours.</p>
|
|
42
|
+
<a href="${link}">${link}</a>
|
|
43
|
+
<p>If you did not create an account, ignore this email.</p>
|
|
44
|
+
`;
|
|
45
|
+
await emailSender(to, "Verify your email", html);
|
|
46
|
+
}
|
|
47
|
+
async function sendPasswordResetEmail(to, token) {
|
|
48
|
+
const { emailSender, verificationUrl } = requireEmailConfig();
|
|
49
|
+
const link = `${verificationUrl}/reset-password?token=${token}`;
|
|
50
|
+
const html = `
|
|
51
|
+
<h2>Reset your password</h2>
|
|
52
|
+
<p>Click the link below to reset your password. This link expires in 15 minutes.</p>
|
|
53
|
+
<a href="${link}">${link}</a>
|
|
54
|
+
<p>If you did not request a password reset, ignore this email.</p>
|
|
55
|
+
`;
|
|
56
|
+
await emailSender(to, "Reset your password", html);
|
|
57
|
+
}
|
|
58
|
+
//# sourceMappingURL=email.service.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"email.service.js","sourceRoot":"","sources":["../../src/services/email.service.ts"],"names":[],"mappings":";;;;;AAoBA,gDAeC;AAGD,sCAEC;AAED,sCAEC;AAID,sDAgBC;AAED,wDAgBC;AAlFD,oDAA4B;AAC5B,uDAAkD;AAClD,4CAA4C;AAkB5C,SAAgB,kBAAkB;IAChC,MAAM,MAAM,GAAG,IAAA,uBAAS,GAAE,CAAC;IAE3B,IAAI,CAAC,MAAM,CAAC,WAAW;QACrB,MAAM,IAAI,kBAAS,CAAC,yDAAyD,EAAE,GAAG,CAAC,CAAC;IACtF,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,UAAU;QAC5B,MAAM,IAAI,kBAAS,CAAC,0CAA0C,EAAE,GAAG,CAAC,CAAC;IACvE,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,qBAAqB;QACvC,MAAM,IAAI,kBAAS,CAAC,qDAAqD,EAAE,GAAG,CAAC,CAAC;IAClF,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,qBAAqB;QACvC,MAAM,IAAI,kBAAS,CAAC,qDAAqD,EAAE,GAAG,CAAC,CAAC;IAClF,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,uBAAuB;QACzC,MAAM,IAAI,kBAAS,CAAC,uDAAuD,EAAE,GAAG,CAAC,CAAC;IAEpF,OAAO,MAAqC,CAAC,CAAC,oCAAoC;AACpF,CAAC;AACD,qEAAqE;AAErE,SAAgB,aAAa;IAC3B,OAAO,gBAAM,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AAChD,CAAC;AAED,SAAgB,aAAa,CAAC,OAAe;IAC3C,OAAO,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,OAAO,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC;AACpD,CAAC;AAED,qEAAqE;AAE9D,KAAK,UAAU,qBAAqB,CACzC,EAAU,EACV,KAAa;IAEb,MAAM,EAAE,WAAW,EAAE,eAAe,EAAE,GAAG,kBAAkB,EAAE,CAAC;IAE9D,MAAM,IAAI,GAAG,GAAG,eAAe,uBAAuB,KAAK,EAAE,CAAC;IAE9D,MAAM,IAAI,GAAG;;;eAGA,IAAI,KAAK,IAAI;;GAEzB,CAAC;IAEF,MAAM,WAAW,CAAC,EAAE,EAAE,mBAAmB,EAAE,IAAI,CAAC,CAAC;AACnD,CAAC;AAEM,KAAK,UAAU,sBAAsB,CAC1C,EAAU,EACV,KAAa;IAEb,MAAM,EAAE,WAAW,EAAE,eAAe,EAAE,GAAG,kBAAkB,EAAE,CAAC;IAE9D,MAAM,IAAI,GAAG,GAAG,eAAe,yBAAyB,KAAK,EAAE,CAAC;IAEhE,MAAM,IAAI,GAAG;;;eAGA,IAAI,KAAK,IAAI;;GAEzB,CAAC;IAEF,MAAM,WAAW,CAAC,EAAE,EAAE,qBAAqB,EAAE,IAAI,CAAC,CAAC;AACrD,CAAC"}
|
package/dist/types/index.d.ts
CHANGED
|
@@ -4,16 +4,30 @@ export interface AuthUser {
|
|
|
4
4
|
email: string;
|
|
5
5
|
password: string;
|
|
6
6
|
role?: string;
|
|
7
|
+
isVerified?: boolean;
|
|
8
|
+
[key: string]: unknown;
|
|
9
|
+
}
|
|
10
|
+
export interface VerificationToken {
|
|
11
|
+
token: string;
|
|
12
|
+
userId: string;
|
|
13
|
+
type: "email_verification" | "password_reset";
|
|
14
|
+
expiresAt: Date;
|
|
7
15
|
}
|
|
8
16
|
export interface AuthAdapter {
|
|
9
17
|
findUserByEmail: (email: string) => Promise<AuthUser | null>;
|
|
10
18
|
findUserById: (id: string) => Promise<AuthUser | null>;
|
|
11
19
|
createUser: (data: Partial<AuthUser>) => Promise<AuthUser>;
|
|
20
|
+
updateUser?: (id: string, data: Partial<AuthUser>) => Promise<AuthUser>;
|
|
21
|
+
saveVerificationToken?: (payload: VerificationToken) => Promise<void>;
|
|
22
|
+
findVerificationToken?: (token: string) => Promise<VerificationToken | null>;
|
|
23
|
+
deleteVerificationToken?: (token: string) => Promise<void>;
|
|
12
24
|
}
|
|
13
25
|
export interface AuthConfig {
|
|
14
26
|
secret: string;
|
|
15
27
|
accessTokenExpiry?: string;
|
|
16
28
|
refreshTokenExpiry?: string;
|
|
29
|
+
verificationUrl?: string;
|
|
30
|
+
emailSender?: (to: string, subject: string, html: string) => Promise<void>;
|
|
17
31
|
adapter: AuthAdapter;
|
|
18
32
|
}
|
|
19
33
|
export interface AuthRequest extends Request {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAElC,MAAM,WAAW,QAAQ;IACvB,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,MAAM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AAW,WAAY,SAAQ,OAAO;IAC1C,IAAI,CAAC,EAAE,QAAQ,CAAC;CACjB"}
|
package/package.json
CHANGED
|
@@ -1,27 +1,40 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ilman00/authkit",
|
|
3
|
-
"version": "1.0
|
|
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",
|
|
7
|
-
"files": [
|
|
7
|
+
"files": [
|
|
8
|
+
"dist"
|
|
9
|
+
],
|
|
8
10
|
"scripts": {
|
|
9
11
|
"build": "tsc",
|
|
10
|
-
"dev": "tsc --watch"
|
|
12
|
+
"dev": "tsc --watch",
|
|
13
|
+
"test": "jest",
|
|
14
|
+
"test:watch": "jest --watch"
|
|
11
15
|
},
|
|
12
16
|
"peerDependencies": {
|
|
13
17
|
"express": "^4.x || ^5.x"
|
|
14
18
|
},
|
|
15
19
|
"dependencies": {
|
|
20
|
+
"@ilman00/authkit": "^1.0.0",
|
|
16
21
|
"bcryptjs": "^2.4.3",
|
|
17
22
|
"jsonwebtoken": "^9.0.0"
|
|
18
23
|
},
|
|
19
24
|
"devDependencies": {
|
|
20
25
|
"@types/bcryptjs": "^2.4.6",
|
|
21
26
|
"@types/express": "^4.17.21",
|
|
27
|
+
"@types/jest": "^30.0.0",
|
|
22
28
|
"@types/jsonwebtoken": "^9.0.0",
|
|
29
|
+
"jest": "^30.4.2",
|
|
30
|
+
"ts-jest": "^29.4.9",
|
|
23
31
|
"typescript": "^5.0.0"
|
|
24
32
|
},
|
|
25
|
-
"keywords": [
|
|
33
|
+
"keywords": [
|
|
34
|
+
"auth",
|
|
35
|
+
"jwt",
|
|
36
|
+
"express",
|
|
37
|
+
"authentication"
|
|
38
|
+
],
|
|
26
39
|
"license": "MIT"
|
|
27
|
-
}
|
|
40
|
+
}
|