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,90 @@
1
+ import { extendZodWithOpenApi, OpenAPIRegistry } from '@asteasolutions/zod-to-openapi';
2
+ import { z } from 'zod';
3
+ import { ROLE_VALUES } from '../constants/roles.ts';
4
+ import { USER_RULES } from '../constants/user.rules.ts';
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 type PublicUser = Omit<z.output<typeof PublicUser>, 'createdAt' | 'updatedAt'> & {
24
+ // The schema describes the JSON response, where dates are ISO strings. In code they are Dates.
25
+ createdAt: Date;
26
+ updatedAt: Date;
27
+ };
28
+
29
+ export const ErrorResponse = registry.register(
30
+ 'ErrorResponse',
31
+ z.object({ success: z.literal(false), message: z.string() }),
32
+ );
33
+
34
+ export const ValidationErrorResponse = registry.register(
35
+ 'ValidationErrorResponse',
36
+ z.object({
37
+ success: z.literal(false),
38
+ message: z.string(),
39
+ errors: z.array(z.object({ field: z.string(), message: z.string() })),
40
+ }),
41
+ );
42
+
43
+ const PaginationMeta = registry.register(
44
+ 'PaginationMeta',
45
+ z.object({
46
+ page: z.number().int(),
47
+ limit: z.number().int(),
48
+ total: z.number().int(),
49
+ totalPages: z.number().int(),
50
+ }),
51
+ );
52
+
53
+ registry.registerComponent('securitySchemes', 'bearerAuth', {
54
+ type: 'http',
55
+ scheme: 'bearer',
56
+ bearerFormat: 'JWT',
57
+ });
58
+
59
+ registry.registerComponent('securitySchemes', 'refreshCookie', {
60
+ type: 'apiKey',
61
+ in: 'cookie',
62
+ name: 'refreshToken',
63
+ });
64
+
65
+ // The only place the success envelope `{ success, message, data, meta? }` is described.
66
+ export function successResponse(
67
+ dataSchema?: z.ZodType,
68
+ { withMeta = false }: { withMeta?: boolean } = {},
69
+ ) {
70
+ const shape: Record<string, z.ZodType> = {
71
+ success: z.literal(true),
72
+ message: z.string(),
73
+ data: dataSchema ?? z.null(),
74
+ };
75
+ if (withMeta) shape.meta = PaginationMeta;
76
+ return z.object(shape);
77
+ }
78
+
79
+ export function jsonContent(schema: z.ZodType) {
80
+ return { 'application/json': { schema } };
81
+ }
82
+
83
+ export function errorResponse(description: string, schema: z.ZodType = ErrorResponse) {
84
+ return { description, content: jsonContent(schema) };
85
+ }
86
+
87
+ // The validation email field is `trim().toLowerCase().pipe(z.email())`, which
88
+ // zod-to-openapi cannot describe. This replaces only that field; the limit still
89
+ // comes from USER_RULES.
90
+ export const emailDocSchema = z.email().max(USER_RULES.EMAIL.MAX);
@@ -0,0 +1,36 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { OpenApiGeneratorV31 } from '@asteasolutions/zod-to-openapi';
3
+ import { registerAuthPaths } from './paths/auth.paths.ts';
4
+ import { registerUserPaths } from './paths/user.paths.ts';
5
+ import { registry } from './openapi.registry.ts';
6
+
7
+ type OpenApiDocument = ReturnType<OpenApiGeneratorV31['generateDocument']>;
8
+
9
+ interface PackageInfo {
10
+ name: string;
11
+ version: string;
12
+ description?: string;
13
+ }
14
+
15
+ let cached: OpenApiDocument | undefined;
16
+
17
+ export function buildOpenApiDocument() {
18
+ if (cached) return cached;
19
+
20
+ const pkg: PackageInfo = JSON.parse(
21
+ readFileSync(new URL('../../package.json', import.meta.url), 'utf8'),
22
+ );
23
+ registerAuthPaths(registry);
24
+ registerUserPaths(registry);
25
+
26
+ cached = new OpenApiGeneratorV31(registry.definitions).generateDocument({
27
+ openapi: '3.1.0',
28
+ info: {
29
+ title: pkg.name,
30
+ version: pkg.version,
31
+ ...(pkg.description && { description: pkg.description }),
32
+ },
33
+ servers: [{ url: '/api/v1' }],
34
+ });
35
+ return cached;
36
+ }
@@ -0,0 +1,88 @@
1
+ import { z } from 'zod';
2
+ import { loginSchema, registerSchema } from '../../modules/auth/auth.validation.ts';
3
+ import {
4
+ emailDocSchema,
5
+ errorResponse,
6
+ jsonContent,
7
+ PublicUser,
8
+ successResponse,
9
+ ValidationErrorResponse,
10
+ } from '../openapi.registry.ts';
11
+ import type { OpenAPIRegistry } from '@asteasolutions/zod-to-openapi';
12
+
13
+ const TAG = ['Auth'];
14
+ const registerBody = registerSchema.shape.body.extend({ email: emailDocSchema });
15
+ const loginBody = loginSchema.shape.body.extend({ email: emailDocSchema });
16
+ const sessionData = z.object({ user: PublicUser, accessToken: z.string() });
17
+
18
+ export function registerAuthPaths(registry: OpenAPIRegistry) {
19
+ registry.registerPath({
20
+ method: 'post',
21
+ path: '/auth/register',
22
+ tags: TAG,
23
+ summary: 'Register',
24
+ description: 'Creates a user with role `user`. Rate limited.',
25
+ request: { body: { required: true, content: jsonContent(registerBody) } },
26
+ responses: {
27
+ 201: {
28
+ description: 'User registered',
29
+ content: jsonContent(successResponse(z.object({ user: PublicUser }))),
30
+ },
31
+ 400: errorResponse('Validation error', ValidationErrorResponse),
32
+ 409: errorResponse('Email already registered'),
33
+ 429: errorResponse('Too many requests'),
34
+ },
35
+ });
36
+
37
+ registry.registerPath({
38
+ method: 'post',
39
+ path: '/auth/login',
40
+ tags: TAG,
41
+ summary: 'Log in',
42
+ description:
43
+ 'Returns the access token. The refresh token is set as an httpOnly cookie. Rate limited.',
44
+ request: { body: { required: true, content: jsonContent(loginBody) } },
45
+ responses: {
46
+ 200: {
47
+ description: 'Logged in. Sets the `refreshToken` cookie.',
48
+ headers: { 'Set-Cookie': { schema: { type: 'string' } } },
49
+ content: jsonContent(successResponse(sessionData)),
50
+ },
51
+ 400: errorResponse('Validation error', ValidationErrorResponse),
52
+ 401: errorResponse('Invalid email or password'),
53
+ 429: errorResponse('Too many requests'),
54
+ },
55
+ });
56
+
57
+ registry.registerPath({
58
+ method: 'post',
59
+ path: '/auth/refresh',
60
+ tags: TAG,
61
+ summary: 'Refresh the session',
62
+ description:
63
+ "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.",
64
+ responses: {
65
+ 200: {
66
+ description: 'Token refreshed. Sets a new `refreshToken` cookie.',
67
+ headers: { 'Set-Cookie': { schema: { type: 'string' } } },
68
+ content: jsonContent(successResponse(sessionData)),
69
+ },
70
+ 401: errorResponse('Missing, invalid or revoked refresh token'),
71
+ },
72
+ });
73
+
74
+ registry.registerPath({
75
+ method: 'post',
76
+ path: '/auth/logout',
77
+ tags: TAG,
78
+ summary: 'Log out',
79
+ description:
80
+ 'Revokes the refresh token and clears the cookie. Succeeds even if already logged out.',
81
+ responses: {
82
+ 200: {
83
+ description: 'Logged out',
84
+ content: jsonContent(successResponse()),
85
+ },
86
+ },
87
+ });
88
+ }
@@ -0,0 +1,88 @@
1
+ import { z } from 'zod';
2
+ import { listUsersSchema, userIdParamSchema } from '../../modules/user/user.validation.ts';
3
+ import {
4
+ errorResponse,
5
+ jsonContent,
6
+ PublicUser,
7
+ successResponse,
8
+ ValidationErrorResponse,
9
+ } from '../openapi.registry.ts';
10
+ import type { OpenAPIRegistry } from '@asteasolutions/zod-to-openapi';
11
+
12
+ const TAG = ['Users'];
13
+ const security = [{ bearerAuth: [] }];
14
+ const unauthorized = errorResponse('Missing or invalid access token');
15
+ const forbidden = errorResponse('Admin role required');
16
+
17
+ export function registerUserPaths(registry: OpenAPIRegistry) {
18
+ registry.registerPath({
19
+ method: 'get',
20
+ path: '/users/me',
21
+ tags: TAG,
22
+ summary: 'Get my profile',
23
+ security,
24
+ responses: {
25
+ 200: {
26
+ description: 'Your profile',
27
+ content: jsonContent(successResponse(z.object({ user: PublicUser }))),
28
+ },
29
+ 401: unauthorized,
30
+ },
31
+ });
32
+
33
+ registry.registerPath({
34
+ method: 'get',
35
+ path: '/users',
36
+ tags: TAG,
37
+ summary: 'List users (admin)',
38
+ security,
39
+ request: { query: listUsersSchema.shape.query },
40
+ responses: {
41
+ 200: {
42
+ description: 'A page of users',
43
+ content: jsonContent(
44
+ successResponse(z.object({ users: z.array(PublicUser) }), { withMeta: true }),
45
+ ),
46
+ },
47
+ 400: errorResponse('Validation error', ValidationErrorResponse),
48
+ 401: unauthorized,
49
+ 403: forbidden,
50
+ },
51
+ });
52
+
53
+ registry.registerPath({
54
+ method: 'get',
55
+ path: '/users/{id}',
56
+ tags: TAG,
57
+ summary: 'Get a user (admin)',
58
+ security,
59
+ request: { params: userIdParamSchema.shape.params },
60
+ responses: {
61
+ 200: {
62
+ description: 'The user',
63
+ content: jsonContent(successResponse(z.object({ user: PublicUser }))),
64
+ },
65
+ 400: errorResponse('Malformed id', ValidationErrorResponse),
66
+ 401: unauthorized,
67
+ 403: forbidden,
68
+ 404: errorResponse('User not found'),
69
+ },
70
+ });
71
+
72
+ registry.registerPath({
73
+ method: 'delete',
74
+ path: '/users/{id}',
75
+ tags: TAG,
76
+ summary: 'Delete a user (admin)',
77
+ description: "Also deletes the user's refresh tokens. An admin cannot delete themselves.",
78
+ security,
79
+ request: { params: userIdParamSchema.shape.params },
80
+ responses: {
81
+ 204: { description: 'Deleted' },
82
+ 400: errorResponse('Malformed id or self-delete', ValidationErrorResponse),
83
+ 401: unauthorized,
84
+ 403: forbidden,
85
+ 404: errorResponse('User not found'),
86
+ },
87
+ });
88
+ }
@@ -0,0 +1,20 @@
1
+ import * as userRepository from '../modules/user/user.repository.ts';
2
+ import { ApiError } from '../utils/ApiError.ts';
3
+ import { verifyAccessToken } from '../utils/token.ts';
4
+ import type { NextFunction, Request, Response } from 'express';
5
+
6
+ const BEARER_PATTERN = /^Bearer (\S+)$/;
7
+
8
+ // Verifies the access token, then loads the user so a deleted user or a changed
9
+ // role takes effect at once. The role comes from the database, not the token.
10
+ export async function authenticate(req: Request, _res: Response, next: NextFunction) {
11
+ const match = BEARER_PATTERN.exec(req.headers.authorization ?? '');
12
+ if (!match) throw ApiError.unauthorized('Authentication required');
13
+
14
+ const { userId } = verifyAccessToken(match[1]);
15
+ const user = await userRepository.findById(userId);
16
+ if (!user) throw ApiError.unauthorized('Invalid or expired token');
17
+
18
+ req.user = user;
19
+ next();
20
+ }
@@ -0,0 +1,13 @@
1
+ import { ApiError } from '../utils/ApiError.ts';
2
+ import type { NextFunction, Request, Response } from 'express';
3
+ import type { Role } from '../constants/roles.ts';
4
+
5
+ // Must run after `authenticate`, which sets req.user.
6
+ export function authorize(...allowedRoles: Role[]) {
7
+ return (req: Request, _res: Response, next: NextFunction) => {
8
+ if (!(allowedRoles as (Role | undefined)[]).includes(req.user?.role)) {
9
+ throw ApiError.forbidden('You do not have permission to perform this action');
10
+ }
11
+ next();
12
+ };
13
+ }
@@ -0,0 +1,52 @@
1
+ import { env } from '../config/env.ts';
2
+ import { mapDatabaseError } from '../database/connection.ts';
3
+ import { ApiError } from '../utils/ApiError.ts';
4
+ import type { NextFunction, Request, Response } from 'express';
5
+
6
+ interface ThrownError extends Partial<Error> {
7
+ // Anything can be thrown. These are the optional fields read from it, such as the
8
+ // `type`, `status` and `expose` that http-errors (used by body-parser) adds.
9
+ type?: string;
10
+ status?: number;
11
+ statusCode?: number;
12
+ expose?: boolean;
13
+ }
14
+
15
+ interface ErrorBody {
16
+ success: false;
17
+ message: string;
18
+ errors?: unknown;
19
+ stack?: string;
20
+ }
21
+
22
+ // Errors raised by body-parser carry a `type` and a 4xx status.
23
+ function fromBodyParser(err: ThrownError) {
24
+ if (err.type === 'entity.parse.failed') return ApiError.badRequest('Invalid JSON body');
25
+ if (err.type === 'entity.too.large') return new ApiError(413, 'Request body too large');
26
+ // Other http-errors from middleware (e.g. 415 for an unsupported charset) are
27
+ // marked `expose` when their message is safe to show.
28
+ const status = (err.status ?? err.statusCode) as number;
29
+ if (Number.isInteger(status) && status >= 400 && status < 500 && err.expose === true) {
30
+ return new ApiError(status, err.message as string);
31
+ }
32
+ return null;
33
+ }
34
+
35
+ function toApiError(err: ThrownError) {
36
+ if (err instanceof ApiError) return err;
37
+ return mapDatabaseError(err) ?? fromBodyParser(err);
38
+ }
39
+
40
+ export function errorHandler(err: ThrownError, req: Request, res: Response, _next: NextFunction) {
41
+ const known = toApiError(err);
42
+ const statusCode = known?.statusCode ?? 500;
43
+ const message = known?.message ?? 'Internal server error';
44
+
45
+ if (statusCode >= 500) req.log.error({ err }, message);
46
+ else req.log.warn({ err }, message);
47
+
48
+ const body: ErrorBody = { success: false, message };
49
+ if (known?.errors !== undefined) body.errors = known.errors;
50
+ if (env.NODE_ENV === 'development' && err.stack) body.stack = err.stack;
51
+ res.status(statusCode).json(body);
52
+ }
@@ -0,0 +1,6 @@
1
+ import { ApiError } from '../utils/ApiError.ts';
2
+ import type { NextFunction, Request, Response } from 'express';
3
+
4
+ export function notFound(_req: Request, _res: Response, next: NextFunction) {
5
+ next(ApiError.notFound('Route not found'));
6
+ }
@@ -0,0 +1,20 @@
1
+ import { rateLimit } from 'express-rate-limit';
2
+ import { env } from '../config/env.ts';
3
+ import { ApiError } from '../utils/ApiError.ts';
4
+
5
+ export function createRateLimiter({ windowMs, max }: { windowMs: number; max: number }) {
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,39 @@
1
+ import { ApiError } from '../utils/ApiError.ts';
2
+ import type { NextFunction, Request, Response } from 'express';
3
+ import type { z } from 'zod';
4
+
5
+ export type ValidatedRequest<T> = Request & {
6
+ // What a handler after validate(schema) receives. Express's types cannot know that
7
+ // validate ran, so `validated` stays optional, but it is always set by then.
8
+ validated?: T;
9
+ };
10
+
11
+ function toFieldErrors(issues: z.core.$ZodIssue[]) {
12
+ return issues.flatMap((issue) => {
13
+ if (issue.code === 'unrecognized_keys') {
14
+ const prefix = issue.path.slice(1).join('.');
15
+ return issue.keys.map((key) => ({
16
+ field: prefix ? `${prefix}.${key}` : key,
17
+ message: `Unrecognized field "${key}"`,
18
+ }));
19
+ }
20
+ return [{ field: issue.path.slice(1).join('.'), message: issue.message }];
21
+ });
22
+ }
23
+
24
+ // Validates { body, params, query } against a schema. Parsed values go to
25
+ // req.validated, because Express 5 makes req.query read-only.
26
+ export function validate(schema: z.ZodType) {
27
+ return (req: ValidatedRequest<unknown>, _res: Response, next: NextFunction) => {
28
+ const result = schema.safeParse({
29
+ body: req.body ?? {},
30
+ params: req.params,
31
+ query: req.query,
32
+ });
33
+ if (!result.success) {
34
+ return next(ApiError.badRequest('Validation failed', toFieldErrors(result.error.issues)));
35
+ }
36
+ req.validated = result.data;
37
+ return next();
38
+ };
39
+ }
@@ -0,0 +1,45 @@
1
+ import { sendSuccess } from '../../utils/apiResponse.ts';
2
+ import { ApiError } from '../../utils/ApiError.ts';
3
+ import { clearRefreshCookie, REFRESH_COOKIE_NAME, setRefreshCookie } from './auth.cookie.ts';
4
+ import * as authService from './auth.service.ts';
5
+ import type { Request, Response } from 'express';
6
+ import type { ValidatedRequest } from '../../middlewares/validate.ts';
7
+ import type { LoginInput, RegisterInput } from './auth.validation.ts';
8
+
9
+ type Session = Awaited<ReturnType<typeof authService.loginUser>>;
10
+
11
+ // The refresh token travels only in the cookie, never in the body.
12
+ function sendSession(res: Response, message: string, session: Session) {
13
+ setRefreshCookie(res, session.refreshToken, session.refreshExpiresAt);
14
+ return sendSuccess(res, {
15
+ message,
16
+ data: { user: session.user, accessToken: session.accessToken },
17
+ });
18
+ }
19
+
20
+ export async function register(req: ValidatedRequest<RegisterInput>, res: Response) {
21
+ const user = await authService.registerUser(req.validated!.body);
22
+ return sendSuccess(res, {
23
+ statusCode: 201,
24
+ message: 'User registered successfully',
25
+ data: { user },
26
+ });
27
+ }
28
+
29
+ export async function login(req: ValidatedRequest<LoginInput>, res: Response) {
30
+ const session = await authService.loginUser(req.validated!.body);
31
+ return sendSession(res, 'Logged in successfully', session);
32
+ }
33
+
34
+ export async function refresh(req: Request, res: Response) {
35
+ const token = req.cookies?.[REFRESH_COOKIE_NAME];
36
+ if (!token) throw ApiError.unauthorized('Refresh token required');
37
+ const session = await authService.refreshSession(token);
38
+ return sendSession(res, 'Token refreshed', session);
39
+ }
40
+
41
+ export async function logout(req: Request, res: Response) {
42
+ await authService.logoutUser(req.cookies?.[REFRESH_COOKIE_NAME]);
43
+ clearRefreshCookie(res);
44
+ return sendSuccess(res, { message: 'Logged out successfully' });
45
+ }
@@ -0,0 +1,22 @@
1
+ import { env } from '../../config/env.ts';
2
+ import type { CookieOptions, Response } from 'express';
3
+
4
+ export const REFRESH_COOKIE_NAME = 'refreshToken';
5
+
6
+ // One place for the cookie options, so set and clear always match.
7
+ function baseCookieOptions(): CookieOptions {
8
+ return {
9
+ httpOnly: true,
10
+ secure: env.NODE_ENV === 'production',
11
+ sameSite: 'strict',
12
+ path: '/api/v1/auth',
13
+ };
14
+ }
15
+
16
+ export function setRefreshCookie(res: Response, token: string, expiresAt: Date) {
17
+ res.cookie(REFRESH_COOKIE_NAME, token, { ...baseCookieOptions(), expires: expiresAt });
18
+ }
19
+
20
+ export function clearRefreshCookie(res: Response) {
21
+ res.clearCookie(REFRESH_COOKIE_NAME, baseCookieOptions());
22
+ }
@@ -0,0 +1,12 @@
1
+ import { Router } from 'express';
2
+ import { authRateLimiter } from '../../middlewares/rateLimiter.ts';
3
+ import { validate } from '../../middlewares/validate.ts';
4
+ import * as authController from './auth.controller.ts';
5
+ import { loginSchema, registerSchema } from './auth.validation.ts';
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,81 @@
1
+ import * as userRepository from '../user/user.repository.ts';
2
+ import { ApiError } from '../../utils/ApiError.ts';
3
+ import { hashPassword, verifyPassword } from '../../utils/password.ts';
4
+ import {
5
+ hashToken,
6
+ signAccessToken,
7
+ signRefreshToken,
8
+ verifyRefreshToken,
9
+ } from '../../utils/token.ts';
10
+ import type { PublicUser } from '../../docs/openapi.registry.ts';
11
+ import type { LoginInput, RegisterInput } from './auth.validation.ts';
12
+
13
+ // Hashed once, on first use. Verifying against it when the user is unknown keeps
14
+ // login timing close to the wrong-password case.
15
+ let dummyHashPromise: Promise<string> | undefined;
16
+ const getDummyHash = () => (dummyHashPromise ??= hashPassword('dummy-password-for-timing'));
17
+
18
+ async function issueTokens(user: PublicUser) {
19
+ const accessToken = signAccessToken({ userId: user.id, role: user.role });
20
+ const { token: refreshToken, expiresAt: refreshExpiresAt } = signRefreshToken({
21
+ userId: user.id,
22
+ });
23
+ await userRepository.saveRefreshToken({
24
+ userId: user.id,
25
+ tokenHash: hashToken(refreshToken),
26
+ expiresAt: refreshExpiresAt,
27
+ });
28
+ return { user, accessToken, refreshToken, refreshExpiresAt };
29
+ }
30
+
31
+ export async function registerUser({ name, email, password }: RegisterInput['body']) {
32
+ if (await userRepository.findByEmail(email)) {
33
+ throw ApiError.conflict('Email is already registered');
34
+ }
35
+ // The unique index still catches a race between two registrations.
36
+ return userRepository.create({ name, email, password: await hashPassword(password) });
37
+ }
38
+
39
+ export async function loginUser({ email, password }: LoginInput['body']) {
40
+ const found = await userRepository.findByEmail(email, { withPassword: true });
41
+ const passwordOk = await verifyPassword(found?.password ?? (await getDummyHash()), password);
42
+ if (!found || !passwordOk) throw ApiError.unauthorized('Invalid email or password');
43
+
44
+ const { password: _password, ...user } = found;
45
+ return issueTokens(user);
46
+ }
47
+
48
+ export async function refreshSession(refreshToken: string) {
49
+ const { userId } = verifyRefreshToken(refreshToken);
50
+ const tokenHash = hashToken(refreshToken);
51
+ const stored = await userRepository.findRefreshToken(tokenHash);
52
+ if (!stored) throw ApiError.unauthorized('Invalid or expired token');
53
+
54
+ if (stored.revokedAt) {
55
+ // A revoked token being used again means it was probably stolen.
56
+ await userRepository.revokeAllRefreshTokens(userId);
57
+ throw ApiError.unauthorized('Invalid or expired token');
58
+ }
59
+ if (stored.expiresAt <= new Date()) throw ApiError.unauthorized('Invalid or expired token');
60
+
61
+ const user = await userRepository.findById(userId);
62
+ if (!user) throw ApiError.unauthorized('Invalid or expired token');
63
+
64
+ // Only one of two concurrent refreshes can flip the token to revoked. The loser
65
+ // is treated like a reuse of a rotated token.
66
+ if (!(await userRepository.revokeRefreshToken(tokenHash))) {
67
+ await userRepository.revokeAllRefreshTokens(userId);
68
+ throw ApiError.unauthorized('Invalid or expired token');
69
+ }
70
+ return issueTokens(user);
71
+ }
72
+
73
+ export async function logoutUser(refreshToken: string | undefined) {
74
+ if (!refreshToken) return;
75
+ try {
76
+ verifyRefreshToken(refreshToken);
77
+ await userRepository.revokeRefreshToken(hashToken(refreshToken));
78
+ } catch {
79
+ // Logout always succeeds, even with a bad or already revoked token.
80
+ }
81
+ }
@@ -0,0 +1,44 @@
1
+ import { z } from 'zod';
2
+ import { USER_RULES } from '../../constants/user.rules.ts';
3
+ import { emptyObject } from '../../utils/zod.ts';
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
+ });
42
+
43
+ export type RegisterInput = z.output<typeof registerSchema>;
44
+ export type LoginInput = z.output<typeof loginSchema>;