sentri 1.1.2 → 2.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/README.md +325 -181
- package/dist/cli.d.ts +0 -2
- package/dist/cli.js +10 -103
- package/dist/index.d.ts +1046 -11
- package/dist/index.js +1 -5
- package/package.json +13 -6
- package/templates/drizzle/auth.ts +47 -4
- package/templates/prisma/auth.ts +47 -4
- package/dist/cli.d.ts.map +0 -1
- package/dist/cli.js.map +0 -1
- package/dist/client.d.ts +0 -160
- package/dist/client.d.ts.map +0 -1
- package/dist/client.js +0 -45
- package/dist/client.js.map +0 -1
- package/dist/errors/AuthError.d.ts +0 -99
- package/dist/errors/AuthError.d.ts.map +0 -1
- package/dist/errors/AuthError.js +0 -97
- package/dist/errors/AuthError.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/libs/config.d.ts +0 -62
- package/dist/libs/config.d.ts.map +0 -1
- package/dist/libs/config.js +0 -97
- package/dist/libs/config.js.map +0 -1
- package/dist/libs/hash.d.ts +0 -17
- package/dist/libs/hash.d.ts.map +0 -1
- package/dist/libs/hash.js +0 -22
- package/dist/libs/hash.js.map +0 -1
- package/dist/libs/token.d.ts +0 -46
- package/dist/libs/token.d.ts.map +0 -1
- package/dist/libs/token.js +0 -118
- package/dist/libs/token.js.map +0 -1
- package/dist/middleware/authorize.d.ts +0 -18
- package/dist/middleware/authorize.d.ts.map +0 -1
- package/dist/middleware/authorize.js +0 -30
- package/dist/middleware/authorize.js.map +0 -1
- package/dist/middleware/errorHandler.d.ts +0 -71
- package/dist/middleware/errorHandler.d.ts.map +0 -1
- package/dist/middleware/errorHandler.js +0 -74
- package/dist/middleware/errorHandler.js.map +0 -1
- package/dist/middleware/permit.d.ts +0 -62
- package/dist/middleware/permit.d.ts.map +0 -1
- package/dist/middleware/permit.js +0 -61
- package/dist/middleware/permit.js.map +0 -1
- package/dist/middleware/protect.d.ts +0 -31
- package/dist/middleware/protect.d.ts.map +0 -1
- package/dist/middleware/protect.js +0 -54
- package/dist/middleware/protect.js.map +0 -1
- package/dist/middleware/router.d.ts +0 -34
- package/dist/middleware/router.d.ts.map +0 -1
- package/dist/middleware/router.js +0 -264
- package/dist/middleware/router.js.map +0 -1
- package/dist/services/auth.d.ts +0 -85
- package/dist/services/auth.d.ts.map +0 -1
- package/dist/services/auth.js +0 -173
- package/dist/services/auth.js.map +0 -1
- package/dist/types/auth.d.ts +0 -450
- package/dist/types/auth.d.ts.map +0 -1
- package/dist/types/auth.js +0 -21
- package/dist/types/auth.js.map +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,18 +1,1053 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { Request, ErrorRequestHandler, RequestHandler, Router } from 'express';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Discriminant codes for built-in {@link SentriError} instances.
|
|
5
|
+
*
|
|
6
|
+
* - `INVALID_CREDENTIALS` — identifier or password did not match (intentionally vague to prevent user enumeration)
|
|
7
|
+
* - `USER_NOT_FOUND` — an operation required a user that does not exist
|
|
8
|
+
* - `USER_ALREADY_EXISTS` — registration was attempted with an identifier already in the database
|
|
9
|
+
* - `TOKEN_EXPIRED` — the JWT was valid but its `exp` claim is in the past
|
|
10
|
+
* - `TOKEN_INVALID` — the JWT could not be verified (bad signature, malformed, wrong type)
|
|
11
|
+
* - `FORBIDDEN` — the user is authenticated but lacks the required role
|
|
12
|
+
* - `UNAUTHORIZED` — no valid access token was present on the request, or the session was revoked
|
|
13
|
+
* - `INVALID_ROLE` — a role name was used that is not in `validRoles`
|
|
14
|
+
* - `VALIDATION_ERROR` — a required field was missing or had an invalid value
|
|
15
|
+
* - `CONFIGURATION_ERROR` — `createAuth` was called with an invalid configuration
|
|
16
|
+
*
|
|
17
|
+
* When you extend {@link SentriError} for your own error types you can use any
|
|
18
|
+
* string as `code` — it does not need to be one of these built-in values.
|
|
19
|
+
*/
|
|
20
|
+
type SentriErrorCode = 'INVALID_CREDENTIALS' | 'USER_NOT_FOUND' | 'USER_ALREADY_EXISTS' | 'TOKEN_EXPIRED' | 'TOKEN_INVALID' | 'FORBIDDEN' | 'UNAUTHORIZED' | 'INVALID_ROLE' | 'VALIDATION_ERROR' | 'CONFIGURATION_ERROR';
|
|
21
|
+
/**
|
|
22
|
+
* Default HTTP status codes for built-in error codes.
|
|
23
|
+
* Custom codes that are not in this map default to 500.
|
|
24
|
+
*
|
|
25
|
+
* @internal
|
|
26
|
+
*/
|
|
27
|
+
declare const AUTH_ERROR_STATUS: Record<string, number>;
|
|
28
|
+
/**
|
|
29
|
+
* Base error class for all authentication and authorization failures in sentri.
|
|
30
|
+
*
|
|
31
|
+
* Every error thrown by sentri is an instance of `SentriError`. The `code`
|
|
32
|
+
* property is a machine-readable string that lets you distinguish error
|
|
33
|
+
* types without string-matching on the message. Built-in codes are listed
|
|
34
|
+
* in {@link SentriErrorCode}; custom subclasses may use any string.
|
|
35
|
+
*
|
|
36
|
+
* The `statusCode` property holds the HTTP status that the built-in router
|
|
37
|
+
* and `auth.errorHandler()` will use in the response. For built-in codes
|
|
38
|
+
* it is derived automatically. Pass it explicitly when subclassing with a
|
|
39
|
+
* custom code.
|
|
40
|
+
*
|
|
41
|
+
* ---
|
|
42
|
+
*
|
|
43
|
+
* **Extending SentriError**
|
|
44
|
+
*
|
|
45
|
+
* You can create application-specific error classes by extending `SentriError`.
|
|
46
|
+
* Any subclass will be caught automatically by `auth.errorHandler()` because
|
|
47
|
+
* `instanceof SentriError` is `true` for all subclasses.
|
|
48
|
+
*
|
|
49
|
+
* ```typescript
|
|
50
|
+
* import { SentriError } from 'sentri';
|
|
51
|
+
*
|
|
52
|
+
* // Domain error with a custom code and explicit HTTP status
|
|
53
|
+
* export class PaymentError extends SentriError {
|
|
54
|
+
* constructor(message: string) {
|
|
55
|
+
* super('PAYMENT_FAILED', message, 402);
|
|
56
|
+
* }
|
|
57
|
+
* }
|
|
58
|
+
*
|
|
59
|
+
* // Throw it anywhere in your routes — auth.errorHandler() catches it
|
|
60
|
+
* router.post('/checkout', auth.protect(), async (req, res) => {
|
|
61
|
+
* const ok = await chargeCard(req.body.cardToken);
|
|
62
|
+
* if (!ok) throw new PaymentError('Card declined');
|
|
63
|
+
* res.json({ success: true });
|
|
64
|
+
* });
|
|
65
|
+
* ```
|
|
66
|
+
*
|
|
67
|
+
* ---
|
|
68
|
+
*
|
|
69
|
+
* **Error handling in custom routes**
|
|
70
|
+
*
|
|
71
|
+
* ```typescript
|
|
72
|
+
* app.use('/auth', auth.router());
|
|
73
|
+
* app.use('/api', apiRouter);
|
|
74
|
+
*
|
|
75
|
+
* // Mount after all routes — catches SentriError from sentri AND your subclasses
|
|
76
|
+
* app.use(auth.errorHandler());
|
|
77
|
+
* ```
|
|
78
|
+
*/
|
|
79
|
+
declare class SentriError extends Error {
|
|
80
|
+
/**
|
|
81
|
+
* Machine-readable error code.
|
|
82
|
+
* Built-in codes are defined by {@link SentriErrorCode}.
|
|
83
|
+
* Custom subclasses may use any string.
|
|
84
|
+
*/
|
|
85
|
+
readonly code: string;
|
|
86
|
+
/**
|
|
87
|
+
* HTTP status code associated with this error.
|
|
88
|
+
* Derived automatically for built-in codes; pass it explicitly when
|
|
89
|
+
* subclassing with a custom `code`.
|
|
90
|
+
*/
|
|
91
|
+
readonly statusCode: number;
|
|
92
|
+
/**
|
|
93
|
+
* @param code - Machine-readable error code. Use a built-in {@link SentriErrorCode}
|
|
94
|
+
* or any string for custom subclasses.
|
|
95
|
+
* @param message - Human-readable description of the error.
|
|
96
|
+
* @param statusCode - HTTP status to use in the response. For built-in codes
|
|
97
|
+
* this is derived automatically; for custom codes it defaults to `500`.
|
|
98
|
+
*/
|
|
99
|
+
constructor(code: SentriErrorCode | (string & {}), message: string, statusCode?: number);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Standard API response envelope returned by all built-in router endpoints. */
|
|
103
|
+
interface ApiResponse<T = null> {
|
|
104
|
+
error: boolean;
|
|
105
|
+
statusCode: number;
|
|
106
|
+
message: string;
|
|
107
|
+
data: T | null;
|
|
108
|
+
}
|
|
109
|
+
/** Shape of a user row returned by the adapter — used internally by the library. */
|
|
110
|
+
interface UserRecord {
|
|
111
|
+
id: string;
|
|
112
|
+
/**
|
|
113
|
+
* The credential identifier for this user (email, username, phone number, etc.).
|
|
114
|
+
* The adapter decides which column(s) this maps to.
|
|
115
|
+
*/
|
|
116
|
+
identifier: string;
|
|
117
|
+
passwordHash: string;
|
|
118
|
+
/** Role names currently assigned to the user. */
|
|
119
|
+
roles: string[];
|
|
120
|
+
}
|
|
121
|
+
/** Shape of a session row returned by the adapter. */
|
|
122
|
+
interface SessionRecord {
|
|
123
|
+
id: string;
|
|
124
|
+
userId: string;
|
|
125
|
+
expiresAt: Date;
|
|
126
|
+
createdAt: Date;
|
|
127
|
+
}
|
|
128
|
+
/** Data the library passes to the adapter when creating a new user. */
|
|
129
|
+
interface CreateUserData {
|
|
130
|
+
/**
|
|
131
|
+
* The credential identifier supplied at registration (email, username, phone, etc.).
|
|
132
|
+
* Store this in whichever column(s) your schema uses for login lookup.
|
|
133
|
+
*/
|
|
134
|
+
identifier: string;
|
|
135
|
+
passwordHash: string;
|
|
136
|
+
/** Validated role names to assign at creation. */
|
|
137
|
+
roles: string[];
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* The database adapter interface the library depends on.
|
|
141
|
+
*
|
|
142
|
+
* Implement this to connect the library to any ORM or data layer.
|
|
143
|
+
*
|
|
144
|
+
* The library uses a single `identifier` string for credentials — your adapter
|
|
145
|
+
* decides what that means: email column, username column, phone column, or a
|
|
146
|
+
* query across multiple columns.
|
|
147
|
+
*/
|
|
148
|
+
interface AuthAdapter {
|
|
149
|
+
user: {
|
|
150
|
+
/**
|
|
151
|
+
* Find a user by their login identifier.
|
|
152
|
+
*
|
|
153
|
+
* The adapter decides which column(s) to query — email, username, phone,
|
|
154
|
+
* or a combined lookup (`WHERE email = $1 OR username = $1`).
|
|
155
|
+
* Returns `null` if not found.
|
|
156
|
+
*/
|
|
157
|
+
findByIdentifier(identifier: string): Promise<UserRecord | null>;
|
|
158
|
+
/** Find a user by their primary key. Returns `null` if not found. */
|
|
159
|
+
findById(id: string): Promise<UserRecord | null>;
|
|
160
|
+
/**
|
|
161
|
+
* Persist a new user with the given identifier, hashed password, and roles.
|
|
162
|
+
* The adapter maps `identifier` to the appropriate column(s) in your schema.
|
|
163
|
+
*/
|
|
164
|
+
create(data: CreateUserData): Promise<{
|
|
165
|
+
id: string;
|
|
166
|
+
}>;
|
|
167
|
+
/**
|
|
168
|
+
* Replace the complete role list for a user.
|
|
169
|
+
* Called by `assignRoles` after merging the new roles with the existing ones.
|
|
170
|
+
*/
|
|
171
|
+
updateRoles(userId: string, roles: string[]): Promise<void>;
|
|
172
|
+
};
|
|
173
|
+
session: {
|
|
174
|
+
/**
|
|
175
|
+
* Persist a new session and return its generated ID.
|
|
176
|
+
* `expiresAt` is computed from `refreshExpiresIn` in config.
|
|
177
|
+
*/
|
|
178
|
+
create(data: {
|
|
179
|
+
userId: string;
|
|
180
|
+
expiresAt: Date;
|
|
181
|
+
}): Promise<{
|
|
182
|
+
id: string;
|
|
183
|
+
}>;
|
|
184
|
+
/**
|
|
185
|
+
* Find a session by its ID, including the associated user.
|
|
186
|
+
* Returns `null` if the session does not exist (i.e. has been revoked).
|
|
187
|
+
*/
|
|
188
|
+
findById(sessionId: string): Promise<(SessionRecord & {
|
|
189
|
+
user: UserRecord;
|
|
190
|
+
}) | null>;
|
|
191
|
+
/** Delete a single session. Used during logout and token rotation. */
|
|
192
|
+
delete(sessionId: string): Promise<void>;
|
|
193
|
+
/** Delete all sessions belonging to a user. Used for "logout from all devices". */
|
|
194
|
+
deleteAllForUser(userId: string): Promise<void>;
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Custom service functions for the built-in auth router.
|
|
199
|
+
*
|
|
200
|
+
* Each key matches the internal service function name. When provided, the
|
|
201
|
+
* custom function replaces the default service call for that route while the
|
|
202
|
+
* router still handles request parsing, input validation, and response formatting.
|
|
203
|
+
*
|
|
204
|
+
* The function signatures mirror the internal services exactly but without the
|
|
205
|
+
* `config` parameter — the library passes config at bind time.
|
|
206
|
+
*
|
|
207
|
+
* @example
|
|
208
|
+
* createAuth({
|
|
209
|
+
* // ...
|
|
210
|
+
* router: {
|
|
211
|
+
* login: async (input) => {
|
|
212
|
+
* // add OTP check, custom user lookup, etc.
|
|
213
|
+
* // must return AuthResult
|
|
214
|
+
* },
|
|
215
|
+
* register: async (input) => {
|
|
216
|
+
* // send welcome email, set default profile, etc.
|
|
217
|
+
* // must return RegisterResult
|
|
218
|
+
* },
|
|
219
|
+
* },
|
|
220
|
+
* });
|
|
221
|
+
*/
|
|
222
|
+
interface RouterHandlers {
|
|
223
|
+
/**
|
|
224
|
+
* Replaces the default register service (`POST /register`).
|
|
225
|
+
*
|
|
226
|
+
* The router validates the request body (identifier, password, roles) first,
|
|
227
|
+
* then calls this function with the parsed input. Must return a `RegisterResult`.
|
|
228
|
+
* If omitted, the library's built-in registration logic runs instead.
|
|
229
|
+
*
|
|
230
|
+
* @example
|
|
231
|
+
* register: async (input) => {
|
|
232
|
+
* const result = await defaultRegister(input);
|
|
233
|
+
* if (result.success) {
|
|
234
|
+
* await emailService.sendWelcome(input.identifier);
|
|
235
|
+
* }
|
|
236
|
+
* return result;
|
|
237
|
+
* }
|
|
238
|
+
*/
|
|
239
|
+
register?: (input: RegisterInput) => Promise<RegisterResult>;
|
|
240
|
+
/**
|
|
241
|
+
* Replaces the default login service.
|
|
242
|
+
*
|
|
243
|
+
* The router validates the request body (identifier, password) first,
|
|
244
|
+
* then calls this function with the parsed input. Must return an `AuthResult`.
|
|
245
|
+
* If omitted, the library's built-in login logic runs instead.
|
|
246
|
+
*
|
|
247
|
+
* @example
|
|
248
|
+
* login: async (input) => {
|
|
249
|
+
* // verify OTP before issuing tokens
|
|
250
|
+
* const otpValid = await redis.get(`otp:${input.identifier}`);
|
|
251
|
+
* if (!otpValid) {
|
|
252
|
+
* return { success: false, error: new SentriError('INVALID_CREDENTIALS', 'OTP required') };
|
|
253
|
+
* }
|
|
254
|
+
* return defaultLogin(input);
|
|
255
|
+
* }
|
|
256
|
+
*/
|
|
257
|
+
login?: (input: LoginInput) => Promise<AuthResult>;
|
|
258
|
+
/**
|
|
259
|
+
* Replaces the default refresh service.
|
|
260
|
+
*
|
|
261
|
+
* Receives the raw refresh token string extracted from the cookie.
|
|
262
|
+
* Must return a `RefreshResult`. If omitted, the built-in session-rotation
|
|
263
|
+
* logic runs instead.
|
|
264
|
+
*
|
|
265
|
+
* @example
|
|
266
|
+
* refresh: async (refreshToken) => {
|
|
267
|
+
* const result = await defaultRefresh(refreshToken);
|
|
268
|
+
* if (result.success) {
|
|
269
|
+
* await auditLog.record('token_rotated', result.user.id);
|
|
270
|
+
* }
|
|
271
|
+
* return result;
|
|
272
|
+
* }
|
|
273
|
+
*/
|
|
274
|
+
refresh?: (refreshToken: string) => Promise<RefreshResult>;
|
|
275
|
+
/**
|
|
276
|
+
* Replaces the default logout service.
|
|
277
|
+
*
|
|
278
|
+
* Receives the raw refresh token from the cookie, or `undefined` if no cookie
|
|
279
|
+
* was present. The router clears the cookie after this function resolves.
|
|
280
|
+
* If omitted, the built-in session deletion logic runs instead.
|
|
281
|
+
*
|
|
282
|
+
* @example
|
|
283
|
+
* logout: async (refreshToken) => {
|
|
284
|
+
* if (refreshToken) {
|
|
285
|
+
* await defaultLogout(refreshToken);
|
|
286
|
+
* await auditLog.record('logout', refreshToken);
|
|
287
|
+
* }
|
|
288
|
+
* }
|
|
289
|
+
*/
|
|
290
|
+
logout?: (refreshToken: string | undefined) => Promise<void>;
|
|
291
|
+
/**
|
|
292
|
+
* Replaces the default logoutAll service.
|
|
293
|
+
*
|
|
294
|
+
* Receives the authenticated user's ID (from `req.user`, set by `protect()`).
|
|
295
|
+
* If omitted, the built-in "delete all sessions" logic runs instead.
|
|
296
|
+
*
|
|
297
|
+
* @example
|
|
298
|
+
* logoutAll: async (userId) => {
|
|
299
|
+
* await defaultLogoutAll(userId);
|
|
300
|
+
* await notifyService.push(userId, 'You have been signed out from all devices.');
|
|
301
|
+
* }
|
|
302
|
+
*/
|
|
303
|
+
logoutAll?: (userId: string) => Promise<void>;
|
|
304
|
+
/**
|
|
305
|
+
* Replaces the default assignRoles service.
|
|
306
|
+
*
|
|
307
|
+
* The router validates the request body and params first, then calls this
|
|
308
|
+
* function with the target `userId` and the validated `roles` array.
|
|
309
|
+
* Must return an `AssignRolesResult`. If omitted, the built-in role-merge
|
|
310
|
+
* logic runs instead.
|
|
311
|
+
*
|
|
312
|
+
* @example
|
|
313
|
+
* assignRoles: async (userId, roles) => {
|
|
314
|
+
* const result = await defaultAssignRoles(userId, roles);
|
|
315
|
+
* if (result.success) {
|
|
316
|
+
* await auditLog.record('roles_assigned', { userId, roles });
|
|
317
|
+
* }
|
|
318
|
+
* return result;
|
|
319
|
+
* }
|
|
320
|
+
*/
|
|
321
|
+
assignRoles?: (userId: string, roles: string[]) => Promise<AssignRolesResult>;
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Lifecycle hooks called by the built-in auth router at key points in the
|
|
325
|
+
* authentication flow. All hooks are optional and fire as side effects —
|
|
326
|
+
* returning a rejected Promise from a hook **does not** abort the request.
|
|
327
|
+
*
|
|
328
|
+
* Common uses: audit logging, metrics, rate-limit counters, notifications.
|
|
329
|
+
*
|
|
330
|
+
* @example
|
|
331
|
+
* createAuth({
|
|
332
|
+
* hooks: {
|
|
333
|
+
* onLogin: (user) => logger.info('login', { userId: user.id }),
|
|
334
|
+
* onFailedLogin: (identifier) => rateLimiter.hit(identifier),
|
|
335
|
+
* onLogout: (userId) => cache.invalidate(userId),
|
|
336
|
+
* },
|
|
337
|
+
* });
|
|
338
|
+
*/
|
|
339
|
+
interface AuthHooks {
|
|
340
|
+
/**
|
|
341
|
+
* Called after a successful login.
|
|
342
|
+
* Receives the authenticated user. Use for audit logs, login notifications, etc.
|
|
343
|
+
*/
|
|
344
|
+
onLogin?: (user: AuthUser) => void | Promise<void>;
|
|
345
|
+
/**
|
|
346
|
+
* Called after a failed login attempt (wrong password or unknown identifier).
|
|
347
|
+
* Receives the identifier that was attempted and the error.
|
|
348
|
+
* Use to increment rate-limit counters or alert on repeated failures.
|
|
349
|
+
*/
|
|
350
|
+
onFailedLogin?: (identifier: string, error: SentriError) => void | Promise<void>;
|
|
351
|
+
/**
|
|
352
|
+
* Called after a successful logout (single session or all sessions).
|
|
353
|
+
* Receives the user ID. Use for audit logs or cache invalidation.
|
|
354
|
+
*/
|
|
355
|
+
onLogout?: (userId: string) => void | Promise<void>;
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Configuration passed to {@link createAuth}.
|
|
359
|
+
*
|
|
360
|
+
* Only `secret`, `validRoles`, and `adapter` are required.
|
|
361
|
+
* All other fields have sensible defaults.
|
|
362
|
+
*
|
|
363
|
+
* @example
|
|
364
|
+
* createAuth({
|
|
365
|
+
* secret: process.env.JWT_SECRET!,
|
|
366
|
+
* validRoles: ['user', 'admin'] as const,
|
|
367
|
+
* adapter: myAdapter,
|
|
368
|
+
* });
|
|
369
|
+
*/
|
|
370
|
+
interface AuthConfig<TRole extends string = string> {
|
|
371
|
+
/** Secret used to sign JWT tokens. Must not be empty. Keep this in an env variable. */
|
|
372
|
+
secret: string;
|
|
373
|
+
/**
|
|
374
|
+
* How long access tokens are valid.
|
|
375
|
+
* Accepts a duration string (`'15m'`, `'1h'`) or seconds as a number.
|
|
376
|
+
* @default '15m'
|
|
377
|
+
*/
|
|
378
|
+
accessExpiresIn?: string | number;
|
|
379
|
+
/**
|
|
380
|
+
* How long refresh tokens / sessions are valid.
|
|
381
|
+
* Accepts a duration string (`'7d'`, `'30d'`) or seconds as a number.
|
|
382
|
+
* @default '7d'
|
|
383
|
+
*/
|
|
384
|
+
refreshExpiresIn?: string | number;
|
|
385
|
+
/**
|
|
386
|
+
* HMAC signing algorithm used for JWTs.
|
|
387
|
+
* @default 'HS256'
|
|
388
|
+
*/
|
|
389
|
+
algorithm?: 'HS256' | 'HS384' | 'HS512';
|
|
390
|
+
/**
|
|
391
|
+
* bcrypt cost factor. Higher = slower hashing but more secure.
|
|
392
|
+
* @default 12
|
|
393
|
+
*/
|
|
394
|
+
saltRounds?: number;
|
|
395
|
+
/**
|
|
396
|
+
* Exhaustive list of role names your application uses.
|
|
397
|
+
* Registration will be rejected with `INVALID_ROLE` if a role outside this list is requested.
|
|
398
|
+
* Use `as const` to get TypeScript union-type safety on `authorize()`.
|
|
399
|
+
*
|
|
400
|
+
* @example
|
|
401
|
+
* validRoles: ['user', 'admin', 'moderator'] as const
|
|
402
|
+
*/
|
|
403
|
+
validRoles: readonly TRole[];
|
|
404
|
+
/** ORM adapter that connects the library to your database. */
|
|
405
|
+
adapter: AuthAdapter;
|
|
406
|
+
/**
|
|
407
|
+
* API key required to call `POST /register`.
|
|
408
|
+
*
|
|
409
|
+
* When set, the `/register` endpoint expects an `X-Api-Key` header whose
|
|
410
|
+
* value matches this string exactly. Requests without the header, or with
|
|
411
|
+
* the wrong value, are rejected with HTTP 401 (`UNAUTHORIZED`).
|
|
412
|
+
*
|
|
413
|
+
* Use this to restrict self-registration — for example, only your own
|
|
414
|
+
* back-office service or admin panel should be able to create new accounts,
|
|
415
|
+
* so you never expose user registration to arbitrary callers.
|
|
416
|
+
*
|
|
417
|
+
* @example
|
|
418
|
+
* createAuth({
|
|
419
|
+
* // ...
|
|
420
|
+
* apiKey: process.env.REGISTER_API_KEY!,
|
|
421
|
+
* });
|
|
422
|
+
*
|
|
423
|
+
* // Client must send:
|
|
424
|
+
* // POST /auth/register
|
|
425
|
+
* // X-Api-Key: <value of REGISTER_API_KEY>
|
|
426
|
+
*/
|
|
427
|
+
apiKey?: string;
|
|
428
|
+
/**
|
|
429
|
+
* Custom service functions for individual routes in the built-in auth router.
|
|
430
|
+
*
|
|
431
|
+
* The router still handles request parsing, validation, and response formatting.
|
|
432
|
+
* Only the core service logic is replaced by your function.
|
|
433
|
+
*
|
|
434
|
+
* @example
|
|
435
|
+
* createAuth({
|
|
436
|
+
* // ...
|
|
437
|
+
* router: {
|
|
438
|
+
* login: async (input) => {
|
|
439
|
+
* // verify OTP, then delegate to default or return custom result
|
|
440
|
+
* return { success: true, accessToken, refreshToken, user };
|
|
441
|
+
* },
|
|
442
|
+
* register: async (input) => {
|
|
443
|
+
* // send welcome email after successful registration
|
|
444
|
+
* const result = await defaultRegister(input);
|
|
445
|
+
* if (result.success) await emailService.sendWelcome(input.identifier);
|
|
446
|
+
* return result;
|
|
447
|
+
* },
|
|
448
|
+
* },
|
|
449
|
+
* });
|
|
450
|
+
*/
|
|
451
|
+
router?: RouterHandlers;
|
|
452
|
+
/**
|
|
453
|
+
* When set, the built-in router (`auth.router()`) stores the refresh token
|
|
454
|
+
* in an httpOnly cookie instead of returning it in the response body.
|
|
455
|
+
*
|
|
456
|
+
* The `refreshToken` field is omitted from `/login` and `/refresh` responses.
|
|
457
|
+
* The `/logout` and `/logout-all` routes automatically clear the cookie.
|
|
458
|
+
*
|
|
459
|
+
* No extra middleware (e.g. `cookie-parser`) is required.
|
|
460
|
+
*
|
|
461
|
+
* @example
|
|
462
|
+
* createAuth({
|
|
463
|
+
* // ...
|
|
464
|
+
* cookie: { secure: process.env.NODE_ENV === 'production' },
|
|
465
|
+
* });
|
|
466
|
+
*/
|
|
467
|
+
cookie?: CookieConfig;
|
|
468
|
+
/**
|
|
469
|
+
* Lifecycle hooks called at key points in the auth flow.
|
|
470
|
+
*
|
|
471
|
+
* All hooks fire as side effects — a rejected hook Promise is silently
|
|
472
|
+
* swallowed so a broken hook can never take down a login request.
|
|
473
|
+
*
|
|
474
|
+
* @example
|
|
475
|
+
* createAuth({
|
|
476
|
+
* hooks: {
|
|
477
|
+
* onLogin: async (user) => {
|
|
478
|
+
* await auditLog.record('login', user.id);
|
|
479
|
+
* },
|
|
480
|
+
* onFailedLogin: (identifier) => {
|
|
481
|
+
* rateLimiter.hit(`login:${identifier}`);
|
|
482
|
+
* },
|
|
483
|
+
* },
|
|
484
|
+
* });
|
|
485
|
+
*/
|
|
486
|
+
hooks?: AuthHooks;
|
|
487
|
+
/**
|
|
488
|
+
* Optional guard called by `protect()` after verifying the access token's
|
|
489
|
+
* signature and expiry. Return `true` to reject the token immediately, even
|
|
490
|
+
* if it is cryptographically valid.
|
|
491
|
+
*
|
|
492
|
+
* Use this for **immediate token revocation** — for example, store revoked
|
|
493
|
+
* `sessionId` values in Redis and check membership here:
|
|
494
|
+
*
|
|
495
|
+
* ```typescript
|
|
496
|
+
* isTokenRevoked: async (sessionId) =>
|
|
497
|
+
* await redis.sismember('revoked_sessions', sessionId),
|
|
498
|
+
* ```
|
|
499
|
+
*
|
|
500
|
+
* **Performance note:** this function is called on every protected request.
|
|
501
|
+
* Keep it fast (e.g. a single Redis GET/SISMEMBER) or the latency benefit
|
|
502
|
+
* of stateless access tokens is lost. If you can tolerate a short revocation
|
|
503
|
+
* window equal to `accessExpiresIn`, omit this hook entirely.
|
|
504
|
+
*
|
|
505
|
+
* @param sessionId - The `sessionId` embedded in the access token at login time.
|
|
506
|
+
* @returns `true` if the token should be rejected, `false` (or `undefined`) to allow.
|
|
507
|
+
*/
|
|
508
|
+
isTokenRevoked?: (sessionId: string) => boolean | Promise<boolean>;
|
|
509
|
+
/**
|
|
510
|
+
* When set, the built-in router also stores the **access token** in a
|
|
511
|
+
* non-httpOnly cookie so browser JavaScript can read it via
|
|
512
|
+
* `document.cookie` or the `getCurrentAccessToken` helper.
|
|
513
|
+
*
|
|
514
|
+
* `protect()` reads the access token from this cookie when no
|
|
515
|
+
* `Authorization: Bearer` header is present, so clients can skip the
|
|
516
|
+
* manual header management entirely.
|
|
517
|
+
*
|
|
518
|
+
* The cookie's `max-age` is derived automatically from `config.accessExpiresIn`.
|
|
519
|
+
* When `protect()` performs a silent refresh, the access token cookie is
|
|
520
|
+
* updated in the same response.
|
|
521
|
+
*
|
|
522
|
+
* @example
|
|
523
|
+
* createAuth({
|
|
524
|
+
* accessExpiresIn: '5m',
|
|
525
|
+
* accessCookie: { secure: process.env.NODE_ENV === 'production' },
|
|
526
|
+
* cookie: { secure: process.env.NODE_ENV === 'production' },
|
|
527
|
+
* });
|
|
528
|
+
*/
|
|
529
|
+
accessCookie?: AccessCookieConfig;
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* Cookie settings for storing the refresh token in an httpOnly cookie.
|
|
533
|
+
* All fields are optional — defaults are chosen for security.
|
|
534
|
+
*/
|
|
535
|
+
interface CookieConfig {
|
|
536
|
+
/**
|
|
537
|
+
* Name of the cookie.
|
|
538
|
+
* @default 'refresh_token'
|
|
539
|
+
*/
|
|
540
|
+
name?: string;
|
|
541
|
+
/**
|
|
542
|
+
* Prevents JavaScript from reading the cookie (`document.cookie`).
|
|
543
|
+
* @default true
|
|
544
|
+
*/
|
|
545
|
+
httpOnly?: boolean;
|
|
546
|
+
/**
|
|
547
|
+
* Restricts the cookie to HTTPS connections.
|
|
548
|
+
* Set to `true` in production.
|
|
549
|
+
* @default false
|
|
550
|
+
*/
|
|
551
|
+
secure?: boolean;
|
|
552
|
+
/**
|
|
553
|
+
* Controls cross-site request behaviour.
|
|
554
|
+
* @default 'strict'
|
|
555
|
+
*/
|
|
556
|
+
sameSite?: 'strict' | 'lax' | 'none';
|
|
557
|
+
/**
|
|
558
|
+
* URL path the cookie is scoped to.
|
|
559
|
+
* @default '/'
|
|
560
|
+
*/
|
|
561
|
+
path?: string;
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* Cookie settings for storing the access token in a **non**-httpOnly cookie.
|
|
565
|
+
*
|
|
566
|
+
* Because `httpOnly` is intentionally `false`, browser JavaScript can read this
|
|
567
|
+
* cookie via `document.cookie` or the `getCurrentAccessToken` helper, which makes
|
|
568
|
+
* it convenient for SPAs that need to attach the token to outgoing requests.
|
|
569
|
+
*
|
|
570
|
+
* The cookie's `max-age` is derived automatically from `config.accessExpiresIn`.
|
|
571
|
+
*
|
|
572
|
+
* All fields are optional — safe defaults are applied.
|
|
573
|
+
*/
|
|
574
|
+
interface AccessCookieConfig {
|
|
575
|
+
/**
|
|
576
|
+
* Name of the access token cookie.
|
|
577
|
+
* @default 'access_token'
|
|
578
|
+
*/
|
|
579
|
+
name?: string;
|
|
580
|
+
/**
|
|
581
|
+
* Restricts the cookie to HTTPS connections.
|
|
582
|
+
* Set to `true` in production.
|
|
583
|
+
* @default false
|
|
584
|
+
*/
|
|
585
|
+
secure?: boolean;
|
|
586
|
+
/**
|
|
587
|
+
* Controls cross-site request behaviour.
|
|
588
|
+
* @default 'strict'
|
|
589
|
+
*/
|
|
590
|
+
sameSite?: 'strict' | 'lax' | 'none';
|
|
591
|
+
/**
|
|
592
|
+
* URL path the cookie is scoped to.
|
|
593
|
+
* @default '/'
|
|
594
|
+
*/
|
|
595
|
+
path?: string;
|
|
596
|
+
}
|
|
597
|
+
/**
|
|
598
|
+
* The user payload injected as `req.user` after `protect()` runs.
|
|
599
|
+
*
|
|
600
|
+
* Access tokens issued by sentri >= 1.1.0 embed a `sessionId` that is
|
|
601
|
+
* validated against the database on every request. Tokens from older
|
|
602
|
+
* versions that lack this claim are accepted but bypass session validation.
|
|
603
|
+
*/
|
|
604
|
+
interface AuthUser<TRole extends string = string> {
|
|
605
|
+
id: string;
|
|
606
|
+
/**
|
|
607
|
+
* The credential identifier for this user (email, username, phone, etc.).
|
|
608
|
+
* Reflects whatever value was passed as `identifier` at registration or login.
|
|
609
|
+
*/
|
|
610
|
+
identifier: string;
|
|
611
|
+
roles: TRole[];
|
|
612
|
+
}
|
|
613
|
+
/** Return type of `register`. */
|
|
614
|
+
type RegisterResult<TRole extends string = string> = {
|
|
615
|
+
success: true;
|
|
616
|
+
user: AuthUser<TRole>;
|
|
617
|
+
} | {
|
|
618
|
+
success: false;
|
|
619
|
+
error: SentriError;
|
|
620
|
+
};
|
|
621
|
+
/** Return type of `login`. */
|
|
622
|
+
type AuthResult<TRole extends string = string> = {
|
|
623
|
+
success: true;
|
|
624
|
+
accessToken: string;
|
|
625
|
+
refreshToken: string;
|
|
626
|
+
user: AuthUser<TRole>;
|
|
627
|
+
} | {
|
|
628
|
+
success: false;
|
|
629
|
+
error: SentriError;
|
|
630
|
+
};
|
|
631
|
+
/** Return type of `assignRoles`. */
|
|
632
|
+
type AssignRolesResult<TRole extends string = string> = {
|
|
633
|
+
success: true;
|
|
634
|
+
user: AuthUser<TRole>;
|
|
635
|
+
} | {
|
|
636
|
+
success: false;
|
|
637
|
+
error: SentriError;
|
|
638
|
+
};
|
|
639
|
+
/** Return type of `refresh`. */
|
|
640
|
+
type RefreshResult<TRole extends string = string> = {
|
|
641
|
+
success: true;
|
|
642
|
+
accessToken: string;
|
|
643
|
+
refreshToken: string;
|
|
644
|
+
user: AuthUser<TRole>;
|
|
645
|
+
} | {
|
|
646
|
+
success: false;
|
|
647
|
+
error: SentriError;
|
|
648
|
+
};
|
|
649
|
+
/** Input for `register`. */
|
|
650
|
+
interface RegisterInput<TRole extends string = string> {
|
|
651
|
+
/**
|
|
652
|
+
* The user's login credential — email, username, phone number, or any unique string.
|
|
653
|
+
* The adapter maps this to the appropriate column in your database.
|
|
654
|
+
*/
|
|
655
|
+
identifier: string;
|
|
656
|
+
password: string;
|
|
657
|
+
/** Roles to assign at creation. Must be a subset of `validRoles`. */
|
|
658
|
+
roles?: TRole[];
|
|
659
|
+
}
|
|
660
|
+
/** Input for `login`. */
|
|
661
|
+
interface LoginInput {
|
|
662
|
+
/**
|
|
663
|
+
* The user's login credential — email, username, phone number, or any unique string.
|
|
664
|
+
* The adapter's `findByIdentifier` handles the lookup.
|
|
665
|
+
*/
|
|
666
|
+
identifier: string;
|
|
667
|
+
password: string;
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
/** A function that determines whether the current request is permitted. */
|
|
671
|
+
type PermitCheck = (request: Request) => boolean | Promise<boolean>;
|
|
672
|
+
/**
|
|
673
|
+
* Options for {@link permit} when you need role-bypass alongside a resource check.
|
|
674
|
+
*
|
|
675
|
+
* @example
|
|
676
|
+
* // Admins can edit any post; others only their own
|
|
677
|
+
* auth.permit({
|
|
678
|
+
* roles: ['admin'],
|
|
679
|
+
* check: async (request) => {
|
|
680
|
+
* const post = await db.findPost(request.params['id']);
|
|
681
|
+
* return post?.authorId === request.user!.id;
|
|
682
|
+
* },
|
|
683
|
+
* })
|
|
684
|
+
*/
|
|
685
|
+
interface PermitOptions<TRole extends string> {
|
|
686
|
+
/**
|
|
687
|
+
* Roles whose members are granted access without running `check`.
|
|
688
|
+
* Use for privileged roles like `'admin'` that should bypass ownership checks.
|
|
689
|
+
*/
|
|
690
|
+
roles?: TRole[];
|
|
691
|
+
/**
|
|
692
|
+
* Permission check executed when the user has none of the bypass `roles`.
|
|
693
|
+
* Return `true` to allow, `false` to deny with `FORBIDDEN`.
|
|
694
|
+
* May be async — useful for database-backed ownership checks.
|
|
695
|
+
*/
|
|
696
|
+
check: PermitCheck;
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
/**
|
|
700
|
+
* Options for {@link createErrorHandler}.
|
|
701
|
+
*/
|
|
702
|
+
interface ErrorHandlerOptions {
|
|
703
|
+
/**
|
|
704
|
+
* Called for errors that are **not** a `SentriError` instance (or subclass).
|
|
705
|
+
*
|
|
706
|
+
* Use this to log unexpected server errors before the generic 500 response
|
|
707
|
+
* is sent. The error is passed as-is and may be any unknown value.
|
|
708
|
+
*
|
|
709
|
+
* @example
|
|
710
|
+
* app.use(auth.errorHandler({
|
|
711
|
+
* onUnhandled: (err) => logger.error('Unhandled error', { err }),
|
|
712
|
+
* }));
|
|
713
|
+
*/
|
|
714
|
+
onUnhandled?: (error: unknown) => void;
|
|
715
|
+
}
|
|
716
|
+
/**
|
|
717
|
+
* Creates an Express error-handling middleware that formats every `SentriError`
|
|
718
|
+
* (including subclasses) into the standard sentri response envelope:
|
|
719
|
+
*
|
|
720
|
+
* ```json
|
|
721
|
+
* { "error": true, "statusCode": 401, "code": "UNAUTHORIZED", "message": "...", "data": null }
|
|
722
|
+
* ```
|
|
723
|
+
*
|
|
724
|
+
* Prefer using `auth.errorHandler()` instead of calling this directly:
|
|
725
|
+
*
|
|
726
|
+
* ```typescript
|
|
727
|
+
* app.use('/auth', auth.router());
|
|
728
|
+
* app.use('/api', apiRouter);
|
|
729
|
+
*
|
|
730
|
+
* // Must come after all route/middleware registrations
|
|
731
|
+
* app.use(auth.errorHandler());
|
|
732
|
+
* ```
|
|
733
|
+
*
|
|
734
|
+
* ---
|
|
735
|
+
*
|
|
736
|
+
* **Works with built-in sentri errors and your own subclasses**
|
|
737
|
+
*
|
|
738
|
+
* Because `instanceof SentriError` matches any subclass, you can define
|
|
739
|
+
* application-specific error types and have them automatically formatted
|
|
740
|
+
* by this handler:
|
|
741
|
+
*
|
|
742
|
+
* ```typescript
|
|
743
|
+
* import { SentriError } from 'sentri';
|
|
744
|
+
*
|
|
745
|
+
* // Extend SentriError for domain-specific failures
|
|
746
|
+
* export class NotFoundError extends SentriError {
|
|
747
|
+
* constructor(resource: string) {
|
|
748
|
+
* super('NOT_FOUND', `${resource} not found`, 404);
|
|
749
|
+
* }
|
|
750
|
+
* }
|
|
751
|
+
*
|
|
752
|
+
* export class PaymentError extends SentriError {
|
|
753
|
+
* constructor(message: string) {
|
|
754
|
+
* super('PAYMENT_FAILED', message, 402);
|
|
755
|
+
* }
|
|
756
|
+
* }
|
|
757
|
+
*
|
|
758
|
+
* // All of the above are caught and formatted by one handler
|
|
759
|
+
* app.use(auth.errorHandler({
|
|
760
|
+
* onUnhandled: (err) => console.error('Unexpected error:', err),
|
|
761
|
+
* }));
|
|
762
|
+
* ```
|
|
763
|
+
*
|
|
764
|
+
* @param options - Optional configuration (see {@link ErrorHandlerOptions}).
|
|
765
|
+
* @returns An Express `ErrorRequestHandler` (4-argument middleware).
|
|
766
|
+
*/
|
|
767
|
+
declare function createErrorHandler(options?: ErrorHandlerOptions): ErrorRequestHandler;
|
|
768
|
+
|
|
769
|
+
/**
|
|
770
|
+
* The bound auth client returned by {@link createAuth}.
|
|
771
|
+
*
|
|
772
|
+
* All methods are pre-configured with the options passed to `createAuth` —
|
|
773
|
+
* you never need to pass config around yourself.
|
|
774
|
+
*
|
|
775
|
+
* `TRole` is inferred from `validRoles` and narrows role strings to your
|
|
776
|
+
* application's exact union type everywhere (authorize, req.user, etc.).
|
|
777
|
+
*/
|
|
778
|
+
interface AuthClient<TRole extends string = string> {
|
|
779
|
+
/**
|
|
780
|
+
* Express middleware factory that enforces authentication.
|
|
781
|
+
*
|
|
782
|
+
* Reads the `Authorization: Bearer <token>` header, verifies the access token,
|
|
783
|
+
* confirms the session is still active in the database, and injects the decoded
|
|
784
|
+
* payload as `request.user`. Calls `next(SentriError)` on any failure.
|
|
785
|
+
*
|
|
786
|
+
* @example
|
|
787
|
+
* router.get('/me', auth.protect(), (request, response) => {
|
|
788
|
+
* response.json(request.user);
|
|
789
|
+
* });
|
|
790
|
+
*/
|
|
791
|
+
protect(): RequestHandler;
|
|
792
|
+
/**
|
|
793
|
+
* Express middleware factory that enforces role-based access.
|
|
794
|
+
*
|
|
795
|
+
* Must be used **after** `protect()`. Passes if the authenticated user has
|
|
796
|
+
* at least one of the specified roles; otherwise calls `next(SentriError)` with
|
|
797
|
+
* code `FORBIDDEN`.
|
|
798
|
+
*
|
|
799
|
+
* @example
|
|
800
|
+
* router.delete('/posts/:id', auth.protect(), auth.authorize('admin'), handler);
|
|
801
|
+
*/
|
|
802
|
+
authorize(...roles: TRole[]): RequestHandler;
|
|
803
|
+
/**
|
|
804
|
+
* Express middleware factory for resource-level permission checks.
|
|
805
|
+
*
|
|
806
|
+
* Must be used **after** `protect()`. Evaluates a check function against the
|
|
807
|
+
* current request and calls `next(SentriError)` with `FORBIDDEN` if it returns `false`.
|
|
808
|
+
*
|
|
809
|
+
* Accepts either a bare check function or an options object with an optional
|
|
810
|
+
* `roles` list whose members bypass the check entirely.
|
|
811
|
+
*
|
|
812
|
+
* @example
|
|
813
|
+
* // User can only update their own profile
|
|
814
|
+
* router.put('/users/:id',
|
|
815
|
+
* auth.protect(),
|
|
816
|
+
* auth.permit((request) => request.user!.id === request.params['id']),
|
|
817
|
+
* handler,
|
|
818
|
+
* );
|
|
819
|
+
*
|
|
820
|
+
* @example
|
|
821
|
+
* // Admins bypass the check; others must own the resource
|
|
822
|
+
* router.delete('/posts/:id',
|
|
823
|
+
* auth.protect(),
|
|
824
|
+
* auth.permit({
|
|
825
|
+
* roles: ['admin'],
|
|
826
|
+
* check: async (request) => {
|
|
827
|
+
* const post = await db.post.findUnique({ where: { id: request.params['id'] } });
|
|
828
|
+
* return post?.authorId === request.user!.id;
|
|
829
|
+
* },
|
|
830
|
+
* }),
|
|
831
|
+
* handler,
|
|
832
|
+
* );
|
|
833
|
+
*/
|
|
834
|
+
permit(check: PermitCheck): RequestHandler;
|
|
835
|
+
permit(options: PermitOptions<TRole>): RequestHandler;
|
|
836
|
+
/** Hash a plain-text password using the configured `saltRounds`. */
|
|
837
|
+
hashPassword(plain: string): Promise<string>;
|
|
838
|
+
/** Compare a plain-text password against a stored bcrypt hash. */
|
|
839
|
+
verifyPassword(plain: string, hash: string): Promise<boolean>;
|
|
840
|
+
/** Sign an access token for the given user payload. */
|
|
841
|
+
signAccessToken(payload: AuthUser<TRole>): string;
|
|
842
|
+
/** Sign a refresh token bound to a session ID. */
|
|
843
|
+
signRefreshToken(sessionId: string): string;
|
|
844
|
+
/** Verify and decode an access token. Throws `SentriError` if invalid or expired. */
|
|
845
|
+
verifyAccessToken(token: string): AuthUser<TRole>;
|
|
846
|
+
/** Verify and decode a refresh token. Throws `SentriError` if invalid or expired. */
|
|
847
|
+
verifyRefreshToken(token: string): {
|
|
848
|
+
sessionId: string;
|
|
849
|
+
};
|
|
850
|
+
/**
|
|
851
|
+
* Extract the raw access token string from an incoming Express request.
|
|
852
|
+
*
|
|
853
|
+
* Checks two sources in order:
|
|
854
|
+
* 1. `Authorization: Bearer <token>` header
|
|
855
|
+
* 2. Access token cookie (name from `config.accessCookie.name`, default `'access_token'`)
|
|
856
|
+
*
|
|
857
|
+
* Returns `undefined` when neither source is present.
|
|
858
|
+
*
|
|
859
|
+
* Useful in custom middleware or logging where you need the raw token without
|
|
860
|
+
* running full JWT verification.
|
|
861
|
+
*
|
|
862
|
+
* @example
|
|
863
|
+
* app.use((req, _res, next) => {
|
|
864
|
+
* const token = auth.getCurrentAccessToken(req);
|
|
865
|
+
* if (token) logger.debug('access token present');
|
|
866
|
+
* next();
|
|
867
|
+
* });
|
|
868
|
+
*/
|
|
869
|
+
getCurrentAccessToken(request: Request): string | undefined;
|
|
870
|
+
/**
|
|
871
|
+
* Returns a pre-built Express Router with all standard auth endpoints mounted.
|
|
872
|
+
*
|
|
873
|
+
* Endpoints:
|
|
874
|
+
* - `POST /register` — register a new user. Requires `X-Api-Key` header when `config.apiKey` is set.
|
|
875
|
+
* - `POST /login` — authenticate, sets refresh token cookie, returns `{ accessToken, user }`
|
|
876
|
+
* - `POST /refresh` — rotate refresh token, returns new `{ accessToken }`
|
|
877
|
+
* - `POST /logout` — delete the current session; the bound access token is immediately rejected by `protect()`
|
|
878
|
+
* - `POST /logout-all` — delete all sessions for the user (requires valid access token)
|
|
879
|
+
* - `GET /me` — return the authenticated user
|
|
880
|
+
* - `POST /users/:userId/roles` — assign roles (requires admin)
|
|
881
|
+
*
|
|
882
|
+
* Requires `express.json()` before the router.
|
|
883
|
+
*
|
|
884
|
+
* @example
|
|
885
|
+
* app.use(express.json());
|
|
886
|
+
* app.use('/auth', auth.router());
|
|
887
|
+
*/
|
|
888
|
+
router(): Router;
|
|
889
|
+
/**
|
|
890
|
+
* Returns an Express error-handling middleware that formats every `SentriError`
|
|
891
|
+
* (and any subclass) into the standard sentri response envelope:
|
|
892
|
+
*
|
|
893
|
+
* ```json
|
|
894
|
+
* { "error": true, "statusCode": 401, "code": "UNAUTHORIZED", "message": "...", "data": null }
|
|
895
|
+
* ```
|
|
896
|
+
*
|
|
897
|
+
* Mount it **after all your routes** so it acts as the global catch-all for
|
|
898
|
+
* both sentri errors and your own `SentriError` subclasses.
|
|
899
|
+
*
|
|
900
|
+
* @example
|
|
901
|
+
* import { SentriError } from 'sentri';
|
|
902
|
+
*
|
|
903
|
+
* // Define app-specific errors by extending SentriError
|
|
904
|
+
* class NotFoundError extends SentriError {
|
|
905
|
+
* constructor(resource: string) {
|
|
906
|
+
* super('NOT_FOUND', `${resource} not found`, 404);
|
|
907
|
+
* }
|
|
908
|
+
* }
|
|
909
|
+
*
|
|
910
|
+
* app.use('/auth', auth.router());
|
|
911
|
+
* app.use('/api', apiRouter);
|
|
912
|
+
*
|
|
913
|
+
* // Catches errors from sentri AND your own subclasses
|
|
914
|
+
* app.use(auth.errorHandler());
|
|
915
|
+
*
|
|
916
|
+
* @example
|
|
917
|
+
* // With optional unhandled-error logger
|
|
918
|
+
* app.use(auth.errorHandler({
|
|
919
|
+
* onUnhandled: (err) => logger.error('Unexpected error', { err }),
|
|
920
|
+
* }));
|
|
921
|
+
*/
|
|
922
|
+
errorHandler(options?: ErrorHandlerOptions): ErrorRequestHandler;
|
|
923
|
+
}
|
|
924
|
+
/**
|
|
925
|
+
* Create a fully configured auth client for your application.
|
|
926
|
+
*
|
|
927
|
+
* Pass your config once here and use the returned client everywhere — it
|
|
928
|
+
* binds all library functions to your settings so you never need to pass
|
|
929
|
+
* config manually.
|
|
930
|
+
*
|
|
931
|
+
* The generic parameter `TRole` is inferred automatically from `validRoles`
|
|
932
|
+
* when you use `as const`:
|
|
933
|
+
*
|
|
934
|
+
* @example
|
|
935
|
+
* export const auth = createAuth({
|
|
936
|
+
* secret: process.env.JWT_SECRET!,
|
|
937
|
+
* validRoles: ['user', 'admin', 'moderator'] as const,
|
|
938
|
+
* adapter: myAdapter,
|
|
939
|
+
* });
|
|
940
|
+
*
|
|
941
|
+
* // auth.authorize('admin') is type-safe — 'superuser' would be a compile error.
|
|
942
|
+
*/
|
|
943
|
+
declare function createAuth<TRole extends string = string>(config: AuthConfig<TRole>): AuthClient<TRole>;
|
|
944
|
+
|
|
945
|
+
/**
|
|
946
|
+
* Options for {@link createIdempotencyMiddleware}.
|
|
947
|
+
*/
|
|
948
|
+
interface IdempotencyOptions {
|
|
949
|
+
/**
|
|
950
|
+
* How long a cached response is kept, in milliseconds.
|
|
951
|
+
* @default 300_000 (5 minutes)
|
|
952
|
+
*/
|
|
953
|
+
ttl?: number;
|
|
954
|
+
/**
|
|
955
|
+
* Name of the request header that carries the idempotency key.
|
|
956
|
+
* @default 'X-Idempotency-Key'
|
|
957
|
+
*/
|
|
958
|
+
header?: string;
|
|
959
|
+
/**
|
|
960
|
+
* HTTP methods to apply idempotency checking to.
|
|
961
|
+
* @default ['POST', 'PUT', 'PATCH']
|
|
962
|
+
*/
|
|
963
|
+
methods?: string[];
|
|
964
|
+
/**
|
|
965
|
+
* Maximum number of cached entries. When the limit is reached, the oldest
|
|
966
|
+
* entry (by insertion order) is evicted before a new one is stored. This
|
|
967
|
+
* prevents unbounded memory growth under high traffic with unique keys.
|
|
968
|
+
* @default 10_000
|
|
969
|
+
*/
|
|
970
|
+
maxSize?: number;
|
|
971
|
+
}
|
|
972
|
+
/**
|
|
973
|
+
* Creates an Express middleware that makes mutating operations idempotent.
|
|
974
|
+
*
|
|
975
|
+
* When a request includes an idempotency-key header (default `X-Idempotency-Key`),
|
|
976
|
+
* the middleware:
|
|
977
|
+
* 1. Attaches the key as `req.requestId` and echoes it in the `X-Request-Id` response header.
|
|
978
|
+
* 2. Checks an in-memory cache for a prior successful response under that key.
|
|
979
|
+
* - **Cache hit**: replies immediately with the stored response and sets
|
|
980
|
+
* `X-Idempotent-Replayed: true` — no handler runs.
|
|
981
|
+
* - **Cache miss**: intercepts `response.json()` to store the result after the
|
|
982
|
+
* handler completes (only 2xx responses are cached).
|
|
983
|
+
*
|
|
984
|
+
* The cache is per-process and in-memory with a configurable TTL. It is suitable
|
|
985
|
+
* for protecting create/update operations against duplicate submissions (network
|
|
986
|
+
* retries, double-clicks) within the same server process. For multi-process
|
|
987
|
+
* deployments consider using a shared cache such as Redis.
|
|
988
|
+
*
|
|
989
|
+
* Requests without the idempotency-key header, or using non-mutating methods, pass
|
|
990
|
+
* straight through to the next middleware.
|
|
991
|
+
*
|
|
992
|
+
* @example
|
|
993
|
+
* import { createIdempotencyMiddleware } from 'sentri';
|
|
994
|
+
*
|
|
995
|
+
* // Apply globally before routes
|
|
996
|
+
* app.use(createIdempotencyMiddleware());
|
|
997
|
+
*
|
|
998
|
+
* // Or scoped to a router with a shorter TTL
|
|
999
|
+
* apiRouter.use(createIdempotencyMiddleware({ ttl: 60_000 }));
|
|
1000
|
+
*/
|
|
1001
|
+
declare function createIdempotencyMiddleware(options?: IdempotencyOptions): RequestHandler;
|
|
1002
|
+
|
|
1003
|
+
/**
|
|
1004
|
+
* Extract the access token from an incoming Express request.
|
|
1005
|
+
*
|
|
1006
|
+
* Looks in two places, in order:
|
|
1007
|
+
* 1. `Authorization: Bearer <token>` header
|
|
1008
|
+
* 2. The access token cookie (name from `config.accessCookie.name`, default `'access_token'`)
|
|
1009
|
+
*
|
|
1010
|
+
* Returns `undefined` when neither source is present.
|
|
1011
|
+
*
|
|
1012
|
+
* This is the server-side companion to reading `document.cookie` on the client.
|
|
1013
|
+
* Use it when you need the raw token string for custom middleware or logging.
|
|
1014
|
+
*
|
|
1015
|
+
* @example
|
|
1016
|
+
* import { getCurrentAccessToken } from 'sentri';
|
|
1017
|
+
*
|
|
1018
|
+
* app.get('/debug/token', (req, res) => {
|
|
1019
|
+
* const token = getCurrentAccessToken(req, config);
|
|
1020
|
+
* res.json({ token });
|
|
1021
|
+
* });
|
|
1022
|
+
*/
|
|
1023
|
+
declare function getCurrentAccessToken(request: Request, config: AuthConfig): string | undefined;
|
|
1024
|
+
|
|
1025
|
+
/**
|
|
1026
|
+
* Register a new user.
|
|
1027
|
+
*
|
|
1028
|
+
* Validates that every requested role is in `validRoles`, rejects duplicate
|
|
1029
|
+
* identifiers, hashes the password with bcrypt, creates the user record via
|
|
1030
|
+
* the adapter, and returns the created user.
|
|
1031
|
+
*
|
|
1032
|
+
* No tokens are issued — the caller should invoke `login` after registration
|
|
1033
|
+
* if immediate authentication is desired.
|
|
1034
|
+
*
|
|
1035
|
+
* @param input - Registration data: identifier, plain-text password, and optional roles.
|
|
1036
|
+
* @param config - Auth configuration containing the adapter and role definitions.
|
|
1037
|
+
* @returns `{ success: true, user }` on success, or `{ success: false, error }` with
|
|
1038
|
+
* code `INVALID_ROLE` or `USER_ALREADY_EXISTS` on failure.
|
|
1039
|
+
*/
|
|
1040
|
+
declare function register(input: RegisterInput, config: AuthConfig): Promise<RegisterResult>;
|
|
1041
|
+
|
|
2
1042
|
declare global {
|
|
3
1043
|
namespace Express {
|
|
4
1044
|
interface Request {
|
|
1045
|
+
/** Decoded user payload injected by `protect()` on every authenticated request. */
|
|
5
1046
|
user?: AuthUser;
|
|
1047
|
+
/** Idempotency key from `X-Idempotency-Key` header, attached by `createIdempotencyMiddleware()`. */
|
|
1048
|
+
requestId?: string;
|
|
6
1049
|
}
|
|
7
1050
|
}
|
|
8
1051
|
}
|
|
9
|
-
|
|
10
|
-
export type
|
|
11
|
-
export type { AuthClient } from './client.js';
|
|
12
|
-
export type { ErrorHandlerOptions } from './middleware/errorHandler.js';
|
|
13
|
-
export { SentriError, AUTH_ERROR_STATUS } from './errors/AuthError.js';
|
|
14
|
-
export { createAuth } from './client.js';
|
|
15
|
-
export { createErrorHandler } from './middleware/errorHandler.js';
|
|
16
|
-
export { register } from './services/auth.js';
|
|
17
|
-
export type { PermitCheck, PermitOptions } from './middleware/permit.js';
|
|
18
|
-
//# sourceMappingURL=index.d.ts.map
|
|
1052
|
+
|
|
1053
|
+
export { AUTH_ERROR_STATUS, type AccessCookieConfig, type ApiResponse, type AssignRolesResult, type AuthAdapter, type AuthClient, type AuthConfig, type AuthHooks, type AuthResult, type AuthUser, type CookieConfig, type CreateUserData, type ErrorHandlerOptions, type IdempotencyOptions, type LoginInput, type PermitCheck, type PermitOptions, type RefreshResult, type RegisterInput, type RegisterResult, type RouterHandlers, SentriError, type SentriErrorCode, type SessionRecord, type UserRecord, createAuth, createErrorHandler, createIdempotencyMiddleware, getCurrentAccessToken, register };
|