authkit-api 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/LICENSE +21 -0
  3. package/README.md +109 -2
  4. package/bin/cli.js +8 -0
  5. package/package.json +69 -4
  6. package/src/constants.js +24 -0
  7. package/src/generator.js +112 -0
  8. package/src/index.js +89 -0
  9. package/src/prompts.js +43 -0
  10. package/src/utils/fs.js +36 -0
  11. package/src/utils/logger.js +8 -0
  12. package/src/utils/packageJson.js +16 -0
  13. package/src/utils/validateProjectName.js +19 -0
  14. package/templates/base/Dockerfile +22 -0
  15. package/templates/base/README.md +108 -0
  16. package/templates/base/_dockerignore +16 -0
  17. package/templates/base/_env.example +25 -0
  18. package/templates/base/_gitignore +5 -0
  19. package/templates/base/_husky/pre-commit +1 -0
  20. package/templates/base/_prettierignore +5 -0
  21. package/templates/base/_prettierrc +1 -0
  22. package/templates/base/eslint.config.js +23 -0
  23. package/templates/base/package.json +62 -0
  24. package/templates/base/scripts/docker-entrypoint.sh +9 -0
  25. package/templates/base/scripts/generate-postman.js +70 -0
  26. package/templates/base/scripts/seed-admin.js +61 -0
  27. package/templates/base/src/app.js +46 -0
  28. package/templates/base/src/config/env.js +15 -0
  29. package/templates/base/src/config/env.schema.js +85 -0
  30. package/templates/base/src/config/logger.js +20 -0
  31. package/templates/base/src/constants/examples.js +3 -0
  32. package/templates/base/src/constants/roles.js +2 -0
  33. package/templates/base/src/constants/user.rules.js +16 -0
  34. package/templates/base/src/docs/openapi.js +26 -0
  35. package/templates/base/src/docs/openapi.registry.js +81 -0
  36. package/templates/base/src/docs/paths/auth.paths.js +87 -0
  37. package/templates/base/src/docs/paths/user.paths.js +87 -0
  38. package/templates/base/src/middlewares/authenticate.js +19 -0
  39. package/templates/base/src/middlewares/authorize.js +11 -0
  40. package/templates/base/src/middlewares/errorHandler.js +35 -0
  41. package/templates/base/src/middlewares/notFound.js +5 -0
  42. package/templates/base/src/middlewares/rateLimiter.js +20 -0
  43. package/templates/base/src/middlewares/validate.js +31 -0
  44. package/templates/base/src/modules/auth/auth.controller.js +40 -0
  45. package/templates/base/src/modules/auth/auth.cookie.js +21 -0
  46. package/templates/base/src/modules/auth/auth.routes.js +12 -0
  47. package/templates/base/src/modules/auth/auth.service.js +79 -0
  48. package/templates/base/src/modules/auth/auth.validation.js +41 -0
  49. package/templates/base/src/modules/user/user.controller.js +21 -0
  50. package/templates/base/src/modules/user/user.routes.js +22 -0
  51. package/templates/base/src/modules/user/user.service.js +19 -0
  52. package/templates/base/src/modules/user/user.validation.js +24 -0
  53. package/templates/base/src/routes/docs.routes.js +16 -0
  54. package/templates/base/src/routes/health.routes.js +17 -0
  55. package/templates/base/src/routes/index.js +13 -0
  56. package/templates/base/src/server.js +50 -0
  57. package/templates/base/src/utils/ApiError.js +32 -0
  58. package/templates/base/src/utils/apiResponse.js +8 -0
  59. package/templates/base/src/utils/password.js +14 -0
  60. package/templates/base/src/utils/token.js +46 -0
  61. package/templates/base/src/utils/zod.js +5 -0
  62. package/templates/base/tests/app.test.js +67 -0
  63. package/templates/base/tests/auth.test.js +185 -0
  64. package/templates/base/tests/authenticate.test.js +61 -0
  65. package/templates/base/tests/docs.test.js +115 -0
  66. package/templates/base/tests/env.test.js +94 -0
  67. package/templates/base/tests/health.test.js +21 -0
  68. package/templates/base/tests/helpers/auth.helper.js +41 -0
  69. package/templates/base/tests/password.test.js +18 -0
  70. package/templates/base/tests/postman.test.js +31 -0
  71. package/templates/base/tests/rateLimiter.test.js +27 -0
  72. package/templates/base/tests/seedAdmin.test.js +42 -0
  73. package/templates/base/tests/token.test.js +69 -0
  74. package/templates/base/tests/trustProxy.test.js +24 -0
  75. package/templates/base/tests/user.repository.test.js +210 -0
  76. package/templates/base/tests/user.test.js +144 -0
  77. package/templates/base/tests/validate.test.js +35 -0
  78. package/templates/base/tests/validation.test.js +61 -0
  79. package/templates/base/vitest.config.js +16 -0
  80. package/templates/databases/mongodb/README.part.md +23 -0
  81. package/templates/databases/mongodb/_github/workflows/ci.yml +29 -0
  82. package/templates/databases/mongodb/docker-compose.yml +30 -0
  83. package/templates/databases/mongodb/env.part +2 -0
  84. package/templates/databases/mongodb/package.part.json +4 -0
  85. package/templates/databases/mongodb/src/database/connection.js +39 -0
  86. package/templates/databases/mongodb/src/database/env.schema.js +3 -0
  87. package/templates/databases/mongodb/src/database/id.schema.js +3 -0
  88. package/templates/databases/mongodb/src/database/models/refreshToken.model.js +15 -0
  89. package/templates/databases/mongodb/src/database/models/user.model.js +41 -0
  90. package/templates/databases/mongodb/src/modules/user/user.repository.js +68 -0
  91. package/templates/databases/mongodb/tests/globalSetup.js +13 -0
  92. package/templates/databases/mongodb/tests/setup.js +17 -0
  93. package/templates/databases/postgres/README.part.md +31 -0
  94. package/templates/databases/postgres/_github/workflows/ci.yml +46 -0
  95. package/templates/databases/postgres/docker-compose.yml +34 -0
  96. package/templates/databases/postgres/env.part +2 -0
  97. package/templates/databases/postgres/package.part.json +15 -0
  98. package/templates/databases/postgres/prisma/migrations/20261030073256_init/migration.sql +39 -0
  99. package/templates/databases/postgres/prisma/migrations/migration_lock.toml +3 -0
  100. package/templates/databases/postgres/prisma/schema.prisma +39 -0
  101. package/templates/databases/postgres/prisma.config.js +14 -0
  102. package/templates/databases/postgres/src/database/connection.js +61 -0
  103. package/templates/databases/postgres/src/database/env.schema.js +3 -0
  104. package/templates/databases/postgres/src/database/id.schema.js +3 -0
  105. package/templates/databases/postgres/src/database/prisma.js +9 -0
  106. package/templates/databases/postgres/src/modules/user/user.repository.js +88 -0
  107. package/templates/databases/postgres/tests/connection.test.js +17 -0
  108. package/templates/databases/postgres/tests/globalSetup.js +60 -0
  109. package/templates/databases/postgres/tests/prismaSchema.test.js +27 -0
  110. package/templates/databases/postgres/tests/setup.js +15 -0
@@ -0,0 +1,81 @@
1
+ import { extendZodWithOpenApi, OpenAPIRegistry } from '@asteasolutions/zod-to-openapi';
2
+ import { z } from 'zod';
3
+ import { ROLE_VALUES } from '../constants/roles.js';
4
+ import { USER_RULES } from '../constants/user.rules.js';
5
+
6
+ // Called once, here only. Validation files stay free of docs code.
7
+ extendZodWithOpenApi(z);
8
+
9
+ export const registry = new OpenAPIRegistry();
10
+
11
+ export const PublicUser = registry.register(
12
+ 'PublicUser',
13
+ z.object({
14
+ id: z.string(),
15
+ name: z.string(),
16
+ email: z.email(),
17
+ role: z.enum(ROLE_VALUES),
18
+ createdAt: z.iso.datetime(),
19
+ updatedAt: z.iso.datetime(),
20
+ }),
21
+ );
22
+
23
+ export const ErrorResponse = registry.register(
24
+ 'ErrorResponse',
25
+ z.object({ success: z.literal(false), message: z.string() }),
26
+ );
27
+
28
+ export const ValidationErrorResponse = registry.register(
29
+ 'ValidationErrorResponse',
30
+ z.object({
31
+ success: z.literal(false),
32
+ message: z.string(),
33
+ errors: z.array(z.object({ field: z.string(), message: z.string() })),
34
+ }),
35
+ );
36
+
37
+ const PaginationMeta = registry.register(
38
+ 'PaginationMeta',
39
+ z.object({
40
+ page: z.number().int(),
41
+ limit: z.number().int(),
42
+ total: z.number().int(),
43
+ totalPages: z.number().int(),
44
+ }),
45
+ );
46
+
47
+ registry.registerComponent('securitySchemes', 'bearerAuth', {
48
+ type: 'http',
49
+ scheme: 'bearer',
50
+ bearerFormat: 'JWT',
51
+ });
52
+
53
+ registry.registerComponent('securitySchemes', 'refreshCookie', {
54
+ type: 'apiKey',
55
+ in: 'cookie',
56
+ name: 'refreshToken',
57
+ });
58
+
59
+ // The only place the success envelope `{ success, message, data, meta? }` is described.
60
+ export function successResponse(dataSchema, { withMeta = false } = {}) {
61
+ const shape = {
62
+ success: z.literal(true),
63
+ message: z.string(),
64
+ data: dataSchema ?? z.null(),
65
+ };
66
+ if (withMeta) shape.meta = PaginationMeta;
67
+ return z.object(shape);
68
+ }
69
+
70
+ export function jsonContent(schema) {
71
+ return { 'application/json': { schema } };
72
+ }
73
+
74
+ export function errorResponse(description, schema = ErrorResponse) {
75
+ return { description, content: jsonContent(schema) };
76
+ }
77
+
78
+ // The validation email field is `trim().toLowerCase().pipe(z.email())`, which
79
+ // zod-to-openapi cannot describe. This replaces only that field; the limit still
80
+ // comes from USER_RULES.
81
+ export const emailDocSchema = z.email().max(USER_RULES.EMAIL.MAX);
@@ -0,0 +1,87 @@
1
+ import { z } from 'zod';
2
+ import { loginSchema, registerSchema } from '../../modules/auth/auth.validation.js';
3
+ import {
4
+ emailDocSchema,
5
+ errorResponse,
6
+ jsonContent,
7
+ PublicUser,
8
+ successResponse,
9
+ ValidationErrorResponse,
10
+ } from '../openapi.registry.js';
11
+
12
+ const TAG = ['Auth'];
13
+ const registerBody = registerSchema.shape.body.extend({ email: emailDocSchema });
14
+ const loginBody = loginSchema.shape.body.extend({ email: emailDocSchema });
15
+ const sessionData = z.object({ user: PublicUser, accessToken: z.string() });
16
+
17
+ export function registerAuthPaths(registry) {
18
+ registry.registerPath({
19
+ method: 'post',
20
+ path: '/auth/register',
21
+ tags: TAG,
22
+ summary: 'Register',
23
+ description: 'Creates a user with role `user`. Rate limited.',
24
+ request: { body: { required: true, content: jsonContent(registerBody) } },
25
+ responses: {
26
+ 201: {
27
+ description: 'User registered',
28
+ content: jsonContent(successResponse(z.object({ user: PublicUser }))),
29
+ },
30
+ 400: errorResponse('Validation error', ValidationErrorResponse),
31
+ 409: errorResponse('Email already registered'),
32
+ 429: errorResponse('Too many requests'),
33
+ },
34
+ });
35
+
36
+ registry.registerPath({
37
+ method: 'post',
38
+ path: '/auth/login',
39
+ tags: TAG,
40
+ summary: 'Log in',
41
+ description:
42
+ 'Returns the access token. The refresh token is set as an httpOnly cookie. Rate limited.',
43
+ request: { body: { required: true, content: jsonContent(loginBody) } },
44
+ responses: {
45
+ 200: {
46
+ description: 'Logged in. Sets the `refreshToken` cookie.',
47
+ headers: { 'Set-Cookie': { schema: { type: 'string' } } },
48
+ content: jsonContent(successResponse(sessionData)),
49
+ },
50
+ 400: errorResponse('Validation error', ValidationErrorResponse),
51
+ 401: errorResponse('Invalid email or password'),
52
+ 429: errorResponse('Too many requests'),
53
+ },
54
+ });
55
+
56
+ registry.registerPath({
57
+ method: 'post',
58
+ path: '/auth/refresh',
59
+ tags: TAG,
60
+ summary: 'Refresh the session',
61
+ description:
62
+ "Rotates the refresh token (sent as a cookie) and returns a new access token. Reusing a revoked token revokes all of the user's tokens.",
63
+ responses: {
64
+ 200: {
65
+ description: 'Token refreshed. Sets a new `refreshToken` cookie.',
66
+ headers: { 'Set-Cookie': { schema: { type: 'string' } } },
67
+ content: jsonContent(successResponse(sessionData)),
68
+ },
69
+ 401: errorResponse('Missing, invalid or revoked refresh token'),
70
+ },
71
+ });
72
+
73
+ registry.registerPath({
74
+ method: 'post',
75
+ path: '/auth/logout',
76
+ tags: TAG,
77
+ summary: 'Log out',
78
+ description:
79
+ 'Revokes the refresh token and clears the cookie. Succeeds even if already logged out.',
80
+ responses: {
81
+ 200: {
82
+ description: 'Logged out',
83
+ content: jsonContent(successResponse()),
84
+ },
85
+ },
86
+ });
87
+ }
@@ -0,0 +1,87 @@
1
+ import { z } from 'zod';
2
+ import { listUsersSchema, userIdParamSchema } from '../../modules/user/user.validation.js';
3
+ import {
4
+ errorResponse,
5
+ jsonContent,
6
+ PublicUser,
7
+ successResponse,
8
+ ValidationErrorResponse,
9
+ } from '../openapi.registry.js';
10
+
11
+ const TAG = ['Users'];
12
+ const security = [{ bearerAuth: [] }];
13
+ const unauthorized = errorResponse('Missing or invalid access token');
14
+ const forbidden = errorResponse('Admin role required');
15
+
16
+ export function registerUserPaths(registry) {
17
+ registry.registerPath({
18
+ method: 'get',
19
+ path: '/users/me',
20
+ tags: TAG,
21
+ summary: 'Get my profile',
22
+ security,
23
+ responses: {
24
+ 200: {
25
+ description: 'Your profile',
26
+ content: jsonContent(successResponse(z.object({ user: PublicUser }))),
27
+ },
28
+ 401: unauthorized,
29
+ },
30
+ });
31
+
32
+ registry.registerPath({
33
+ method: 'get',
34
+ path: '/users',
35
+ tags: TAG,
36
+ summary: 'List users (admin)',
37
+ security,
38
+ request: { query: listUsersSchema.shape.query },
39
+ responses: {
40
+ 200: {
41
+ description: 'A page of users',
42
+ content: jsonContent(
43
+ successResponse(z.object({ users: z.array(PublicUser) }), { withMeta: true }),
44
+ ),
45
+ },
46
+ 400: errorResponse('Validation error', ValidationErrorResponse),
47
+ 401: unauthorized,
48
+ 403: forbidden,
49
+ },
50
+ });
51
+
52
+ registry.registerPath({
53
+ method: 'get',
54
+ path: '/users/{id}',
55
+ tags: TAG,
56
+ summary: 'Get a user (admin)',
57
+ security,
58
+ request: { params: userIdParamSchema.shape.params },
59
+ responses: {
60
+ 200: {
61
+ description: 'The user',
62
+ content: jsonContent(successResponse(z.object({ user: PublicUser }))),
63
+ },
64
+ 400: errorResponse('Malformed id', ValidationErrorResponse),
65
+ 401: unauthorized,
66
+ 403: forbidden,
67
+ 404: errorResponse('User not found'),
68
+ },
69
+ });
70
+
71
+ registry.registerPath({
72
+ method: 'delete',
73
+ path: '/users/{id}',
74
+ tags: TAG,
75
+ summary: 'Delete a user (admin)',
76
+ description: "Also deletes the user's refresh tokens. An admin cannot delete themselves.",
77
+ security,
78
+ request: { params: userIdParamSchema.shape.params },
79
+ responses: {
80
+ 204: { description: 'Deleted' },
81
+ 400: errorResponse('Malformed id or self-delete', ValidationErrorResponse),
82
+ 401: unauthorized,
83
+ 403: forbidden,
84
+ 404: errorResponse('User not found'),
85
+ },
86
+ });
87
+ }
@@ -0,0 +1,19 @@
1
+ import * as userRepository from '../modules/user/user.repository.js';
2
+ import { ApiError } from '../utils/ApiError.js';
3
+ import { verifyAccessToken } from '../utils/token.js';
4
+
5
+ const BEARER_PATTERN = /^Bearer (\S+)$/;
6
+
7
+ // Verifies the access token, then loads the user so a deleted user or a changed
8
+ // role takes effect at once. The role comes from the database, not the token.
9
+ export async function authenticate(req, _res, next) {
10
+ const match = BEARER_PATTERN.exec(req.headers.authorization ?? '');
11
+ if (!match) throw ApiError.unauthorized('Authentication required');
12
+
13
+ const { userId } = verifyAccessToken(match[1]);
14
+ const user = await userRepository.findById(userId);
15
+ if (!user) throw ApiError.unauthorized('Invalid or expired token');
16
+
17
+ req.user = user;
18
+ next();
19
+ }
@@ -0,0 +1,11 @@
1
+ import { ApiError } from '../utils/ApiError.js';
2
+
3
+ // Must run after `authenticate`, which sets req.user.
4
+ export function authorize(...allowedRoles) {
5
+ return (req, _res, next) => {
6
+ if (!allowedRoles.includes(req.user?.role)) {
7
+ throw ApiError.forbidden('You do not have permission to perform this action');
8
+ }
9
+ next();
10
+ };
11
+ }
@@ -0,0 +1,35 @@
1
+ import { env } from '../config/env.js';
2
+ import { mapDatabaseError } from '../database/connection.js';
3
+ import { ApiError } from '../utils/ApiError.js';
4
+
5
+ // Errors raised by body-parser carry a `type` and a 4xx status.
6
+ function fromBodyParser(err) {
7
+ if (err.type === 'entity.parse.failed') return ApiError.badRequest('Invalid JSON body');
8
+ if (err.type === 'entity.too.large') return new ApiError(413, 'Request body too large');
9
+ // Other http-errors from middleware (e.g. 415 for an unsupported charset) are
10
+ // marked `expose` when their message is safe to show.
11
+ const status = err.status ?? err.statusCode;
12
+ if (Number.isInteger(status) && status >= 400 && status < 500 && err.expose === true) {
13
+ return new ApiError(status, err.message);
14
+ }
15
+ return null;
16
+ }
17
+
18
+ function toApiError(err) {
19
+ if (err instanceof ApiError) return err;
20
+ return mapDatabaseError(err) ?? fromBodyParser(err);
21
+ }
22
+
23
+ export function errorHandler(err, req, res, _next) {
24
+ const known = toApiError(err);
25
+ const statusCode = known?.statusCode ?? 500;
26
+ const message = known?.message ?? 'Internal server error';
27
+
28
+ if (statusCode >= 500) req.log.error({ err }, message);
29
+ else req.log.warn({ err }, message);
30
+
31
+ const body = { success: false, message };
32
+ if (known?.errors !== undefined) body.errors = known.errors;
33
+ if (env.NODE_ENV === 'development' && err.stack) body.stack = err.stack;
34
+ res.status(statusCode).json(body);
35
+ }
@@ -0,0 +1,5 @@
1
+ import { ApiError } from '../utils/ApiError.js';
2
+
3
+ export function notFound(_req, _res, next) {
4
+ next(ApiError.notFound('Route not found'));
5
+ }
@@ -0,0 +1,20 @@
1
+ import { rateLimit } from 'express-rate-limit';
2
+ import { env } from '../config/env.js';
3
+ import { ApiError } from '../utils/ApiError.js';
4
+
5
+ export function createRateLimiter({ windowMs, max }) {
6
+ return rateLimit({
7
+ windowMs,
8
+ limit: max,
9
+ standardHeaders: 'draft-8',
10
+ legacyHeaders: false,
11
+ // Hand the error to errorHandler so the JSON shape stays in one place.
12
+ handler: (_req, _res, next) =>
13
+ next(ApiError.tooManyRequests('Too many requests, please try again later')),
14
+ });
15
+ }
16
+
17
+ export const authRateLimiter = createRateLimiter({
18
+ windowMs: 15 * 60 * 1000,
19
+ max: env.AUTH_RATE_LIMIT_MAX,
20
+ });
@@ -0,0 +1,31 @@
1
+ import { ApiError } from '../utils/ApiError.js';
2
+
3
+ function toFieldErrors(issues) {
4
+ return issues.flatMap((issue) => {
5
+ if (issue.code === 'unrecognized_keys') {
6
+ const prefix = issue.path.slice(1).join('.');
7
+ return issue.keys.map((key) => ({
8
+ field: prefix ? `${prefix}.${key}` : key,
9
+ message: `Unrecognized field "${key}"`,
10
+ }));
11
+ }
12
+ return [{ field: issue.path.slice(1).join('.'), message: issue.message }];
13
+ });
14
+ }
15
+
16
+ // Validates { body, params, query } against a schema. Parsed values go to
17
+ // req.validated, because Express 5 makes req.query read-only.
18
+ export function validate(schema) {
19
+ return (req, _res, next) => {
20
+ const result = schema.safeParse({
21
+ body: req.body ?? {},
22
+ params: req.params,
23
+ query: req.query,
24
+ });
25
+ if (!result.success) {
26
+ return next(ApiError.badRequest('Validation failed', toFieldErrors(result.error.issues)));
27
+ }
28
+ req.validated = result.data;
29
+ return next();
30
+ };
31
+ }
@@ -0,0 +1,40 @@
1
+ import { sendSuccess } from '../../utils/apiResponse.js';
2
+ import { ApiError } from '../../utils/ApiError.js';
3
+ import { clearRefreshCookie, REFRESH_COOKIE_NAME, setRefreshCookie } from './auth.cookie.js';
4
+ import * as authService from './auth.service.js';
5
+
6
+ // The refresh token travels only in the cookie, never in the body.
7
+ function sendSession(res, message, session) {
8
+ setRefreshCookie(res, session.refreshToken, session.refreshExpiresAt);
9
+ return sendSuccess(res, {
10
+ message,
11
+ data: { user: session.user, accessToken: session.accessToken },
12
+ });
13
+ }
14
+
15
+ export async function register(req, res) {
16
+ const user = await authService.registerUser(req.validated.body);
17
+ return sendSuccess(res, {
18
+ statusCode: 201,
19
+ message: 'User registered successfully',
20
+ data: { user },
21
+ });
22
+ }
23
+
24
+ export async function login(req, res) {
25
+ const session = await authService.loginUser(req.validated.body);
26
+ return sendSession(res, 'Logged in successfully', session);
27
+ }
28
+
29
+ export async function refresh(req, res) {
30
+ const token = req.cookies?.[REFRESH_COOKIE_NAME];
31
+ if (!token) throw ApiError.unauthorized('Refresh token required');
32
+ const session = await authService.refreshSession(token);
33
+ return sendSession(res, 'Token refreshed', session);
34
+ }
35
+
36
+ export async function logout(req, res) {
37
+ await authService.logoutUser(req.cookies?.[REFRESH_COOKIE_NAME]);
38
+ clearRefreshCookie(res);
39
+ return sendSuccess(res, { message: 'Logged out successfully' });
40
+ }
@@ -0,0 +1,21 @@
1
+ import { env } from '../../config/env.js';
2
+
3
+ export const REFRESH_COOKIE_NAME = 'refreshToken';
4
+
5
+ // One place for the cookie options, so set and clear always match.
6
+ function baseCookieOptions() {
7
+ return {
8
+ httpOnly: true,
9
+ secure: env.NODE_ENV === 'production',
10
+ sameSite: 'strict',
11
+ path: '/api/v1/auth',
12
+ };
13
+ }
14
+
15
+ export function setRefreshCookie(res, token, expiresAt) {
16
+ res.cookie(REFRESH_COOKIE_NAME, token, { ...baseCookieOptions(), expires: expiresAt });
17
+ }
18
+
19
+ export function clearRefreshCookie(res) {
20
+ res.clearCookie(REFRESH_COOKIE_NAME, baseCookieOptions());
21
+ }
@@ -0,0 +1,12 @@
1
+ import { Router } from 'express';
2
+ import { authRateLimiter } from '../../middlewares/rateLimiter.js';
3
+ import { validate } from '../../middlewares/validate.js';
4
+ import * as authController from './auth.controller.js';
5
+ import { loginSchema, registerSchema } from './auth.validation.js';
6
+
7
+ export const authRouter = Router();
8
+
9
+ authRouter.post('/register', authRateLimiter, validate(registerSchema), authController.register);
10
+ authRouter.post('/login', authRateLimiter, validate(loginSchema), authController.login);
11
+ authRouter.post('/refresh', authController.refresh);
12
+ authRouter.post('/logout', authController.logout);
@@ -0,0 +1,79 @@
1
+ import * as userRepository from '../user/user.repository.js';
2
+ import { ApiError } from '../../utils/ApiError.js';
3
+ import { hashPassword, verifyPassword } from '../../utils/password.js';
4
+ import {
5
+ hashToken,
6
+ signAccessToken,
7
+ signRefreshToken,
8
+ verifyRefreshToken,
9
+ } from '../../utils/token.js';
10
+
11
+ // Hashed once, on first use. Verifying against it when the user is unknown keeps
12
+ // login timing close to the wrong-password case.
13
+ let dummyHashPromise;
14
+ const getDummyHash = () => (dummyHashPromise ??= hashPassword('dummy-password-for-timing'));
15
+
16
+ async function issueTokens(user) {
17
+ const accessToken = signAccessToken({ userId: user.id, role: user.role });
18
+ const { token: refreshToken, expiresAt: refreshExpiresAt } = signRefreshToken({
19
+ userId: user.id,
20
+ });
21
+ await userRepository.saveRefreshToken({
22
+ userId: user.id,
23
+ tokenHash: hashToken(refreshToken),
24
+ expiresAt: refreshExpiresAt,
25
+ });
26
+ return { user, accessToken, refreshToken, refreshExpiresAt };
27
+ }
28
+
29
+ export async function registerUser({ name, email, password }) {
30
+ if (await userRepository.findByEmail(email)) {
31
+ throw ApiError.conflict('Email is already registered');
32
+ }
33
+ // The unique index still catches a race between two registrations.
34
+ return userRepository.create({ name, email, password: await hashPassword(password) });
35
+ }
36
+
37
+ export async function loginUser({ email, password }) {
38
+ const found = await userRepository.findByEmail(email, { withPassword: true });
39
+ const passwordOk = await verifyPassword(found?.password ?? (await getDummyHash()), password);
40
+ if (!found || !passwordOk) throw ApiError.unauthorized('Invalid email or password');
41
+
42
+ const { password: _password, ...user } = found;
43
+ return issueTokens(user);
44
+ }
45
+
46
+ export async function refreshSession(refreshToken) {
47
+ const { userId } = verifyRefreshToken(refreshToken);
48
+ const tokenHash = hashToken(refreshToken);
49
+ const stored = await userRepository.findRefreshToken(tokenHash);
50
+ if (!stored) throw ApiError.unauthorized('Invalid or expired token');
51
+
52
+ if (stored.revokedAt) {
53
+ // A revoked token being used again means it was probably stolen.
54
+ await userRepository.revokeAllRefreshTokens(userId);
55
+ throw ApiError.unauthorized('Invalid or expired token');
56
+ }
57
+ if (stored.expiresAt <= new Date()) throw ApiError.unauthorized('Invalid or expired token');
58
+
59
+ const user = await userRepository.findById(userId);
60
+ if (!user) throw ApiError.unauthorized('Invalid or expired token');
61
+
62
+ // Only one of two concurrent refreshes can flip the token to revoked. The loser
63
+ // is treated like a reuse of a rotated token.
64
+ if (!(await userRepository.revokeRefreshToken(tokenHash))) {
65
+ await userRepository.revokeAllRefreshTokens(userId);
66
+ throw ApiError.unauthorized('Invalid or expired token');
67
+ }
68
+ return issueTokens(user);
69
+ }
70
+
71
+ export async function logoutUser(refreshToken) {
72
+ if (!refreshToken) return;
73
+ try {
74
+ verifyRefreshToken(refreshToken);
75
+ await userRepository.revokeRefreshToken(hashToken(refreshToken));
76
+ } catch {
77
+ // Logout always succeeds, even with a bad or already revoked token.
78
+ }
79
+ }
@@ -0,0 +1,41 @@
1
+ import { z } from 'zod';
2
+ import { USER_RULES } from '../../constants/user.rules.js';
3
+ import { emptyObject } from '../../utils/zod.js';
4
+
5
+ const { NAME, EMAIL, PASSWORD } = USER_RULES;
6
+
7
+ // Trim and lowercase first, then validate, so " Foo@X.com " is accepted.
8
+ const emailSchema = z
9
+ .string()
10
+ .trim()
11
+ .toLowerCase()
12
+ .pipe(z.email('Invalid email address').max(EMAIL.MAX));
13
+
14
+ const passwordSchema = z
15
+ .string()
16
+ .min(PASSWORD.MIN)
17
+ .max(PASSWORD.MAX)
18
+ .regex(
19
+ PASSWORD.PATTERN,
20
+ 'Password must contain a lowercase letter, an uppercase letter and a digit',
21
+ );
22
+
23
+ export const registerSchema = z.strictObject({
24
+ body: z.strictObject({
25
+ name: z.string().trim().min(NAME.MIN).max(NAME.MAX),
26
+ email: emailSchema,
27
+ password: passwordSchema,
28
+ }),
29
+ params: emptyObject(),
30
+ query: emptyObject(),
31
+ });
32
+
33
+ // Login only checks presence, so it never reveals the password rules.
34
+ export const loginSchema = z.strictObject({
35
+ body: z.strictObject({
36
+ email: emailSchema,
37
+ password: z.string().min(1),
38
+ }),
39
+ params: emptyObject(),
40
+ query: emptyObject(),
41
+ });
@@ -0,0 +1,21 @@
1
+ import { sendSuccess } from '../../utils/apiResponse.js';
2
+ import * as userService from './user.service.js';
3
+
4
+ export function getMe(req, res) {
5
+ return sendSuccess(res, { message: 'Profile fetched successfully', data: { user: req.user } });
6
+ }
7
+
8
+ export async function getUsers(req, res) {
9
+ const { users, meta } = await userService.listUsers(req.validated.query);
10
+ return sendSuccess(res, { message: 'Users fetched successfully', data: { users }, meta });
11
+ }
12
+
13
+ export async function getUser(req, res) {
14
+ const user = await userService.getUserById(req.validated.params.id);
15
+ return sendSuccess(res, { message: 'User fetched successfully', data: { user } });
16
+ }
17
+
18
+ export async function removeUser(req, res) {
19
+ await userService.deleteUser({ targetId: req.validated.params.id, actorId: req.user.id });
20
+ return res.status(204).end();
21
+ }
@@ -0,0 +1,22 @@
1
+ import { Router } from 'express';
2
+ import { authenticate } from '../../middlewares/authenticate.js';
3
+ import { authorize } from '../../middlewares/authorize.js';
4
+ import { validate } from '../../middlewares/validate.js';
5
+ import { ROLES } from '../../constants/roles.js';
6
+ import * as userController from './user.controller.js';
7
+ import { listUsersSchema, userIdParamSchema } from './user.validation.js';
8
+
9
+ export const userRouter = Router();
10
+
11
+ userRouter.use(authenticate);
12
+
13
+ // `/me` must be declared before `/:id`.
14
+ userRouter.get('/me', userController.getMe);
15
+ userRouter.get('/', authorize(ROLES.ADMIN), validate(listUsersSchema), userController.getUsers);
16
+ userRouter.get('/:id', authorize(ROLES.ADMIN), validate(userIdParamSchema), userController.getUser);
17
+ userRouter.delete(
18
+ '/:id',
19
+ authorize(ROLES.ADMIN),
20
+ validate(userIdParamSchema),
21
+ userController.removeUser,
22
+ );
@@ -0,0 +1,19 @@
1
+ import { ApiError } from '../../utils/ApiError.js';
2
+ import * as userRepository from './user.repository.js';
3
+
4
+ export async function getUserById(id) {
5
+ const user = await userRepository.findById(id);
6
+ if (!user) throw ApiError.notFound('User not found');
7
+ return user;
8
+ }
9
+
10
+ export async function listUsers({ page, limit }) {
11
+ const { users, total } = await userRepository.findMany({ page, limit });
12
+ return { users, meta: { page, limit, total, totalPages: Math.ceil(total / limit) } };
13
+ }
14
+
15
+ export async function deleteUser({ targetId, actorId }) {
16
+ if (targetId === actorId) throw ApiError.badRequest('You cannot delete your own account');
17
+ const deleted = await userRepository.deleteById(targetId);
18
+ if (!deleted) throw ApiError.notFound('User not found');
19
+ }
@@ -0,0 +1,24 @@
1
+ import { z } from 'zod';
2
+ import { PAGINATION } from '../../constants/user.rules.js';
3
+ import { idSchema } from '../../database/id.schema.js';
4
+ import { emptyObject } from '../../utils/zod.js';
5
+
6
+ export const userIdParamSchema = z.strictObject({
7
+ body: emptyObject(),
8
+ params: z.strictObject({ id: idSchema }),
9
+ query: emptyObject(),
10
+ });
11
+
12
+ export const listUsersSchema = z.strictObject({
13
+ body: emptyObject(),
14
+ params: emptyObject(),
15
+ query: z.strictObject({
16
+ page: z.coerce.number().int().min(1).default(PAGINATION.DEFAULT_PAGE),
17
+ limit: z.coerce
18
+ .number()
19
+ .int()
20
+ .min(1)
21
+ .max(PAGINATION.MAX_LIMIT)
22
+ .default(PAGINATION.DEFAULT_LIMIT),
23
+ }),
24
+ });