create-tigra 3.3.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (203) hide show
  1. package/README.md +81 -12
  2. package/bin/create-tigra.js +495 -472
  3. package/lib/patchers/email-verification.patcher.js +72 -10
  4. package/modules/email-verification/client/hooks/useVerification.ts +4 -1
  5. package/modules/email-verification/server/__tests__/verification.integration.test.ts +115 -0
  6. package/modules/email-verification/server/verification.controller.ts +3 -1
  7. package/modules/email-verification/server/verification.service.ts +44 -13
  8. package/package.json +3 -2
  9. package/template/.github/dependabot.yml +47 -0
  10. package/template/.github/workflows/audit.yml +36 -0
  11. package/template/.github/workflows/ci.yml +79 -0
  12. package/template/AGENTS.md +18 -9
  13. package/template/client/.dockerignore +1 -0
  14. package/template/client/.env.example.production +13 -2
  15. package/template/client/AGENTS.md +13 -5
  16. package/template/client/Dockerfile +186 -14
  17. package/template/client/next.config.ts +1 -1
  18. package/template/client/package-lock.json +15983 -14181
  19. package/template/client/package.json +56 -48
  20. package/template/client/scripts/check-sharp.mjs +53 -0
  21. package/template/client/scripts/next-dev.cjs +5 -1
  22. package/template/client/src/__tests__/proxy.test.ts +92 -0
  23. package/template/client/src/app/healthz/route.ts +16 -0
  24. package/template/client/src/app/layout.tsx +9 -3
  25. package/template/client/src/app/page.tsx +2 -2
  26. package/template/client/src/app/providers.tsx +23 -4
  27. package/template/client/src/components/layout/Header.tsx +7 -3
  28. package/template/client/src/features/admin/hooks/useAdminSessions.ts +2 -1
  29. package/template/client/src/features/admin/hooks/useAdminUsers.ts +3 -1
  30. package/template/client/src/features/admin/types/admin.types.ts +2 -3
  31. package/template/client/src/features/auth/components/AuthInitializer.tsx +35 -18
  32. package/template/client/src/features/auth/components/ForgotPasswordForm.tsx +107 -0
  33. package/template/client/src/features/auth/components/LimitNotice.tsx +28 -0
  34. package/template/client/src/features/auth/components/LoginForm.tsx +13 -2
  35. package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
  36. package/template/client/src/features/auth/hooks/useAuth.ts +11 -1
  37. package/template/client/src/features/auth/hooks/usePasswordReset.ts +7 -1
  38. package/template/client/src/features/auth/services/auth.service.ts +8 -3
  39. package/template/client/src/features/auth/store/authSlice.ts +7 -2
  40. package/template/client/src/lib/api/__tests__/axios.config.test.ts +183 -0
  41. package/template/client/src/lib/api/api.types.ts +14 -0
  42. package/template/client/src/lib/api/axios.config.ts +101 -15
  43. package/template/client/src/lib/api/hard-redirect.ts +8 -0
  44. package/template/client/src/lib/api/session-events.ts +29 -0
  45. package/template/client/src/lib/constants/routes.ts +12 -0
  46. package/template/client/src/lib/observability/sentry-scrub.ts +1 -1
  47. package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
  48. package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
  49. package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
  50. package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
  51. package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
  52. package/template/client/src/lib/utils/error.ts +81 -0
  53. package/template/client/src/lib/utils/form.ts +31 -0
  54. package/template/client/src/lib/utils/paths.ts +18 -0
  55. package/template/client/src/lib/utils/session-marker.ts +24 -0
  56. package/template/client/src/{middleware.ts → proxy.ts} +25 -11
  57. package/template/client/src/store/__tests__/store.test.ts +44 -0
  58. package/template/client/src/store/index.ts +26 -8
  59. package/template/client/vitest.config.mts +48 -0
  60. package/template/server/.env.example +280 -270
  61. package/template/server/.env.example.production +283 -242
  62. package/template/server/AGENTS.md +13 -4
  63. package/template/server/Dockerfile +176 -14
  64. package/template/server/docker-compose.yml +4 -2
  65. package/template/server/docs/deployment.md +63 -0
  66. package/template/server/docs/logging.md +52 -4
  67. package/template/server/docs/rate-limits.md +153 -0
  68. package/template/server/docs/testing.md +63 -0
  69. package/template/server/eslint.config.mjs +19 -0
  70. package/template/server/package-lock.json +8784 -8743
  71. package/template/server/package.json +79 -75
  72. package/template/server/prisma/migrations/0_init/migration.sql +82 -0
  73. package/template/server/prisma/migrations/migration_lock.toml +3 -0
  74. package/template/server/prisma/schema.prisma +0 -3
  75. package/template/server/scripts/check-heic.mjs +40 -0
  76. package/template/server/scripts/check-sharp.mjs +53 -0
  77. package/template/server/src/__tests__/routes.integration.test.ts +280 -0
  78. package/template/server/src/app.ts +248 -346
  79. package/template/server/src/config/__tests__/env.test.ts +219 -0
  80. package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
  81. package/template/server/src/config/env.ts +326 -182
  82. package/template/server/src/config/rate-limit.config.ts +157 -106
  83. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +60 -8
  84. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
  85. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
  86. package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
  87. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +38 -36
  88. package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
  89. package/template/server/src/jobs/index.ts +12 -2
  90. package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
  91. package/template/server/src/jobs/schedule.ts +50 -0
  92. package/template/server/src/libs/__tests__/auth.test.ts +98 -7
  93. package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
  94. package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
  95. package/template/server/src/libs/__tests__/cookies.test.ts +53 -2
  96. package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
  97. package/template/server/src/libs/__tests__/email.test.ts +68 -0
  98. package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
  99. package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
  100. package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
  101. package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
  102. package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
  103. package/template/server/src/libs/__tests__/http.test.ts +74 -2
  104. package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
  105. package/template/server/src/libs/__tests__/logger.test.ts +50 -0
  106. package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
  107. package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
  108. package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
  109. package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
  110. package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
  111. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
  112. package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
  113. package/template/server/src/libs/__tests__/redis.test.ts +38 -2
  114. package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
  115. package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
  116. package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
  117. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -80
  118. package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
  119. package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
  120. package/template/server/src/libs/auth.ts +39 -10
  121. package/template/server/src/libs/client-ip.ts +158 -77
  122. package/template/server/src/libs/cloudflare-ranges.ts +132 -0
  123. package/template/server/src/libs/cookies.ts +53 -14
  124. package/template/server/src/libs/email-quota.ts +74 -0
  125. package/template/server/src/libs/email.ts +46 -9
  126. package/template/server/src/libs/error-handler.ts +111 -0
  127. package/template/server/src/libs/health-routes.ts +53 -0
  128. package/template/server/src/libs/http.ts +139 -47
  129. package/template/server/src/libs/ip-address.ts +37 -0
  130. package/template/server/src/libs/ip-block.ts +284 -221
  131. package/template/server/src/libs/logger.ts +41 -12
  132. package/template/server/src/libs/monitoring.ts +127 -41
  133. package/template/server/src/libs/observability/sentry.ts +1 -1
  134. package/template/server/src/libs/origin-check.ts +9 -7
  135. package/template/server/src/libs/prisma.ts +47 -4
  136. package/template/server/src/libs/query-counter.ts +71 -59
  137. package/template/server/src/libs/rate-limiting.ts +110 -0
  138. package/template/server/src/libs/redis-required.ts +28 -0
  139. package/template/server/src/libs/redis.ts +27 -1
  140. package/template/server/src/libs/request-id.ts +18 -0
  141. package/template/server/src/libs/requestLogger.ts +112 -17
  142. package/template/server/src/libs/safe-http.ts +101 -0
  143. package/template/server/src/libs/shutdown.ts +87 -0
  144. package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
  145. package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +59 -0
  146. package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
  147. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
  148. package/template/server/src/libs/storage/file-storage.service.ts +94 -84
  149. package/template/server/src/libs/storage/file-validator.ts +48 -46
  150. package/template/server/src/libs/storage/image-optimizer.service.ts +16 -5
  151. package/template/server/src/libs/token-hash.ts +18 -0
  152. package/template/server/src/libs/url-safety.ts +127 -121
  153. package/template/server/src/libs/validation-errors.ts +86 -0
  154. package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
  155. package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
  156. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
  157. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
  158. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
  159. package/template/server/src/modules/admin/admin.controller.ts +66 -49
  160. package/template/server/src/modules/admin/admin.repo.ts +49 -10
  161. package/template/server/src/modules/admin/admin.routes.ts +48 -2
  162. package/template/server/src/modules/admin/admin.schemas.ts +18 -6
  163. package/template/server/src/modules/admin/admin.service.ts +66 -4
  164. package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
  165. package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
  166. package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
  167. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +197 -37
  168. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
  169. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
  170. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
  171. package/template/server/src/modules/auth/auth.controller.ts +133 -128
  172. package/template/server/src/modules/auth/auth.repo.ts +44 -44
  173. package/template/server/src/modules/auth/auth.schemas.ts +4 -2
  174. package/template/server/src/modules/auth/auth.service.ts +167 -96
  175. package/template/server/src/modules/auth/session.repo.ts +12 -0
  176. package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
  177. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
  178. package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
  179. package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
  180. package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
  181. package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
  182. package/template/server/src/modules/users/users.controller.ts +9 -38
  183. package/template/server/src/modules/users/users.repo.ts +23 -7
  184. package/template/server/src/modules/users/users.routes.ts +3 -22
  185. package/template/server/src/modules/users/users.schemas.ts +15 -9
  186. package/template/server/src/modules/users/users.service.ts +105 -93
  187. package/template/server/src/scripts/make-admin.ts +48 -0
  188. package/template/server/src/server.ts +48 -26
  189. package/template/server/src/shared/errors/AppError.ts +27 -1
  190. package/template/server/src/shared/errors/errors.ts +42 -5
  191. package/template/server/src/shared/responses/successResponse.ts +22 -3
  192. package/template/server/src/shared/types/index.ts +7 -0
  193. package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
  194. package/template/server/src/test/integration-helpers.ts +343 -0
  195. package/template/server/src/test/integration-services.ts +74 -0
  196. package/template/server/src/test/integration.global-setup.ts +144 -0
  197. package/template/server/src/test/integration.setup.ts +35 -158
  198. package/template/server/src/test/setup.ts +3 -10
  199. package/template/server/tsconfig.build.json +1 -1
  200. package/template/server/tsconfig.json +1 -0
  201. package/template/server/vitest.config.ts +17 -4
  202. package/template/server/vitest.integration.config.ts +18 -13
  203. package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Boot-time env validation (src/config/env.ts). The module validates at import
3
+ * and exits the process on a mistake, so every case boots it in a fresh child
4
+ * process with an exact environment and checks the exit code and message (or
5
+ * the parsed values it prints).
6
+ *
7
+ * The child runs in an empty temp directory so dotenv cannot load a developer's
8
+ * real server/.env (dotenv never overrides variables that are already set, but
9
+ * it would fill in the ones a case deliberately leaves out).
10
+ */
11
+ import { spawnSync } from 'node:child_process';
12
+ import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
13
+ import { tmpdir } from 'node:os';
14
+ import path from 'node:path';
15
+ import { fileURLToPath, pathToFileURL } from 'node:url';
16
+ import { afterAll, describe, expect, it } from 'vitest';
17
+
18
+ const serverRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');
19
+ const tsxCli = path.join(serverRoot, 'node_modules', 'tsx', 'dist', 'cli.mjs');
20
+ const envModuleUrl = pathToFileURL(path.join(serverRoot, 'src', 'config', 'env.ts')).href;
21
+
22
+ /** The email-verification module adds this file (and turns verification on by default). */
23
+ const EMAIL_MODULE_INSTALLED = existsSync(path.join(serverRoot, 'src', 'modules', 'auth', 'verification.service.ts'));
24
+
25
+ const workDir = mkdtempSync(path.join(tmpdir(), 'env-validation-'));
26
+ const probe = path.join(workDir, 'probe.mts');
27
+ writeFileSync(
28
+ probe,
29
+ `const { env } = await import(${JSON.stringify(envModuleUrl)});\n` +
30
+ 'console.log(JSON.stringify({ RATE_LIMIT_ENABLED: env.RATE_LIMIT_ENABLED, ' +
31
+ 'REQUIRE_USER_VERIFICATION: env.REQUIRE_USER_VERIFICATION, REDIS_URL: env.REDIS_URL, ' +
32
+ 'CLIENT_URL: env.CLIENT_URL, CORS_ORIGINS: env.CORS_ORIGINS }));\n',
33
+ );
34
+ afterAll(() => rmSync(workDir, { recursive: true, force: true }));
35
+
36
+ /** Only what node and tsx need to run on any OS; nothing from this test process's app env. */
37
+ const SYSTEM = Object.fromEntries(
38
+ ['PATH', 'Path', 'SystemRoot', 'TEMP', 'TMP', 'HOME', 'USERPROFILE'].flatMap((key) =>
39
+ process.env[key] === undefined ? [] : [[key, process.env[key] as string]],
40
+ ),
41
+ );
42
+
43
+ /** The only variables without a default. */
44
+ const REQUIRED = { DATABASE_URL: 'mysql://user:pass@localhost:3306/app', JWT_SECRET: 'x'.repeat(48) };
45
+ /** The smallest valid environment (verification off, so no Resend key is needed). */
46
+ const BASE = { ...REQUIRED, REQUIRE_USER_VERIFICATION: 'false' };
47
+ const PRODUCTION = { ...BASE, NODE_ENV: 'production', CORS_ORIGIN: 'https://app.example.test' };
48
+
49
+ function boot(vars: Record<string, string>): { code: number | null; out: string; err: string } {
50
+ const result = spawnSync(process.execPath, [tsxCli, probe], {
51
+ cwd: workDir,
52
+ env: { ...SYSTEM, ...vars },
53
+ encoding: 'utf8',
54
+ timeout: 60_000,
55
+ });
56
+ return { code: result.status, out: result.stdout, err: result.stderr };
57
+ }
58
+
59
+ function parsed(vars: Record<string, string>): Record<string, unknown> {
60
+ const result = boot(vars);
61
+ expect(result.code, result.err).toBe(0);
62
+ return JSON.parse(result.out.trim().split('\n').pop() as string) as Record<string, unknown>;
63
+ }
64
+
65
+ describe('env validation at boot', { timeout: 60_000 }, () => {
66
+ it('refuses to start in production without REDIS_URL', () => {
67
+ const result = boot(PRODUCTION);
68
+ expect(result.code).toBe(1);
69
+ expect(result.err).toContain('REDIS_URL is required in production');
70
+ });
71
+
72
+ it('starts in production with REDIS_URL and keeps its value', () => {
73
+ expect(parsed({ ...PRODUCTION, REDIS_URL: 'redis://cache.internal:6379' }).REDIS_URL).toBe(
74
+ 'redis://cache.internal:6379',
75
+ );
76
+ });
77
+
78
+ it('defaults REDIS_URL to the local Redis outside production', () => {
79
+ expect(parsed({ ...BASE, NODE_ENV: 'development' }).REDIS_URL).toBe('redis://localhost:6379');
80
+ });
81
+
82
+ describe('CORS_ORIGIN (bare origins only)', () => {
83
+ const WITH_REDIS = { ...PRODUCTION, REDIS_URL: 'redis://cache.internal:6379' };
84
+
85
+ it('refuses an entry that is not a bare origin, with the corrected value', () => {
86
+ for (const [value, fix] of [
87
+ ['https://app.example.test/', 'https://app.example.test'],
88
+ ['https://app.example.test/login', 'https://app.example.test'],
89
+ ['https://App.Example.test', 'https://app.example.test'],
90
+ ['https://app.example.test:443', 'https://app.example.test'],
91
+ ]) {
92
+ const result = boot({ ...WITH_REDIS, CORS_ORIGIN: value });
93
+ expect(result.code, value).toBe(1);
94
+ expect(result.err).toContain(`write it as "${fix}"`);
95
+ }
96
+ });
97
+
98
+ it('refuses * and anything that is not an http(s) URL', () => {
99
+ for (const value of ['*', 'app.example.test', 'ftp://app.example.test']) {
100
+ const result = boot({ ...WITH_REDIS, CORS_ORIGIN: value });
101
+ expect(result.code, value).toBe(1);
102
+ expect(result.err).toContain('must be a full origin such as https://app.example.com');
103
+ }
104
+ });
105
+
106
+ it('trims entries and ignores empty ones', () => {
107
+ const env = parsed({ ...WITH_REDIS, CORS_ORIGIN: ' https://a.example.test , https://b.example.test ,' });
108
+ expect(env.CORS_ORIGINS).toEqual(['https://a.example.test', 'https://b.example.test']);
109
+ });
110
+
111
+ it('still requires at least one origin in production', () => {
112
+ const result = boot({ ...WITH_REDIS, CORS_ORIGIN: ' , ' });
113
+ expect(result.code).toBe(1);
114
+ expect(result.err).toContain('CORS_ORIGIN is required in production');
115
+ });
116
+ });
117
+
118
+ describe('plain http in production', () => {
119
+ const WITH_REDIS = { ...PRODUCTION, REDIS_URL: 'redis://cache.internal:6379' };
120
+
121
+ it('warns (but starts) when CORS_ORIGIN uses http:// in production', () => {
122
+ const result = boot({ ...WITH_REDIS, CORS_ORIGIN: 'http://app.example.test' });
123
+ expect(result.code, result.err).toBe(0);
124
+ expect(result.err).toContain('CORS_ORIGIN uses http:// in production');
125
+ });
126
+
127
+ it('stays quiet for https and for a local http origin', () => {
128
+ for (const origin of ['https://app.example.test', 'http://localhost:3000']) {
129
+ const result = boot({ ...WITH_REDIS, CORS_ORIGIN: origin });
130
+ expect(result.code, origin).toBe(0);
131
+ expect(result.err, origin).not.toContain('uses http://');
132
+ }
133
+ });
134
+ });
135
+
136
+ describe('CLIENT_URL (email links)', () => {
137
+ const WITH_REDIS = { ...PRODUCTION, REDIS_URL: 'redis://cache.internal:6379' };
138
+
139
+ it('refuses to start in production when a Resend key is set but CLIENT_URL is not', () => {
140
+ const result = boot({ ...WITH_REDIS, RESEND_API_KEY: 're_test' });
141
+ expect(result.code).toBe(1);
142
+ expect(result.err).toContain('CLIENT_URL is required in production when RESEND_API_KEY is set');
143
+ });
144
+
145
+ it('starts in production with a Resend key and CLIENT_URL', () => {
146
+ const env = parsed({ ...WITH_REDIS, RESEND_API_KEY: 're_test', CLIENT_URL: 'https://app.example.test' });
147
+ expect(env.CLIENT_URL).toBe('https://app.example.test');
148
+ });
149
+
150
+ it('needs no CLIENT_URL in production without a Resend key (server-only project)', () => {
151
+ expect(parsed(WITH_REDIS).CLIENT_URL).toBe('http://localhost:3000');
152
+ });
153
+
154
+ describe('placeholder email settings', () => {
155
+ const READY = { ...WITH_REDIS, CLIENT_URL: 'https://app.example.test' };
156
+
157
+ it.each(['CHANGE_ME_your_resend_api_key', 're_xxxxxxxxxxxxxxxxxxxxxxxxxxxx'])('refuses the placeholder key %s in production', (key) => {
158
+ const result = boot({ ...READY, RESEND_API_KEY: key, RESEND_FROM_EMAIL: 'noreply@app.example.test' });
159
+ expect(result.code).toBe(1);
160
+ expect(result.err).toContain('RESEND_API_KEY is still the placeholder');
161
+ });
162
+
163
+ it('refuses the placeholder sender @yourdomain.com in production', () => {
164
+ const result = boot({ ...READY, RESEND_API_KEY: 're_live_key', RESEND_FROM_EMAIL: 'noreply@yourdomain.com' });
165
+ expect(result.code).toBe(1);
166
+ expect(result.err).toContain('RESEND_FROM_EMAIL is still the placeholder');
167
+ });
168
+
169
+ it("warns (but starts) on Resend's test sender", () => {
170
+ const result = boot({ ...READY, RESEND_API_KEY: 're_live_key', RESEND_FROM_EMAIL: 'onboarding@resend.dev' });
171
+ expect(result.code, result.err).toBe(0);
172
+ expect(result.err).toContain("Resend's test sender");
173
+ });
174
+
175
+ it('starts quietly with a real key and a real sender', () => {
176
+ const result = boot({ ...READY, RESEND_API_KEY: 're_live_key', RESEND_FROM_EMAIL: 'noreply@app.example.test' });
177
+ expect(result.code, result.err).toBe(0);
178
+ expect(result.err).not.toContain('RESEND_');
179
+ });
180
+
181
+ it('lets development boot with the placeholders (no email goes out by accident there)', () => {
182
+ const result = boot({ ...BASE, NODE_ENV: 'development', RESEND_API_KEY: 'CHANGE_ME_your_resend_api_key', RESEND_FROM_EMAIL: 'noreply@yourdomain.com' });
183
+ expect(result.code, result.err).toBe(0);
184
+ });
185
+ });
186
+ });
187
+
188
+ it('reads on/off switches in any letter case, and defaults them when unset', () => {
189
+ expect(parsed({ ...BASE, NODE_ENV: 'development', RATE_LIMIT_ENABLED: 'TRUE' }).RATE_LIMIT_ENABLED).toBe(true);
190
+ expect(parsed({ ...BASE, NODE_ENV: 'development', RATE_LIMIT_ENABLED: ' False ' }).RATE_LIMIT_ENABLED).toBe(false);
191
+ expect(parsed({ ...BASE, NODE_ENV: 'development' }).RATE_LIMIT_ENABLED).toBe(true);
192
+ // Verification defaults to OFF without the email module (no verify route),
193
+ // and ON once the module is installed (its patcher flips the default; a
194
+ // Resend key is then required).
195
+ const unset = parsed({
196
+ ...REQUIRED,
197
+ NODE_ENV: 'development',
198
+ ...(EMAIL_MODULE_INSTALLED ? { RESEND_API_KEY: 're_test' } : {}),
199
+ });
200
+ expect(unset.REQUIRE_USER_VERIFICATION).toBe(EMAIL_MODULE_INSTALLED);
201
+ });
202
+
203
+ it('refuses verification switched on without a Resend key', () => {
204
+ const result = boot({ ...REQUIRED, NODE_ENV: 'development', REQUIRE_USER_VERIFICATION: 'true' });
205
+ expect(result.code).toBe(1);
206
+ expect(result.err).toContain('RESEND_API_KEY is required when REQUIRE_USER_VERIFICATION is enabled');
207
+ });
208
+
209
+ it('refuses a switch value that is not true or false instead of reading it as off', () => {
210
+ for (const [name, value] of [
211
+ ['RATE_LIMIT_ENABLED', '1'],
212
+ ['REQUIRE_USER_VERIFICATION', 'yes'],
213
+ ]) {
214
+ const result = boot({ ...BASE, NODE_ENV: 'development', [name]: value });
215
+ expect(result.code, `${name}=${value}`).toBe(1);
216
+ expect(result.err).toContain(`${name}: must be true or false`);
217
+ }
218
+ });
219
+ });
@@ -0,0 +1,158 @@
1
+ import { describe, it, expect, vi, afterEach } from 'vitest';
2
+ import { env as realEnv } from '@config/env.js';
3
+ import {
4
+ RATE_LIMITS,
5
+ DEFAULT_LIMIT,
6
+ EMAIL_PER_ADDRESS,
7
+ RateLimitConfigError,
8
+ parseOverrides,
9
+ parseWindow,
10
+ unknownOverrideNames,
11
+ } from '../rate-limit.config.js';
12
+
13
+ const MIN = 60_000;
14
+ const HOUR = 60 * MIN;
15
+
16
+ /**
17
+ * The shipped defaults (Tornike, 2026-10-19). Changing a limit means changing it here
18
+ * too, on purpose. The two email-module entries exist only in projects scaffolded with
19
+ * (or patched to add) email verification.
20
+ */
21
+ const EXPECTED: Record<string, { max: number; timeWindow: number }> = {
22
+ AUTH_REGISTER: { max: 40, timeWindow: HOUR },
23
+ AUTH_LOGIN: { max: 100, timeWindow: 15 * MIN },
24
+ AUTH_LOGOUT: { max: 200, timeWindow: 15 * MIN },
25
+ AUTH_REFRESH: { max: 200, timeWindow: 15 * MIN },
26
+ AUTH_ME: { max: 200, timeWindow: MIN },
27
+ AUTH_SESSIONS: { max: 30, timeWindow: MIN },
28
+ AUTH_LOGOUT_ALL: { max: 10, timeWindow: 15 * MIN },
29
+ AUTH_FORGOT_PASSWORD: { max: 20, timeWindow: 15 * MIN },
30
+ AUTH_RESET_PASSWORD: { max: 100, timeWindow: 15 * MIN },
31
+ USERS_UPDATE_PROFILE: { max: 30, timeWindow: MIN },
32
+ USERS_CHANGE_PASSWORD: { max: 10, timeWindow: 15 * MIN },
33
+ USERS_DELETE_ACCOUNT: { max: 10, timeWindow: MIN },
34
+ USERS_UPLOAD_AVATAR: { max: 10, timeWindow: MIN },
35
+ USERS_DELETE_AVATAR: { max: 30, timeWindow: MIN },
36
+ FILES_GET: { max: 100, timeWindow: MIN },
37
+ ADMIN_DEFAULT: { max: 30, timeWindow: MIN },
38
+ };
39
+ const EXPECTED_EMAIL_MODULE = {
40
+ AUTH_SEND_VERIFICATION: { max: 10, timeWindow: 15 * MIN },
41
+ AUTH_VERIFY_ACCOUNT: { max: 10, timeWindow: 15 * MIN },
42
+ };
43
+
44
+ describe('shipped rate limits', () => {
45
+ it('match the agreed table exactly, entry by entry', () => {
46
+ const limits = RATE_LIMITS as Record<string, unknown>;
47
+ const hasEmailModule = 'AUTH_SEND_VERIFICATION' in limits;
48
+ const expected = hasEmailModule ? { ...EXPECTED, ...EXPECTED_EMAIL_MODULE } : EXPECTED;
49
+ expect(Object.keys(limits).sort()).toEqual(Object.keys(expected).sort());
50
+ for (const [name, limit] of Object.entries(expected)) {
51
+ expect({ name, ...(limits[name] as object) }).toEqual({ name, ...limit });
52
+ }
53
+ });
54
+
55
+ it('default limit is 200 per minute, email cap is 3 per address per hour', () => {
56
+ expect(DEFAULT_LIMIT).toEqual({ max: 200, timeWindow: MIN });
57
+ expect(EMAIL_PER_ADDRESS).toEqual({ max: 3, timeWindow: HOUR });
58
+ });
59
+ });
60
+
61
+ describe('RATE_LIMIT_OVERRIDES parsing', () => {
62
+ it('parses windows in seconds, minutes and hours', () => {
63
+ expect(parseWindow('30s')).toBe(30_000);
64
+ expect(parseWindow('15m')).toBe(15 * MIN);
65
+ expect(parseWindow('1h')).toBe(HOUR);
66
+ });
67
+
68
+ it('rejects malformed windows', () => {
69
+ for (const bad of ['15', '0m', '1d', '1.5h', 'm', '-1m']) {
70
+ expect(() => parseWindow(bad)).toThrow(RateLimitConfigError);
71
+ }
72
+ });
73
+
74
+ it('parses a list, ignoring spaces and empty items', () => {
75
+ const map = parseOverrides(' AUTH_LOGIN=50/15m , DEFAULT=300/1m,,EMAIL_PER_ADDRESS=5/1h ');
76
+ expect(Object.fromEntries(map)).toEqual({
77
+ AUTH_LOGIN: { max: 50, timeWindow: 15 * MIN },
78
+ DEFAULT: { max: 300, timeWindow: MIN },
79
+ EMAIL_PER_ADDRESS: { max: 5, timeWindow: HOUR },
80
+ });
81
+ expect(parseOverrides(undefined).size).toBe(0);
82
+ expect(parseOverrides(' ').size).toBe(0);
83
+ });
84
+
85
+ it('rejects bad entries with a message that names them', () => {
86
+ expect(() => parseOverrides('AUTH_LOGIN=abc')).toThrow(/AUTH_LOGIN=abc/);
87
+ expect(() => parseOverrides('AUTH_LOGIN=0/1m')).toThrow(/invalid max/);
88
+ expect(() => parseOverrides('auth_login=5/1m')).toThrow(/expected NAME=MAX\/WINDOW/);
89
+ expect(() => parseOverrides('AUTH_LOGIN=5/1m,AUTH_LOGIN=6/1m')).toThrow(/more than once/);
90
+ expect(() => parseOverrides('AUTH_LOGIN=5/1d')).toThrow(/invalid window/);
91
+ });
92
+
93
+ it('finds names that match no limit', () => {
94
+ const map = parseOverrides('AUTH_LOGN=5/1m,DEFAULT=1/1m');
95
+ expect(unknownOverrideNames(map, ['AUTH_LOGIN', 'DEFAULT'])).toEqual(['AUTH_LOGN']);
96
+ });
97
+ });
98
+
99
+ describe('rate-limit.config at boot', () => {
100
+ afterEach(() => {
101
+ vi.doUnmock('@config/env.js');
102
+ vi.doUnmock('@libs/logger.js');
103
+ vi.restoreAllMocks();
104
+ vi.resetModules();
105
+ delete process.env.RATE_LIMIT_AUTH_LOGIN_MAX;
106
+ });
107
+
108
+ async function loadWith(overrides: Partial<typeof realEnv>): Promise<typeof import('../rate-limit.config.js')> {
109
+ vi.resetModules();
110
+ vi.doMock('@config/env.js', () => ({ env: { ...realEnv, ...overrides } }));
111
+ return import('../rate-limit.config.js');
112
+ }
113
+
114
+ it('applies an override, then the multiplier on top', async () => {
115
+ const mod = await loadWith({ RATE_LIMIT_OVERRIDES: 'AUTH_LOGIN=5/30s,DEFAULT=300/2m', RATE_LIMIT_MULTIPLIER: 2 });
116
+ expect(mod.RATE_LIMITS.AUTH_LOGIN).toEqual({ max: 10, timeWindow: 30_000 });
117
+ expect(mod.DEFAULT_LIMIT).toEqual({ max: 600, timeWindow: 2 * MIN });
118
+ expect(mod.RATE_LIMITS.AUTH_REGISTER).toEqual({ max: 80, timeWindow: HOUR }); // multiplier only
119
+ });
120
+
121
+ it('turns every limit into 1,000,000 when RATE_LIMIT_ENABLED is off', async () => {
122
+ const mod = await loadWith({ RATE_LIMIT_ENABLED: false });
123
+ expect(mod.RATE_LIMITS.AUTH_LOGIN.max).toBe(1_000_000);
124
+ expect(mod.EMAIL_PER_ADDRESS.max).toBe(1_000_000);
125
+ });
126
+
127
+ it('stops the server on an unknown name, listing the valid names', async () => {
128
+ const exit = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
129
+ throw new Error(`exit ${code}`);
130
+ }) as never);
131
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
132
+ await expect(loadWith({ RATE_LIMIT_OVERRIDES: 'AUTH_LOGN=5/1m' })).rejects.toThrow('exit 1');
133
+ expect(exit).toHaveBeenCalledWith(1);
134
+ const message = String(error.mock.calls[0]?.[0]);
135
+ expect(message).toContain('unknown name(s): AUTH_LOGN');
136
+ expect(message).toContain('Valid names: AUTH_REGISTER, AUTH_LOGIN');
137
+ expect(message).toContain('DEFAULT, EMAIL_PER_ADDRESS');
138
+ });
139
+
140
+ it('stops the server on a malformed value', async () => {
141
+ vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
142
+ throw new Error(`exit ${code}`);
143
+ }) as never);
144
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
145
+ await expect(loadWith({ RATE_LIMIT_OVERRIDES: 'AUTH_LOGIN=lots' })).rejects.toThrow('exit 1');
146
+ expect(String(error.mock.calls[0]?.[0])).toContain('Invalid RATE_LIMIT_OVERRIDES: invalid entry "AUTH_LOGIN=lots"');
147
+ });
148
+
149
+ it('warns once that a removed variable is ignored, and ignores it', async () => {
150
+ const warn = vi.fn();
151
+ vi.doMock('@libs/logger.js', () => ({ logger: { warn, info: vi.fn(), error: vi.fn(), debug: vi.fn() } }));
152
+ process.env.RATE_LIMIT_AUTH_LOGIN_MAX = '10';
153
+ const mod = await loadWith({});
154
+ expect(warn).toHaveBeenCalledTimes(1);
155
+ expect(String(warn.mock.calls[0]?.[0])).toContain('RATE_LIMIT_AUTH_LOGIN_MAX is no longer read');
156
+ expect(mod.RATE_LIMITS.AUTH_LOGIN.max).toBe(100);
157
+ });
158
+ });