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
@@ -1,170 +1,47 @@
1
1
  /**
2
- * Integration test setup — REAL Testcontainers, NOT mocks.
3
- *
4
- * This file is the load-bearing piece of the money-path integration harness.
5
- * It is wired via `vitest.integration.config.ts` → `setupFiles`, and is SEPARATE
6
- * from the Docker-free unit `src/test/setup.ts` (which mocks env/DB/Redis).
2
+ * Integration tests, once per test file (vitest.integration.config.ts →
3
+ * setupFiles): the app's environment, pointed at the MySQL and Redis that
4
+ * integration.global-setup.ts prepared once for the whole run. SEPARATE from
5
+ * the Docker-free unit `src/test/setup.ts` (which mocks env/DB/Redis).
7
6
  *
8
7
  * ── The central gotcha: env-before-import ──────────────────────────────────
9
8
  * `src/config/env.ts` validates `process.env` at IMPORT time and calls
10
9
  * `process.exit(1)` if DATABASE_URL / JWT_SECRET / … are missing. So the
11
- * container connection strings MUST be in `process.env` BEFORE anything that
12
- * transitively imports `env.ts` (which is `@/app`, `@/libs/prisma`, etc.).
13
- *
14
- * How we guarantee that ordering:
15
- * 1. Vitest evaluates `setupFiles` — INCLUDING their top-level `await` — to
16
- * completion BEFORE it evaluates any test module. We start the containers
17
- * and run the schema sync here with TOP-LEVEL await, then populate
18
- * process.env.
19
- * 2. The test files themselves import `@/app` / `@/libs/prisma` LAZILY
20
- * (`await import(...)` inside `beforeAll`), so a test module's own static
21
- * import graph never evaluates `env.ts` before this setup has finished.
22
- *
23
- * ── Why a process-global singleton ─────────────────────────────────────────
24
- * Vitest runs `setupFiles` ONCE PER TEST FILE, not once for the whole run. With
25
- * `singleFork: true` (vitest.integration.config.ts) every test file shares ONE
26
- * worker process, so we boot the MySQL + Redis containers exactly once and cache
27
- * them on `globalThis`. The second (and later) test files reuse the running
28
- * containers instead of each spinning up their own pair and racing two
29
- * concurrent `prisma db push` invocations against a saturated Docker daemon
30
- * (which produced intermittent `P1001: can't reach database server`).
31
- *
32
- * ── Teardown ───────────────────────────────────────────────────────────────
33
- * Because the containers are shared across files, we CANNOT tear them down from
34
- * a per-file `afterAll` (the first file to finish would stop the DB out from
35
- * under the others). Instead we stop them once on the worker process's
36
- * `beforeExit`, and rely on Testcontainers' Ryuk reaper as the backstop — it
37
- * removes any container we started the moment this process dies, even on crash.
38
- *
39
- * The committed template ships NO `prisma/migrations/` directory (apps run
40
- * `prisma migrate dev` locally to author their first migration). `prisma migrate
41
- * deploy` therefore has nothing to apply against a fresh container. We use
42
- * `prisma db push` instead — it syncs the Prisma schema straight to the empty
43
- * container database, which is exactly what an ephemeral test DB wants.
10
+ * addresses MUST be in `process.env` BEFORE anything that transitively
11
+ * imports `env.ts` (which is `@/app`, `@/libs/prisma`, etc.):
12
+ * 1. Vitest evaluates `setupFiles` before it evaluates the test module.
13
+ * 2. Test files import `@/app` / `@/libs/prisma` LAZILY (`await import(...)`
14
+ * inside `beforeAll`), so their own static imports never evaluate env.ts
15
+ * first.
16
+ * Each test file runs with fresh modules, so a file may change process.env
17
+ * before its lazy import (the rate-limit tests switch limits on this way).
44
18
  */
45
- import { execSync } from 'node:child_process';
46
- import { fileURLToPath } from 'node:url';
47
- import path from 'node:path';
48
- import os from 'node:os';
49
- import { MySqlContainer, type StartedMySqlContainer } from '@testcontainers/mysql';
50
- import { RedisContainer, type StartedRedisContainer } from '@testcontainers/redis';
51
-
52
- const __filename = fileURLToPath(import.meta.url);
53
- const __dirname = path.dirname(__filename);
54
- const serverRoot = path.resolve(__dirname, '..', '..');
55
-
56
- interface IntegrationContainers {
57
- mysql: StartedMySqlContainer;
58
- redis: StartedRedisContainer;
59
- databaseUrl: string;
60
- redisUrl: string;
61
- uploadPublicDir: string;
62
- uploadPrivateDir: string;
63
- }
64
-
65
- // Singleton cache on globalThis — survives across the per-file setup invocations
66
- // that share one worker process (singleFork). Keyed under a unique symbol so it
67
- // can't collide with anything else on the global object.
68
- const CONTAINERS_KEY = Symbol.for('create-tigra.integration.containers');
69
- const TEARDOWN_KEY = Symbol.for('create-tigra.integration.teardownRegistered');
70
-
71
- type GlobalWithContainers = typeof globalThis & {
72
- [CONTAINERS_KEY]?: Promise<IntegrationContainers>;
73
- [TEARDOWN_KEY]?: boolean;
74
- };
75
-
76
- const g = globalThis as GlobalWithContainers;
19
+ import { inject } from 'vitest';
77
20
 
78
- async function bootContainers(): Promise<IntegrationContainers> {
79
- const mysql = await new MySqlContainer('mysql:8.0')
80
- .withDatabase('test_db')
81
- .withUsername('test')
82
- .withUserPassword('test')
83
- .withRootPassword('rootpass')
84
- .start();
21
+ const services = inject('integration');
85
22
 
86
- const redis = await new RedisContainer('redis:7-alpine').start();
87
-
88
- // MySqlContainer.getConnectionUri() returns `mysql://user:pass@host:port/db`
89
- // — exactly Prisma's DATABASE_URL shape.
90
- const databaseUrl = mysql.getConnectionUri();
91
- const redisUrl = redis.getConnectionUrl();
92
-
93
- // Populate env BEFORE any consumer of env.ts is imported.
94
- process.env.NODE_ENV = 'test';
95
- process.env.DATABASE_URL = databaseUrl;
96
- process.env.REDIS_URL = redisUrl;
97
- process.env.JWT_SECRET = 'integration-test-jwt-secret-at-least-32-chars-long';
98
- process.env.JWT_ACCESS_EXPIRY = '15m';
99
- process.env.JWT_REFRESH_EXPIRY = '7d';
100
- // Tests don't send email and don't activate via the verify flow — register
101
- // must mint tokens and login must work immediately, so disable verification.
102
- process.env.REQUIRE_USER_VERIFICATION = 'false';
103
- // This is a money-PATH harness, not a rate-limit test. Disabling the limiter
104
- // keeps the suite deterministic (no per-IP counters, no auto-block self-ban
105
- // across repeated register/login calls).
106
- process.env.RATE_LIMIT_ENABLED = 'false';
107
- // In NODE_ENV=test the app's CORS config (see app.ts) is NOT the dev "allow
108
- // all" branch — it reads CORS_ORIGIN, and an undefined value makes
109
- // @fastify/cors throw "Invalid CORS origin option" → 500 on EVERY request.
110
- // Pin a concrete origin so the real app boots a valid CORS policy.
111
- process.env.CORS_ORIGIN = 'http://localhost:3000';
112
-
113
- // Two-tier upload dirs under an isolated temp root, set BEFORE env.ts is ever
114
- // evaluated (the storage-service singleton reads env.UPLOAD_*_DIR at
115
- // construction, which happens when a test lazily imports @/app). The
116
- // files-route integration test writes fixtures directly into these dirs.
117
- const uploadsRoot = path.join(os.tmpdir(), `create-tigra-uploads-${process.pid}`);
118
- const uploadPublicDir = path.join(uploadsRoot, 'public');
119
- const uploadPrivateDir = path.join(uploadsRoot, 'private');
120
- process.env.UPLOAD_PUBLIC_DIR = uploadPublicDir;
121
- process.env.UPLOAD_PRIVATE_DIR = uploadPrivateDir;
122
-
123
- // Sync the Prisma schema into the fresh container DB. `db push` (not
124
- // `migrate deploy`) because the template ships no migrations. The container's
125
- // wait strategy already guarantees MySQL is accepting connections by here.
126
- execSync('npx prisma db push --skip-generate --accept-data-loss', {
127
- cwd: serverRoot,
128
- env: process.env,
129
- stdio: 'inherit',
130
- });
131
-
132
- return { mysql, redis, databaseUrl, redisUrl, uploadPublicDir, uploadPrivateDir };
133
- }
134
-
135
- // Boot once (or await the in-flight boot) — TOP-LEVEL await, completes before
136
- // any test module is evaluated.
137
- if (!g[CONTAINERS_KEY]) {
138
- g[CONTAINERS_KEY] = bootContainers();
139
- }
140
- const containers = await g[CONTAINERS_KEY];
141
-
142
- // Subsequent per-file setup runs need env populated too (the boot only set it on
143
- // the first run). Re-assert from the cached values — cheap and idempotent.
144
- process.env.DATABASE_URL = containers.databaseUrl;
145
- process.env.REDIS_URL = containers.redisUrl;
146
23
  process.env.NODE_ENV = 'test';
147
- process.env.JWT_SECRET ??= 'integration-test-jwt-secret-at-least-32-chars-long';
24
+ process.env.DATABASE_URL = services.databaseUrl;
25
+ process.env.REDIS_URL = services.redisUrl;
26
+ process.env.JWT_SECRET = 'integration-test-jwt-secret-at-least-32-chars-long';
27
+ process.env.JWT_ACCESS_EXPIRY = '15m';
28
+ process.env.JWT_REFRESH_EXPIRY = '7d';
29
+ // Register mints tokens and login works at once, without the verify flow;
30
+ // the email module's own tests switch verification on in their file.
148
31
  process.env.REQUIRE_USER_VERIFICATION = 'false';
32
+ // Rate limits are off by default so repeated register/login calls stay
33
+ // deterministic (no per-IP counters, no auto-block self-ban). The rate-limit
34
+ // test file switches them on for itself.
149
35
  process.env.RATE_LIMIT_ENABLED = 'false';
36
+ // In NODE_ENV=test the app's CORS config (see app.ts) is NOT the dev "allow
37
+ // all" branch: it uses the checked CORS_ORIGIN list (env.CORS_ORIGINS).
38
+ // Pin a concrete origin so the real app boots a realistic CORS policy.
150
39
  process.env.CORS_ORIGIN = 'http://localhost:3000';
151
- process.env.UPLOAD_PUBLIC_DIR = containers.uploadPublicDir;
152
- process.env.UPLOAD_PRIVATE_DIR = containers.uploadPrivateDir;
153
-
154
- // Register the teardown exactly once for the whole run. Tied to the worker
155
- // process lifecycle (NOT a per-file afterAll, which would stop the shared
156
- // containers while later files still need them). Ryuk is the crash-safe backstop.
157
- if (!g[TEARDOWN_KEY]) {
158
- g[TEARDOWN_KEY] = true;
159
- process.once('beforeExit', () => {
160
- void containers.redis.stop();
161
- void containers.mysql.stop();
162
- });
163
- }
164
-
165
- export const containerInfo = {
166
- databaseUrl: containers.databaseUrl,
167
- redisUrl: containers.redisUrl,
168
- uploadPublicDir: containers.uploadPublicDir,
169
- uploadPrivateDir: containers.uploadPrivateDir,
170
- };
40
+ // Two-tier upload dirs under an isolated temp root, set BEFORE env.ts is ever
41
+ // evaluated (the storage-service singleton reads env.UPLOAD_*_DIR at
42
+ // construction, which happens when a test lazily imports @/app).
43
+ process.env.UPLOAD_PUBLIC_DIR = services.uploadPublicDir;
44
+ process.env.UPLOAD_PRIVATE_DIR = services.uploadPrivateDir;
45
+
46
+ /** The prepared services (addresses and upload folders) for tests that need them directly. */
47
+ export const integrationServices = services;
@@ -13,8 +13,9 @@ process.env.JWT_ACCESS_EXPIRY = '15m';
13
13
  process.env.JWT_REFRESH_EXPIRY = '7d';
14
14
  process.env.PORT = '3000';
15
15
  process.env.HOST = '0.0.0.0';
16
- // REQUIRE_USER_VERIFICATION defaults to 'true', and env.ts exits when it is
17
- // enabled without RESEND_API_KEY. Tests don't send email — disable it.
16
+ // Pinned off (the template default; the email module switches the default to
17
+ // true): env.ts exits when it is on without RESEND_API_KEY, and tests send no
18
+ // email. Tests that need it on switch it explicitly.
18
19
  process.env.REQUIRE_USER_VERIFICATION = 'false';
19
20
 
20
21
  // Test user data
@@ -30,8 +31,6 @@ export const testUsers = {
30
31
  isActive: true,
31
32
  emailVerifiedAt: new Date('2024-01-01T00:00:00Z'),
32
33
  deletedAt: null,
33
- failedLoginAttempts: 0,
34
- lockedUntil: null,
35
34
  createdAt: new Date('2024-01-01T00:00:00Z'),
36
35
  updatedAt: new Date('2024-01-01T00:00:00Z'),
37
36
  },
@@ -48,8 +47,6 @@ export const testUsers = {
48
47
  isActive: false,
49
48
  emailVerifiedAt: new Date('2024-01-01T00:00:00Z'),
50
49
  deletedAt: null,
51
- failedLoginAttempts: 0,
52
- lockedUntil: null,
53
50
  createdAt: new Date('2024-01-01T00:00:00Z'),
54
51
  updatedAt: new Date('2024-01-01T00:00:00Z'),
55
52
  },
@@ -65,8 +62,6 @@ export const testUsers = {
65
62
  isActive: true,
66
63
  emailVerifiedAt: null,
67
64
  deletedAt: null,
68
- failedLoginAttempts: 0,
69
- lockedUntil: null,
70
65
  createdAt: new Date('2024-01-01T00:00:00Z'),
71
66
  updatedAt: new Date('2024-01-01T00:00:00Z'),
72
67
  },
@@ -81,8 +76,6 @@ export const testUsers = {
81
76
  isActive: true,
82
77
  emailVerifiedAt: new Date('2024-01-01T00:00:00Z'),
83
78
  deletedAt: null,
84
- failedLoginAttempts: 0,
85
- lockedUntil: null,
86
79
  createdAt: new Date('2024-01-01T00:00:00Z'),
87
80
  updatedAt: new Date('2024-01-01T00:00:00Z'),
88
81
  },
@@ -1,4 +1,4 @@
1
1
  {
2
2
  "extends": "./tsconfig.json",
3
- "exclude": ["node_modules", "dist", "src/test", "src/**/*.test.ts", "src/**/*.spec.ts"]
3
+ "exclude": ["node_modules", "dist", "src/test", "src/**/*.test.ts", "src/**/*.spec.ts", "src/**/__tests__/**"]
4
4
  }
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "compilerOptions": {
3
3
  "target": "ES2020",
4
+ "lib": ["ES2023"],
4
5
  "module": "NodeNext",
5
6
  "moduleResolution": "NodeNext",
6
7
  "strict": true,
@@ -8,21 +8,34 @@ export default defineConfig({
8
8
  coverage: {
9
9
  provider: 'v8',
10
10
  reporter: ['text', 'json', 'html', 'lcov'],
11
+ // Every source file counts, also the ones no unit test loads (Vitest 4
12
+ // reports only loaded files without this, which made the number look
13
+ // better than it was). Type-only files and test helpers are left out.
14
+ include: ['src/**/*.ts'],
11
15
  exclude: [
12
16
  'node_modules/**',
13
17
  'dist/**',
14
18
  '**/*.config.ts',
15
19
  '**/*.config.js',
20
+ '**/*.d.ts',
16
21
  '**/test/**',
17
22
  '**/__tests__/**',
23
+ 'src/shared/types/**',
18
24
  'prisma/**',
19
25
  'scripts/**',
20
26
  ],
27
+ // A ratchet, not a target: the unit suite's real numbers when they were
28
+ // set (2026-10-20), rounded down, taken from a project made with the
29
+ // email-verification module (its code adds lines no unit test covers, so
30
+ // it sits about one point below a plain project). `npm run test:coverage`
31
+ // (and CI) fails if coverage drops below them; raise them when tests are
32
+ // added. Routes and controllers are tested by the integration suite
33
+ // instead (npm run test:integration), which this gate does not count.
21
34
  thresholds: {
22
- lines: 80,
23
- functions: 80,
24
- branches: 80,
25
- statements: 80,
35
+ lines: 62,
36
+ functions: 56,
37
+ branches: 69,
38
+ statements: 62,
26
39
  // Money-path forward-contract: any future payments module is held to a
27
40
  // stricter bar than the 80% global gate. The scaffold ships no payments
28
41
  // module, so this glob matches nothing today and is vacuously satisfied;
@@ -2,16 +2,18 @@ import { defineConfig } from 'vitest/config';
2
2
  import { resolve } from 'path';
3
3
 
4
4
  /**
5
- * Integration test config — REAL Testcontainers (MySQL 8 + Redis), app.inject().
5
+ * Integration test config — REAL MySQL 8 + Redis, app.inject().
6
6
  *
7
7
  * Deliberately SEPARATE from the Docker-free unit `vitest.config.ts`:
8
8
  * - includes ONLY `*.integration.test.ts`
9
- * - uses `src/test/integration.setup.ts` (boots containers) — NOT the mocking
10
- * unit setup `src/test/setup.ts`
11
- * - runs serially in a single fork: the containers are shared process-wide and
12
- * started once via the setup file's top-level await, so parallel workers
13
- * must not fight over them or each re-boot Docker.
14
- * - generous timeouts: container boot + `prisma db push` is slow on a cold
9
+ * - `globalSetup` prepares MySQL and Redis ONCE per run (Testcontainers, or
10
+ * existing services named by INTEGRATION_DATABASE_URL and
11
+ * INTEGRATION_REDIS_URL) and applies prisma/migrations; see
12
+ * src/test/integration.global-setup.ts and docs/testing.md
13
+ * - `setupFiles` points each test file's env at them (integration.setup.ts),
14
+ * NOT the mocking unit setup `src/test/setup.ts`
15
+ * - files run one after another: they share one database and Redis
16
+ * - generous timeouts: container boot + migrations are slow on a cold
15
17
  * Docker daemon / first image pull.
16
18
  *
17
19
  * Run with: npm run test:integration
@@ -20,17 +22,20 @@ export default defineConfig({
20
22
  test: {
21
23
  globals: true,
22
24
  environment: 'node',
25
+ globalSetup: ['./src/test/integration.global-setup.ts'],
23
26
  setupFiles: ['./src/test/integration.setup.ts'],
24
27
  include: ['**/*.integration.test.ts'],
25
28
  exclude: ['node_modules', 'dist'],
26
- // Containers are shared — never parallelize across files or forks.
27
- // Vitest 4 flattened `poolOptions.forks.singleFork` to the top-level
28
- // `singleFork` option (the nested form is deprecated/removed).
29
+ // One file at a time: every file uses the same database and Redis (counts,
30
+ // limiter keys and IP block lists would otherwise cross between files).
31
+ // Each file still gets its own process and fresh modules, so a file can
32
+ // change the env (for example switch rate limits on) before importing the
33
+ // app. (A `singleFork` option sat here before; Vitest 4 has no such option,
34
+ // so it did nothing.)
29
35
  pool: 'forks',
30
- singleFork: true,
31
36
  fileParallelism: false,
32
- // Container boot + image pull + schema push can take well over a minute on
33
- // a cold daemon; the setup file does all of that under hookTimeout.
37
+ // Container boot + image pull + migrations can take well over a minute on a
38
+ // cold daemon; globalSetup does that once, before the first file.
34
39
  testTimeout: 120_000,
35
40
  hookTimeout: 120_000,
36
41
  teardownTimeout: 60_000,
@@ -1,71 +0,0 @@
1
- /**
2
- * Filename Sanitizer Utility
3
- *
4
- * Generates SEO-friendly, URL-safe filenames from user names.
5
- * Supports international characters including Georgian letters.
6
- */
7
-
8
- /**
9
- * Sanitizes text for use in filenames
10
- *
11
- * Rules:
12
- * - Convert to lowercase
13
- * - Replace spaces with hyphens
14
- * - Keep only: a-z, 0-9, hyphens, Georgian letters (ა-ჰ), common diacritics (à-ÿ)
15
- * - Replace multiple consecutive hyphens with single hyphen
16
- * - Remove leading/trailing hyphens
17
- *
18
- * @param text - Text to sanitize
19
- * @returns Sanitized filename-safe string
20
- *
21
- * @example
22
- * sanitizeForFilename("John Doe") // "john-doe"
23
- * sanitizeForFilename("მარიამ გელაშვილი") // "მარიამ-გელაშვილი"
24
- * sanitizeForFilename("José García-López") // "jose-garcia-lopez"
25
- * sanitizeForFilename("Anna Marie O'Brien") // "anna-marie-obrien"
26
- */
27
- export function sanitizeForFilename(text: string): string {
28
- return (
29
- text
30
- .toLowerCase()
31
- .trim()
32
- // Replace spaces with hyphens
33
- .replace(/\s+/g, '-')
34
- // Keep only: a-z, 0-9, hyphens, Georgian letters (ა-ჰ), common diacritics (à-ÿ)
35
- .replace(/[^a-z0-9\-ა-ჰà-ÿ]/g, '')
36
- // Replace multiple consecutive hyphens with single hyphen
37
- .replace(/-+/g, '-')
38
- // Remove leading/trailing hyphens
39
- .replace(/^-|-$/g, '')
40
- );
41
- }
42
-
43
- /**
44
- * Generates an SEO-friendly avatar filename based on user's name
45
- *
46
- * Format: {firstName}-{lastName}-avatar.{extension}
47
- *
48
- * @param firstName - User's first name
49
- * @param lastName - User's last name
50
- * @param extension - File extension (default: 'webp')
51
- * @returns SEO-friendly filename
52
- *
53
- * @example
54
- * generateAvatarFilename("John", "Doe") // "john-doe-avatar.webp"
55
- * generateAvatarFilename("მარიამ", "გელაშვილი") // "მარიამ-გელაშვილი-avatar.webp"
56
- * generateAvatarFilename("José", "García", "jpg") // "jose-garcia-avatar.jpg"
57
- */
58
- export function generateAvatarFilename(
59
- firstName: string,
60
- lastName: string,
61
- extension: string = 'webp'
62
- ): string {
63
- const sanitizedFirst = sanitizeForFilename(firstName);
64
- const sanitizedLast = sanitizeForFilename(lastName);
65
-
66
- // Handle edge case where sanitization results in empty string
67
- const first = sanitizedFirst || 'user';
68
- const last = sanitizedLast || 'avatar';
69
-
70
- return `${first}-${last}-avatar.${extension}`;
71
- }