sentri 1.1.2 → 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.
Files changed (64) hide show
  1. package/README.md +268 -448
  2. package/dist/cli.d.ts +0 -2
  3. package/dist/cli.js +113 -107
  4. package/dist/index.d.ts +545 -11
  5. package/dist/index.js +1 -5
  6. package/package.json +9 -7
  7. package/dist/cli.d.ts.map +0 -1
  8. package/dist/cli.js.map +0 -1
  9. package/dist/client.d.ts +0 -160
  10. package/dist/client.d.ts.map +0 -1
  11. package/dist/client.js +0 -45
  12. package/dist/client.js.map +0 -1
  13. package/dist/errors/AuthError.d.ts +0 -99
  14. package/dist/errors/AuthError.d.ts.map +0 -1
  15. package/dist/errors/AuthError.js +0 -97
  16. package/dist/errors/AuthError.js.map +0 -1
  17. package/dist/index.d.ts.map +0 -1
  18. package/dist/index.js.map +0 -1
  19. package/dist/libs/config.d.ts +0 -62
  20. package/dist/libs/config.d.ts.map +0 -1
  21. package/dist/libs/config.js +0 -97
  22. package/dist/libs/config.js.map +0 -1
  23. package/dist/libs/hash.d.ts +0 -17
  24. package/dist/libs/hash.d.ts.map +0 -1
  25. package/dist/libs/hash.js +0 -22
  26. package/dist/libs/hash.js.map +0 -1
  27. package/dist/libs/token.d.ts +0 -46
  28. package/dist/libs/token.d.ts.map +0 -1
  29. package/dist/libs/token.js +0 -118
  30. package/dist/libs/token.js.map +0 -1
  31. package/dist/middleware/authorize.d.ts +0 -18
  32. package/dist/middleware/authorize.d.ts.map +0 -1
  33. package/dist/middleware/authorize.js +0 -30
  34. package/dist/middleware/authorize.js.map +0 -1
  35. package/dist/middleware/errorHandler.d.ts +0 -71
  36. package/dist/middleware/errorHandler.d.ts.map +0 -1
  37. package/dist/middleware/errorHandler.js +0 -74
  38. package/dist/middleware/errorHandler.js.map +0 -1
  39. package/dist/middleware/permit.d.ts +0 -62
  40. package/dist/middleware/permit.d.ts.map +0 -1
  41. package/dist/middleware/permit.js +0 -61
  42. package/dist/middleware/permit.js.map +0 -1
  43. package/dist/middleware/protect.d.ts +0 -31
  44. package/dist/middleware/protect.d.ts.map +0 -1
  45. package/dist/middleware/protect.js +0 -54
  46. package/dist/middleware/protect.js.map +0 -1
  47. package/dist/middleware/router.d.ts +0 -34
  48. package/dist/middleware/router.d.ts.map +0 -1
  49. package/dist/middleware/router.js +0 -264
  50. package/dist/middleware/router.js.map +0 -1
  51. package/dist/services/auth.d.ts +0 -85
  52. package/dist/services/auth.d.ts.map +0 -1
  53. package/dist/services/auth.js +0 -173
  54. package/dist/services/auth.js.map +0 -1
  55. package/dist/types/auth.d.ts +0 -450
  56. package/dist/types/auth.d.ts.map +0 -1
  57. package/dist/types/auth.js +0 -21
  58. package/dist/types/auth.js.map +0 -1
  59. package/templates/drizzle/adapter.ts +0 -154
  60. package/templates/drizzle/auth.ts +0 -82
  61. package/templates/drizzle/schema.ts +0 -47
  62. package/templates/prisma/adapter.ts +0 -122
  63. package/templates/prisma/auth.ts +0 -85
  64. package/templates/prisma/schema.prisma +0 -56
package/dist/cli.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AACtF,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AAEpC,MAAM,SAAS,GAAG,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AAE1D,MAAM,QAAQ,GAAG,CAAC,UAAU,CAAU,CAAC;AAGvC,MAAM,IAAI,GAAG,CAAC,QAAQ,EAAE,SAAS,CAAU,CAAC;AAG5C,SAAS,IAAI;IACX,OAAO,CAAC,GAAG,CAAC;;;;;;;;;;CAUb,CA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CAAC,GAAG,CAAC,uFAAuF,CAAC,CAAC;QACrG,OAAO,CAAC,GAAG,CAAC,wEAAwE,CAAC,CAAC;QACtF,OAAO,CAAC,GAAG,CAAC,uCAAuC,CAAC,CAAC;IACvD,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,yCAAyC,CAAC,CAAC;IACvD,OAAO,CAAC,GAAG,CAAC,kDAAkD,CAAC,CAAC;IAChE,OAAO,CAAC,GAAG,CAAC,sCAAsC,CAAC,CAAC;IACpD,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;AAClB,CAAC;AAED,MAAM,CAAC,EAAE,AAAD,EAAG,OAAO,EAAE,GAAG,IAAI,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;AAE5C,IAAI,CAAC,OAAO,IAAI,OAAO,KAAK,QAAQ,IAAI,OAAO,KAAK,IAAI,EAAE,CAAC;IACzD,IAAI,EAAE,CAAC;IACP,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC;AAED,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,OAAkB,CAAC,EAAE,CAAC;IAC3C,OAAO,CAAC,KAAK,CAAC,oBAAoB,OAAO,EAAE,CAAC,CAAC;IAC7C,IAAI,EAAE,CAAC;IACP,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC;AAED,IAAI,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;IACnD,IAAI,EAAE,CAAC;IACP,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC;AAED,IAAI,OAAO,KAAK,UAAU;IAAE,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC"}
package/dist/client.d.ts DELETED
@@ -1,160 +0,0 @@
1
- import type { PermitCheck, PermitOptions } from './middleware/permit.js';
2
- import type { ErrorHandlerOptions } from './middleware/errorHandler.js';
3
- import type { AuthConfig, AuthUser } from './types/auth.js';
4
- import type { ErrorRequestHandler, RequestHandler, Router } from 'express';
5
- /**
6
- * The bound auth client returned by {@link createAuth}.
7
- *
8
- * All methods are pre-configured with the options passed to `createAuth` —
9
- * you never need to pass config around yourself.
10
- *
11
- * `TRole` is inferred from `validRoles` and narrows role strings to your
12
- * application's exact union type everywhere (authorize, req.user, etc.).
13
- */
14
- export interface AuthClient<TRole extends string = string> {
15
- /**
16
- * Express middleware factory that enforces authentication.
17
- *
18
- * Reads the `Authorization: Bearer <token>` header, verifies the access token,
19
- * confirms the session is still active in the database, and injects the decoded
20
- * payload as `request.user`. Calls `next(SentriError)` on any failure.
21
- *
22
- * @example
23
- * router.get('/me', auth.protect(), (request, response) => {
24
- * response.json(request.user);
25
- * });
26
- */
27
- protect(): RequestHandler;
28
- /**
29
- * Express middleware factory that enforces role-based access.
30
- *
31
- * Must be used **after** `protect()`. Passes if the authenticated user has
32
- * at least one of the specified roles; otherwise calls `next(SentriError)` with
33
- * code `FORBIDDEN`.
34
- *
35
- * @example
36
- * router.delete('/posts/:id', auth.protect(), auth.authorize('admin'), handler);
37
- */
38
- authorize(...roles: TRole[]): RequestHandler;
39
- /**
40
- * Express middleware factory for resource-level permission checks.
41
- *
42
- * Must be used **after** `protect()`. Evaluates a check function against the
43
- * current request and calls `next(SentriError)` with `FORBIDDEN` if it returns `false`.
44
- *
45
- * Accepts either a bare check function or an options object with an optional
46
- * `roles` list whose members bypass the check entirely.
47
- *
48
- * @example
49
- * // User can only update their own profile
50
- * router.put('/users/:id',
51
- * auth.protect(),
52
- * auth.permit((request) => request.user!.id === request.params['id']),
53
- * handler,
54
- * );
55
- *
56
- * @example
57
- * // Admins bypass the check; others must own the resource
58
- * router.delete('/posts/:id',
59
- * auth.protect(),
60
- * auth.permit({
61
- * roles: ['admin'],
62
- * check: async (request) => {
63
- * const post = await db.post.findUnique({ where: { id: request.params['id'] } });
64
- * return post?.authorId === request.user!.id;
65
- * },
66
- * }),
67
- * handler,
68
- * );
69
- */
70
- permit(check: PermitCheck): RequestHandler;
71
- permit(options: PermitOptions<TRole>): RequestHandler;
72
- /** Hash a plain-text password using the configured `saltRounds`. */
73
- hashPassword(plain: string): Promise<string>;
74
- /** Compare a plain-text password against a stored bcrypt hash. */
75
- verifyPassword(plain: string, hash: string): Promise<boolean>;
76
- /** Sign an access token for the given user payload. */
77
- signAccessToken(payload: AuthUser<TRole>): string;
78
- /** Sign a refresh token bound to a session ID. */
79
- signRefreshToken(sessionId: string): string;
80
- /** Verify and decode an access token. Throws `SentriError` if invalid or expired. */
81
- verifyAccessToken(token: string): AuthUser<TRole>;
82
- /** Verify and decode a refresh token. Throws `SentriError` if invalid or expired. */
83
- verifyRefreshToken(token: string): {
84
- sessionId: string;
85
- };
86
- /**
87
- * Returns a pre-built Express Router with all standard auth endpoints mounted.
88
- *
89
- * Endpoints:
90
- * - `POST /register` — register a new user. Requires `X-Api-Key` header when `config.apiKey` is set.
91
- * - `POST /login` — authenticate, sets refresh token cookie, returns `{ accessToken, user }`
92
- * - `POST /refresh` — rotate refresh token, returns new `{ accessToken }`
93
- * - `POST /logout` — delete the current session; the bound access token is immediately rejected by `protect()`
94
- * - `POST /logout-all` — delete all sessions for the user (requires valid access token)
95
- * - `GET /me` — return the authenticated user
96
- * - `POST /users/:userId/roles` — assign roles (requires admin)
97
- *
98
- * Requires `express.json()` before the router.
99
- *
100
- * @example
101
- * app.use(express.json());
102
- * app.use('/auth', auth.router());
103
- */
104
- router(): Router;
105
- /**
106
- * Returns an Express error-handling middleware that formats every `SentriError`
107
- * (and any subclass) into the standard sentri response envelope:
108
- *
109
- * ```json
110
- * { "error": true, "statusCode": 401, "code": "UNAUTHORIZED", "message": "...", "data": null }
111
- * ```
112
- *
113
- * Mount it **after all your routes** so it acts as the global catch-all for
114
- * both sentri errors and your own `SentriError` subclasses.
115
- *
116
- * @example
117
- * import { SentriError } from 'sentri';
118
- *
119
- * // Define app-specific errors by extending SentriError
120
- * class NotFoundError extends SentriError {
121
- * constructor(resource: string) {
122
- * super('NOT_FOUND', `${resource} not found`, 404);
123
- * }
124
- * }
125
- *
126
- * app.use('/auth', auth.router());
127
- * app.use('/api', apiRouter);
128
- *
129
- * // Catches errors from sentri AND your own subclasses
130
- * app.use(auth.errorHandler());
131
- *
132
- * @example
133
- * // With optional unhandled-error logger
134
- * app.use(auth.errorHandler({
135
- * onUnhandled: (err) => logger.error('Unexpected error', { err }),
136
- * }));
137
- */
138
- errorHandler(options?: ErrorHandlerOptions): ErrorRequestHandler;
139
- }
140
- /**
141
- * Create a fully configured auth client for your application.
142
- *
143
- * Pass your config once here and use the returned client everywhere — it
144
- * binds all library functions to your settings so you never need to pass
145
- * config manually.
146
- *
147
- * The generic parameter `TRole` is inferred automatically from `validRoles`
148
- * when you use `as const`:
149
- *
150
- * @example
151
- * export const auth = createAuth({
152
- * secret: process.env.JWT_SECRET!,
153
- * validRoles: ['user', 'admin', 'moderator'] as const,
154
- * adapter: myAdapter,
155
- * });
156
- *
157
- * // auth.authorize('admin') is type-safe — 'superuser' would be a compile error.
158
- */
159
- export declare function createAuth<TRole extends string = string>(config: AuthConfig<TRole>): AuthClient<TRole>;
160
- //# sourceMappingURL=client.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACzE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC5D,OAAO,KAAK,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAE3E;;;;;;;;GAQG;AACH,MAAM,WAAW,UAAU,CAAC,KAAK,SAAS,MAAM,GAAG,MAAM;IACvD;;;;;;;;;;;OAWG;IACH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- import { hashPassword, verifyPassword } from './libs/hash.js';
2
- import { signAccessToken, signRefreshToken, verifyAccessToken, verifyRefreshToken } from './libs/token.js';
3
- import { resolveConfig, validateConfig } from './libs/config.js';
4
- import { protect } from './middleware/protect.js';
5
- import { authorize } from './middleware/authorize.js';
6
- import { permit } from './middleware/permit.js';
7
- import { createAuthRouter } from './middleware/router.js';
8
- import { createErrorHandler } from './middleware/errorHandler.js';
9
- /**
10
- * Create a fully configured auth client for your application.
11
- *
12
- * Pass your config once here and use the returned client everywhere — it
13
- * binds all library functions to your settings so you never need to pass
14
- * config manually.
15
- *
16
- * The generic parameter `TRole` is inferred automatically from `validRoles`
17
- * when you use `as const`:
18
- *
19
- * @example
20
- * export const auth = createAuth({
21
- * secret: process.env.JWT_SECRET!,
22
- * validRoles: ['user', 'admin', 'moderator'] as const,
23
- * adapter: myAdapter,
24
- * });
25
- *
26
- * // auth.authorize('admin') is type-safe — 'superuser' would be a compile error.
27
- */
28
- export function createAuth(config) {
29
- validateConfig(config);
30
- const resolved = resolveConfig(config);
31
- return {
32
- protect: () => protect(config),
33
- authorize: (...roles) => authorize(...roles),
34
- permit: (optionsOrCheck) => permit(optionsOrCheck),
35
- hashPassword: (plain) => hashPassword(plain, resolved.saltRounds),
36
- verifyPassword: (plain, hash) => verifyPassword(plain, hash),
37
- signAccessToken: (payload) => signAccessToken(payload, config),
38
- signRefreshToken: (sessionId) => signRefreshToken(sessionId, config),
39
- verifyAccessToken: (token) => verifyAccessToken(token, config),
40
- verifyRefreshToken: (token) => verifyRefreshToken(token, config),
41
- router: () => createAuthRouter(config),
42
- errorHandler: (options) => createErrorHandler(options),
43
- };
44
- }
45
- //# sourceMappingURL=client.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAC9D,OAAO,EAAE,eAAe,EAAE,gBAAgB,EA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AAoB;QAC/F,kBAAkB,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,kBAAkB,CAAC,KAAK,EAAE,MAAoB,CAAC;QAC9E,MAAM,EAAE,GAAG,EAAE,CAAC,gBAAgB,CAAC,MAAM,CAAC;QACtC,YAAY,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,kBAAkB,CAAC,OAAO,CAAC;KACvD,CAAC;AACJ,CAAC"}
@@ -1,99 +0,0 @@
1
- /**
2
- * Discriminant codes for built-in {@link SentriError} instances.
3
- *
4
- * - `INVALID_CREDENTIALS` — identifier or password did not match (intentionally vague to prevent user enumeration)
5
- * - `USER_NOT_FOUND` — an operation required a user that does not exist
6
- * - `USER_ALREADY_EXISTS` — registration was attempted with an identifier already in the database
7
- * - `TOKEN_EXPIRED` — the JWT was valid but its `exp` claim is in the past
8
- * - `TOKEN_INVALID` — the JWT could not be verified (bad signature, malformed, wrong type)
9
- * - `FORBIDDEN` — the user is authenticated but lacks the required role
10
- * - `UNAUTHORIZED` — no valid access token was present on the request, or the session was revoked
11
- * - `INVALID_ROLE` — a role name was used that is not in `validRoles`
12
- * - `VALIDATION_ERROR` — a required field was missing or had an invalid value
13
- * - `CONFIGURATION_ERROR` — `createAuth` was called with an invalid configuration
14
- *
15
- * When you extend {@link SentriError} for your own error types you can use any
16
- * string as `code` — it does not need to be one of these built-in values.
17
- */
18
- export type SentriErrorCode = 'INVALID_CREDENTIALS' | 'USER_NOT_FOUND' | 'USER_ALREADY_EXISTS' | 'TOKEN_EXPIRED' | 'TOKEN_INVALID' | 'FORBIDDEN' | 'UNAUTHORIZED' | 'INVALID_ROLE' | 'VALIDATION_ERROR' | 'CONFIGURATION_ERROR';
19
- /**
20
- * Default HTTP status codes for built-in error codes.
21
- * Custom codes that are not in this map default to 500.
22
- *
23
- * @internal
24
- */
25
- export declare const AUTH_ERROR_STATUS: Record<string, number>;
26
- /**
27
- * Base error class for all authentication and authorization failures in sentri.
28
- *
29
- * Every error thrown by sentri is an instance of `SentriError`. The `code`
30
- * property is a machine-readable string that lets you distinguish error
31
- * types without string-matching on the message. Built-in codes are listed
32
- * in {@link SentriErrorCode}; custom subclasses may use any string.
33
- *
34
- * The `statusCode` property holds the HTTP status that the built-in router
35
- * and `auth.errorHandler()` will use in the response. For built-in codes
36
- * it is derived automatically. Pass it explicitly when subclassing with a
37
- * custom code.
38
- *
39
- * ---
40
- *
41
- * **Extending SentriError**
42
- *
43
- * You can create application-specific error classes by extending `SentriError`.
44
- * Any subclass will be caught automatically by `auth.errorHandler()` because
45
- * `instanceof SentriError` is `true` for all subclasses.
46
- *
47
- * ```typescript
48
- * import { SentriError } from 'sentri';
49
- *
50
- * // Domain error with a custom code and explicit HTTP status
51
- * export class PaymentError extends SentriError {
52
- * constructor(message: string) {
53
- * super('PAYMENT_FAILED', message, 402);
54
- * }
55
- * }
56
- *
57
- * // Throw it anywhere in your routes — auth.errorHandler() catches it
58
- * router.post('/checkout', auth.protect(), async (req, res) => {
59
- * const ok = await chargeCard(req.body.cardToken);
60
- * if (!ok) throw new PaymentError('Card declined');
61
- * res.json({ success: true });
62
- * });
63
- * ```
64
- *
65
- * ---
66
- *
67
- * **Error handling in custom routes**
68
- *
69
- * ```typescript
70
- * app.use('/auth', auth.router());
71
- * app.use('/api', apiRouter);
72
- *
73
- * // Mount after all routes — catches SentriError from sentri AND your subclasses
74
- * app.use(auth.errorHandler());
75
- * ```
76
- */
77
- export declare class SentriError extends Error {
78
- /**
79
- * Machine-readable error code.
80
- * Built-in codes are defined by {@link SentriErrorCode}.
81
- * Custom subclasses may use any string.
82
- */
83
- readonly code: string;
84
- /**
85
- * HTTP status code associated with this error.
86
- * Derived automatically for built-in codes; pass it explicitly when
87
- * subclassing with a custom `code`.
88
- */
89
- readonly statusCode: number;
90
- /**
91
- * @param code - Machine-readable error code. Use a built-in {@link SentriErrorCode}
92
- * or any string for custom subclasses.
93
- * @param message - Human-readable description of the error.
94
- * @param statusCode - HTTP status to use in the response. For built-in codes
95
- * this is derived automatically; for custom codes it defaults to `500`.
96
- */
97
- constructor(code: SentriErrorCode | (string & {}), message: string, statusCode?: number);
98
- }
99
- //# sourceMappingURL=AuthError.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"AuthError.d.ts","sourceRoot":"","sources":["../../src/errors/AuthError.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,MAAM,eAAe,GACvB,qBAAqB,GACrB,gBAAgB,GAChB,qBAAqB,GACrB,eAAe,GACf,eAAe,GACf,WAAW,GACX,cAAc,GACd,cAAc,GACd,kBAAkB,GAClB,qBAAqB,CAAC;AAE1B;;;;;GAKG;AACH,eAAO,MAAM,iBAAiB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAWpD,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkDG;AACH,qBAAa,WAAY,SAAQ,KAAK;IACpC;;;;OAIG;IACH,SAAgB,IAAI,EAAE,MAAM,CAAC;IAE7B;;;;OAIG;IACH,SAAgB,UAAU,EAAE,MAAM,CAAC;IAEnC;;;;;;OAMG;gBAED,IAAI,EAAE,eAAe,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,EACrC,OAAO,EAAE,MAAM,EACf,UAAU,CAAC,EAAE,MAAM;CAOtB"}
@@ -1,97 +0,0 @@
1
- /**
2
- * Default HTTP status codes for built-in error codes.
3
- * Custom codes that are not in this map default to 500.
4
- *
5
- * @internal
6
- */
7
- export const AUTH_ERROR_STATUS = {
8
- UNAUTHORIZED: 401,
9
- TOKEN_EXPIRED: 401,
10
- TOKEN_INVALID: 401,
11
- INVALID_CREDENTIALS: 401,
12
- FORBIDDEN: 403,
13
- USER_NOT_FOUND: 404,
14
- USER_ALREADY_EXISTS: 409,
15
- INVALID_ROLE: 400,
16
- VALIDATION_ERROR: 400,
17
- CONFIGURATION_ERROR: 500,
18
- };
19
- /**
20
- * Base error class for all authentication and authorization failures in sentri.
21
- *
22
- * Every error thrown by sentri is an instance of `SentriError`. The `code`
23
- * property is a machine-readable string that lets you distinguish error
24
- * types without string-matching on the message. Built-in codes are listed
25
- * in {@link SentriErrorCode}; custom subclasses may use any string.
26
- *
27
- * The `statusCode` property holds the HTTP status that the built-in router
28
- * and `auth.errorHandler()` will use in the response. For built-in codes
29
- * it is derived automatically. Pass it explicitly when subclassing with a
30
- * custom code.
31
- *
32
- * ---
33
- *
34
- * **Extending SentriError**
35
- *
36
- * You can create application-specific error classes by extending `SentriError`.
37
- * Any subclass will be caught automatically by `auth.errorHandler()` because
38
- * `instanceof SentriError` is `true` for all subclasses.
39
- *
40
- * ```typescript
41
- * import { SentriError } from 'sentri';
42
- *
43
- * // Domain error with a custom code and explicit HTTP status
44
- * export class PaymentError extends SentriError {
45
- * constructor(message: string) {
46
- * super('PAYMENT_FAILED', message, 402);
47
- * }
48
- * }
49
- *
50
- * // Throw it anywhere in your routes — auth.errorHandler() catches it
51
- * router.post('/checkout', auth.protect(), async (req, res) => {
52
- * const ok = await chargeCard(req.body.cardToken);
53
- * if (!ok) throw new PaymentError('Card declined');
54
- * res.json({ success: true });
55
- * });
56
- * ```
57
- *
58
- * ---
59
- *
60
- * **Error handling in custom routes**
61
- *
62
- * ```typescript
63
- * app.use('/auth', auth.router());
64
- * app.use('/api', apiRouter);
65
- *
66
- * // Mount after all routes — catches SentriError from sentri AND your subclasses
67
- * app.use(auth.errorHandler());
68
- * ```
69
- */
70
- export class SentriError extends Error {
71
- /**
72
- * Machine-readable error code.
73
- * Built-in codes are defined by {@link SentriErrorCode}.
74
- * Custom subclasses may use any string.
75
- */
76
- code;
77
- /**
78
- * HTTP status code associated with this error.
79
- * Derived automatically for built-in codes; pass it explicitly when
80
- * subclassing with a custom `code`.
81
- */
82
- statusCode;
83
- /**
84
- * @param code - Machine-readable error code. Use a built-in {@link SentriErrorCode}
85
- * or any string for custom subclasses.
86
- * @param message - Human-readable description of the error.
87
- * @param statusCode - HTTP status to use in the response. For built-in codes
88
- * this is derived automatically; for custom codes it defaults to `500`.
89
- */
90
- constructor(code, message, statusCode) {
91
- super(message);
92
- this.name = 'SentriError';
93
- this.code = code;
94
- this.statusCode = statusCode ?? AUTH_ERROR_STATUS[code] ?? 500;
95
- }
96
- }
97
- //# sourceMappingURL=AuthError.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"AuthError.js","sourceRoot":"","sources":["../../src/errors/AuthError.ts"],"names":[],"mappings":"AA6BA;;;;;GAKG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAA2B;IACvD,YAAY,EAAE,GAAG;IACjB,aAAa,EAAE,GAAG;IAClB,aAAa,EAAE,GAAG;IAClB,mBAAmB,EAAE,GAAG;IACxB,SAAS,EAAE,GAAG;IACd,cAAc,EAAE,GAAG;IACnB,mBAAmB,EAAE,GAAG;IACxB,YAAY,EAAE,GAAG;IACjB,gBAAgB,EAAE,GAAG;IACrB,mBAAmB,EAAE,GAAG;CACzB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkDG;AACH,MAAM,OAAO,WAAY,SAAQ,KAAK;IACpC;;;;OAIG;IACa,IAAI,CAAS;IAE7B;;;;OAIG;IACa,UAAU,CAAS;IAEnC;;;;;;OAMG;IACH,YACE,IAAqC,EACrC,OAAe,EACf,UAAmB;QAEnB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;QAC1B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,UAAU,GAAG,UAAU,IAAI,iBAAiB,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC;IACjE,CAAC;CACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAGhD,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,OAAO,CAAC;QAChB,UAAU,OAAO;YACf,IAAI,CAAC,EAAE,QAAQ,CAAC;SACjB;KACF;CACF;AAED,YAAY,EACV,UAAU,EACV,YAAY,EACZ,QAAQ,EACR,WAAW,EACX,WAAW,EACX,UAAU,EACV,aAAa,EACb,cAAc,EACd,cAAc,EACd,aAAa,EACb,UAAU,EACV,cAAc,EACd,UAAU,EACV,aAAa,EACb,iBAAiB,GAClB,MAAM,iBAAiB,CAAC;AACzB,YAAY,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC7D,YAAY,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC9C,YAAY,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AAExE,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,YAAY,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC"}
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAgCA,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC"}
@@ -1,62 +0,0 @@
1
- import type { AuthAdapter, AuthConfig } from '../types/auth.js';
2
- /**
3
- * Fully-resolved configuration with all optional fields filled in by
4
- * their defaults. Produced by {@link resolveConfig} and used internally
5
- * wherever the library needs guaranteed values.
6
- */
7
- export interface ResolvedConfig {
8
- secret: string;
9
- accessExpiresIn: string | number;
10
- refreshExpiresIn: string | number;
11
- algorithm: 'HS256' | 'HS384' | 'HS512';
12
- saltRounds: number;
13
- validRoles: readonly string[];
14
- adapter: AuthAdapter;
15
- }
16
- /**
17
- * Validate configuration at startup so misconfiguration is caught immediately,
18
- * not at the first login attempt.
19
- *
20
- * Throws {@link SentriError} with code `CONFIGURATION_ERROR` for any of:
21
- * - `secret` missing or shorter than 32 characters
22
- * - `saltRounds` outside the range 10–31
23
- * - `validRoles` is empty or missing
24
- * - `adapter` is missing
25
- *
26
- * @param config - The raw config passed to {@link createAuth}.
27
- * @throws {SentriError} With code `CONFIGURATION_ERROR` on any invalid field.
28
- */
29
- export declare function validateConfig(config: AuthConfig): void;
30
- /**
31
- * Merge a partial {@link AuthConfig} with library defaults and return a
32
- * fully-resolved configuration object.
33
- *
34
- * Does **not** validate the config — call {@link validateConfig} first.
35
- *
36
- * Defaults applied:
37
- * - `accessExpiresIn` → `'15m'`
38
- * - `refreshExpiresIn` → `'7d'`
39
- * - `algorithm` → `'HS256'`
40
- * - `saltRounds` → `12`
41
- *
42
- * @param partial - The raw config passed to {@link createAuth}.
43
- * @returns A {@link ResolvedConfig} with every field guaranteed to be present.
44
- */
45
- export declare function resolveConfig(partial: AuthConfig): ResolvedConfig;
46
- /**
47
- * Convert a duration string or a number of seconds into milliseconds.
48
- *
49
- * Supported unit suffixes: `s` (seconds), `m` (minutes), `h` (hours),
50
- * `d` (days), `w` (weeks). Numeric inputs are treated as seconds.
51
- *
52
- * @example
53
- * parseExpiry('15m') // 900_000
54
- * parseExpiry('7d') // 604_800_000
55
- * parseExpiry(60) // 60_000
56
- *
57
- * @param expiresIn - A duration string (e.g. `'15m'`, `'7d'`) or a number of seconds.
58
- * @returns The equivalent duration in milliseconds.
59
- * @throws {Error} If the string format is unrecognised.
60
- */
61
- export declare function parseExpiry(expiresIn: string | number): number;
62
- //# sourceMappingURL=config.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/libs/config.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEhE;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,eAAe,EAAE,MAAM,GAAG,MAAM,CAAC;IACjC,gBAAgB,EAAE,MAAM,GAAG,MAAM,CAAC;IAClC,SAAS,EAAE,OAAO,GAAG,OAAO,GAAG,OAAO,CAAC;IACvC,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;IAC9B,OAAO,EAAE,WAAW,CAAC;CACtB;AAMD;;;;;;;;;;;;GAYG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,UAAU,GAAG,IAAI,CA0BvD;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,UAAU,GAAG,cAAc,CAUjE;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,WAAW,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAkB9D"}
@@ -1,97 +0,0 @@
1
- import { SentriError } from '../errors/AuthError.js';
2
- const MIN_SECRET_LENGTH = 32;
3
- const MIN_SALT_ROUNDS = 10;
4
- const MAX_SALT_ROUNDS = 31;
5
- /**
6
- * Validate configuration at startup so misconfiguration is caught immediately,
7
- * not at the first login attempt.
8
- *
9
- * Throws {@link SentriError} with code `CONFIGURATION_ERROR` for any of:
10
- * - `secret` missing or shorter than 32 characters
11
- * - `saltRounds` outside the range 10–31
12
- * - `validRoles` is empty or missing
13
- * - `adapter` is missing
14
- *
15
- * @param config - The raw config passed to {@link createAuth}.
16
- * @throws {SentriError} With code `CONFIGURATION_ERROR` on any invalid field.
17
- */
18
- export function validateConfig(config) {
19
- if (!config.secret || config.secret.trim().length === 0) {
20
- throw new SentriError('CONFIGURATION_ERROR', 'secret must not be empty');
21
- }
22
- if (config.secret.length < MIN_SECRET_LENGTH) {
23
- throw new SentriError('CONFIGURATION_ERROR', `secret must be at least ${MIN_SECRET_LENGTH} characters to be cryptographically safe`);
24
- }
25
- const saltRounds = config.saltRounds ?? 12;
26
- if (!Number.isInteger(saltRounds) || saltRounds < MIN_SALT_ROUNDS || saltRounds > MAX_SALT_ROUNDS) {
27
- throw new SentriError('CONFIGURATION_ERROR', `saltRounds must be an integer between ${MIN_SALT_ROUNDS} and ${MAX_SALT_ROUNDS}`);
28
- }
29
- if (!config.validRoles || config.validRoles.length === 0) {
30
- throw new SentriError('CONFIGURATION_ERROR', 'validRoles must contain at least one role');
31
- }
32
- if (!config.adapter) {
33
- throw new SentriError('CONFIGURATION_ERROR', 'adapter is required');
34
- }
35
- }
36
- /**
37
- * Merge a partial {@link AuthConfig} with library defaults and return a
38
- * fully-resolved configuration object.
39
- *
40
- * Does **not** validate the config — call {@link validateConfig} first.
41
- *
42
- * Defaults applied:
43
- * - `accessExpiresIn` → `'15m'`
44
- * - `refreshExpiresIn` → `'7d'`
45
- * - `algorithm` → `'HS256'`
46
- * - `saltRounds` → `12`
47
- *
48
- * @param partial - The raw config passed to {@link createAuth}.
49
- * @returns A {@link ResolvedConfig} with every field guaranteed to be present.
50
- */
51
- export function resolveConfig(partial) {
52
- return {
53
- secret: partial.secret,
54
- accessExpiresIn: partial.accessExpiresIn ?? '15m',
55
- refreshExpiresIn: partial.refreshExpiresIn ?? '7d',
56
- algorithm: partial.algorithm ?? 'HS256',
57
- saltRounds: partial.saltRounds ?? 12,
58
- validRoles: partial.validRoles,
59
- adapter: partial.adapter,
60
- };
61
- }
62
- /**
63
- * Convert a duration string or a number of seconds into milliseconds.
64
- *
65
- * Supported unit suffixes: `s` (seconds), `m` (minutes), `h` (hours),
66
- * `d` (days), `w` (weeks). Numeric inputs are treated as seconds.
67
- *
68
- * @example
69
- * parseExpiry('15m') // 900_000
70
- * parseExpiry('7d') // 604_800_000
71
- * parseExpiry(60) // 60_000
72
- *
73
- * @param expiresIn - A duration string (e.g. `'15m'`, `'7d'`) or a number of seconds.
74
- * @returns The equivalent duration in milliseconds.
75
- * @throws {Error} If the string format is unrecognised.
76
- */
77
- export function parseExpiry(expiresIn) {
78
- if (typeof expiresIn === 'number')
79
- return expiresIn * 1000;
80
- const multipliers = {
81
- s: 1_000,
82
- m: 60_000,
83
- h: 3_600_000,
84
- d: 86_400_000,
85
- w: 604_800_000,
86
- };
87
- const match = /^(\d+)([smhdw])$/.exec(expiresIn);
88
- if (!match?.[1] || !match?.[2]) {
89
- throw new Error(`Invalid expiresIn: "${expiresIn}". Use e.g. "15m", "7d", "1h".`);
90
- }
91
- const unit = multipliers[match[2]];
92
- if (unit === undefined) {
93
- throw new Error(`Invalid expiresIn: "${expiresIn}". Use e.g. "15m", "7d", "1h".`);
94
- }
95
- return parseInt(match[1], 10) * unit;
96
- }
97
- //# sourceMappingURL=config.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/libs/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAkBrD,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAC7B,MAAM,eAAe,GAAG,EAAE,CAAC;AAC3B,MAAM,eAAe,GAAG,EAAE,CAAC;AAE3B;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,cAAc,CAAC,MAAkB;IAC/C,IAAI,CAAC,MAAM,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACxD,MAAM,IAAI,WAAW,CAAC,qBAAqB,EAAE,0BAA0B,CAAC,CAAC;IAC3E,CAAC;IACD,IAAI,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,iBAAiB,EAAE,CAAC;QAC7C,MAAM,IAAI,WAAW,CACnB,qBAAqB,EACrB,2BAA2B,iBAAiB,0CAA0C,CACvF,CAAC;I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S;QACZ,CAAC,EAAE,UAAU;QACb,CAAC,EAAE,WAAW;KACf,CAAC;IACF,MAAM,KAAK,GAAG,kBAAkB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACjD,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC/B,MAAM,IAAI,KAAK,CAAC,uBAAuB,SAAS,gCAAgC,CAAC,CAAC;IACpF,CAAC;IACD,MAAM,IAAI,GAAG,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IACnC,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QACvB,MAAM,IAAI,KAAK,CAAC,uBAAuB,SAAS,gCAAgC,CAAC,CAAC;IACpF,CAAC;IACD,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,IAAI,CAAC;AACvC,CAAC"}
@@ -1,17 +0,0 @@
1
- /**
2
- * Hash a plain-text password using bcrypt.
3
- *
4
- * @param plain - The raw password string supplied by the user.
5
- * @param saltRounds - bcrypt cost factor; higher values increase security at the cost of speed.
6
- * @returns The bcrypt hash string to persist in the database.
7
- */
8
- export declare function hashPassword(plain: string, saltRounds?: number): Promise<string>;
9
- /**
10
- * Compare a plain-text password against a stored bcrypt hash.
11
- *
12
- * @param plain - The raw password string to verify.
13
- * @param hash - The stored bcrypt hash from the database.
14
- * @returns `true` if the password matches the hash, `false` otherwise.
15
- */
16
- export declare function verifyPassword(plain: string, hash: string): Promise<boolean>;
17
- //# sourceMappingURL=hash.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"hash.d.ts","sourceRoot":"","sources":["../../src/libs/hash.ts"],"names":[],"mappings":"AAEA;;;;;;GAMG;AACH,wBAAsB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,UAAU,SAAK,GAAG,OAAO,CAAC,MAAM,CAAC,CAElF;AAED;;;;;;GAMG;AACH,wBAAsB,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAElF"}
package/dist/libs/hash.js DELETED
@@ -1,22 +0,0 @@
1
- import bcrypt from 'bcrypt';
2
- /**
3
- * Hash a plain-text password using bcrypt.
4
- *
5
- * @param plain - The raw password string supplied by the user.
6
- * @param saltRounds - bcrypt cost factor; higher values increase security at the cost of speed.
7
- * @returns The bcrypt hash string to persist in the database.
8
- */
9
- export async function hashPassword(plain, saltRounds = 12) {
10
- return bcrypt.hash(plain, saltRounds);
11
- }
12
- /**
13
- * Compare a plain-text password against a stored bcrypt hash.
14
- *
15
- * @param plain - The raw password string to verify.
16
- * @param hash - The stored bcrypt hash from the database.
17
- * @returns `true` if the password matches the hash, `false` otherwise.
18
- */
19
- export async function verifyPassword(plain, hash) {
20
- return bcrypt.compare(plain, hash);
21
- }
22
- //# sourceMappingURL=hash.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"hash.js","sourceRoot":"","sources":["../../src/libs/hash.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,KAAa,EAAE,UAAU,GAAG,EAAE;IAC/D,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;AACxC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,KAAa,EAAE,IAAY;IAC9D,OAAO,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;AACrC,CAAC"}