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,82 +1,86 @@
1
- {
2
- "name": "{{PROJECT_NAME}}-server",
3
- "version": "1.0.0",
4
- "type": "module",
5
- "description": "",
6
- "main": "dist/server.js",
7
- "scripts": {
8
- "dev": "tsx watch src/server.ts",
9
- "build": "tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json",
10
- "start": "node dist/server.js",
11
- "test": "vitest run",
12
- "test:integration": "vitest run --config vitest.integration.config.ts",
13
- "test:watch": "vitest",
14
- "test:ui": "vitest --ui",
15
- "test:coverage": "vitest run --coverage",
16
- "prisma:generate": "prisma generate",
17
- "prisma:migrate:dev": "prisma migrate dev",
18
- "prisma:migrate:deploy": "prisma migrate deploy",
19
- "prisma:reset": "prisma migrate reset",
20
- "prisma:seed": "prisma db seed",
21
- "prisma:studio": "prisma studio",
22
- "lint": "eslint src/",
23
- "typecheck": "tsc --noEmit",
24
- "audit": "npm audit --audit-level=high",
25
- "redis:flush": "tsx scripts/flush-redis.ts",
26
- "docker:up": "docker compose up -d",
27
- "docker:tools": "docker compose --profile tools up -d",
28
- "docker:down": "docker compose --profile tools down",
29
- "docker:logs": "docker compose logs -f",
30
- "generate:env": "node -e \"import('fs').then(f=>{if(f.existsSync('.env'))console.log('.env already exists, skipping');else{f.copyFileSync('.env.example','.env');console.log('.env created from .env.example')}})\""
31
- },
32
- "prisma": {
33
- "seed": "tsx prisma/seed.ts"
34
- },
35
- "dependencies": {
36
- "@fastify/cookie": "^11.0.2",
37
- "@fastify/cors": "^11.2.0",
38
- "@fastify/helmet": "^13.0.2",
39
- "@fastify/jwt": "^10.1.0",
40
- "@fastify/multipart": "^9.0.2",
41
- "@fastify/rate-limit": "^10.3.0",
1
+ {
2
+ "name": "{{PROJECT_NAME}}-server",
3
+ "version": "1.0.0",
4
+ "engines": {
5
+ "node": ">=24"
6
+ },
7
+ "type": "module",
8
+ "description": "",
9
+ "main": "dist/server.js",
10
+ "scripts": {
11
+ "dev": "tsx watch src/server.ts",
12
+ "build": "tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json",
13
+ "start": "node dist/server.js",
14
+ "test": "vitest run",
15
+ "test:integration": "vitest run --config vitest.integration.config.ts",
16
+ "test:watch": "vitest",
17
+ "test:ui": "vitest --ui",
18
+ "test:coverage": "vitest run --coverage",
19
+ "prisma:generate": "prisma generate",
20
+ "prisma:migrate:dev": "prisma migrate dev",
21
+ "prisma:migrate:deploy": "prisma migrate deploy",
22
+ "prisma:reset": "prisma migrate reset",
23
+ "prisma:seed": "prisma db seed",
24
+ "prisma:studio": "prisma studio",
25
+ "lint": "eslint src/",
26
+ "typecheck": "tsc --noEmit",
27
+ "audit": "npm audit --audit-level=high",
28
+ "redis:flush": "tsx scripts/flush-redis.ts",
29
+ "docker:up": "docker compose up -d",
30
+ "docker:tools": "docker compose --profile tools up -d",
31
+ "docker:down": "docker compose --profile tools down",
32
+ "docker:logs": "docker compose logs -f",
33
+ "generate:env": "node -e \"import('fs').then(f=>{if(f.existsSync('.env'))console.log('.env already exists, skipping');else{f.copyFileSync('.env.example','.env');console.log('.env created from .env.example')}})\""
34
+ },
35
+ "prisma": {
36
+ "seed": "tsx prisma/seed.ts",
37
+ "make-admin": "tsx src/scripts/make-admin.ts"
38
+ },
39
+ "dependencies": {
40
+ "@fastify/cookie": "^11.0.2",
41
+ "@fastify/cors": "^11.2.0",
42
+ "@fastify/helmet": "^13.0.2",
43
+ "@fastify/jwt": "^10.1.0",
44
+ "@fastify/multipart": "^9.0.2",
45
+ "@fastify/rate-limit": "^10.3.0",
42
46
  "@fastify/static": "^10.1.4",
43
- "@prisma/client": "^6.19.3",
44
- "@sentry/node": "^10.62.0",
45
- "argon2": "^0.44.0",
47
+ "@prisma/client": "^6.19.3",
48
+ "@sentry/node": "^10.62.0",
49
+ "argon2": "^0.44.0",
46
50
  "axios": "^1.20.0",
47
- "dotenv": "^16.4.7",
51
+ "dotenv": "^16.4.7",
48
52
  "fastify": "^5.12.5",
49
- "fastify-type-provider-zod": "^6.1.0",
50
- "ioredis": "^5.9.2",
51
- "pino": "^10.3.1",
52
- "pino-pretty": "^13.1.3",
53
- "resend": "^6.9.4",
54
- "sharp": "^0.35.4",
53
+ "fastify-type-provider-zod": "^6.1.0",
54
+ "ioredis": "^5.9.2",
55
+ "pino": "^10.3.1",
56
+ "pino-pretty": "^13.1.3",
57
+ "resend": "^6.9.4",
58
+ "sharp": "^0.35.5",
55
59
  "uuid": "^14.0.2",
56
- "zod": "^4.3.6"
57
- },
58
- "overrides": {
59
- "bn.js": ">=5.2.3",
60
- "flatted": ">=3.4.2",
61
- "@typescript-eslint/typescript-estree": {
62
- "minimatch": ">=10.2.1"
63
- }
64
- },
65
- "devDependencies": {
66
- "@eslint/js": "^10.0.1",
67
- "@testcontainers/mysql": "^12.0.3",
68
- "@testcontainers/redis": "^12.0.3",
69
- "@types/node": "^20.17.10",
70
- "@types/uuid": "^10.0.0",
60
+ "zod": "^4.3.6"
61
+ },
62
+ "overrides": {
63
+ "bn.js": ">=5.2.3",
64
+ "flatted": ">=3.4.2",
65
+ "@typescript-eslint/typescript-estree": {
66
+ "minimatch": ">=10.2.1"
67
+ }
68
+ },
69
+ "devDependencies": {
70
+ "@eslint/js": "^10.0.1",
71
+ "@testcontainers/mysql": "^12.0.3",
72
+ "@testcontainers/redis": "^12.0.3",
73
+ "@types/node": "^24",
74
+ "@types/uuid": "^10.0.0",
71
75
  "@vitest/coverage-v8": "^4.1.11",
72
76
  "@vitest/ui": "^4.1.11",
73
- "eslint": "^10.0.1",
74
- "prisma": "^6.19.3",
75
- "testcontainers": "^12.0.3",
76
- "tsc-alias": "^1.8.16",
77
- "tsx": "^4.21.0",
78
- "typescript": "^5.9.3",
79
- "typescript-eslint": "^8.55.0",
77
+ "eslint": "^10.0.1",
78
+ "prisma": "^6.19.3",
79
+ "testcontainers": "^12.0.3",
80
+ "tsc-alias": "^1.8.16",
81
+ "tsx": "^4.21.0",
82
+ "typescript": "^5.9.3",
83
+ "typescript-eslint": "^8.55.0",
80
84
  "vitest": "^4.1.11"
81
- }
82
- }
85
+ }
86
+ }
@@ -0,0 +1,82 @@
1
+ -- CreateTable
2
+ CREATE TABLE `users` (
3
+ `id` VARCHAR(191) NOT NULL,
4
+ `email` VARCHAR(191) NOT NULL,
5
+ `password` VARCHAR(191) NOT NULL,
6
+ `firstName` VARCHAR(191) NOT NULL,
7
+ `lastName` VARCHAR(191) NOT NULL,
8
+ `avatarUrl` VARCHAR(191) NULL,
9
+ `role` ENUM('USER', 'ADMIN') NOT NULL DEFAULT 'USER',
10
+ `isActive` BOOLEAN NOT NULL DEFAULT true,
11
+ `emailVerifiedAt` DATETIME(3) NULL,
12
+ `deletedAt` DATETIME(3) NULL,
13
+ `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
14
+ `updatedAt` DATETIME(3) NOT NULL,
15
+
16
+ UNIQUE INDEX `users_email_key`(`email`),
17
+ INDEX `users_role_idx`(`role`),
18
+ INDEX `users_isActive_idx`(`isActive`),
19
+ INDEX `users_deletedAt_idx`(`deletedAt`),
20
+ INDEX `users_email_isActive_idx`(`email`, `isActive`),
21
+ PRIMARY KEY (`id`)
22
+ ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
23
+
24
+ -- CreateTable
25
+ CREATE TABLE `refresh_tokens` (
26
+ `id` VARCHAR(191) NOT NULL,
27
+ `token` VARCHAR(500) NOT NULL,
28
+ `userId` VARCHAR(191) NOT NULL,
29
+ `sessionId` VARCHAR(191) NULL,
30
+ `expiresAt` DATETIME(3) NOT NULL,
31
+ `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
32
+
33
+ UNIQUE INDEX `refresh_tokens_token_key`(`token`),
34
+ INDEX `refresh_tokens_userId_idx`(`userId`),
35
+ INDEX `refresh_tokens_token_idx`(`token`),
36
+ INDEX `refresh_tokens_userId_expiresAt_idx`(`userId`, `expiresAt`),
37
+ INDEX `refresh_tokens_expiresAt_idx`(`expiresAt`),
38
+ INDEX `refresh_tokens_sessionId_idx`(`sessionId`),
39
+ PRIMARY KEY (`id`)
40
+ ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
41
+
42
+ -- CreateTable
43
+ CREATE TABLE `sessions` (
44
+ `id` VARCHAR(191) NOT NULL,
45
+ `userId` VARCHAR(191) NOT NULL,
46
+ `deviceInfo` VARCHAR(500) NULL,
47
+ `ipAddress` VARCHAR(45) NULL,
48
+ `lastActiveAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
49
+ `expiresAt` DATETIME(3) NOT NULL,
50
+ `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
51
+
52
+ INDEX `sessions_userId_idx`(`userId`),
53
+ INDEX `sessions_userId_expiresAt_idx`(`userId`, `expiresAt`),
54
+ INDEX `sessions_expiresAt_idx`(`expiresAt`),
55
+ PRIMARY KEY (`id`)
56
+ ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
57
+
58
+ -- CreateTable
59
+ CREATE TABLE `blocked_ips` (
60
+ `id` VARCHAR(191) NOT NULL,
61
+ `ip` VARCHAR(45) NOT NULL,
62
+ `reason` VARCHAR(500) NULL,
63
+ `blockedBy` VARCHAR(191) NULL,
64
+ `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
65
+ `updatedAt` DATETIME(3) NOT NULL,
66
+
67
+ UNIQUE INDEX `blocked_ips_ip_key`(`ip`),
68
+ PRIMARY KEY (`id`)
69
+ ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
70
+
71
+ -- AddForeignKey
72
+ ALTER TABLE `refresh_tokens` ADD CONSTRAINT `refresh_tokens_userId_fkey` FOREIGN KEY (`userId`) REFERENCES `users`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
73
+
74
+ -- AddForeignKey
75
+ ALTER TABLE `refresh_tokens` ADD CONSTRAINT `refresh_tokens_sessionId_fkey` FOREIGN KEY (`sessionId`) REFERENCES `sessions`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
76
+
77
+ -- AddForeignKey
78
+ ALTER TABLE `sessions` ADD CONSTRAINT `sessions_userId_fkey` FOREIGN KEY (`userId`) REFERENCES `users`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
79
+
80
+ -- AddForeignKey
81
+ ALTER TABLE `blocked_ips` ADD CONSTRAINT `blocked_ips_blockedBy_fkey` FOREIGN KEY (`blockedBy`) REFERENCES `users`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
82
+
@@ -0,0 +1,3 @@
1
+ # Please do not edit this file manually
2
+ # It should be added in your version-control system (e.g., Git)
3
+ provider = "mysql"
@@ -30,9 +30,6 @@ model User {
30
30
  emailVerifiedAt DateTime?
31
31
  deletedAt DateTime?
32
32
 
33
- // Account lockout
34
- failedLoginAttempts Int @default(0)
35
- lockedUntil DateTime?
36
33
 
37
34
  createdAt DateTime @default(now())
38
35
  updatedAt DateTime @updatedAt
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Build-time proof that the server image decodes real HEIC (iPhone) photos.
3
+ * The Dockerfile runs it right after check-sharp.mjs, as the runtime user; any
4
+ * failure fails the image build.
5
+ *
6
+ * Why a separate check: sharp.format.heif.input is also true for a build that
7
+ * only reads AVIF (sharp's own prebuilt binaries report it too), so it proves
8
+ * nothing about HEIC. HEIC needs libheif's libde265 plugin (Dockerfile:
9
+ * libheif-libde265), and only decoding a real HEVC file shows it loads.
10
+ * The avatar upload accepts HEIC (src/libs/storage/image-optimizer.service.ts).
11
+ *
12
+ * Server only: the client image does not take HEIC uploads, and check-sharp.mjs
13
+ * must stay identical in both apps.
14
+ */
15
+ import assert from 'node:assert/strict';
16
+
17
+ const { default: sharp } = await import('sharp');
18
+
19
+ // 16x16 solid-colour HEIC, 467 bytes, no metadata, generated (not a photo).
20
+ // Same bytes as src/libs/storage/__tests__/fixtures/tiny-heic.ts.
21
+ const TINY_HEIC_BASE64 =
22
+ 'AAAAHGZ0eXBoZWljAAAAAG1pZjFoZWljbWlhZgAAAXxtZXRhAAAAAAAAACFoZGxyAAAAAAAAAABwaWN0AAAAAAAAAAAAAAAAAAAA' +
23
+ 'ACJpbG9jAAAAAERAAAEAAQAAAAABoAABAAAAAAAAADMAAAAjaWluZgAAAAAAAQAAABVpbmZlAgAAAAABAABodmMxAAAAAA5waXRt' +
24
+ 'AAAAAAABAAAA/GlwcnAAAADcaXBjbwAAAHVodmNDAQNwAAAAkAAAAAAAHvAA/P34+AAADwNgAAEAGEABDAH//wNwAAADAJAAAAMA' +
25
+ 'AAMAHroCQGEAAQApQgEBA3AAAAMAkAAAAwAAAwAeoCCBBZbqrprm4CGgwIAAAAyAAAADAIRiAAEABkQBwXPBiQAAABNjb2xybmNs' +
26
+ 'eAABAA0ABoAAAAAUaXNwZQAAAAAAAABAAAAAQAAAAChjbGFwAAAAEAAAAAEAAAAQAAAAAf///9AAAAAC////0AAAAAIAAAAQcGl4' +
27
+ 'aQAAAAADCAgIAAAAGGlwbWEAAAAAAAAAAQABBYECAwWEAAAAO21kYXQAAAAvKAGvEyFkY0D4EPdn/9RdjB6iuj/gbsenOyEdwNIg' +
28
+ 'gJtASJNdUAsWEICHdqVW3Pg=';
29
+
30
+ const heic = Buffer.from(TINY_HEIC_BASE64, 'base64');
31
+ const meta = await sharp(heic).metadata();
32
+ assert.equal(meta.format, 'heif', 'HEIC fixture: container format');
33
+ assert.equal(meta.compression, 'hevc', 'HEIC fixture: must be HEVC-coded (a real iPhone-style HEIC)');
34
+
35
+ const { data, info } = await sharp(heic, { autoOrient: true }).resize(8, 8).webp().toBuffer({ resolveWithObject: true });
36
+ assert.equal(info.format, 'webp', 'HEIC: output format');
37
+ assert.equal(info.width, 8, 'HEIC: resize width');
38
+ assert.equal((await sharp(data).metadata()).exif, undefined, 'HEIC: metadata must be stripped');
39
+
40
+ console.log('check-heic: HEIC (HEVC) photos decode in this image');
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Build-time proof that sharp works in the final Docker image. The Dockerfile
3
+ * runs it as the runtime user after everything is copied in; any failure
4
+ * fails the image build, so an image whose sharp cannot load never ships.
5
+ * It needs no env, network, database or application code.
6
+ *
7
+ * Why the addon file is loaded directly first: when our source-built addon
8
+ * fails to load, sharp silently falls back to its prebuilt addon. On a build
9
+ * host with a newer (x86-64-v2) CPU that fallback works, hides the broken
10
+ * build, and the image then crashes on an older production CPU. Requiring our
11
+ * own file first turns a missing library into a build error here.
12
+ *
13
+ * Keep this file identical in server/scripts and client/scripts.
14
+ */
15
+ import assert from 'node:assert/strict';
16
+ import { execFileSync } from 'node:child_process';
17
+ import { readFileSync } from 'node:fs';
18
+ import { createRequire } from 'node:module';
19
+
20
+ const require = createRequire(import.meta.url);
21
+ const { version } = require('../node_modules/sharp/package.json');
22
+ require(`../node_modules/sharp/src/build/Release/sharp-linuxmusl-${process.arch}-${version}.node`);
23
+
24
+ // The libvips the Dockerfile compiled. sharp must report this one, not the
25
+ // libvips bundled with its prebuilt addon.
26
+ const pc = readFileSync('/opt/vips/lib/pkgconfig/vips-cpp.pc', 'utf8');
27
+ const shipped = /^Version:\s*(\S+)/m.exec(pc)?.[1];
28
+
29
+ const { default: sharp } = await import('sharp');
30
+ assert.equal(sharp.versions.vips, shipped, 'sharp is not using the libvips built into this image');
31
+
32
+ // The work the apps do: decode, auto-orient, resize, encode WebP and drop
33
+ // metadata (avatars on the server, /_next/image on the client).
34
+ const jpeg = await sharp({ create: { width: 16, height: 16, channels: 3, background: '#3366cc' } })
35
+ .jpeg()
36
+ .withExif({ IFD0: { Copyright: 'check-sharp' } })
37
+ .toBuffer();
38
+ assert.ok((await sharp(jpeg).metadata()).exif, 'the test JPEG should carry EXIF');
39
+ const png = await sharp({ create: { width: 16, height: 16, channels: 4, background: '#00000000' } }).png().toBuffer();
40
+
41
+ for (const [name, input] of [['jpeg', jpeg], ['png', png]]) {
42
+ const { data, info } = await sharp(input).autoOrient().resize(8, 8).webp().toBuffer({ resolveWithObject: true });
43
+ assert.equal(info.format, 'webp', `${name}: output format`);
44
+ assert.equal(info.width, 8, `${name}: resize width`);
45
+ assert.equal((await sharp(data).metadata()).exif, undefined, `${name}: metadata must be stripped`);
46
+ }
47
+
48
+ // HEIC/HEIF input (phone photos) is accepted by the server's avatar upload.
49
+ assert.equal(sharp.format.heif.input.buffer, true, 'HEIF input support missing');
50
+
51
+ // Also prove which runtime the image ships (the deploy log shows this line).
52
+ const npmVersion = execFileSync('npm', ['-v'], { encoding: 'utf8' }).trim();
53
+ console.log(`check-sharp: sharp ${version} works with libvips ${sharp.versions.vips} on Node ${process.version}, npm ${npmVersion}`);
@@ -0,0 +1,280 @@
1
+ /**
2
+ * The contract of every API route, in the real app against a real MySQL and
3
+ * Redis: who may call it (401 anonymous, 403 the wrong user or role), what
4
+ * wrong input answers (422 VALIDATION_FAILED with the field list), and its
5
+ * success answer. The deeper guarantees of each area live in that area's own
6
+ * integration file. Add rows here for every new route: the last test fails,
7
+ * naming the route, when a registered route is never called in this file and is
8
+ * not in COVERED_ELSEWHERE (routes another file tests, with that file's name).
9
+ */
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest';
13
+ import type { FastifyInstance } from 'fastify';
14
+ import { integrationServices } from '@/test/integration.setup.js';
15
+ import {
16
+ PASSWORD,
17
+ buildTestApp,
18
+ call,
19
+ image,
20
+ multipartFile,
21
+ registerAdmin,
22
+ registerUser,
23
+ routeCoverage,
24
+ signIn,
25
+ startEmailStub,
26
+ tokenOf,
27
+ uniqueEmail,
28
+ uploadAvatar,
29
+ type EmailStub,
30
+ type TestUser,
31
+ } from '@/test/integration-helpers.js';
32
+
33
+ type Method = 'GET' | 'POST' | 'PATCH' | 'DELETE';
34
+
35
+ /** A valid UUID that belongs to nobody. */
36
+ const NOBODY = '00000000-0000-4000-8000-000000000000';
37
+
38
+ const ADMIN_ROUTES: [Method, string][] = [
39
+ ['GET', '/admin/blocked-ips'],
40
+ ['GET', '/admin/client-ip'],
41
+ ['POST', '/admin/blocked-ips'],
42
+ ['DELETE', '/admin/blocked-ips/203.0.113.9'],
43
+ ['GET', '/admin/health'],
44
+ ['GET', '/admin/stats'],
45
+ ['GET', '/admin/users'],
46
+ ['GET', `/admin/users/${NOBODY}`],
47
+ ['PATCH', `/admin/users/${NOBODY}/status`],
48
+ ['POST', `/admin/users/${NOBODY}/restore`],
49
+ ['PATCH', `/admin/users/${NOBODY}/role`],
50
+ ['GET', '/admin/sessions'],
51
+ ['DELETE', `/admin/sessions/${NOBODY}`],
52
+ ];
53
+
54
+ const SIGNED_IN_ROUTES: [Method, string][] = [
55
+ ['GET', '/auth/me'],
56
+ ['GET', '/auth/sessions'],
57
+ ['POST', '/auth/logout-all'],
58
+ ['PATCH', '/users/me'],
59
+ ['PATCH', '/users/me/password'],
60
+ ['DELETE', '/users/me'],
61
+ ['POST', '/users/avatar'],
62
+ ['DELETE', '/users/avatar'],
63
+ ['PATCH', `/users/${NOBODY}`],
64
+ ['PATCH', `/users/${NOBODY}/password`],
65
+ ['DELETE', `/users/${NOBODY}`],
66
+ ['POST', `/users/${NOBODY}/avatar`],
67
+ ['DELETE', `/users/${NOBODY}/avatar`],
68
+ ['GET', '/files/anything.txt'],
69
+ ...ADMIN_ROUTES,
70
+ ];
71
+
72
+ /**
73
+ * Routes whose contract lives in another file, with that file. Only the routes
74
+ * this file does not call belong here. The email-verification module's routes
75
+ * exist only in projects that installed it; listing them is harmless elsewhere.
76
+ */
77
+ const COVERED_ELSEWHERE: Record<string, string> = {
78
+ 'GET /api/v1/health': 'src/libs/__tests__/health.integration.test.ts',
79
+ 'GET /api/v1/ready': 'src/libs/__tests__/health.integration.test.ts',
80
+ 'GET /api/v1/live': 'src/libs/__tests__/health.integration.test.ts',
81
+ 'GET /uploads/*': 'src/modules/files/__tests__/files.integration.test.ts',
82
+ 'POST /api/v1/auth/send-verification': 'src/modules/auth/__tests__/verification.integration.test.ts (email-verification module)',
83
+ 'POST /api/v1/auth/verify-account': 'src/modules/auth/__tests__/verification.integration.test.ts (email-verification module)',
84
+ };
85
+
86
+ /** Records which routes this file calls (the last test checks it). */
87
+ const coverage = routeCoverage();
88
+
89
+ let app: FastifyInstance;
90
+ let mail: EmailStub;
91
+ let admin: TestUser;
92
+ let user: TestUser;
93
+
94
+ beforeAll(async () => {
95
+ mail = await startEmailStub();
96
+ app = await buildTestApp({ onRoute: coverage.onRoute });
97
+ admin = await registerAdmin(app, 'contract-admin');
98
+ user = await registerUser(app, 'contract-user');
99
+ });
100
+
101
+ afterAll(async () => {
102
+ await app?.close();
103
+ await mail?.close();
104
+ });
105
+
106
+ describe('who may call', () => {
107
+ it.each(SIGNED_IN_ROUTES)('%s %s anonymously → 401', async (method, url) => {
108
+ expect((await call(app, method, url)).status).toBe(401);
109
+ });
110
+
111
+ it.each(ADMIN_ROUTES)('%s %s as a USER → 403', async (method, url) => {
112
+ expect((await call(app, method, url, { jar: user.jar })).status).toBe(403);
113
+ });
114
+
115
+ it.each([
116
+ ['PATCH', '', { firstName: 'Hacker' }],
117
+ ['PATCH', '/password', { currentPassword: PASSWORD, newPassword: 'Other-Passw0rd-1' }],
118
+ ['DELETE', '', { password: PASSWORD }],
119
+ ['DELETE', '/avatar', undefined],
120
+ ] as const)("%s /users/<someone else>%s → 403", async (method, suffix, payload) => {
121
+ const owner = await registerUser(app, 'contract-owner');
122
+ const r = await call(app, method, `/users/${owner.id}${suffix}`, { jar: user.jar, payload });
123
+ expect(r.status).toBe(403);
124
+ });
125
+
126
+ it("POST /users/<someone else>/avatar → 403", async () => {
127
+ const owner = await registerUser(app, 'contract-owner-av');
128
+ expect((await uploadAvatar(app, user.jar, await image('png'), { url: `/users/${owner.id}/avatar` })).status).toBe(403);
129
+ });
130
+ });
131
+
132
+ describe('wrong input → 422 VALIDATION_FAILED, naming the fields', () => {
133
+ it.each([
134
+ ['POST', '/auth/register', { email: 'x' }, 'none'],
135
+ ['POST', '/auth/login', { email: 'x' }, 'none'],
136
+ ['POST', '/auth/forgot-password', { email: 'x' }, 'none'],
137
+ ['POST', '/auth/reset-password', {}, 'none'],
138
+ ['PATCH', '/users/me', {}, 'user'],
139
+ ['PATCH', '/users/me/password', {}, 'user'],
140
+ ['DELETE', '/users/me', {}, 'user'],
141
+ // As an admin: for a USER the owner-or-admin check runs first (403), so a
142
+ // stranger cannot even probe another path's validation.
143
+ ['PATCH', '/users/not-a-uuid', { firstName: 'Valid' }, 'admin'],
144
+ ['POST', '/admin/blocked-ips', {}, 'admin'],
145
+ ['GET', '/admin/users?limit=abc', undefined, 'admin'],
146
+ ['GET', '/admin/users/not-a-uuid', undefined, 'admin'],
147
+ ['PATCH', `/admin/users/${NOBODY}/status`, {}, 'admin'],
148
+ ['PATCH', `/admin/users/${NOBODY}/role`, { role: 'GOD' }, 'admin'],
149
+ ['GET', '/admin/sessions?userId=nope', undefined, 'admin'],
150
+ ['DELETE', '/admin/sessions/not-a-uuid', undefined, 'admin'],
151
+ ] as const)('%s %s', async (method, url, payload, who) => {
152
+ const jar = who === 'admin' ? admin.jar : who === 'user' ? user.jar : undefined;
153
+ const r = await call(app, method, url, { jar, payload });
154
+ expect([r.status, r.code]).toEqual([422, 'VALIDATION_FAILED']);
155
+ expect(Array.isArray(r.body?.error?.fields)).toBe(true);
156
+ });
157
+ });
158
+
159
+ describe('auth routes answer', () => {
160
+ it('register 201 (and signs in), login 200, me 200, sessions 200, refresh 200', async () => {
161
+ const email = uniqueEmail('contract-auth');
162
+ const reg = await call(app, 'POST', '/auth/register', { payload: { email, password: PASSWORD, firstName: 'Con', lastName: 'Tract' } });
163
+ expect([reg.status, reg.body?.data?.user?.email]).toEqual([201, email]);
164
+ const jar = await signIn(app, email);
165
+ expect((await call(app, 'GET', '/auth/me', { jar })).body?.data?.email).toBe(email);
166
+ const sessions = await call(app, 'GET', '/auth/sessions', { jar });
167
+ expect([sessions.status, Array.isArray(sessions.body?.data) && sessions.body?.data.length >= 1]).toEqual([200, true]);
168
+ expect((await call(app, 'POST', '/auth/refresh', { jar })).status).toBe(200);
169
+ });
170
+
171
+ it('logout 200 (also without a session), logout-all 200', async () => {
172
+ const u = await registerUser(app, 'contract-logout');
173
+ expect((await call(app, 'POST', '/auth/logout', { jar: u.jar })).status).toBe(200);
174
+ expect((await call(app, 'POST', '/auth/logout')).status).toBe(200);
175
+ const v = await registerUser(app, 'contract-logoutall');
176
+ expect((await call(app, 'POST', '/auth/logout-all', { jar: v.jar })).status).toBe(200);
177
+ });
178
+
179
+ it('forgot-password 200 for any address; reset-password 200 with the emailed token, 400 with another', async () => {
180
+ const u = await registerUser(app, 'contract-reset');
181
+ expect((await call(app, 'POST', '/auth/forgot-password', { payload: { email: u.email } })).status).toBe(200);
182
+ expect((await call(app, 'POST', '/auth/forgot-password', { payload: { email: uniqueEmail('nobody') } })).status).toBe(200);
183
+ const token = tokenOf(mail.to(u.email).at(-1)?.link ?? null);
184
+ expect((await call(app, 'POST', '/auth/reset-password', { payload: { token, newPassword: 'Reset-Passw0rd-1' } })).status).toBe(200);
185
+ const bad = await call(app, 'POST', '/auth/reset-password', { payload: { token: 'f'.repeat(64), newPassword: 'Reset-Passw0rd-1' } });
186
+ expect([bad.status, bad.code]).toEqual([400, 'INVALID_RESET_TOKEN']);
187
+ });
188
+ });
189
+
190
+ describe('users routes answer', () => {
191
+ it('/users/me: PATCH 200, password 200, avatar POST 200 and DELETE 200, DELETE account 200', async () => {
192
+ const u = await registerUser(app, 'contract-me');
193
+ expect((await call(app, 'PATCH', '/users/me', { jar: u.jar, payload: { lastName: 'Renamed' } })).body?.data?.lastName).toBe('Renamed');
194
+ const pw = await call(app, 'PATCH', '/users/me/password', { jar: u.jar, payload: { currentPassword: PASSWORD, newPassword: 'Changed-Passw0rd-1' } });
195
+ expect(pw.status).toBe(200);
196
+ expect((await uploadAvatar(app, u.jar, await image('jpeg'))).status).toBe(200);
197
+ expect((await call(app, 'DELETE', '/users/avatar', { jar: u.jar })).status).toBe(200);
198
+ expect((await call(app, 'DELETE', '/users/me', { jar: u.jar, payload: { password: 'Changed-Passw0rd-1' } })).status).toBe(200);
199
+ });
200
+
201
+ it('/users/:userId as the owner: PATCH 200, password 200, avatar POST 200 and DELETE 200', async () => {
202
+ const u = await registerUser(app, 'contract-byid');
203
+ const base = `/users/${u.id}`;
204
+ expect((await call(app, 'PATCH', base, { jar: u.jar, payload: { firstName: 'Owner' } })).status).toBe(200);
205
+ expect((await call(app, 'PATCH', `${base}/password`, { jar: u.jar, payload: { currentPassword: PASSWORD, newPassword: 'Owner-Passw0rd-1' } })).status).toBe(200);
206
+ const { payload, headers } = multipartFile(await image('png'));
207
+ expect((await call(app, 'POST', `${base}/avatar`, { jar: u.jar, payload, headers })).status).toBe(200);
208
+ expect((await call(app, 'DELETE', `${base}/avatar`, { jar: u.jar })).status).toBe(200);
209
+ });
210
+
211
+ it('/users/:userId as an admin: password 200 (no current password), DELETE 200; an unknown id 404', async () => {
212
+ const u = await registerUser(app, 'contract-adminbyid');
213
+ expect((await call(app, 'PATCH', `/users/${u.id}/password`, { jar: admin.jar, payload: { newPassword: 'Admin-Set-Passw0rd-1' } })).status).toBe(200);
214
+ expect((await call(app, 'DELETE', `/users/${u.id}`, { jar: admin.jar })).status).toBe(200);
215
+ expect((await call(app, 'PATCH', `/users/${NOBODY}`, { jar: admin.jar, payload: { firstName: 'Ghost' } })).status).toBe(404);
216
+ });
217
+
218
+ it('GET /files/:filename: the owner 200, a missing file 404', async () => {
219
+ const dir = path.join(integrationServices.uploadPrivateDir, 'users', user.id);
220
+ fs.mkdirSync(dir, { recursive: true });
221
+ fs.writeFileSync(path.join(dir, 'contract.txt'), 'contract');
222
+ expect((await call(app, 'GET', '/files/contract.txt', { jar: user.jar })).status).toBe(200);
223
+ expect((await call(app, 'GET', '/files/missing.txt', { jar: user.jar })).status).toBe(404);
224
+ });
225
+ });
226
+
227
+ describe('admin routes answer', () => {
228
+ it('stats, health, client-ip and blocked-ips lists → 200 with their shapes', async () => {
229
+ const stats = await call(app, 'GET', '/admin/stats', { jar: admin.jar });
230
+ expect(stats.status).toBe(200);
231
+ expect(stats.body?.data).toEqual(expect.objectContaining({ totalUsers: expect.any(Number) }));
232
+ expect((await call(app, 'GET', '/admin/health', { jar: admin.jar })).status).toBe(200);
233
+ expect(Object.keys((await call(app, 'GET', '/admin/client-ip', { jar: admin.jar })).body?.data ?? {}).sort()).toEqual(['ip', 'source']);
234
+ expect(Object.keys((await call(app, 'GET', '/admin/blocked-ips', { jar: admin.jar })).body?.data ?? {}).sort()).toEqual(['autoBlocked', 'permanent']);
235
+ });
236
+
237
+ it('block 201, unblock 200', async () => {
238
+ expect((await call(app, 'POST', '/admin/blocked-ips', { jar: admin.jar, payload: { ip: '203.0.113.99' } })).status).toBe(201);
239
+ expect((await call(app, 'DELETE', '/admin/blocked-ips/203.0.113.99', { jar: admin.jar })).status).toBe(200);
240
+ });
241
+
242
+ it('users list 200 (paginated), detail 200 / unknown 404, status 200, role 200, restore 200 / not deleted 409', async () => {
243
+ const u = await registerUser(app, 'contract-managed');
244
+ const list = await call(app, 'GET', `/admin/users?search=${encodeURIComponent(u.email)}`, { jar: admin.jar });
245
+ expect([list.status, list.body?.data?.items?.[0]?.id]).toEqual([200, u.id]);
246
+ expect((await call(app, 'GET', `/admin/users/${u.id}`, { jar: admin.jar })).status).toBe(200);
247
+ expect((await call(app, 'GET', `/admin/users/${NOBODY}`, { jar: admin.jar })).status).toBe(404);
248
+ expect((await call(app, 'PATCH', `/admin/users/${u.id}/role`, { jar: admin.jar, payload: { role: 'ADMIN' } })).status).toBe(200);
249
+ expect((await call(app, 'PATCH', `/admin/users/${u.id}/role`, { jar: admin.jar, payload: { role: 'USER' } })).status).toBe(200);
250
+ expect((await call(app, 'PATCH', `/admin/users/${u.id}/status`, { jar: admin.jar, payload: { isActive: false } })).status).toBe(200);
251
+ expect((await call(app, 'PATCH', `/admin/users/${u.id}/status`, { jar: admin.jar, payload: { isActive: true } })).status).toBe(200);
252
+ expect((await call(app, 'POST', `/admin/users/${u.id}/restore`, { jar: admin.jar })).status).toBe(409);
253
+ await call(app, 'DELETE', `/users/${u.id}`, { jar: admin.jar });
254
+ expect((await call(app, 'POST', `/admin/users/${u.id}/restore`, { jar: admin.jar })).status).toBe(200);
255
+ });
256
+
257
+ it('sessions list 200, revoke 200 / unknown 404', async () => {
258
+ const u = await registerUser(app, 'contract-session');
259
+ const list = await call(app, 'GET', `/admin/sessions?userId=${u.id}`, { jar: admin.jar });
260
+ expect(list.status).toBe(200);
261
+ const sessionId = list.body?.data?.items?.[0]?.id as string;
262
+ expect((await call(app, 'DELETE', `/admin/sessions/${sessionId}`, { jar: admin.jar })).status).toBe(200);
263
+ expect((await call(app, 'DELETE', `/admin/sessions/${NOBODY}`, { jar: admin.jar })).status).toBe(404);
264
+ });
265
+ });
266
+
267
+ /** The parts of a Vitest task this file reads: a suite has `tasks`, a test does not. */
268
+ type TaskLike = { mode: string; tasks?: TaskLike[] };
269
+ const testsIn = (t: TaskLike): TaskLike[] => (t.tasks ? t.tasks.flatMap(testsIn) : [t]);
270
+
271
+ // Keep this last: it reads what every test above called (tests in a file run in order).
272
+ describe('no route is forgotten', () => {
273
+ it('every registered route was called above, or is in COVERED_ELSEWHERE', ({ task, skip }) => {
274
+ // With a name filter (-t) the other tests did not run, so their routes would look uncalled.
275
+ const self = task as unknown as TaskLike;
276
+ const others = testsIn(task.file as unknown as TaskLike).filter((t) => t !== self);
277
+ if (others.some((t) => t.mode === 'skip' || t.mode === 'todo')) skip('needs the whole file to run');
278
+ expect(coverage.uncalled(COVERED_ELSEWHERE)).toEqual([]);
279
+ });
280
+ });