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,62 +1,179 @@
1
- import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import { getRedis } from '@libs/redis.js';
3
- import { recordRateLimitViolation } from '../ip-block.js';
4
-
5
- // Self-contained env so ip-block.ts can read its threshold constants at import
6
- // time without loading/validating the real environment.
7
- vi.mock('@config/env.js', () => ({
8
- env: {
9
- IP_AUTO_BLOCK_THRESHOLD: 20,
10
- IP_AUTO_BLOCK_WINDOW_SECONDS: 300,
11
- IP_AUTO_BLOCK_DURATION_SECONDS: 3600,
12
- },
13
- }));
14
-
15
- vi.mock('@libs/prisma.js', () => ({
16
- prisma: {
17
- blockedIp: {
18
- findMany: vi.fn(),
19
- findUnique: vi.fn(),
20
- create: vi.fn(),
21
- deleteMany: vi.fn(),
22
- },
23
- },
24
- }));
25
-
26
- vi.mock('@libs/redis.js');
27
- vi.mock('@libs/logger.js', () => ({
28
- logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() },
29
- }));
30
-
31
- const redisMock = {
32
- del: vi.fn(),
33
- zadd: vi.fn(),
34
- incr: vi.fn(),
35
- expire: vi.fn(),
36
- };
37
-
38
- describe('recordRateLimitViolation — infra-IP guard', () => {
39
- beforeEach(() => {
40
- vi.clearAllMocks();
41
- vi.mocked(getRedis).mockReturnValue(redisMock as never);
42
- });
43
-
44
- it('never auto-blocks a private/reserved IP (skips Redis accounting entirely)', async () => {
45
- // A shared Traefik/Docker internal IP must never be auto-banned — that would
46
- // lock out every real user behind it.
47
- await recordRateLimitViolation('10.0.0.5');
48
- expect(redisMock.incr).not.toHaveBeenCalled();
49
- expect(redisMock.zadd).not.toHaveBeenCalled();
50
- });
51
-
52
- it('skips loopback addresses', async () => {
53
- await recordRateLimitViolation('127.0.0.1');
54
- expect(redisMock.incr).not.toHaveBeenCalled();
55
- });
56
-
57
- it('records a violation for a public client IP', async () => {
58
- redisMock.incr.mockResolvedValue(1);
59
- await recordRateLimitViolation('93.184.216.34');
60
- expect(redisMock.incr).toHaveBeenCalledTimes(1);
61
- });
62
- });
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { getRedis } from '@libs/redis.js';
3
+ import { prisma } from '@libs/prisma.js';
4
+ import { blockIp, getIpBlock, pruneExpiredAutoBlocks, recordRateLimitViolation, unblockIp } from '../ip-block.js';
5
+
6
+ // Self-contained env so ip-block.ts can read its threshold constants at import
7
+ // time without loading/validating the real environment.
8
+ vi.mock('@config/env.js', () => ({
9
+ env: {
10
+ IP_AUTO_BLOCK_THRESHOLD: 20,
11
+ IP_AUTO_BLOCK_WINDOW_SECONDS: 300,
12
+ IP_AUTO_BLOCK_DURATION_SECONDS: 3600,
13
+ },
14
+ }));
15
+
16
+ vi.mock('@libs/prisma.js', () => ({
17
+ isPrismaUniqueViolation: (e: unknown): boolean => (e as { code?: string })?.code === 'P2002',
18
+ prisma: {
19
+ blockedIp: {
20
+ findMany: vi.fn(),
21
+ findUnique: vi.fn(),
22
+ create: vi.fn(),
23
+ deleteMany: vi.fn(),
24
+ },
25
+ },
26
+ }));
27
+
28
+ vi.mock('@libs/redis.js');
29
+ vi.mock('@libs/logger.js', () => ({
30
+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() },
31
+ }));
32
+
33
+ const redisMock = {
34
+ del: vi.fn(),
35
+ zadd: vi.fn(),
36
+ incr: vi.fn(),
37
+ expire: vi.fn(),
38
+ sismember: vi.fn(),
39
+ zscore: vi.fn(),
40
+ zrem: vi.fn(),
41
+ sadd: vi.fn(),
42
+ srem: vi.fn(),
43
+ zremrangebyscore: vi.fn(),
44
+ };
45
+
46
+ describe('recordRateLimitViolation — infra-IP guard', () => {
47
+ beforeEach(() => {
48
+ vi.clearAllMocks();
49
+ vi.mocked(getRedis).mockReturnValue(redisMock as never);
50
+ });
51
+
52
+ it('never auto-blocks a private/reserved IP (skips Redis accounting entirely)', async () => {
53
+ // A shared Traefik/Docker internal IP must never be auto-banned — that would
54
+ // lock out every real user behind it.
55
+ await recordRateLimitViolation('10.0.0.5');
56
+ expect(redisMock.incr).not.toHaveBeenCalled();
57
+ expect(redisMock.zadd).not.toHaveBeenCalled();
58
+ });
59
+
60
+ it('skips loopback addresses', async () => {
61
+ await recordRateLimitViolation('127.0.0.1');
62
+ expect(redisMock.incr).not.toHaveBeenCalled();
63
+ });
64
+
65
+ it('records a violation for a public client IP', async () => {
66
+ redisMock.incr.mockResolvedValue(1);
67
+ await recordRateLimitViolation('93.184.216.34');
68
+ expect(redisMock.incr).toHaveBeenCalledTimes(1);
69
+ });
70
+ });
71
+
72
+ describe('getIpBlock — block state with the time left', () => {
73
+ beforeEach(() => {
74
+ vi.clearAllMocks();
75
+ vi.mocked(getRedis).mockReturnValue(redisMock as never);
76
+ redisMock.sismember.mockResolvedValue(0);
77
+ redisMock.zscore.mockResolvedValue(null);
78
+ });
79
+
80
+ it('reports a permanent (admin) block without an end time', async () => {
81
+ redisMock.sismember.mockResolvedValue(1);
82
+ expect(await getIpBlock('93.184.216.34')).toEqual({ blocked: true, permanent: true });
83
+ });
84
+
85
+ it('reports an automatic block with the whole seconds until it ends', async () => {
86
+ redisMock.zscore.mockResolvedValue(String(Date.now() / 1000 + 1799.2));
87
+ expect(await getIpBlock('93.184.216.34')).toEqual({ blocked: true, permanent: false, retryAfterSeconds: 1800 });
88
+ });
89
+
90
+ it('cleans up an expired automatic block and reports no block', async () => {
91
+ redisMock.zscore.mockResolvedValue(String(Date.now() / 1000 - 5));
92
+ expect(await getIpBlock('93.184.216.34')).toEqual({ blocked: false });
93
+ expect(redisMock.zrem).toHaveBeenCalledWith('auto_blocked_ips', '93.184.216.34');
94
+ });
95
+
96
+ it('fails open when Redis is down', async () => {
97
+ redisMock.sismember.mockRejectedValue(new Error('down'));
98
+ expect(await getIpBlock('93.184.216.34')).toEqual({ blocked: false });
99
+ });
100
+ });
101
+
102
+ // Admin blocks: stored and matched in the one canonical spelling (the visitor
103
+ // key uses the same), and an admin can never lock themselves or everyone out.
104
+ describe('blockIp / unblockIp — one spelling, no self-lockout', () => {
105
+ const ADMIN_IP = '198.51.100.9';
106
+
107
+ beforeEach(() => {
108
+ vi.clearAllMocks();
109
+ vi.mocked(getRedis).mockReturnValue(redisMock as never);
110
+ vi.mocked(prisma.blockedIp.findUnique).mockResolvedValue(null);
111
+ vi.mocked(prisma.blockedIp.create).mockImplementation((async ({ data }: { data: { ip: string } }) => ({
112
+ id: 'b1', ip: data.ip, reason: null, blockedBy: 'admin-1', createdAt: new Date(),
113
+ })) as never);
114
+ });
115
+
116
+ it('stores any spelling of an address in its canonical form, in the DB and in Redis', async () => {
117
+ const blocked = await blockIp('2001:0DB8:0000::0001', 'admin-1', undefined, ADMIN_IP);
118
+ expect(blocked.ip).toBe('2001:db8::1');
119
+ expect(redisMock.sadd).toHaveBeenCalledWith('blocked_ips', '2001:db8::1');
120
+
121
+ await blockIp('::ffff:203.0.113.7', 'admin-1', undefined, ADMIN_IP);
122
+ expect(vi.mocked(prisma.blockedIp.create).mock.calls[1]?.[0]).toMatchObject({ data: { ip: '203.0.113.7' } });
123
+ });
124
+
125
+ it("refuses the admin's own address, however it is written", async () => {
126
+ await expect(blockIp(`::ffff:${ADMIN_IP}`, 'admin-1', undefined, ADMIN_IP)).rejects.toMatchObject({
127
+ statusCode: 422,
128
+ code: 'CANNOT_BLOCK_OWN_IP',
129
+ });
130
+ expect(prisma.blockedIp.create).not.toHaveBeenCalled();
131
+ });
132
+
133
+ it.each(['10.0.0.5', '192.168.1.1', '127.0.0.1', '::1'])('refuses the private/reserved address %s', async (ip) => {
134
+ await expect(blockIp(ip, 'admin-1', undefined, ADMIN_IP)).rejects.toMatchObject({
135
+ statusCode: 422,
136
+ code: 'IP_NOT_BLOCKABLE',
137
+ });
138
+ });
139
+
140
+ it('answers 409 for an address already blocked, and for a parallel duplicate insert', async () => {
141
+ vi.mocked(prisma.blockedIp.findUnique).mockResolvedValueOnce({ id: 'b0' } as never);
142
+ await expect(blockIp('203.0.113.7', 'admin-1', undefined, ADMIN_IP)).rejects.toMatchObject({
143
+ statusCode: 409,
144
+ code: 'IP_ALREADY_BLOCKED',
145
+ });
146
+
147
+ vi.mocked(prisma.blockedIp.create).mockRejectedValueOnce(Object.assign(new Error('unique'), { code: 'P2002' }));
148
+ await expect(blockIp('203.0.113.8', 'admin-1', undefined, ADMIN_IP)).rejects.toMatchObject({
149
+ statusCode: 409,
150
+ code: 'IP_ALREADY_BLOCKED',
151
+ });
152
+ });
153
+
154
+ it('unblocks by the canonical form, in the DB and both Redis lists', async () => {
155
+ await unblockIp('2001:DB8::1');
156
+ expect(prisma.blockedIp.deleteMany).toHaveBeenCalledWith({ where: { ip: '2001:db8::1' } });
157
+ expect(redisMock.srem).toHaveBeenCalledWith('blocked_ips', '2001:db8::1');
158
+ expect(redisMock.zrem).toHaveBeenCalledWith('auto_blocked_ips', '2001:db8::1');
159
+ });
160
+ });
161
+
162
+ describe('pruneExpiredAutoBlocks', () => {
163
+ beforeEach(() => {
164
+ vi.clearAllMocks();
165
+ vi.mocked(getRedis).mockReturnValue(redisMock as never);
166
+ });
167
+
168
+ it('removes every automatic block whose end time has passed, and says how many', async () => {
169
+ redisMock.zremrangebyscore.mockResolvedValue(3);
170
+ await expect(pruneExpiredAutoBlocks(1_700_000_000)).resolves.toBe(3);
171
+ expect(redisMock.zremrangebyscore).toHaveBeenCalledWith('auto_blocked_ips', '-inf', 1_700_000_000);
172
+ });
173
+
174
+ it('does nothing and reports 0 when Redis is down (fail-open)', async () => {
175
+ redisMock.zremrangebyscore.mockRejectedValue(new Error('ECONNREFUSED'));
176
+ await expect(pruneExpiredAutoBlocks()).resolves.toBe(0);
177
+ });
178
+ });
179
+
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Log redaction (REDACT_PATHS in src/libs/logger.ts), checked on a fresh pino
3
+ * instance with the same redact settings writing to memory, so the result does
4
+ * not depend on the pretty transport used outside production.
5
+ */
6
+ import pino from 'pino';
7
+ import { describe, expect, it } from 'vitest';
8
+ import { REDACT_PATHS } from '@libs/logger.js';
9
+
10
+ function logged(obj: Record<string, unknown>): string {
11
+ const lines: string[] = [];
12
+ const log = pino({ redact: { paths: REDACT_PATHS, remove: true } }, { write: (line: string) => lines.push(line) });
13
+ log.info(obj);
14
+ return lines.join('');
15
+ }
16
+
17
+ const SECRET = 'leak-canary-9W4K';
18
+
19
+ describe('log redaction', () => {
20
+ it('removes secrets at the top level and one, two and three levels deep', () => {
21
+ for (const obj of [
22
+ { password: SECRET },
23
+ { body: { newPassword: SECRET } },
24
+ { input: { user: { accessToken: SECRET } } },
25
+ { a: { b: { c: { refresh_token: SECRET } } } },
26
+ ]) {
27
+ expect(logged(obj), JSON.stringify(obj)).not.toContain(SECRET);
28
+ }
29
+ });
30
+
31
+ it('removes secrets inside arrays', () => {
32
+ expect(logged({ items: [{ apiKey: SECRET }] })).not.toContain(SECRET);
33
+ });
34
+
35
+ it('removes secret headers, raw and under req', () => {
36
+ const out = logged({
37
+ req: { headers: { authorization: `Bearer ${SECRET}`, 'x-origin-verify': SECRET, host: 'api.example.test' } },
38
+ headers: { cookie: `access_token=${SECRET}`, 'set-cookie': SECRET },
39
+ });
40
+ expect(out).not.toContain(SECRET);
41
+ expect(out).toContain('api.example.test');
42
+ });
43
+
44
+ it('keeps ordinary fields', () => {
45
+ const out = logged({ userId: 'u-1', email: 'a@example.test', tokenCount: 3 });
46
+ expect(out).toContain('u-1');
47
+ expect(out).toContain('a@example.test');
48
+ expect(out).toContain('"tokenCount":3');
49
+ });
50
+ });
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Health checks (../monitoring.ts) with the database and Redis mocked: the
3
+ * memory rule judges the heap LIMIT, not V8's current heap size, and a failing
4
+ * check logs the real error.
5
+ */
6
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
7
+ import { tmpdir } from 'node:os';
8
+ import path from 'node:path';
9
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
10
+ import { prisma } from '@libs/prisma.js';
11
+ import { getRedis } from '@libs/redis.js';
12
+ import { logger } from '@libs/logger.js';
13
+
14
+ vi.mock('@libs/prisma.js', () => ({ prisma: { $queryRaw: vi.fn() } }));
15
+ vi.mock('@libs/redis.js', () => ({ getRedis: vi.fn() }));
16
+ vi.mock('@libs/logger.js', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } }));
17
+ vi.mock('@config/env.js', () => ({ env: { NODE_ENV: 'test', REDIS_MAX_RETRIES: 3, REDIS_CONNECT_TIMEOUT: 10000 } }));
18
+
19
+ const monitoring = await import('../monitoring.js');
20
+ const MB = 1024 * 1024;
21
+ const ping = vi.fn();
22
+
23
+ beforeEach(() => {
24
+ vi.clearAllMocks();
25
+ vi.mocked(prisma.$queryRaw).mockResolvedValue([{ 1: 1 }] as never);
26
+ ping.mockResolvedValue('PONG');
27
+ vi.mocked(getRedis).mockReturnValue({ ping } as never);
28
+ monitoring.resetHealthCacheForTests();
29
+ vi.useRealTimers();
30
+ });
31
+
32
+ describe('checkMemory', () => {
33
+ it('is up when heap use is far from the heap LIMIT, even with heapUsed ≈ heapTotal', () => {
34
+ // 354 MB used of a 4 GB limit: the old heapUsed/heapTotal rule called this "99%".
35
+ const result = monitoring.checkMemory({ used_heap_size: 354 * MB, heap_size_limit: 4096 * MB }, { rss: 400 * MB, external: 5 * MB });
36
+ expect(result.status).toBe('up');
37
+ expect(result.details).toEqual({ heapUsedMB: 354, heapLimitMB: 4096, heapUsagePercent: 9, rssMB: 400, externalMB: 5 });
38
+ });
39
+
40
+ it('is degraded above 85% of the heap limit', () => {
41
+ expect(monitoring.checkMemory({ used_heap_size: 860 * MB, heap_size_limit: 1000 * MB }, { rss: 0, external: 0 }).status).toBe('degraded');
42
+ expect(monitoring.checkMemory({ used_heap_size: 850 * MB, heap_size_limit: 1000 * MB }, { rss: 0, external: 0 }).status).toBe('up');
43
+ });
44
+
45
+ it('a real fresh process reads as up', () => {
46
+ expect(monitoring.checkMemory().status).toBe('up');
47
+ });
48
+ });
49
+
50
+ describe('failing checks log the real error', () => {
51
+ it('a database failure is logged under err (pino serializes only err)', async () => {
52
+ const failure = new Error("Can't reach database server");
53
+ vi.mocked(prisma.$queryRaw).mockRejectedValue(failure);
54
+ const report = await monitoring.performHealthCheck();
55
+ expect(report.status).toBe('unhealthy');
56
+ expect(logger.error).toHaveBeenCalledWith({ err: failure }, 'Database health check failed');
57
+ });
58
+
59
+ it('a Redis failure is logged under err and makes the status degraded', async () => {
60
+ const failure = new Error('ECONNREFUSED');
61
+ ping.mockRejectedValue(failure);
62
+ const report = await monitoring.performHealthCheck();
63
+ expect(report.status).toBe('degraded');
64
+ expect(logger.warn).toHaveBeenCalledWith({ err: failure }, 'Redis health check failed');
65
+ });
66
+ });
67
+
68
+ describe('dependency check cache (5 s, single-flight)', () => {
69
+ it('100 probes inside 5 s run one database query and one PING', async () => {
70
+ vi.useFakeTimers();
71
+ for (let i = 0; i < 100; i++) await monitoring.performHealthCheck();
72
+ expect(prisma.$queryRaw).toHaveBeenCalledTimes(1);
73
+ expect(ping).toHaveBeenCalledTimes(1);
74
+ });
75
+
76
+ it('checks again once 5 s have passed', async () => {
77
+ vi.useFakeTimers();
78
+ await monitoring.performHealthCheck();
79
+ vi.advanceTimersByTime(monitoring.DEPENDENCY_CHECK_TTL_MS - 1);
80
+ await monitoring.performHealthCheck();
81
+ expect(prisma.$queryRaw).toHaveBeenCalledTimes(1);
82
+ vi.advanceTimersByTime(1);
83
+ const report = await monitoring.performHealthCheck();
84
+ expect(prisma.$queryRaw).toHaveBeenCalledTimes(2);
85
+ expect(report.checkedAt).toBe(new Date(Date.now()).toISOString());
86
+ });
87
+
88
+ it('concurrent probes during a slow check share it instead of queueing more queries', async () => {
89
+ let answer!: (rows: unknown) => void;
90
+ vi.mocked(prisma.$queryRaw).mockReturnValue(new Promise((resolve) => (answer = resolve)) as never);
91
+ const probes = Promise.all([
92
+ ...Array.from({ length: 10 }, () => monitoring.performHealthCheck()),
93
+ monitoring.checkReadiness(),
94
+ ]);
95
+ answer([{ 1: 1 }]);
96
+ const results = await probes;
97
+ expect(prisma.$queryRaw).toHaveBeenCalledTimes(1);
98
+ expect(results.at(-1)).toBe(true);
99
+ });
100
+
101
+ it('/ready reuses the check /health just made, and a cached failure is not retried', async () => {
102
+ vi.mocked(prisma.$queryRaw).mockRejectedValue(new Error('down'));
103
+ expect((await monitoring.performHealthCheck()).status).toBe('unhealthy');
104
+ expect(await monitoring.checkReadiness()).toBe(false);
105
+ expect((await monitoring.performHealthCheck()).status).toBe('unhealthy');
106
+ expect(prisma.$queryRaw).toHaveBeenCalledTimes(1);
107
+ });
108
+
109
+ it('a slow database is still ready (only down is not ready)', async () => {
110
+ vi.useFakeTimers();
111
+ vi.mocked(prisma.$queryRaw).mockImplementation((() => {
112
+ vi.advanceTimersByTime(150);
113
+ return Promise.resolve([{ 1: 1 }]);
114
+ }) as never);
115
+ expect(await monitoring.checkReadiness()).toBe(true);
116
+ expect((await monitoring.performHealthCheck()).checks.database.status).toBe('degraded');
117
+ });
118
+ });
119
+
120
+ describe('overall status rules', () => {
121
+ /** Makes the mocked call take `ms` of fake time, so the 100 ms / 50 ms thresholds apply. */
122
+ const takes = (ms: number, value: unknown) => (): Promise<unknown> => {
123
+ vi.advanceTimersByTime(ms);
124
+ return Promise.resolve(value);
125
+ };
126
+
127
+ it('all fast and memory normal: healthy, every check up', async () => {
128
+ const report = await monitoring.performHealthCheck();
129
+ expect(report.status).toBe('healthy');
130
+ expect(Object.values(report.checks).map((c) => c.status)).toEqual(['up', 'up', 'up', 'up']);
131
+ });
132
+
133
+ it('a database at 100 ms or more: degraded, not unhealthy', async () => {
134
+ vi.useFakeTimers();
135
+ vi.mocked(prisma.$queryRaw).mockImplementation(takes(100, [{ 1: 1 }]) as never);
136
+ const report = await monitoring.performHealthCheck();
137
+ expect(report.checks.database).toMatchObject({ status: 'degraded', message: 'Database responding slowly' });
138
+ expect(report.status).toBe('degraded');
139
+ });
140
+
141
+ it('Redis at 50 ms or more: degraded', async () => {
142
+ vi.useFakeTimers();
143
+ ping.mockImplementation(takes(50, 'PONG'));
144
+ const report = await monitoring.performHealthCheck();
145
+ expect(report.checks.redis).toMatchObject({ status: 'degraded', message: 'Redis responding slowly' });
146
+ expect(report.status).toBe('degraded');
147
+ });
148
+
149
+ it('the database down wins over everything: unhealthy', async () => {
150
+ vi.mocked(prisma.$queryRaw).mockRejectedValue(new Error('down'));
151
+ ping.mockRejectedValue(new Error('down'));
152
+ expect((await monitoring.performHealthCheck()).status).toBe('unhealthy');
153
+ });
154
+ });
155
+
156
+ describe('version and commit in the report', () => {
157
+ it('readAppVersion reads package.json, else answers unknown', () => {
158
+ const dir = mkdtempSync(path.join(tmpdir(), 'tigra-version-'));
159
+ try {
160
+ expect(monitoring.readAppVersion(dir)).toBe('unknown'); // no package.json
161
+ writeFileSync(path.join(dir, 'package.json'), '{ not json');
162
+ expect(monitoring.readAppVersion(dir)).toBe('unknown');
163
+ writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'x' }));
164
+ expect(monitoring.readAppVersion(dir)).toBe('unknown');
165
+ writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ version: '2.4.0' }));
166
+ expect(monitoring.readAppVersion(dir)).toBe('2.4.0');
167
+ } finally {
168
+ rmSync(dir, { recursive: true, force: true });
169
+ }
170
+ });
171
+
172
+ it('shortCommit keeps 12 characters, trims, and turns empty into null', () => {
173
+ expect(monitoring.shortCommit('abc1234def5678901234')).toBe('abc1234def56');
174
+ expect(monitoring.shortCommit(' abc1234 ')).toBe('abc1234');
175
+ expect(monitoring.shortCommit(' ')).toBeNull();
176
+ expect(monitoring.shortCommit(undefined)).toBeNull();
177
+ });
178
+
179
+ it('the report carries the server package version and a null commit when SOURCE_COMMIT is unset', async () => {
180
+ const report = await monitoring.performHealthCheck();
181
+ expect(report.version).toBe(monitoring.readAppVersion());
182
+ expect(report.version).not.toBe('unknown');
183
+ expect(report.commit).toBeNull();
184
+ });
185
+ });
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Outbound calls from the real app (the layer 7 guarantees that need the
3
+ * whole app): when the email provider hangs or fails, forgot-password still
4
+ * gives the same answer, and gives it within about 10 s instead of holding the
5
+ * request open. The outbound guard itself (internal addresses, redirects,
6
+ * size cap, proxies, URL redaction) is pinned by safe-http.test.ts,
7
+ * http.test.ts and url-safety.test.ts with real local servers.
8
+ */
9
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest';
10
+ import type { FastifyInstance } from 'fastify';
11
+ import { buildTestApp, call, registerUser, startEmailStub, type EmailStub } from '@/test/integration-helpers.js';
12
+
13
+ let app: FastifyInstance;
14
+ let mail: EmailStub;
15
+
16
+ beforeAll(async () => {
17
+ mail = await startEmailStub();
18
+ app = await buildTestApp();
19
+ });
20
+
21
+ afterAll(async () => {
22
+ await app?.close();
23
+ await mail?.close();
24
+ });
25
+
26
+ describe('forgot-password when the email provider misbehaves', () => {
27
+ it('a provider that hangs: still 200, and answered in about 10 s (the send timeout), not minutes', async () => {
28
+ const u = await registerUser(app, 'hung');
29
+ mail.respond({ delayMs: 30_000 });
30
+ const started = Date.now();
31
+ const r = await call(app, 'POST', '/auth/forgot-password', { payload: { email: u.email } });
32
+ const seconds = (Date.now() - started) / 1000;
33
+ mail.respond({});
34
+ expect(r.status).toBe(200);
35
+ expect(seconds).toBeGreaterThanOrEqual(9);
36
+ expect(seconds).toBeLessThan(15);
37
+ }, 30_000);
38
+
39
+ it('a provider that answers an error: still 200, the same answer as for any address', async () => {
40
+ const u = await registerUser(app, 'failing');
41
+ mail.respond({ status: 500 });
42
+ const failing = await call(app, 'POST', '/auth/forgot-password', { payload: { email: u.email } });
43
+ mail.respond({});
44
+ const unknown = await call(app, 'POST', '/auth/forgot-password', { payload: { email: `nobody-${Date.now()}@example.test` } });
45
+ expect(failing.status).toBe(200);
46
+ expect(failing.body).toEqual(unknown.body);
47
+ });
48
+ });
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Which database client the app gets (../prisma.ts): production the plain
3
+ * PrismaClient, untouched; every other environment the client with the
4
+ * query-counting extension behind the dev X-Query-Count header. An extended
5
+ * client has no `$on`, which tells the two apart without a database.
6
+ */
7
+ import { afterEach, describe, expect, it, vi } from 'vitest';
8
+
9
+ async function clientFor(nodeEnv: 'production' | 'development' | 'test'): Promise<Record<string, unknown>> {
10
+ vi.resetModules();
11
+ vi.doMock('@config/env.js', () => ({ env: { NODE_ENV: nodeEnv, LOG_LEVEL: 'silent' } }));
12
+ const { prisma } = await import('../prisma.js');
13
+ return prisma as unknown as Record<string, unknown>;
14
+ }
15
+
16
+ afterEach(() => {
17
+ vi.doUnmock('@config/env.js');
18
+ });
19
+
20
+ describe('prisma client per environment', () => {
21
+ it('production: the plain client, no extension', async () => {
22
+ expect(typeof (await clientFor('production')).$on).toBe('function');
23
+ });
24
+
25
+ it.each(['development', 'test'] as const)('%s: the query-counting extension', async (nodeEnv) => {
26
+ expect((await clientFor(nodeEnv)).$on).toBeUndefined();
27
+ });
28
+ });
@@ -0,0 +1,53 @@
1
+ /**
2
+ * The dev/test-only X-Query-Count header (../query-counter.ts) against a real
3
+ * database: it must count the Prisma queries each request makes, model
4
+ * queries and raw ones alike, and 0 for a request that makes none.
5
+ */
6
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest';
7
+ import type { FastifyInstance } from 'fastify';
8
+
9
+ let app: FastifyInstance;
10
+ let cookie = '';
11
+
12
+ const queryCount = (res: { headers: Record<string, unknown> }): number => Number(res.headers['x-query-count']);
13
+
14
+ beforeAll(async () => {
15
+ const { buildApp } = await import('@/app.js');
16
+ app = await buildApp();
17
+ await app.ready();
18
+ const reg = await app.inject({
19
+ method: 'POST',
20
+ url: '/api/v1/auth/register',
21
+ payload: { email: `qc-${Date.now()}@example.test`, password: 'Integration-Passw0rd!', firstName: 'Query', lastName: 'Counter' },
22
+ });
23
+ expect(reg.statusCode).toBe(201);
24
+ const setCookie = ([] as string[]).concat(reg.headers['set-cookie'] ?? []);
25
+ cookie = setCookie.map((c) => c.split(';')[0]).join('; ');
26
+ });
27
+
28
+ afterAll(async () => {
29
+ await app?.close();
30
+ });
31
+
32
+ describe('X-Query-Count', () => {
33
+ it('counts the model queries of a signed-in request (/auth/me reads the session and the user)', async () => {
34
+ const res = await app.inject({ method: 'GET', url: '/api/v1/auth/me', headers: { cookie } });
35
+ expect(res.statusCode).toBe(200);
36
+ expect(queryCount(res)).toBeGreaterThanOrEqual(1);
37
+ });
38
+
39
+ it('counts raw queries too (/ready runs SELECT 1)', async () => {
40
+ const res = await app.inject({ method: 'GET', url: '/api/v1/ready' });
41
+ expect(res.statusCode).toBe(200);
42
+ expect(queryCount(res)).toBe(1);
43
+ });
44
+
45
+ it('is 0 for a request without queries, and one request never counts another one', async () => {
46
+ const [live, me] = await Promise.all([
47
+ app.inject({ method: 'GET', url: '/api/v1/live' }),
48
+ app.inject({ method: 'GET', url: '/api/v1/auth/me', headers: { cookie } }),
49
+ ]);
50
+ expect(queryCount(live)).toBe(0);
51
+ expect(queryCount(me)).toBeGreaterThanOrEqual(1);
52
+ });
53
+ });