create-tigra 3.2.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 (209) hide show
  1. package/README.md +81 -12
  2. package/bin/create-tigra.js +495 -472
  3. package/lib/patchers/email-verification.patcher.js +160 -44
  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 +81 -21
  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 +38 -19
  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 +18 -4
  35. package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
  36. package/template/client/src/features/auth/hooks/useAuth.ts +27 -7
  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/features/auth/types/auth.types.ts +3 -0
  41. package/template/client/src/instrumentation-client.ts +9 -1
  42. package/template/client/src/instrumentation.ts +6 -0
  43. package/template/client/src/lib/api/__tests__/axios.config.test.ts +183 -0
  44. package/template/client/src/lib/api/api.types.ts +14 -0
  45. package/template/client/src/lib/api/axios.config.ts +101 -15
  46. package/template/client/src/lib/api/hard-redirect.ts +8 -0
  47. package/template/client/src/lib/api/session-events.ts +29 -0
  48. package/template/client/src/lib/constants/routes.ts +12 -0
  49. package/template/client/src/lib/observability/sentry-scrub.ts +71 -0
  50. package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
  51. package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
  52. package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
  53. package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
  54. package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
  55. package/template/client/src/lib/utils/error.ts +86 -1
  56. package/template/client/src/lib/utils/form.ts +31 -0
  57. package/template/client/src/lib/utils/paths.ts +18 -0
  58. package/template/client/src/lib/utils/security.ts +37 -0
  59. package/template/client/src/lib/utils/session-marker.ts +24 -0
  60. package/template/client/src/{middleware.ts → proxy.ts} +25 -11
  61. package/template/client/src/store/__tests__/store.test.ts +44 -0
  62. package/template/client/src/store/index.ts +26 -8
  63. package/template/client/vitest.config.mts +48 -0
  64. package/template/server/.env.example +280 -269
  65. package/template/server/.env.example.production +283 -236
  66. package/template/server/AGENTS.md +13 -4
  67. package/template/server/Dockerfile +181 -14
  68. package/template/server/docker-compose.yml +4 -2
  69. package/template/server/docs/deployment.md +63 -0
  70. package/template/server/docs/logging.md +52 -4
  71. package/template/server/docs/rate-limits.md +153 -0
  72. package/template/server/docs/testing.md +63 -0
  73. package/template/server/eslint.config.mjs +19 -0
  74. package/template/server/package-lock.json +8784 -8743
  75. package/template/server/package.json +79 -75
  76. package/template/server/prisma/migrations/0_init/migration.sql +82 -0
  77. package/template/server/prisma/migrations/migration_lock.toml +3 -0
  78. package/template/server/prisma/schema.prisma +19 -6
  79. package/template/server/prisma/seed.ts +13 -5
  80. package/template/server/scripts/check-heic.mjs +40 -0
  81. package/template/server/scripts/check-sharp.mjs +53 -0
  82. package/template/server/src/__tests__/routes.integration.test.ts +280 -0
  83. package/template/server/src/app.ts +248 -335
  84. package/template/server/src/config/__tests__/env.test.ts +219 -0
  85. package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
  86. package/template/server/src/config/env.ts +326 -171
  87. package/template/server/src/config/rate-limit.config.ts +157 -106
  88. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +110 -0
  89. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
  90. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
  91. package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
  92. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +81 -65
  93. package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
  94. package/template/server/src/jobs/index.ts +12 -2
  95. package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
  96. package/template/server/src/jobs/schedule.ts +50 -0
  97. package/template/server/src/libs/__tests__/auth.test.ts +168 -0
  98. package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
  99. package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
  100. package/template/server/src/libs/__tests__/cookies.test.ts +113 -0
  101. package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
  102. package/template/server/src/libs/__tests__/email.test.ts +68 -0
  103. package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
  104. package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
  105. package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
  106. package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
  107. package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
  108. package/template/server/src/libs/__tests__/http.test.ts +74 -2
  109. package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
  110. package/template/server/src/libs/__tests__/logger.test.ts +50 -0
  111. package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
  112. package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
  113. package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
  114. package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
  115. package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
  116. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
  117. package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
  118. package/template/server/src/libs/__tests__/redis.test.ts +59 -0
  119. package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
  120. package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
  121. package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
  122. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -0
  123. package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
  124. package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
  125. package/template/server/src/libs/account-status.ts +52 -0
  126. package/template/server/src/libs/auth.ts +51 -12
  127. package/template/server/src/libs/client-ip.ts +158 -77
  128. package/template/server/src/libs/cloudflare-ranges.ts +132 -0
  129. package/template/server/src/libs/cookies.ts +91 -24
  130. package/template/server/src/libs/email-quota.ts +74 -0
  131. package/template/server/src/libs/email.ts +46 -9
  132. package/template/server/src/libs/error-handler.ts +111 -0
  133. package/template/server/src/libs/health-routes.ts +53 -0
  134. package/template/server/src/libs/http.ts +139 -47
  135. package/template/server/src/libs/ip-address.ts +37 -0
  136. package/template/server/src/libs/ip-block.ts +284 -220
  137. package/template/server/src/libs/logger.ts +41 -12
  138. package/template/server/src/libs/monitoring.ts +131 -42
  139. package/template/server/src/libs/observability/sentry.ts +80 -0
  140. package/template/server/src/libs/origin-check.ts +9 -7
  141. package/template/server/src/libs/prisma.ts +47 -4
  142. package/template/server/src/libs/query-counter.ts +71 -59
  143. package/template/server/src/libs/rate-limiting.ts +110 -0
  144. package/template/server/src/libs/redis-required.ts +28 -0
  145. package/template/server/src/libs/redis.ts +108 -18
  146. package/template/server/src/libs/request-id.ts +18 -0
  147. package/template/server/src/libs/requestLogger.ts +112 -17
  148. package/template/server/src/libs/safe-http.ts +101 -0
  149. package/template/server/src/libs/shutdown.ts +87 -0
  150. package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
  151. package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +143 -0
  152. package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
  153. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
  154. package/template/server/src/libs/storage/file-storage.service.ts +104 -83
  155. package/template/server/src/libs/storage/file-validator.ts +48 -46
  156. package/template/server/src/libs/storage/image-optimizer.service.ts +78 -72
  157. package/template/server/src/libs/token-hash.ts +18 -0
  158. package/template/server/src/libs/url-safety.ts +127 -121
  159. package/template/server/src/libs/validation-errors.ts +86 -0
  160. package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
  161. package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
  162. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
  163. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
  164. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
  165. package/template/server/src/modules/admin/admin.controller.ts +66 -49
  166. package/template/server/src/modules/admin/admin.repo.ts +56 -13
  167. package/template/server/src/modules/admin/admin.routes.ts +48 -2
  168. package/template/server/src/modules/admin/admin.schemas.ts +18 -6
  169. package/template/server/src/modules/admin/admin.service.ts +73 -7
  170. package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
  171. package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
  172. package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
  173. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +332 -49
  174. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
  175. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
  176. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
  177. package/template/server/src/modules/auth/auth.controller.ts +133 -128
  178. package/template/server/src/modules/auth/auth.repo.ts +60 -42
  179. package/template/server/src/modules/auth/auth.schemas.ts +5 -2
  180. package/template/server/src/modules/auth/auth.service.ts +197 -109
  181. package/template/server/src/modules/auth/session.repo.ts +12 -12
  182. package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
  183. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
  184. package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
  185. package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
  186. package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
  187. package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
  188. package/template/server/src/modules/users/users.controller.ts +9 -38
  189. package/template/server/src/modules/users/users.repo.ts +25 -7
  190. package/template/server/src/modules/users/users.routes.ts +3 -22
  191. package/template/server/src/modules/users/users.schemas.ts +15 -9
  192. package/template/server/src/modules/users/users.service.ts +105 -93
  193. package/template/server/src/scripts/make-admin.ts +48 -0
  194. package/template/server/src/server.ts +48 -26
  195. package/template/server/src/shared/errors/AppError.ts +27 -1
  196. package/template/server/src/shared/errors/errors.ts +42 -5
  197. package/template/server/src/shared/responses/successResponse.ts +22 -3
  198. package/template/server/src/shared/types/index.ts +7 -0
  199. package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
  200. package/template/server/src/test/integration-helpers.ts +343 -0
  201. package/template/server/src/test/integration-services.ts +74 -0
  202. package/template/server/src/test/integration.global-setup.ts +144 -0
  203. package/template/server/src/test/integration.setup.ts +35 -158
  204. package/template/server/src/test/setup.ts +23 -8
  205. package/template/server/tsconfig.build.json +1 -1
  206. package/template/server/tsconfig.json +1 -0
  207. package/template/server/vitest.config.ts +17 -4
  208. package/template/server/vitest.integration.config.ts +18 -13
  209. package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Where the integration tests get MySQL and Redis from, and the guards that
3
+ * keep them away from real data. Pure (no I/O), so the rules are unit-tested
4
+ * (src/test/__tests__/integration-services.test.ts); integration.setup.ts
5
+ * applies them.
6
+ *
7
+ * Two modes:
8
+ * - "containers" (neither variable set): Testcontainers starts a throwaway
9
+ * MySQL and Redis. What CI uses; needs Docker.
10
+ * - "external" (both set): INTEGRATION_DATABASE_URL and INTEGRATION_REDIS_URL
11
+ * point at services that already run, for machines where starting
12
+ * containers is not wanted. The tests DROP every table in that database and
13
+ * FLUSH that Redis database, so both must be visibly disposable: the
14
+ * database name ends in "_test" and the Redis URL names a database 1-15.
15
+ *
16
+ * Error messages name the rule and never the URL: it carries a password.
17
+ */
18
+
19
+ export type IntegrationMode =
20
+ | { kind: 'containers' }
21
+ | { kind: 'external'; databaseUrl: string; redisUrl: string };
22
+
23
+ /** The database name in a mysql:// URL, decoded; '' when there is none or the URL is malformed. */
24
+ export function databaseName(url: string): string {
25
+ try {
26
+ return decodeURIComponent(new URL(url).pathname.replace(/^\//, ''));
27
+ } catch {
28
+ return '';
29
+ }
30
+ }
31
+
32
+ /** The Redis database number in a redis:// URL path (redis://host:6379/15), or null when missing or not a number. */
33
+ export function redisDatabaseIndex(url: string): number | null {
34
+ try {
35
+ const path = new URL(url).pathname.replace(/^\//, '');
36
+ return /^\d+$/.test(path) ? Number(path) : null;
37
+ } catch {
38
+ return null;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Picks the mode from the environment. One variable without the other is a
44
+ * mistake (half a setup), so it is refused instead of silently falling back to
45
+ * containers.
46
+ */
47
+ export function pickIntegrationMode(env: NodeJS.ProcessEnv): IntegrationMode {
48
+ const databaseUrl = env.INTEGRATION_DATABASE_URL?.trim() || undefined;
49
+ const redisUrl = env.INTEGRATION_REDIS_URL?.trim() || undefined;
50
+ if (!databaseUrl && !redisUrl) return { kind: 'containers' };
51
+ if (!databaseUrl || !redisUrl) {
52
+ throw new Error(
53
+ 'Set both INTEGRATION_DATABASE_URL and INTEGRATION_REDIS_URL to use existing services, or neither to use Testcontainers.',
54
+ );
55
+ }
56
+ assertDisposable(databaseUrl, redisUrl);
57
+ return { kind: 'external', databaseUrl, redisUrl };
58
+ }
59
+
60
+ /** Refuses services that could hold real data, before anything connects to them. */
61
+ export function assertDisposable(databaseUrl: string, redisUrl: string): void {
62
+ if (!databaseName(databaseUrl).endsWith('_test')) {
63
+ throw new Error(
64
+ 'INTEGRATION_DATABASE_URL must name a database ending in "_test": the integration tests drop every table in it.',
65
+ );
66
+ }
67
+ const index = redisDatabaseIndex(redisUrl);
68
+ if (index === null || index < 1 || index > 15) {
69
+ throw new Error(
70
+ 'INTEGRATION_REDIS_URL must end with a Redis database number from 1 to 15 (for example redis://localhost:6379/15): ' +
71
+ 'the integration tests flush that database, and database 0 (the default) is refused.',
72
+ );
73
+ }
74
+ }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Integration tests, once per run: get MySQL and Redis ready and hand their
3
+ * addresses to every test file (vitest.integration.config.ts → globalSetup).
4
+ * Runs in Vitest's main process before any test file; each file then reads
5
+ * the addresses with `inject('integration')` (src/test/integration.setup.ts).
6
+ *
7
+ * ── Where MySQL and Redis come from (rules in ./integration-services.ts) ───
8
+ * - Neither INTEGRATION_DATABASE_URL nor INTEGRATION_REDIS_URL set:
9
+ * Testcontainers starts a throwaway MySQL 8.4 and Redis 7. This is what CI
10
+ * does; it needs Docker.
11
+ * - Both set: those already-running services are used and no container is
12
+ * started. Every table in that database is dropped and that Redis database
13
+ * is flushed first, so the database name must end in "_test" and the Redis
14
+ * URL must name a database 1-15; anything else stops the run before it
15
+ * connects.
16
+ *
17
+ * ── The schema comes from the shipped migrations ───────────────────────────
18
+ * `prisma migrate deploy` applies prisma/migrations, exactly what the
19
+ * production container runs at start, so a migration that does not match the
20
+ * code fails here. (It used to be `prisma db push`, which tested the schema
21
+ * file but never the migrations a project actually ships.) The tables are
22
+ * dropped by emptyDatabase below, not by `prisma migrate reset`: Prisma
23
+ * refuses that command when an AI agent runs it, and agents run these tests.
24
+ *
25
+ * All test files share this one database and Redis, so each test creates its
26
+ * own uniquely named data, and the files run one after another.
27
+ */
28
+ import { execSync } from 'node:child_process';
29
+ import { fileURLToPath } from 'node:url';
30
+ import path from 'node:path';
31
+ import os from 'node:os';
32
+ import { Redis } from 'ioredis';
33
+ import type { TestProject } from 'vitest/node';
34
+ import { pickIntegrationMode } from './integration-services.js';
35
+
36
+ /** What every integration test file receives (see integration.setup.ts). */
37
+ export interface IntegrationContext {
38
+ mode: 'containers' | 'external';
39
+ databaseUrl: string;
40
+ redisUrl: string;
41
+ uploadPublicDir: string;
42
+ uploadPrivateDir: string;
43
+ }
44
+
45
+ declare module 'vitest' {
46
+ export interface ProvidedContext {
47
+ integration: IntegrationContext;
48
+ }
49
+ }
50
+
51
+ const serverRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
52
+
53
+ /** Starts a throwaway MySQL and Redis. Imported lazily so the external mode never loads Docker code. */
54
+ async function startContainers(): Promise<{ databaseUrl: string; redisUrl: string; stop: () => Promise<void> }> {
55
+ const [{ MySqlContainer }, { RedisContainer }] = await Promise.all([
56
+ import('@testcontainers/mysql'),
57
+ import('@testcontainers/redis'),
58
+ ]);
59
+ const mysql = await new MySqlContainer('mysql:8.4')
60
+ .withDatabase('test_db')
61
+ .withUsername('test')
62
+ .withUserPassword('test')
63
+ .withRootPassword('rootpass')
64
+ .start();
65
+ const redis = await new RedisContainer('redis:7-alpine').start();
66
+ return {
67
+ // MySqlContainer.getConnectionUri() returns `mysql://user:pass@host:port/db`
68
+ // — exactly Prisma's DATABASE_URL shape.
69
+ databaseUrl: mysql.getConnectionUri(),
70
+ redisUrl: redis.getConnectionUrl(),
71
+ stop: async (): Promise<void> => {
72
+ await Promise.allSettled([redis.stop(), mysql.stop()]);
73
+ },
74
+ };
75
+ }
76
+
77
+ /**
78
+ * Drops every table in the guarded database, `_prisma_migrations` included,
79
+ * so migrate deploy starts from nothing. The interactive transaction pins one
80
+ * connection, which the session-level FOREIGN_KEY_CHECKS switch needs.
81
+ */
82
+ async function emptyDatabase(databaseUrl: string): Promise<void> {
83
+ const { PrismaClient } = await import('@prisma/client');
84
+ const client = new PrismaClient({ datasourceUrl: databaseUrl });
85
+ try {
86
+ await client.$transaction(async (tx) => {
87
+ const tables = await tx.$queryRaw<{ name: string }[]>`
88
+ SELECT TABLE_NAME AS name FROM information_schema.TABLES
89
+ WHERE TABLE_SCHEMA = DATABASE() AND TABLE_TYPE = 'BASE TABLE'`;
90
+ if (tables.length === 0) return;
91
+ const list = tables.map(({ name }) => `\`${name.replace(/`/g, '``')}\``).join(', ');
92
+ await tx.$executeRawUnsafe('SET FOREIGN_KEY_CHECKS = 0');
93
+ await tx.$executeRawUnsafe(`DROP TABLE ${list}`);
94
+ await tx.$executeRawUnsafe('SET FOREIGN_KEY_CHECKS = 1');
95
+ });
96
+ } finally {
97
+ await client.$disconnect();
98
+ }
99
+ }
100
+
101
+ /** Empties the guarded Redis database. */
102
+ async function flushRedis(redisUrl: string): Promise<void> {
103
+ const redis = new Redis(redisUrl, { lazyConnect: true, maxRetriesPerRequest: 1 });
104
+ try {
105
+ await redis.connect();
106
+ await redis.flushdb();
107
+ } finally {
108
+ redis.disconnect();
109
+ }
110
+ }
111
+
112
+ export default async function setup(project: TestProject): Promise<() => Promise<void>> {
113
+ // Throws (with the rule, never the URL) on half a setup or services that do
114
+ // not look disposable, before anything connects.
115
+ const mode = pickIntegrationMode(process.env);
116
+ const services =
117
+ mode.kind === 'external'
118
+ ? { databaseUrl: mode.databaseUrl, redisUrl: mode.redisUrl, stop: async (): Promise<void> => {} }
119
+ : await startContainers();
120
+
121
+ if (mode.kind === 'external') {
122
+ await emptyDatabase(services.databaseUrl);
123
+ await flushRedis(services.redisUrl);
124
+ }
125
+ // Prisma prints the host and database name, never the password.
126
+ execSync('npx prisma migrate deploy', {
127
+ cwd: serverRoot,
128
+ env: { ...process.env, DATABASE_URL: services.databaseUrl },
129
+ stdio: 'inherit',
130
+ });
131
+
132
+ const uploadsRoot = path.join(os.tmpdir(), `create-tigra-uploads-${process.pid}`);
133
+ project.provide('integration', {
134
+ mode: mode.kind,
135
+ databaseUrl: services.databaseUrl,
136
+ redisUrl: services.redisUrl,
137
+ uploadPublicDir: path.join(uploadsRoot, 'public'),
138
+ uploadPrivateDir: path.join(uploadsRoot, 'private'),
139
+ });
140
+
141
+ // Teardown: stop the containers this run started; existing services keep
142
+ // the test data until the next run empties them.
143
+ return services.stop;
144
+ }
@@ -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
@@ -28,12 +29,13 @@ export const testUsers = {
28
29
  avatarUrl: null,
29
30
  role: 'USER' as const,
30
31
  isActive: true,
32
+ emailVerifiedAt: new Date('2024-01-01T00:00:00Z'),
31
33
  deletedAt: null,
32
- failedLoginAttempts: 0,
33
- lockedUntil: null,
34
34
  createdAt: new Date('2024-01-01T00:00:00Z'),
35
35
  updatedAt: new Date('2024-01-01T00:00:00Z'),
36
36
  },
37
+ // Banned by an admin (isActive=false). Its email was verified long ago:
38
+ // a ban is independent of email verification.
37
39
  inactiveUser: {
38
40
  id: 'test-user-id-2',
39
41
  email: 'inactive@example.com',
@@ -43,9 +45,23 @@ export const testUsers = {
43
45
  avatarUrl: null,
44
46
  role: 'USER' as const,
45
47
  isActive: false,
48
+ emailVerifiedAt: new Date('2024-01-01T00:00:00Z'),
49
+ deletedAt: null,
50
+ createdAt: new Date('2024-01-01T00:00:00Z'),
51
+ updatedAt: new Date('2024-01-01T00:00:00Z'),
52
+ },
53
+ // Registered while REQUIRE_USER_VERIFICATION was on and never verified.
54
+ unverifiedUser: {
55
+ id: 'test-user-id-4',
56
+ email: 'unverified@example.com',
57
+ password: '$2a$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewY5GyYiIJU6u1Em',
58
+ firstName: 'Unverified',
59
+ lastName: 'User',
60
+ avatarUrl: null,
61
+ role: 'USER' as const,
62
+ isActive: true,
63
+ emailVerifiedAt: null,
46
64
  deletedAt: null,
47
- failedLoginAttempts: 0,
48
- lockedUntil: null,
49
65
  createdAt: new Date('2024-01-01T00:00:00Z'),
50
66
  updatedAt: new Date('2024-01-01T00:00:00Z'),
51
67
  },
@@ -58,9 +74,8 @@ export const testUsers = {
58
74
  avatarUrl: null,
59
75
  role: 'ADMIN' as const,
60
76
  isActive: true,
77
+ emailVerifiedAt: new Date('2024-01-01T00:00:00Z'),
61
78
  deletedAt: null,
62
- failedLoginAttempts: 0,
63
- lockedUntil: null,
64
79
  createdAt: new Date('2024-01-01T00:00:00Z'),
65
80
  updatedAt: new Date('2024-01-01T00:00:00Z'),
66
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,