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,85 @@
1
+ import { z } from 'zod';
2
+ import { EXAMPLE_SECRET_PREFIX } from '../constants/examples.js';
3
+ import { databaseEnvSchema } from '../database/env.schema.js';
4
+
5
+ const LOG_LEVELS = ['fatal', 'error', 'warn', 'info', 'debug', 'trace', 'silent'];
6
+ // jsonwebtoken (ms) time spans such as 900, 15m or 7d.
7
+ const TIME_SPAN = /^\d+(ms|s|m|h|d|w|y)?$/;
8
+ const timeSpan = (fallback) =>
9
+ z
10
+ .string()
11
+ .regex(TIME_SPAN, 'must be a number with an optional unit (ms, s, m, h, d, w, y), e.g. 15m')
12
+ .default(fallback);
13
+
14
+ // Express "trust proxy": true/false, a hop count, or names/CIDRs such as "loopback" or "10.0.0.0/8".
15
+ // An empty `TRUST_PROXY=` counts as unset.
16
+ const trustProxy = z.preprocess(
17
+ (value) => (typeof value === 'string' && value.trim() === '' ? undefined : value),
18
+ z
19
+ .string()
20
+ .trim()
21
+ .transform((value) => {
22
+ if (value === 'true') return true;
23
+ if (value === 'false') return false;
24
+ if (/^\d+$/.test(value)) return Number(value);
25
+ return value;
26
+ })
27
+ .optional(),
28
+ );
29
+
30
+ const baseEnvSchema = z.object({
31
+ NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
32
+ PORT: z.coerce.number().int().positive().default(3000),
33
+ LOG_LEVEL: z.enum(LOG_LEVELS).default('info'),
34
+ CORS_ORIGIN: z
35
+ .string()
36
+ .default('http://localhost:5173')
37
+ .transform((value) =>
38
+ value
39
+ .split(',')
40
+ .map((origin) => origin.trim())
41
+ .filter(Boolean),
42
+ ),
43
+ TRUST_PROXY: trustProxy,
44
+ JWT_ACCESS_SECRET: z.string().min(32),
45
+ JWT_REFRESH_SECRET: z.string().min(32),
46
+ JWT_ACCESS_EXPIRES_IN: timeSpan('15m'),
47
+ JWT_REFRESH_EXPIRES_IN: timeSpan('7d'),
48
+ AUTH_RATE_LIMIT_MAX: z.coerce.number().int().positive().default(10),
49
+ API_DOCS_ENABLED: z.enum(['true', 'false']).optional(),
50
+ ADMIN_NAME: z.string().optional(),
51
+ ADMIN_EMAIL: z.string().optional(),
52
+ ADMIN_PASSWORD: z.string().optional(),
53
+ });
54
+
55
+ function checkSecrets(value, ctx) {
56
+ if (value.NODE_ENV === 'production') {
57
+ for (const key of ['JWT_ACCESS_SECRET', 'JWT_REFRESH_SECRET']) {
58
+ if (value[key].trim().toLowerCase().startsWith(EXAMPLE_SECRET_PREFIX)) {
59
+ ctx.addIssue({
60
+ code: 'custom',
61
+ path: [key],
62
+ message: `${key} still has the example value; set a real secret (e.g. \`openssl rand -base64 48\`)`,
63
+ });
64
+ }
65
+ }
66
+ }
67
+ if (value.JWT_ACCESS_SECRET === value.JWT_REFRESH_SECRET) {
68
+ ctx.addIssue({
69
+ code: 'custom',
70
+ path: ['JWT_REFRESH_SECRET'],
71
+ message: 'JWT_REFRESH_SECRET must differ from JWT_ACCESS_SECRET',
72
+ });
73
+ }
74
+ }
75
+
76
+ export const envSchema = baseEnvSchema
77
+ .extend(databaseEnvSchema.shape)
78
+ .superRefine(checkSecrets)
79
+ .transform((value) => ({
80
+ ...value,
81
+ // Docs are on by default, except in production.
82
+ API_DOCS_ENABLED: value.API_DOCS_ENABLED
83
+ ? value.API_DOCS_ENABLED === 'true'
84
+ : value.NODE_ENV !== 'production',
85
+ }));
@@ -0,0 +1,20 @@
1
+ import pino from 'pino';
2
+ import { env } from './env.js';
3
+
4
+ export const logger = pino({
5
+ level: env.NODE_ENV === 'test' ? 'silent' : env.LOG_LEVEL,
6
+ redact: {
7
+ paths: [
8
+ 'req.headers.authorization',
9
+ 'req.headers.cookie',
10
+ 'res.headers["set-cookie"]',
11
+ '*.password',
12
+ '*.token',
13
+ '*.refreshToken',
14
+ ],
15
+ censor: '[REDACTED]',
16
+ },
17
+ ...(env.NODE_ENV === 'development' && {
18
+ transport: { target: 'pino-pretty', options: { colorize: true } },
19
+ }),
20
+ });
@@ -0,0 +1,3 @@
1
+ // Values shipped in .env.example. They are fine for local development, never for real use.
2
+ export const EXAMPLE_SECRET_PREFIX = 'change-me';
3
+ export const EXAMPLE_ADMIN_PASSWORD = 'ChangeMe123!';
@@ -0,0 +1,2 @@
1
+ export const ROLES = Object.freeze({ USER: 'user', ADMIN: 'admin' });
2
+ export const ROLE_VALUES = Object.values(ROLES);
@@ -0,0 +1,16 @@
1
+ // Every field limit lives here. Zod schemas and the database models import it.
2
+ export const USER_RULES = Object.freeze({
3
+ NAME: Object.freeze({ MIN: 2, MAX: 50 }),
4
+ EMAIL: Object.freeze({ MAX: 254 }),
5
+ PASSWORD: Object.freeze({
6
+ MIN: 8,
7
+ MAX: 128,
8
+ PATTERN: /(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/,
9
+ }),
10
+ });
11
+
12
+ export const PAGINATION = Object.freeze({
13
+ DEFAULT_PAGE: 1,
14
+ DEFAULT_LIMIT: 20,
15
+ MAX_LIMIT: 100,
16
+ });
@@ -0,0 +1,26 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { OpenApiGeneratorV31 } from '@asteasolutions/zod-to-openapi';
3
+ import { registerAuthPaths } from './paths/auth.paths.js';
4
+ import { registerUserPaths } from './paths/user.paths.js';
5
+ import { registry } from './openapi.registry.js';
6
+
7
+ let cached;
8
+
9
+ export function buildOpenApiDocument() {
10
+ if (cached) return cached;
11
+
12
+ const pkg = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
13
+ registerAuthPaths(registry);
14
+ registerUserPaths(registry);
15
+
16
+ cached = new OpenApiGeneratorV31(registry.definitions).generateDocument({
17
+ openapi: '3.1.0',
18
+ info: {
19
+ title: pkg.name,
20
+ version: pkg.version,
21
+ ...(pkg.description && { description: pkg.description }),
22
+ },
23
+ servers: [{ url: '/api/v1' }],
24
+ });
25
+ return cached;
26
+ }
@@ -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);