authkit-api 0.0.0-stage → 1.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 (210) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/LICENSE +21 -0
  3. package/README.md +125 -2
  4. package/bin/cli.js +8 -0
  5. package/package.json +76 -4
  6. package/src/constants.js +29 -0
  7. package/src/generator.js +142 -0
  8. package/src/index.js +99 -0
  9. package/src/prompts.js +59 -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/package.json +62 -0
  23. package/templates/base/scripts/docker-entrypoint.sh +9 -0
  24. package/templates/base/scripts/generate-postman.ts +102 -0
  25. package/templates/base/scripts/seed-admin.ts +62 -0
  26. package/templates/base/src/app.ts +46 -0
  27. package/templates/base/src/config/env.schema.ts +85 -0
  28. package/templates/base/src/config/env.ts +15 -0
  29. package/templates/base/src/config/logger.ts +20 -0
  30. package/templates/base/src/constants/examples.ts +3 -0
  31. package/templates/base/src/constants/roles.ts +4 -0
  32. package/templates/base/src/constants/user.rules.ts +16 -0
  33. package/templates/base/src/docs/openapi.registry.ts +90 -0
  34. package/templates/base/src/docs/openapi.ts +36 -0
  35. package/templates/base/src/docs/paths/auth.paths.ts +88 -0
  36. package/templates/base/src/docs/paths/user.paths.ts +88 -0
  37. package/templates/base/src/middlewares/authenticate.ts +20 -0
  38. package/templates/base/src/middlewares/authorize.ts +13 -0
  39. package/templates/base/src/middlewares/errorHandler.ts +52 -0
  40. package/templates/base/src/middlewares/notFound.ts +6 -0
  41. package/templates/base/src/middlewares/rateLimiter.ts +20 -0
  42. package/templates/base/src/middlewares/validate.ts +39 -0
  43. package/templates/base/src/modules/auth/auth.controller.ts +45 -0
  44. package/templates/base/src/modules/auth/auth.cookie.ts +22 -0
  45. package/templates/base/src/modules/auth/auth.routes.ts +12 -0
  46. package/templates/base/src/modules/auth/auth.service.ts +81 -0
  47. package/templates/base/src/modules/auth/auth.validation.ts +44 -0
  48. package/templates/base/src/modules/user/user.controller.ts +24 -0
  49. package/templates/base/src/modules/user/user.routes.ts +22 -0
  50. package/templates/base/src/modules/user/user.service.ts +57 -0
  51. package/templates/base/src/modules/user/user.validation.ts +27 -0
  52. package/templates/base/src/routes/docs.routes.ts +16 -0
  53. package/templates/base/src/routes/health.routes.ts +17 -0
  54. package/templates/base/src/routes/index.ts +13 -0
  55. package/templates/base/src/server.ts +51 -0
  56. package/templates/base/src/types/express.d.ts +14 -0
  57. package/templates/base/src/utils/ApiError.ts +35 -0
  58. package/templates/base/src/utils/apiResponse.ts +24 -0
  59. package/templates/base/src/utils/password.ts +14 -0
  60. package/templates/base/src/utils/token.ts +60 -0
  61. package/templates/base/src/utils/zod.ts +5 -0
  62. package/templates/base/tests/app.test.ts +67 -0
  63. package/templates/base/tests/auth.test.ts +194 -0
  64. package/templates/base/tests/authenticate.test.ts +61 -0
  65. package/templates/base/tests/docs.test.ts +127 -0
  66. package/templates/base/tests/env.test.ts +96 -0
  67. package/templates/base/tests/health.test.ts +21 -0
  68. package/templates/base/tests/helpers/auth.helper.ts +49 -0
  69. package/templates/base/tests/password.test.ts +18 -0
  70. package/templates/base/tests/postman.test.ts +32 -0
  71. package/templates/base/tests/rateLimiter.test.ts +27 -0
  72. package/templates/base/tests/seedAdmin.test.ts +42 -0
  73. package/templates/base/tests/token.test.ts +69 -0
  74. package/templates/base/tests/trustProxy.test.ts +24 -0
  75. package/templates/base/tests/user.repository.test.ts +211 -0
  76. package/templates/base/tests/user.test.ts +145 -0
  77. package/templates/base/tests/validate.test.ts +42 -0
  78. package/templates/base/tests/validation.test.ts +62 -0
  79. package/templates/base/vitest.config.ts +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.ts +46 -0
  86. package/templates/databases/mongodb/src/database/env.schema.ts +3 -0
  87. package/templates/databases/mongodb/src/database/id.schema.ts +3 -0
  88. package/templates/databases/mongodb/src/database/models/refreshToken.model.ts +24 -0
  89. package/templates/databases/mongodb/src/database/models/user.model.ts +52 -0
  90. package/templates/databases/mongodb/src/modules/user/user.repository.ts +91 -0
  91. package/templates/databases/mongodb/tests/globalSetup.ts +13 -0
  92. package/templates/databases/mongodb/tests/setup.ts +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.ts +14 -0
  102. package/templates/databases/postgres/src/database/connection.ts +72 -0
  103. package/templates/databases/postgres/src/database/env.schema.ts +3 -0
  104. package/templates/databases/postgres/src/database/id.schema.ts +3 -0
  105. package/templates/databases/postgres/src/database/prisma.ts +9 -0
  106. package/templates/databases/postgres/src/modules/user/user.repository.ts +111 -0
  107. package/templates/databases/postgres/tests/connection.test.ts +19 -0
  108. package/templates/databases/postgres/tests/globalSetup.ts +66 -0
  109. package/templates/databases/postgres/tests/prismaSchema.test.ts +27 -0
  110. package/templates/databases/postgres/tests/setup.ts +15 -0
  111. package/templates/languages/js/eslint.config.js +23 -0
  112. package/templates/languages/ts/eslint.config.js +30 -0
  113. package/templates/languages/ts/package.part.json +21 -0
  114. package/templates/languages/ts/tsconfig.json +15 -0
  115. package/templates-js/base/Dockerfile +22 -0
  116. package/templates-js/base/README.md +108 -0
  117. package/templates-js/base/_dockerignore +16 -0
  118. package/templates-js/base/_env.example +25 -0
  119. package/templates-js/base/_gitignore +5 -0
  120. package/templates-js/base/_husky/pre-commit +1 -0
  121. package/templates-js/base/_prettierignore +5 -0
  122. package/templates-js/base/_prettierrc +1 -0
  123. package/templates-js/base/package.json +62 -0
  124. package/templates-js/base/scripts/docker-entrypoint.sh +9 -0
  125. package/templates-js/base/scripts/generate-postman.js +70 -0
  126. package/templates-js/base/scripts/seed-admin.js +61 -0
  127. package/templates-js/base/src/app.js +46 -0
  128. package/templates-js/base/src/config/env.js +15 -0
  129. package/templates-js/base/src/config/env.schema.js +85 -0
  130. package/templates-js/base/src/config/logger.js +20 -0
  131. package/templates-js/base/src/constants/examples.js +3 -0
  132. package/templates-js/base/src/constants/roles.js +2 -0
  133. package/templates-js/base/src/constants/user.rules.js +16 -0
  134. package/templates-js/base/src/docs/openapi.js +26 -0
  135. package/templates-js/base/src/docs/openapi.registry.js +81 -0
  136. package/templates-js/base/src/docs/paths/auth.paths.js +87 -0
  137. package/templates-js/base/src/docs/paths/user.paths.js +87 -0
  138. package/templates-js/base/src/middlewares/authenticate.js +19 -0
  139. package/templates-js/base/src/middlewares/authorize.js +11 -0
  140. package/templates-js/base/src/middlewares/errorHandler.js +35 -0
  141. package/templates-js/base/src/middlewares/notFound.js +5 -0
  142. package/templates-js/base/src/middlewares/rateLimiter.js +20 -0
  143. package/templates-js/base/src/middlewares/validate.js +31 -0
  144. package/templates-js/base/src/modules/auth/auth.controller.js +40 -0
  145. package/templates-js/base/src/modules/auth/auth.cookie.js +21 -0
  146. package/templates-js/base/src/modules/auth/auth.routes.js +12 -0
  147. package/templates-js/base/src/modules/auth/auth.service.js +79 -0
  148. package/templates-js/base/src/modules/auth/auth.validation.js +41 -0
  149. package/templates-js/base/src/modules/user/user.controller.js +21 -0
  150. package/templates-js/base/src/modules/user/user.routes.js +22 -0
  151. package/templates-js/base/src/modules/user/user.service.js +19 -0
  152. package/templates-js/base/src/modules/user/user.validation.js +24 -0
  153. package/templates-js/base/src/routes/docs.routes.js +16 -0
  154. package/templates-js/base/src/routes/health.routes.js +17 -0
  155. package/templates-js/base/src/routes/index.js +13 -0
  156. package/templates-js/base/src/server.js +50 -0
  157. package/templates-js/base/src/utils/ApiError.js +32 -0
  158. package/templates-js/base/src/utils/apiResponse.js +8 -0
  159. package/templates-js/base/src/utils/password.js +14 -0
  160. package/templates-js/base/src/utils/token.js +46 -0
  161. package/templates-js/base/src/utils/zod.js +5 -0
  162. package/templates-js/base/tests/app.test.js +67 -0
  163. package/templates-js/base/tests/auth.test.js +185 -0
  164. package/templates-js/base/tests/authenticate.test.js +61 -0
  165. package/templates-js/base/tests/docs.test.js +115 -0
  166. package/templates-js/base/tests/env.test.js +94 -0
  167. package/templates-js/base/tests/health.test.js +21 -0
  168. package/templates-js/base/tests/helpers/auth.helper.js +41 -0
  169. package/templates-js/base/tests/password.test.js +18 -0
  170. package/templates-js/base/tests/postman.test.js +31 -0
  171. package/templates-js/base/tests/rateLimiter.test.js +27 -0
  172. package/templates-js/base/tests/seedAdmin.test.js +42 -0
  173. package/templates-js/base/tests/token.test.js +69 -0
  174. package/templates-js/base/tests/trustProxy.test.js +24 -0
  175. package/templates-js/base/tests/user.repository.test.js +210 -0
  176. package/templates-js/base/tests/user.test.js +144 -0
  177. package/templates-js/base/tests/validate.test.js +35 -0
  178. package/templates-js/base/tests/validation.test.js +61 -0
  179. package/templates-js/base/vitest.config.js +16 -0
  180. package/templates-js/databases/mongodb/README.part.md +23 -0
  181. package/templates-js/databases/mongodb/_github/workflows/ci.yml +29 -0
  182. package/templates-js/databases/mongodb/docker-compose.yml +30 -0
  183. package/templates-js/databases/mongodb/env.part +2 -0
  184. package/templates-js/databases/mongodb/package.part.json +4 -0
  185. package/templates-js/databases/mongodb/src/database/connection.js +39 -0
  186. package/templates-js/databases/mongodb/src/database/env.schema.js +3 -0
  187. package/templates-js/databases/mongodb/src/database/id.schema.js +3 -0
  188. package/templates-js/databases/mongodb/src/database/models/refreshToken.model.js +15 -0
  189. package/templates-js/databases/mongodb/src/database/models/user.model.js +41 -0
  190. package/templates-js/databases/mongodb/src/modules/user/user.repository.js +68 -0
  191. package/templates-js/databases/mongodb/tests/globalSetup.js +13 -0
  192. package/templates-js/databases/mongodb/tests/setup.js +17 -0
  193. package/templates-js/databases/postgres/README.part.md +31 -0
  194. package/templates-js/databases/postgres/_github/workflows/ci.yml +46 -0
  195. package/templates-js/databases/postgres/docker-compose.yml +34 -0
  196. package/templates-js/databases/postgres/env.part +2 -0
  197. package/templates-js/databases/postgres/package.part.json +15 -0
  198. package/templates-js/databases/postgres/prisma/migrations/20261030073256_init/migration.sql +39 -0
  199. package/templates-js/databases/postgres/prisma/migrations/migration_lock.toml +3 -0
  200. package/templates-js/databases/postgres/prisma/schema.prisma +39 -0
  201. package/templates-js/databases/postgres/prisma.config.js +14 -0
  202. package/templates-js/databases/postgres/src/database/connection.js +61 -0
  203. package/templates-js/databases/postgres/src/database/env.schema.js +3 -0
  204. package/templates-js/databases/postgres/src/database/id.schema.js +3 -0
  205. package/templates-js/databases/postgres/src/database/prisma.js +9 -0
  206. package/templates-js/databases/postgres/src/modules/user/user.repository.js +88 -0
  207. package/templates-js/databases/postgres/tests/connection.test.js +17 -0
  208. package/templates-js/databases/postgres/tests/globalSetup.js +60 -0
  209. package/templates-js/databases/postgres/tests/prismaSchema.test.js +27 -0
  210. package/templates-js/databases/postgres/tests/setup.js +15 -0
@@ -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
+ });
@@ -0,0 +1,16 @@
1
+ import { Router } from 'express';
2
+ import helmet from 'helmet';
3
+ import swaggerUi from 'swagger-ui-express';
4
+ import { buildOpenApiDocument } from '../docs/openapi.js';
5
+
6
+ export const docsRouter = Router();
7
+
8
+ // Swagger UI uses inline scripts and styles, so the strict CSP is off for the docs only.
9
+ docsRouter.use(['/api-docs', '/api-docs.json'], helmet({ contentSecurityPolicy: false }));
10
+
11
+ docsRouter.get('/api-docs.json', (req, res) => res.json(buildOpenApiDocument()));
12
+ docsRouter.use(
13
+ '/api-docs',
14
+ swaggerUi.serve,
15
+ swaggerUi.setup(buildOpenApiDocument(), { swaggerOptions: { persistAuthorization: true } }),
16
+ );
@@ -0,0 +1,17 @@
1
+ import { Router } from 'express';
2
+ import { isDatabaseConnected } from '../database/connection.js';
3
+ import { sendSuccess } from '../utils/apiResponse.js';
4
+
5
+ export const healthRouter = Router();
6
+
7
+ healthRouter.get('/', async (_req, res) => {
8
+ if (await isDatabaseConnected()) {
9
+ return sendSuccess(res, { message: 'OK', data: { status: 'ok', database: 'up' } });
10
+ }
11
+ // Built here rather than in errorHandler: a degraded health check still reports its data.
12
+ return res.status(503).json({
13
+ success: false,
14
+ message: 'Service unavailable',
15
+ data: { status: 'degraded', database: 'down' },
16
+ });
17
+ });
@@ -0,0 +1,13 @@
1
+ import { Router } from 'express';
2
+ import { authRouter } from '../modules/auth/auth.routes.js';
3
+ import { userRouter } from '../modules/user/user.routes.js';
4
+
5
+ export const apiRouter = Router();
6
+
7
+ // One list drives both the mounting and the docs coverage test.
8
+ export const API_MOUNTS = [
9
+ { path: '/auth', router: authRouter },
10
+ { path: '/users', router: userRouter },
11
+ ];
12
+
13
+ for (const { path, router } of API_MOUNTS) apiRouter.use(path, router);
@@ -0,0 +1,50 @@
1
+ import { env } from './config/env.js';
2
+ import { logger } from './config/logger.js';
3
+ import { connectDatabase, disconnectDatabase } from './database/connection.js';
4
+ import { createApp } from './app.js';
5
+
6
+ const FORCE_EXIT_MS = 10_000;
7
+
8
+ let server;
9
+ try {
10
+ await connectDatabase();
11
+ server = createApp().listen(env.PORT, (err) => {
12
+ // Express 5 also calls this on a listen error, which the handler below reports.
13
+ if (!err) logger.info(`Server listening on port ${env.PORT} (${env.NODE_ENV})`);
14
+ });
15
+ // For example the port is already in use.
16
+ server.on('error', (err) => {
17
+ logger.fatal({ err }, 'Server error');
18
+ process.exit(1);
19
+ });
20
+ } catch (err) {
21
+ logger.fatal({ err }, 'Failed to start');
22
+ process.exit(1);
23
+ }
24
+
25
+ let shuttingDown = false;
26
+
27
+ function shutdown(signal) {
28
+ if (shuttingDown) return;
29
+ shuttingDown = true;
30
+ logger.info(`${signal} received, shutting down`);
31
+
32
+ // Do not wait forever for open connections.
33
+ setTimeout(() => {
34
+ logger.error('Shutdown timed out, forcing exit');
35
+ process.exit(1);
36
+ }, FORCE_EXIT_MS).unref();
37
+
38
+ server.close(async () => {
39
+ await disconnectDatabase();
40
+ process.exit(0);
41
+ });
42
+ server.closeIdleConnections?.();
43
+ }
44
+
45
+ process.on('SIGINT', () => shutdown('SIGINT'));
46
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
47
+ process.on('unhandledRejection', (reason) => {
48
+ logger.error({ err: reason }, 'Unhandled rejection');
49
+ process.exit(1);
50
+ });
@@ -0,0 +1,32 @@
1
+ export class ApiError extends Error {
2
+ constructor(statusCode, message, errors) {
3
+ super(message);
4
+ this.name = 'ApiError';
5
+ this.statusCode = statusCode;
6
+ if (errors !== undefined) this.errors = errors;
7
+ }
8
+
9
+ static badRequest(message, errors) {
10
+ return new ApiError(400, message, errors);
11
+ }
12
+
13
+ static unauthorized(message = 'Unauthorized') {
14
+ return new ApiError(401, message);
15
+ }
16
+
17
+ static forbidden(message = 'Forbidden') {
18
+ return new ApiError(403, message);
19
+ }
20
+
21
+ static notFound(message = 'Resource not found') {
22
+ return new ApiError(404, message);
23
+ }
24
+
25
+ static conflict(message) {
26
+ return new ApiError(409, message);
27
+ }
28
+
29
+ static tooManyRequests(message) {
30
+ return new ApiError(429, message);
31
+ }
32
+ }
@@ -0,0 +1,8 @@
1
+ export function sendSuccess(
2
+ res,
3
+ { statusCode = 200, message = 'Success', data = null, meta } = {},
4
+ ) {
5
+ const body = { success: true, message, data };
6
+ if (meta !== undefined) body.meta = meta;
7
+ return res.status(statusCode).json(body);
8
+ }
@@ -0,0 +1,14 @@
1
+ import argon2 from 'argon2';
2
+
3
+ export function hashPassword(plain) {
4
+ return argon2.hash(plain, { type: argon2.argon2id });
5
+ }
6
+
7
+ export async function verifyPassword(hash, plain) {
8
+ try {
9
+ return await argon2.verify(hash, plain);
10
+ } catch {
11
+ // A malformed hash is just "no match", never an error.
12
+ return false;
13
+ }
14
+ }
@@ -0,0 +1,46 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import jwt from 'jsonwebtoken';
3
+ import { env } from '../config/env.js';
4
+ import { ApiError } from './ApiError.js';
5
+
6
+ const TOKEN_TYPES = Object.freeze({ ACCESS: 'access', REFRESH: 'refresh' });
7
+
8
+ export function signAccessToken({ userId, role }) {
9
+ return jwt.sign({ sub: userId, role, type: TOKEN_TYPES.ACCESS }, env.JWT_ACCESS_SECRET, {
10
+ expiresIn: env.JWT_ACCESS_EXPIRES_IN,
11
+ });
12
+ }
13
+
14
+ export function signRefreshToken({ userId }) {
15
+ const token = jwt.sign(
16
+ { sub: userId, type: TOKEN_TYPES.REFRESH, jti: randomUUID() },
17
+ env.JWT_REFRESH_SECRET,
18
+ { expiresIn: env.JWT_REFRESH_EXPIRES_IN },
19
+ );
20
+ const { exp } = jwt.decode(token);
21
+ return { token, expiresAt: new Date(exp * 1000) };
22
+ }
23
+
24
+ function verify(token, secret, type) {
25
+ try {
26
+ const payload = jwt.verify(token, secret, { algorithms: ['HS256'] });
27
+ if (payload.type !== type) throw new Error('wrong token type');
28
+ return payload;
29
+ } catch {
30
+ throw ApiError.unauthorized('Invalid or expired token');
31
+ }
32
+ }
33
+
34
+ export function verifyAccessToken(token) {
35
+ const payload = verify(token, env.JWT_ACCESS_SECRET, TOKEN_TYPES.ACCESS);
36
+ return { userId: payload.sub, role: payload.role };
37
+ }
38
+
39
+ export function verifyRefreshToken(token) {
40
+ const payload = verify(token, env.JWT_REFRESH_SECRET, TOKEN_TYPES.REFRESH);
41
+ return { userId: payload.sub };
42
+ }
43
+
44
+ export function hashToken(token) {
45
+ return createHash('sha256').update(token).digest('hex');
46
+ }
@@ -0,0 +1,5 @@
1
+ import { z } from 'zod';
2
+
3
+ // A request part (body, params or query) that must be empty. A missing part
4
+ // becomes `{}`, and any extra key is rejected.
5
+ export const emptyObject = () => z.strictObject({}).optional().default({});
@@ -0,0 +1,67 @@
1
+ import request from 'supertest';
2
+ import { describe, expect, it } from 'vitest';
3
+ import { createApp } from '../src/app.js';
4
+ import { isDatabaseConnected } from '../src/database/connection.js';
5
+
6
+ const app = createApp();
7
+
8
+ describe('base app', () => {
9
+ it('GET /health returns ok', async () => {
10
+ const res = await request(app).get('/health');
11
+ expect(res.status).toBe(200);
12
+ expect(res.body.success).toBe(true);
13
+ expect(res.body.data.status).toBe('ok');
14
+ expect(res.body.data.database).toBe('up');
15
+ });
16
+
17
+ it('checks the database live', async () => {
18
+ const check = isDatabaseConnected();
19
+ expect(check).toBeInstanceOf(Promise);
20
+ expect(await check).toBe(true);
21
+ });
22
+
23
+ it('returns a JSON 404 for unknown routes', async () => {
24
+ const res = await request(app).get('/api/v1/nope');
25
+ expect(res.status).toBe(404);
26
+ expect(res.body).toEqual({ success: false, message: 'Route not found' });
27
+ });
28
+
29
+ it('returns 400 for malformed JSON', async () => {
30
+ const res = await request(app)
31
+ .post('/api/v1/anything')
32
+ .set('Content-Type', 'application/json')
33
+ .send('{bad');
34
+ expect(res.status).toBe(400);
35
+ expect(res.headers['content-type']).toMatch(/json/);
36
+ expect(res.body).toEqual({ success: false, message: 'Invalid JSON body' });
37
+ });
38
+
39
+ it('returns 415 JSON for an unsupported charset', async () => {
40
+ const res = await request(app)
41
+ .post('/api/v1/anything')
42
+ .set('Content-Type', 'application/json; charset=iso-8859-1')
43
+ .send('{}');
44
+ expect(res.status).toBe(415);
45
+ expect(res.headers['content-type']).toMatch(/json/);
46
+ expect(res.body.success).toBe(false);
47
+ });
48
+
49
+ it('returns 413 for bodies over 10kb', async () => {
50
+ const res = await request(app)
51
+ .post('/api/v1/anything')
52
+ .send({ blob: 'x'.repeat(11 * 1024) });
53
+ expect(res.status).toBe(413);
54
+ expect(res.headers['content-type']).toMatch(/json/);
55
+ expect(res.body).toEqual({ success: false, message: 'Request body too large' });
56
+ });
57
+
58
+ it('does not trust proxy headers unless TRUST_PROXY is set', () => {
59
+ expect(app.get('trust proxy')).toBe(false);
60
+ });
61
+
62
+ it('sets x-request-id and hides x-powered-by', async () => {
63
+ const res = await request(app).get('/health');
64
+ expect(res.headers['x-request-id']).toBeTruthy();
65
+ expect(res.headers['x-powered-by']).toBeUndefined();
66
+ });
67
+ });