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,61 @@
1
+ import cookieParser from 'cookie-parser';
2
+ import express from 'express';
3
+ import { pinoHttp } from 'pino-http';
4
+ import request from 'supertest';
5
+ import { describe, expect, it } from 'vitest';
6
+ import { logger } from '../src/config/logger.ts';
7
+ import { authenticate } from '../src/middlewares/authenticate.ts';
8
+ import { errorHandler } from '../src/middlewares/errorHandler.ts';
9
+ import * as userRepository from '../src/modules/user/user.repository.ts';
10
+ import { sendSuccess } from '../src/utils/apiResponse.ts';
11
+ import { signAccessToken, signRefreshToken } from '../src/utils/token.ts';
12
+ import { createUser } from './helpers/auth.helper.ts';
13
+
14
+ const app = express();
15
+ app.use(pinoHttp({ logger }));
16
+ app.use(cookieParser());
17
+ app.get('/protected', authenticate, (req, res) => sendSuccess(res, { data: { user: req.user } }));
18
+ app.use(errorHandler);
19
+
20
+ const get = (authorization?: string) => {
21
+ const req = request(app).get('/protected');
22
+ return authorization ? req.set('Authorization', authorization) : req;
23
+ };
24
+
25
+ describe('authenticate', () => {
26
+ it('rejects a missing header', async () => {
27
+ const res = await get();
28
+ expect(res.status).toBe(401);
29
+ expect(res.body.message).toBe('Authentication required');
30
+ });
31
+
32
+ it('rejects a non-Bearer scheme', async () => {
33
+ const res = await get('Basic xyz');
34
+ expect(res.status).toBe(401);
35
+ expect(res.body.message).toBe('Authentication required');
36
+ });
37
+
38
+ it('rejects a refresh token used as Bearer', async () => {
39
+ const { user } = await createUser();
40
+ const { token } = signRefreshToken({ userId: user.id });
41
+ expect((await get(`Bearer ${token}`)).status).toBe(401);
42
+ });
43
+
44
+ it('rejects a token for a deleted user', async () => {
45
+ const { user } = await createUser();
46
+ const token = signAccessToken({ userId: user.id, role: user.role });
47
+ await userRepository.deleteById(user.id);
48
+ expect((await get(`Bearer ${token}`)).status).toBe(401);
49
+ });
50
+
51
+ it('accepts a valid token and takes the role from the database', async () => {
52
+ const { user } = await createUser();
53
+ const token = signAccessToken({ userId: user.id, role: user.role });
54
+ await userRepository.updateRole(user.id, 'admin');
55
+ const res = await get(`Bearer ${token}`);
56
+ expect(res.status).toBe(200);
57
+ expect(res.body.data.user.id).toBe(user.id);
58
+ expect(res.body.data.user.role).toBe('admin');
59
+ expect(res.body.data.user).not.toHaveProperty('password');
60
+ });
61
+ });
@@ -0,0 +1,127 @@
1
+ import request from 'supertest';
2
+ import { afterEach, describe, expect, it, vi } from 'vitest';
3
+ import { createApp } from '../src/app.ts';
4
+ import { USER_RULES } from '../src/constants/user.rules.ts';
5
+ import { buildOpenApiDocument } from '../src/docs/openapi.ts';
6
+ import { API_MOUNTS } from '../src/routes/index.ts';
7
+ import pkg from '../package.json' with { type: 'json' };
8
+
9
+ interface LooseDocument {
10
+ // The OpenAPI document, read loosely: the tests follow paths they know exist.
11
+ [key: string]: LooseDocument;
12
+ }
13
+
14
+ interface RouteLayer {
15
+ // Express's types do not list a route's `methods`.
16
+ route?: { path: string; methods: Record<string, boolean> };
17
+ }
18
+
19
+ const app = createApp();
20
+ const doc = buildOpenApiDocument() as unknown as LooseDocument;
21
+
22
+ // Collect `{ method, path }` for every route layer of every mounted router.
23
+ function collectRoutes() {
24
+ const routes: { method: string; path: string }[] = [];
25
+ for (const { path: mount, router } of API_MOUNTS) {
26
+ for (const layer of router.stack as unknown as RouteLayer[]) {
27
+ if (!layer.route) continue;
28
+ const sub = layer.route.path === '/' ? '' : layer.route.path.replace(/:(\w+)/g, '{$1}');
29
+ for (const method of Object.keys(layer.route.methods)) {
30
+ routes.push({ method, path: `${mount}${sub}` });
31
+ }
32
+ }
33
+ }
34
+ return routes;
35
+ }
36
+
37
+ describe('openapi document', () => {
38
+ it('GET /api-docs.json returns an OpenAPI 3.1 document', async () => {
39
+ const res = await request(app).get('/api-docs.json');
40
+ expect(res.status).toBe(200);
41
+ expect(res.body.openapi).toMatch(/^3\.1/);
42
+ expect(res.body.info.title).toBe(pkg.name);
43
+ expect(res.body.info.version).toBe(pkg.version);
44
+ expect('description' in res.body.info).toBe(
45
+ Boolean((pkg as { description?: string }).description),
46
+ );
47
+ expect(res.body.servers).toEqual([{ url: '/api/v1' }]);
48
+ });
49
+
50
+ it('documents every route mounted under /api/v1', () => {
51
+ const routes = collectRoutes();
52
+ const documented = Object.values(doc.paths).flatMap((item) => Object.keys(item));
53
+ expect(routes.length).toBe(documented.length);
54
+ for (const { method, path } of routes) {
55
+ expect(doc.paths[path]?.[method], `${method.toUpperCase()} ${path}`).toBeDefined();
56
+ }
57
+ });
58
+
59
+ it('builds request bodies from the shared rules', () => {
60
+ const schema = doc.paths['/auth/register'].post.requestBody.content['application/json'].schema;
61
+ const { password, email } = schema.properties;
62
+ expect(password.minLength).toBe(USER_RULES.PASSWORD.MIN);
63
+ expect(password.maxLength).toBe(USER_RULES.PASSWORD.MAX);
64
+ expect(email.maxLength).toBe(USER_RULES.EMAIL.MAX);
65
+ });
66
+
67
+ it('declares bearer auth on user routes only', () => {
68
+ const bearer = [{ bearerAuth: [] }];
69
+ expect(doc.paths['/users'].get.security).toEqual(bearer);
70
+ expect(doc.paths['/users/me'].get.security).toEqual(bearer);
71
+ expect(doc.paths['/users/{id}'].get.security).toEqual(bearer);
72
+ expect(doc.paths['/users/{id}'].delete.security).toEqual(bearer);
73
+ expect(doc.paths['/auth/register'].post.security).toBeUndefined();
74
+ expect(doc.paths['/auth/login'].post.security).toBeUndefined();
75
+ });
76
+
77
+ it('never exposes a password outside the register and login request bodies', () => {
78
+ const allowed = new Set(['/auth/register', '/auth/login']);
79
+ const bodies = [...allowed].map(
80
+ (p) => doc.paths[p].post.requestBody.content['application/json'].schema,
81
+ );
82
+ expect(bodies.every((b) => 'password' in b.properties)).toBe(true);
83
+
84
+ const withoutBodies = structuredClone(doc);
85
+ for (const p of allowed) delete withoutBodies.paths[p].post.requestBody;
86
+ const json = JSON.stringify(withoutBodies);
87
+ expect(json).not.toMatch(/"password"/i);
88
+ expect(json).not.toMatch(/refreshToken"\s*:\s*\{\s*"type"/);
89
+ });
90
+ });
91
+
92
+ describe('swagger ui', () => {
93
+ it('GET /api-docs serves the UI', async () => {
94
+ const res = await request(app).get('/api-docs/');
95
+ expect(res.status).toBe(200);
96
+ expect(res.text).toContain('swagger-ui');
97
+ });
98
+
99
+ it('keeps the strict CSP on the API', async () => {
100
+ const res = await request(app).get('/health');
101
+ expect(res.headers['content-security-policy']).toBeDefined();
102
+ });
103
+ });
104
+
105
+ describe('API_DOCS_ENABLED=false', () => {
106
+ afterEach(() => {
107
+ vi.unstubAllEnvs();
108
+ vi.doUnmock('../src/routes/index.ts');
109
+ vi.doUnmock('../src/routes/health.routes.ts');
110
+ vi.resetModules();
111
+ });
112
+
113
+ it('does not serve the docs', async () => {
114
+ vi.stubEnv('API_DOCS_ENABLED', 'false');
115
+ vi.resetModules();
116
+ // Stub the DB-backed routers, since mongoose models cannot be compiled twice.
117
+ vi.doMock('../src/routes/index.ts', async () => ({
118
+ apiRouter: (await import('express')).Router(),
119
+ }));
120
+ vi.doMock('../src/routes/health.routes.ts', async () => ({
121
+ healthRouter: (await import('express')).Router(),
122
+ }));
123
+ const { createApp: createFreshApp } = await import('../src/app.ts');
124
+ const res = await request(createFreshApp()).get('/api-docs.json');
125
+ expect(res.status).toBe(404);
126
+ });
127
+ });
@@ -0,0 +1,96 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { envSchema } from '../src/config/env.schema.ts';
3
+
4
+ const EXAMPLE_SECRET = 'change-me-access-secret-at-least-32-chars';
5
+ // process.env already holds a valid test setup, including the database URL.
6
+ const parse = (overrides: Record<string, string | undefined>) =>
7
+ envSchema.safeParse({ ...process.env, ...overrides });
8
+ const messages = (r: ReturnType<typeof parse>) =>
9
+ r.error!.issues.map((i) => `${i.path.join('.')}: ${i.message}`);
10
+
11
+ describe('envSchema secrets', () => {
12
+ it('rejects the example secret in production with a hint', () => {
13
+ const r = parse({ NODE_ENV: 'production', JWT_ACCESS_SECRET: EXAMPLE_SECRET });
14
+ expect(r.success).toBe(false);
15
+ expect(messages(r)).toContain(
16
+ 'JWT_ACCESS_SECRET: JWT_ACCESS_SECRET still has the example value; set a real secret (e.g. `openssl rand -base64 48`)',
17
+ );
18
+ });
19
+
20
+ it('rejects identical access and refresh secrets in any environment', () => {
21
+ const same = 'the-same-secret-value-that-is-32-chars-long';
22
+ for (const NODE_ENV of ['development', 'test', 'production']) {
23
+ const r = parse({ NODE_ENV, JWT_ACCESS_SECRET: same, JWT_REFRESH_SECRET: same });
24
+ expect(r.success).toBe(false);
25
+ expect(messages(r).join('\n')).toMatch(/must differ/);
26
+ }
27
+ });
28
+
29
+ it('rejects the example secret in production regardless of case and whitespace', () => {
30
+ const r = parse({
31
+ NODE_ENV: 'production',
32
+ JWT_ACCESS_SECRET: ` ${EXAMPLE_SECRET.toUpperCase()}`,
33
+ });
34
+ expect(r.success).toBe(false);
35
+ expect(messages(r).join('\n')).toMatch(/still has the example value/);
36
+ });
37
+
38
+ it('allows the example secrets in development', () => {
39
+ const r = parse({
40
+ NODE_ENV: 'development',
41
+ JWT_ACCESS_SECRET: EXAMPLE_SECRET,
42
+ JWT_REFRESH_SECRET: 'change-me-refresh-secret-at-least-32-chars',
43
+ });
44
+ expect(r.success).toBe(true);
45
+ });
46
+ });
47
+
48
+ describe('envSchema TRUST_PROXY', () => {
49
+ it('is undefined when unset', () => {
50
+ expect(parse({ TRUST_PROXY: undefined }).data!.TRUST_PROXY).toBeUndefined();
51
+ });
52
+
53
+ it('treats an empty or blank value as unset', () => {
54
+ for (const TRUST_PROXY of ['', ' ']) {
55
+ const r = parse({ TRUST_PROXY });
56
+ expect(r.success).toBe(true);
57
+ expect(r.data!.TRUST_PROXY).toBeUndefined();
58
+ }
59
+ });
60
+
61
+ it('parses booleans, hop counts and strings', () => {
62
+ expect(parse({ TRUST_PROXY: 'true' }).data!.TRUST_PROXY).toBe(true);
63
+ expect(parse({ TRUST_PROXY: 'false' }).data!.TRUST_PROXY).toBe(false);
64
+ expect(parse({ TRUST_PROXY: '1' }).data!.TRUST_PROXY).toBe(1);
65
+ expect(parse({ TRUST_PROXY: 'loopback, 10.0.0.0/8' }).data!.TRUST_PROXY).toBe(
66
+ 'loopback, 10.0.0.0/8',
67
+ );
68
+ });
69
+ });
70
+
71
+ describe('envSchema LOG_LEVEL and token lifetimes', () => {
72
+ it('accepts the pino levels', () => {
73
+ for (const LOG_LEVEL of ['fatal', 'error', 'warn', 'info', 'debug', 'trace', 'silent']) {
74
+ expect(parse({ LOG_LEVEL }).success).toBe(true);
75
+ }
76
+ });
77
+
78
+ it('rejects an unknown log level', () => {
79
+ const r = parse({ LOG_LEVEL: 'verbose' });
80
+ expect(r.success).toBe(false);
81
+ expect(r.error!.issues[0].path).toEqual(['LOG_LEVEL']);
82
+ });
83
+
84
+ it('accepts time spans and rejects anything else', () => {
85
+ for (const span of ['900', '30s', '15m', '1h', '7d', '2w', '1y', '500ms']) {
86
+ expect(parse({ JWT_ACCESS_EXPIRES_IN: span, JWT_REFRESH_EXPIRES_IN: span }).success).toBe(
87
+ true,
88
+ );
89
+ }
90
+ for (const span of ['15 minutes', 'soon', '-1d', '']) {
91
+ const r = parse({ JWT_REFRESH_EXPIRES_IN: span });
92
+ expect(r.success).toBe(false);
93
+ expect(r.error!.issues[0].path).toEqual(['JWT_REFRESH_EXPIRES_IN']);
94
+ }
95
+ });
96
+ });
@@ -0,0 +1,21 @@
1
+ import request from 'supertest';
2
+ import { describe, expect, it, vi } from 'vitest';
3
+
4
+ vi.mock('../src/database/connection.ts', async (importOriginal) => ({
5
+ ...(await importOriginal<typeof import('../src/database/connection.ts')>()),
6
+ isDatabaseConnected: async () => false,
7
+ }));
8
+
9
+ const { createApp } = await import('../src/app.ts');
10
+
11
+ describe('GET /health when the database is down', () => {
12
+ it('returns 503 and reports the database as down', async () => {
13
+ const res = await request(createApp()).get('/health');
14
+ expect(res.status).toBe(503);
15
+ expect(res.body).toEqual({
16
+ success: false,
17
+ message: 'Service unavailable',
18
+ data: { status: 'degraded', database: 'down' },
19
+ });
20
+ });
21
+ });
@@ -0,0 +1,49 @@
1
+ import request from 'supertest';
2
+ import { hashPassword } from '../../src/utils/password.ts';
3
+ import { ROLES } from '../../src/constants/roles.ts';
4
+ import * as userRepository from '../../src/modules/user/user.repository.ts';
5
+ import type { Express } from 'express';
6
+ import type { Response } from 'supertest';
7
+ import type { UserRepository } from '../../src/modules/user/user.service.ts';
8
+
9
+ type UserOverrides = Partial<Parameters<UserRepository['create']>[0]>;
10
+
11
+ const DEFAULT_PASSWORD = 'Passw0rd!';
12
+ let counter = 0;
13
+
14
+ export async function createUser(overrides: UserOverrides = {}) {
15
+ counter += 1;
16
+ const password = overrides.password ?? DEFAULT_PASSWORD;
17
+ const user = await userRepository.create({
18
+ name: 'Test User',
19
+ email: `user-${counter}-${Date.now()}@test.com`,
20
+ role: ROLES.USER,
21
+ ...overrides,
22
+ password: await hashPassword(password),
23
+ });
24
+ return { user, password };
25
+ }
26
+
27
+ export function createAdmin(overrides: UserOverrides = {}) {
28
+ return createUser({ role: ROLES.ADMIN, ...overrides });
29
+ }
30
+
31
+ // Returns the "refreshToken=<value>" pair from a response's Set-Cookie header, or null.
32
+ export function getRefreshCookie(res: Response): string | null {
33
+ const header = (res.headers['set-cookie'] ?? []) as unknown as string[];
34
+ const line = header.find((cookie) => cookie.startsWith('refreshToken='));
35
+ return line ? line.split(';')[0] : null;
36
+ }
37
+
38
+ export async function loginAs(
39
+ app: Express,
40
+ { email, password }: { email: string; password: string },
41
+ ) {
42
+ const res = await request(app).post('/api/v1/auth/login').send({ email, password });
43
+ if (res.status !== 200) throw new Error(`loginAs failed with status ${res.status}`);
44
+ return {
45
+ accessToken: res.body.data.accessToken,
46
+ refreshCookie: getRefreshCookie(res)!,
47
+ user: res.body.data.user,
48
+ };
49
+ }
@@ -0,0 +1,18 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { hashPassword, verifyPassword } from '../src/utils/password.ts';
3
+
4
+ describe('password utils', () => {
5
+ it('hashes with argon2id', async () => {
6
+ const hash = await hashPassword('Passw0rd');
7
+ expect(hash).not.toBe('Passw0rd');
8
+ expect(hash.startsWith('$argon2id$')).toBe(true);
9
+ });
10
+ it('verifies right and wrong passwords', async () => {
11
+ const hash = await hashPassword('Passw0rd');
12
+ expect(await verifyPassword(hash, 'Passw0rd')).toBe(true);
13
+ expect(await verifyPassword(hash, 'Wrong1234')).toBe(false);
14
+ });
15
+ it('returns false for a malformed hash', async () => {
16
+ expect(await verifyPassword('not-a-hash', 'x')).toBe(false);
17
+ });
18
+ });
@@ -0,0 +1,32 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { buildPostmanCollection } from '../scripts/generate-postman.ts';
3
+ import type { PostmanItem } from '../scripts/generate-postman.ts';
4
+
5
+ function find(items: PostmanItem[], name: string): PostmanItem | undefined {
6
+ for (const item of items) {
7
+ if (item.request && item.name.toLowerCase().includes(name)) return item;
8
+ const found = item.item && find(item.item, name);
9
+ if (found) return found;
10
+ }
11
+ return undefined;
12
+ }
13
+
14
+ describe('postman collection', () => {
15
+ it('sets baseUrl, bearer auth and stores the token after login and refresh', async () => {
16
+ const collection = await buildPostmanCollection();
17
+ expect(collection.variable!.find((v) => v.key === 'baseUrl')!.value).toBe(
18
+ 'http://localhost:3000/api/v1',
19
+ );
20
+ expect(collection.auth!.type).toBe('bearer');
21
+ expect(collection.auth!.bearer![0].value).toBe('{{accessToken}}');
22
+
23
+ for (const name of ['log in', 'refresh the session']) {
24
+ const item = find(collection.item, name);
25
+ expect(item, name).toBeDefined();
26
+ const script = item!.event!.find((e) => e.listen === 'test')!.script.exec.join('\n');
27
+ expect(script).toContain("pm.collectionVariables.set('accessToken'");
28
+ }
29
+ expect(find(collection.item, 'log in')!.request!.auth).toEqual({ type: 'noauth' });
30
+ expect(find(collection.item, 'get my profile')!.request!.auth).toBeUndefined();
31
+ });
32
+ });
@@ -0,0 +1,27 @@
1
+ import express from 'express';
2
+ import { pinoHttp } from 'pino-http';
3
+ import request from 'supertest';
4
+ import { describe, expect, it } from 'vitest';
5
+ import { logger } from '../src/config/logger.ts';
6
+ import { errorHandler } from '../src/middlewares/errorHandler.ts';
7
+ import { createRateLimiter } from '../src/middlewares/rateLimiter.ts';
8
+
9
+ describe('createRateLimiter', () => {
10
+ it('returns a JSON 429 once the limit is exceeded', async () => {
11
+ const app = express();
12
+ app.use(pinoHttp({ logger }));
13
+ app.get('/limited', createRateLimiter({ windowMs: 60_000, max: 2 }), (_req, res) =>
14
+ res.json({ ok: true }),
15
+ );
16
+ app.use(errorHandler);
17
+
18
+ expect((await request(app).get('/limited')).status).toBe(200);
19
+ expect((await request(app).get('/limited')).status).toBe(200);
20
+ const res = await request(app).get('/limited');
21
+ expect(res.status).toBe(429);
22
+ expect(res.body).toEqual({
23
+ success: false,
24
+ message: 'Too many requests, please try again later',
25
+ });
26
+ });
27
+ });
@@ -0,0 +1,42 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { EXAMPLE_ADMIN_PASSWORD } from '../src/constants/examples.ts';
3
+ import { ROLES } from '../src/constants/roles.ts';
4
+ import * as userRepository from '../src/modules/user/user.repository.ts';
5
+ import { seedAdmin } from '../scripts/seed-admin.ts';
6
+ import { createUser } from './helpers/auth.helper.ts';
7
+
8
+ const input = { name: 'Admin', email: 'seed-admin@test.com', password: 'Passw0rd!' };
9
+
10
+ describe('seedAdmin', () => {
11
+ it('creates a new admin', async () => {
12
+ const result = await seedAdmin(input);
13
+ expect(result.action).toBe('created');
14
+ expect(result.user.role).toBe(ROLES.ADMIN);
15
+ expect(JSON.stringify(result)).not.toContain('"password"');
16
+ });
17
+
18
+ it('promotes an existing user without changing the password', async () => {
19
+ const { user } = await createUser({ email: input.email });
20
+ const before = await userRepository.findByEmail(input.email, { withPassword: true });
21
+ const result = await seedAdmin(input);
22
+ expect(result.action).toBe('promoted');
23
+ expect(result.user.id).toBe(user.id);
24
+ expect(result.user.role).toBe(ROLES.ADMIN);
25
+ const after = await userRepository.findByEmail(input.email, { withPassword: true });
26
+ expect(after!.password).toBe(before!.password);
27
+ });
28
+
29
+ it('is idempotent', async () => {
30
+ await seedAdmin(input);
31
+ const result = await seedAdmin(input);
32
+ expect(result.action).toBe('unchanged');
33
+ expect((await userRepository.findMany({ page: 1, limit: 10 })).total).toBe(1);
34
+ });
35
+
36
+ it('refuses the example password from .env.example', async () => {
37
+ await expect(seedAdmin({ ...input, password: EXAMPLE_ADMIN_PASSWORD })).rejects.toThrow(
38
+ 'ADMIN_PASSWORD still has the example value',
39
+ );
40
+ expect(await userRepository.findByEmail(input.email)).toBeNull();
41
+ });
42
+ });
@@ -0,0 +1,69 @@
1
+ import jwt from 'jsonwebtoken';
2
+ import { afterEach, describe, expect, it, vi } from 'vitest';
3
+ import { env } from '../src/config/env.ts';
4
+ import {
5
+ hashToken,
6
+ signAccessToken,
7
+ signRefreshToken,
8
+ verifyAccessToken,
9
+ verifyRefreshToken,
10
+ } from '../src/utils/token.ts';
11
+
12
+ const expect401 = (fn: () => unknown) => {
13
+ try {
14
+ fn();
15
+ } catch (err) {
16
+ expect((err as { statusCode: number }).statusCode).toBe(401);
17
+ return;
18
+ }
19
+ throw new Error('expected a 401 ApiError');
20
+ };
21
+
22
+ afterEach(() => vi.useRealTimers());
23
+
24
+ describe('tokens', () => {
25
+ it('round-trips an access token', () => {
26
+ const token = signAccessToken({ userId: 'u1', role: 'user' });
27
+ expect(verifyAccessToken(token)).toEqual({ userId: 'u1', role: 'user' });
28
+ });
29
+ it('round-trips a refresh token and returns expiresAt from exp', () => {
30
+ const { token, expiresAt } = signRefreshToken({ userId: 'u1' });
31
+ expect(verifyRefreshToken(token)).toEqual({ userId: 'u1' });
32
+ const days = (expiresAt.getTime() - Date.now()) / 86_400_000;
33
+ expect(days).toBeGreaterThan(6.9);
34
+ expect(days).toBeLessThan(7.1);
35
+ });
36
+ it('rejects a refresh token as access token and vice versa', () => {
37
+ const access = signAccessToken({ userId: 'u1', role: 'user' });
38
+ const { token: refresh } = signRefreshToken({ userId: 'u1' });
39
+ expect401(() => verifyAccessToken(refresh));
40
+ expect401(() => verifyRefreshToken(access));
41
+ });
42
+ it('rejects a tampered token', () => {
43
+ const token = signAccessToken({ userId: 'u1', role: 'user' });
44
+ const [header, payload, signature] = token.split('.');
45
+ const forged = JSON.parse(Buffer.from(payload, 'base64url').toString());
46
+ forged.sub = 'u2';
47
+ const tampered = `${header}.${Buffer.from(JSON.stringify(forged)).toString('base64url')}.${signature}`;
48
+ expect401(() => verifyAccessToken(tampered));
49
+ });
50
+ it('rejects a refresh-typed token signed with the access secret', () => {
51
+ const token = jwt.sign({ sub: 'u1', role: 'user', type: 'refresh' }, env.JWT_ACCESS_SECRET);
52
+ expect401(() => verifyAccessToken(token));
53
+ });
54
+ it('rejects garbage', () => {
55
+ expect401(() => verifyAccessToken('garbage'));
56
+ });
57
+ it('rejects an expired token', () => {
58
+ vi.useFakeTimers();
59
+ vi.setSystemTime(new Date('2030-01-01T00:00:00Z'));
60
+ const token = signAccessToken({ userId: 'u1', role: 'user' });
61
+ vi.setSystemTime(new Date('2030-01-01T00:16:00Z'));
62
+ expect401(() => verifyAccessToken(token));
63
+ });
64
+ it('hashToken is deterministic sha-256 hex', () => {
65
+ expect(hashToken('a')).toBe(hashToken('a'));
66
+ expect(hashToken('a')).toHaveLength(64);
67
+ expect(hashToken('a')).not.toBe(hashToken('b'));
68
+ });
69
+ });
@@ -0,0 +1,24 @@
1
+ import express from 'express';
2
+ import request from 'supertest';
3
+ import { describe, expect, it, vi } from 'vitest';
4
+
5
+ vi.mock('../src/config/env.ts', async (importOriginal) => {
6
+ const { env } = await importOriginal<typeof import('../src/config/env.ts')>();
7
+ return { env: { ...env, TRUST_PROXY: 1 } };
8
+ });
9
+
10
+ const { createApp } = await import('../src/app.ts');
11
+
12
+ describe('TRUST_PROXY', () => {
13
+ it('sets Express trust proxy, so req.ip comes from X-Forwarded-For', async () => {
14
+ const app = createApp();
15
+ expect(app.get('trust proxy')).toBe(1);
16
+
17
+ // req.ip is what the rate limiter keys on.
18
+ const probe = express();
19
+ probe.set('trust proxy', app.get('trust proxy'));
20
+ probe.get('/ip', (req, res) => res.json({ ip: req.ip }));
21
+ const res = await request(probe).get('/ip').set('X-Forwarded-For', '1.2.3.4');
22
+ expect(res.body.ip).toBe('1.2.3.4');
23
+ });
24
+ });