create-tigra 4.1.0 → 5.0.1

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 (142) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +4 -1
  3. package/bin/create-tigra.js +68 -73
  4. package/lib/installer-transaction.js +275 -0
  5. package/lib/patchers/diagnostics.patcher.js +33 -59
  6. package/lib/patchers/email-verification.patcher.js +86 -92
  7. package/lib/patchers/metrics.patcher.js +18 -18
  8. package/lib/project-files.js +99 -0
  9. package/modules/diagnostics/diagnostics.md +10 -0
  10. package/modules/diagnostics/prisma/diagnostic-hourly-view.sql +24 -0
  11. package/modules/diagnostics/prisma/migration.sql +1 -24
  12. package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +18 -2
  13. package/modules/diagnostics/server/diagnostics.repo.ts +12 -2
  14. package/modules/diagnostics/server/diagnostics.routes.ts +1 -2
  15. package/modules/email-verification/client/hooks/useVerification.ts +4 -7
  16. package/modules/email-verification/server/__tests__/verification.integration.test.ts +17 -0
  17. package/modules/email-verification/server/__tests__/verification.service.test.ts +71 -0
  18. package/modules/email-verification/server/verification.service.ts +102 -157
  19. package/modules/metrics/client/WebVitalsReporter.tsx +2 -0
  20. package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +1 -0
  21. package/modules/metrics/performance.md +2 -2
  22. package/modules/metrics/server/__tests__/metrics.collector.test.ts +22 -0
  23. package/modules/metrics/server/metrics.collector.ts +6 -3
  24. package/modules/metrics/server/metrics.routes.ts +1 -2
  25. package/modules/metrics/server/metrics.service.ts +6 -2
  26. package/package.json +1 -1
  27. package/template/AGENTS.md +4 -3
  28. package/template/client/.dockerignore +2 -5
  29. package/template/client/gitignore +43 -0
  30. package/template/client/package-lock.json +51 -51
  31. package/template/client/package.json +2 -2
  32. package/template/client/src/features/auth/components/AuthInitializer.tsx +45 -7
  33. package/template/client/src/features/auth/hooks/useAuth.ts +10 -33
  34. package/template/client/src/features/auth/hooks/useCurrentUser.ts +3 -3
  35. package/template/client/src/features/auth/hooks/useSessionTransition.ts +51 -0
  36. package/template/client/src/features/auth/services/auth.service.ts +3 -2
  37. package/template/client/src/features/auth/store/authSlice.ts +11 -8
  38. package/template/client/src/features/auth/types/auth.types.ts +1 -0
  39. package/template/client/src/lib/api/__tests__/axios.config.test.ts +17 -0
  40. package/template/client/src/lib/api/__tests__/session-events.test.ts +23 -0
  41. package/template/client/src/lib/api/axios.config.ts +24 -6
  42. package/template/client/src/lib/api/session-events.ts +54 -0
  43. package/template/client/src/lib/observability/sentry-scrub.ts +63 -46
  44. package/template/client/src/store/__tests__/store.test.ts +1 -0
  45. package/template/gitignore +3 -2
  46. package/template/server/.dockerignore +2 -5
  47. package/template/server/.env.example +1 -0
  48. package/template/server/.env.example.production +1 -0
  49. package/template/server/README.md +7 -2
  50. package/template/server/docs/deployment.md +66 -0
  51. package/template/server/docs/logging.md +9 -8
  52. package/template/server/docs/rate-limits.md +6 -4
  53. package/template/server/gitignore +33 -0
  54. package/template/server/prisma/migrations/0_init/migration.sql +25 -0
  55. package/template/server/prisma/retrofits/20261116000000_retired_refresh_tokens/migration.sql +13 -0
  56. package/template/server/prisma/retrofits/20261116000100_avatar_cleanup/migration.sql +9 -0
  57. package/template/server/prisma/retrofits/20261117000000_account_purge/migration.sql +1 -0
  58. package/template/server/prisma/schema.prisma +25 -1
  59. package/template/server/src/__tests__/routes.integration.test.ts +5 -2
  60. package/template/server/src/app.ts +14 -5
  61. package/template/server/src/config/env.ts +8 -0
  62. package/template/server/src/config/rate-limit.config.ts +1 -1
  63. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +26 -9
  64. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +2 -1
  65. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +51 -5
  66. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +30 -34
  67. package/template/server/src/jobs/cleanup-expired-auth.job.ts +2 -0
  68. package/template/server/src/jobs/index.ts +8 -2
  69. package/template/server/src/libs/__tests__/auth.test.ts +1 -1
  70. package/template/server/src/libs/__tests__/cookies.test.ts +16 -0
  71. package/template/server/src/libs/__tests__/error-handler.test.ts +20 -1
  72. package/template/server/src/libs/__tests__/http.test.ts +10 -10
  73. package/template/server/src/libs/__tests__/ip-block.test.ts +39 -7
  74. package/template/server/src/libs/__tests__/logger.test.ts +10 -1
  75. package/template/server/src/libs/__tests__/monitoring.test.ts +19 -0
  76. package/template/server/src/libs/__tests__/outbound.integration.test.ts +7 -10
  77. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +32 -3
  78. package/template/server/src/libs/__tests__/requestLogger.test.ts +9 -1
  79. package/template/server/src/libs/__tests__/safe-http.test.ts +65 -3
  80. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +22 -6
  81. package/template/server/src/libs/__tests__/url-safety.test.ts +3 -1
  82. package/template/server/src/libs/account-mutation.ts +77 -0
  83. package/template/server/src/libs/auth.ts +37 -3
  84. package/template/server/src/libs/cookies.ts +25 -13
  85. package/template/server/src/libs/email-quota.ts +11 -7
  86. package/template/server/src/libs/email.ts +11 -8
  87. package/template/server/src/libs/error-handler.ts +16 -12
  88. package/template/server/src/libs/http.ts +37 -13
  89. package/template/server/src/libs/ip-block.ts +56 -34
  90. package/template/server/src/libs/logger.ts +23 -8
  91. package/template/server/src/libs/monitoring.ts +57 -31
  92. package/template/server/src/libs/observability/sentry.ts +65 -49
  93. package/template/server/src/libs/prisma.ts +1 -1
  94. package/template/server/src/libs/private-cache.ts +6 -0
  95. package/template/server/src/libs/rate-limiting.ts +4 -0
  96. package/template/server/src/libs/requestLogger.ts +3 -3
  97. package/template/server/src/libs/safe-http.ts +58 -18
  98. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +15 -2
  99. package/template/server/src/libs/storage/file-storage.service.ts +59 -109
  100. package/template/server/src/libs/storage/file-validator.ts +2 -1
  101. package/template/server/src/libs/url-safety.ts +10 -2
  102. package/template/server/src/libs/validation-errors.ts +11 -8
  103. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +21 -4
  104. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +11 -0
  105. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +83 -40
  106. package/template/server/src/modules/admin/admin.controller.ts +4 -4
  107. package/template/server/src/modules/admin/admin.repo.ts +37 -54
  108. package/template/server/src/modules/admin/admin.routes.ts +3 -5
  109. package/template/server/src/modules/admin/admin.schemas.ts +3 -6
  110. package/template/server/src/modules/admin/admin.service.ts +61 -62
  111. package/template/server/src/modules/auth/__tests__/auth.schemas.test.ts +12 -0
  112. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +58 -295
  113. package/template/server/src/modules/auth/__tests__/recovery.integration.test.ts +177 -0
  114. package/template/server/src/modules/auth/__tests__/recovery.queue.test.ts +159 -0
  115. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +5 -10
  116. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +1 -1
  117. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +115 -44
  118. package/template/server/src/modules/auth/auth-link-store.ts +64 -0
  119. package/template/server/src/modules/auth/auth-mail-queue.ts +124 -0
  120. package/template/server/src/modules/auth/auth.controller.ts +16 -5
  121. package/template/server/src/modules/auth/auth.repo.ts +152 -61
  122. package/template/server/src/modules/auth/auth.routes.ts +4 -0
  123. package/template/server/src/modules/auth/auth.schemas.ts +7 -3
  124. package/template/server/src/modules/auth/auth.service.ts +33 -237
  125. package/template/server/src/modules/auth/recovery.queue.ts +44 -0
  126. package/template/server/src/modules/auth/recovery.store.ts +7 -0
  127. package/template/server/src/modules/auth/session.repo.ts +5 -4
  128. package/template/server/src/modules/files/__tests__/files.integration.test.ts +29 -1
  129. package/template/server/src/modules/files/files.controller.ts +2 -2
  130. package/template/server/src/modules/users/__tests__/avatar-cleanup.test.ts +49 -0
  131. package/template/server/src/modules/users/__tests__/avatar-controller.test.ts +50 -0
  132. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +56 -105
  133. package/template/server/src/modules/users/__tests__/users.integration.test.ts +2 -2
  134. package/template/server/src/modules/users/__tests__/users.repo.test.ts +8 -11
  135. package/template/server/src/modules/users/__tests__/users.service.test.ts +116 -44
  136. package/template/server/src/modules/users/avatar-cleanup.ts +70 -0
  137. package/template/server/src/modules/users/users.controller.ts +28 -25
  138. package/template/server/src/modules/users/users.repo.ts +12 -51
  139. package/template/server/src/modules/users/users.service.ts +109 -234
  140. package/template/server/src/shared/responses/paginatedResponse.ts +4 -1
  141. package/template/server/src/shared/schemas/pagination.schema.ts +5 -1
  142. package/template/server/src/test/setup.ts +4 -0
@@ -192,14 +192,14 @@ describe('httpClient', () => {
192
192
  expect((thrown as InternalError).code).toBe('INTERNAL_ERROR');
193
193
  });
194
194
 
195
- it('should log the error before throwing', () => {
195
+ it('logs a fixed message when setup fails', () => {
196
196
  const err = new Error('setup fail');
197
197
  try {
198
198
  captured.requestRejected!(err);
199
199
  } catch {
200
200
  // expected
201
201
  }
202
- expect(logger.error).toHaveBeenCalledWith({ err }, '[HTTP] Request setup failed');
202
+ expect(logger.error).toHaveBeenCalledWith('[HTTP] Request setup failed');
203
203
  });
204
204
 
205
205
  it('should not call logger.debug on the error path', () => {
@@ -298,7 +298,7 @@ describe('httpClient', () => {
298
298
  expect((thrown as InternalError).code).toBe('INTERNAL_ERROR');
299
299
  });
300
300
 
301
- it('should log method, url, status, and message', () => {
301
+ it('logs a method, sanitized URL, status and typed failure kind', () => {
302
302
  try {
303
303
  captured.responseRejected!(
304
304
  buildAxiosError({
@@ -311,7 +311,7 @@ describe('httpClient', () => {
311
311
  // expected
312
312
  }
313
313
  expect(logger.error).toHaveBeenCalledWith(
314
- { method: 'POST', url: '/upload', status: 413, message: 'Payload Too Large' },
314
+ { method: 'POST', url: '/upload', status: 413, kind: 'http' },
315
315
  '[HTTP] Outbound request failed',
316
316
  );
317
317
  });
@@ -334,7 +334,7 @@ describe('httpClient', () => {
334
334
  const minimalError = { isAxiosError: true, message: 'timeout' };
335
335
  expect(() => captured.responseRejected!(minimalError)).toThrow(InternalError);
336
336
  expect(logger.error).toHaveBeenCalledWith(
337
- { method: undefined, url: undefined, status: undefined, message: 'timeout' },
337
+ { method: undefined, url: undefined, status: undefined, kind: 'network' },
338
338
  '[HTTP] Outbound request failed',
339
339
  );
340
340
  });
@@ -367,14 +367,14 @@ describe('httpClient', () => {
367
367
  );
368
368
  });
369
369
 
370
- it('should log with the generic message and err field', () => {
370
+ it('logs a fixed message when an unexpected outbound error occurs', () => {
371
371
  const err = new Error('network failure');
372
372
  try {
373
373
  captured.responseRejected!(err);
374
374
  } catch {
375
375
  // expected
376
376
  }
377
- expect(logger.error).toHaveBeenCalledWith({ err }, '[HTTP] Unexpected outbound error');
377
+ expect(logger.error).toHaveBeenCalledWith('[HTTP] Unexpected outbound error');
378
378
  });
379
379
 
380
380
  it('should throw InternalError for thrown string', () => {
@@ -479,10 +479,10 @@ describe('httpClient — secrets never logged, failures typed', () => {
479
479
  expect(thrown).toMatchObject({ kind, status, statusCode: 500, code: 'INTERNAL_ERROR', message: 'Outbound HTTP request failed' });
480
480
  });
481
481
 
482
- it('keeps the original error as a non-enumerable cause (never serialized with the error)', () => {
482
+ it('keeps the HTTP status without retaining the upstream error', () => {
483
483
  const thrown = reject({ response: { status: 500 } });
484
- expect((thrown as { cause?: unknown }).cause).toBeDefined();
485
- expect(Object.keys(thrown)).not.toContain('cause');
484
+ expect(thrown.status).toBe(500);
485
+ expect(thrown).not.toHaveProperty('cause');
486
486
  });
487
487
 
488
488
  it("keeps a guard's OutboundHttpError when it passes through the request chain", () => {
@@ -1,7 +1,7 @@
1
1
  import { describe, it, expect, vi, beforeEach } from 'vitest';
2
2
  import { getRedis } from '@libs/redis.js';
3
3
  import { prisma } from '@libs/prisma.js';
4
- import { blockIp, getIpBlock, pruneExpiredAutoBlocks, recordRateLimitViolation, unblockIp } from '../ip-block.js';
4
+ import { blockIp, getIpBlock, pruneExpiredAutoBlocks, recordRateLimitViolation, syncBlockedIpsToRedis, unblockIp } from '../ip-block.js';
5
5
 
6
6
  // Self-contained env so ip-block.ts can read its threshold constants at import
7
7
  // time without loading/validating the real environment.
@@ -31,15 +31,14 @@ vi.mock('@libs/logger.js', () => ({
31
31
  }));
32
32
 
33
33
  const redisMock = {
34
- del: vi.fn(),
34
+ get: vi.fn(),
35
+ eval: vi.fn(),
35
36
  zadd: vi.fn(),
36
37
  incr: vi.fn(),
37
38
  expire: vi.fn(),
38
39
  sismember: vi.fn(),
39
40
  zscore: vi.fn(),
40
41
  zrem: vi.fn(),
41
- sadd: vi.fn(),
42
- srem: vi.fn(),
43
42
  zremrangebyscore: vi.fn(),
44
43
  };
45
44
 
@@ -89,8 +88,17 @@ describe('getIpBlock — block state with the time left', () => {
89
88
 
90
89
  it('cleans up an expired automatic block and reports no block', async () => {
91
90
  redisMock.zscore.mockResolvedValue(String(Date.now() / 1000 - 5));
91
+ redisMock.eval.mockResolvedValueOnce(null);
92
92
  expect(await getIpBlock('93.184.216.34')).toEqual({ blocked: false });
93
- expect(redisMock.zrem).toHaveBeenCalledWith('auto_blocked_ips', '93.184.216.34');
93
+ expect(redisMock.zrem).not.toHaveBeenCalled();
94
+ });
95
+
96
+ it('keeps an automatic block that was renewed during expiry cleanup', async () => {
97
+ redisMock.zscore.mockResolvedValue(String(Date.now() / 1000 - 5));
98
+ redisMock.eval.mockResolvedValueOnce(String(Date.now() / 1000 + 59.5));
99
+ expect(await getIpBlock('93.184.216.34')).toEqual({
100
+ blocked: true, permanent: false, retryAfterSeconds: 60,
101
+ });
94
102
  });
95
103
 
96
104
  it('fails open when Redis is down', async () => {
@@ -107,16 +115,22 @@ describe('blockIp / unblockIp — one spelling, no self-lockout', () => {
107
115
  beforeEach(() => {
108
116
  vi.clearAllMocks();
109
117
  vi.mocked(getRedis).mockReturnValue(redisMock as never);
118
+ redisMock.get.mockResolvedValue(null);
119
+ redisMock.eval.mockResolvedValue(1);
110
120
  vi.mocked(prisma.blockedIp.findUnique).mockResolvedValue(null);
121
+ vi.mocked(prisma.blockedIp.findMany).mockResolvedValue([]);
111
122
  vi.mocked(prisma.blockedIp.create).mockImplementation((async ({ data }: { data: { ip: string } }) => ({
112
123
  id: 'b1', ip: data.ip, reason: null, blockedBy: 'admin-1', createdAt: new Date(),
113
124
  })) as never);
114
125
  });
115
126
 
116
127
  it('stores any spelling of an address in its canonical form, in the DB and in Redis', async () => {
128
+ vi.mocked(prisma.blockedIp.findMany).mockResolvedValueOnce([{ ip: '2001:db8::1' }] as never);
117
129
  const blocked = await blockIp('2001:0DB8:0000::0001', 'admin-1', undefined, ADMIN_IP);
118
130
  expect(blocked.ip).toBe('2001:db8::1');
119
- expect(redisMock.sadd).toHaveBeenCalledWith('blocked_ips', '2001:db8::1');
131
+ expect(redisMock.eval).toHaveBeenCalledWith(
132
+ expect.any(String), 2, 'blocked_ips', 'blocked_ips:revision', '', expect.any(String), '2001:db8::1',
133
+ );
120
134
 
121
135
  await blockIp('::ffff:203.0.113.7', 'admin-1', undefined, ADMIN_IP);
122
136
  expect(vi.mocked(prisma.blockedIp.create).mock.calls[1]?.[0]).toMatchObject({ data: { ip: '203.0.113.7' } });
@@ -154,11 +168,29 @@ describe('blockIp / unblockIp — one spelling, no self-lockout', () => {
154
168
  it('unblocks by the canonical form, in the DB and both Redis lists', async () => {
155
169
  await unblockIp('2001:DB8::1');
156
170
  expect(prisma.blockedIp.deleteMany).toHaveBeenCalledWith({ where: { ip: '2001:db8::1' } });
157
- expect(redisMock.srem).toHaveBeenCalledWith('blocked_ips', '2001:db8::1');
171
+ expect(redisMock.eval).toHaveBeenCalledWith(
172
+ expect.any(String), 2, 'blocked_ips', 'blocked_ips:revision', '', expect.any(String),
173
+ );
158
174
  expect(redisMock.zrem).toHaveBeenCalledWith('auto_blocked_ips', '2001:db8::1');
159
175
  });
160
176
  });
161
177
 
178
+ it('reads MySQL again when another replica wins the block publication', async () => {
179
+ vi.clearAllMocks();
180
+ vi.mocked(getRedis).mockReturnValue(redisMock as never);
181
+ redisMock.get.mockResolvedValueOnce('previous').mockResolvedValueOnce('current');
182
+ redisMock.eval.mockResolvedValueOnce(0).mockResolvedValueOnce(1);
183
+ vi.mocked(prisma.blockedIp.findMany)
184
+ .mockResolvedValueOnce([{ ip: '198.51.100.72' }] as never)
185
+ .mockResolvedValueOnce([{ ip: '198.51.100.73' }] as never);
186
+
187
+ await syncBlockedIpsToRedis();
188
+
189
+ expect(redisMock.eval).toHaveBeenNthCalledWith(
190
+ 2, expect.any(String), 2, 'blocked_ips', 'blocked_ips:revision', 'current', expect.any(String), '198.51.100.73',
191
+ );
192
+ });
193
+
162
194
  describe('pruneExpiredAutoBlocks', () => {
163
195
  beforeEach(() => {
164
196
  vi.clearAllMocks();
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import pino from 'pino';
7
7
  import { describe, expect, it } from 'vitest';
8
- import { REDACT_PATHS } from '@libs/logger.js';
8
+ import { logger, REDACT_PATHS } from '@libs/logger.js';
9
9
 
10
10
  function logged(obj: Record<string, unknown>): string {
11
11
  const lines: string[] = [];
@@ -17,6 +17,15 @@ function logged(obj: Record<string, unknown>): string {
17
17
  const SECRET = 'leak-canary-9W4K';
18
18
 
19
19
  describe('log redaction', () => {
20
+ it('serializes an error without its message, nested cause or request data', () => {
21
+ const error = Object.assign(new TypeError(`fixture error ${SECRET}`, { cause: new Error(SECRET) }), {
22
+ code: 'P2025', config: { headers: { authorization: SECRET } },
23
+ });
24
+ const { err } = (logger as unknown as { [pino.symbols.serializersSym]: { err: (value: unknown) => unknown } })[pino.symbols.serializersSym];
25
+ const serialized = err(error);
26
+ expect(serialized).toMatchObject({ type: 'TypeError', code: 'P2025' });
27
+ expect(JSON.stringify(serialized)).not.toContain(SECRET);
28
+ });
20
29
  it('removes secrets at the top level and one, two and three levels deep', () => {
21
30
  for (const obj of [
22
31
  { password: SECRET },
@@ -98,6 +98,25 @@ describe('dependency check cache (5 s, single-flight)', () => {
98
98
  expect(results.at(-1)).toBe(true);
99
99
  });
100
100
 
101
+ it('answers during a stalled check without adding more dependency work', async () => {
102
+ vi.useFakeTimers();
103
+ let finish!: (result: unknown) => void;
104
+ vi.mocked(prisma.$queryRaw).mockReturnValue(new Promise((resolve) => { finish = resolve; }) as never);
105
+ const ready = vi.fn();
106
+ void monitoring.checkReadiness().then(ready);
107
+ await vi.advanceTimersByTimeAsync(2000);
108
+ expect(ready).toHaveBeenCalledWith(false);
109
+
110
+ await vi.advanceTimersByTimeAsync(monitoring.DEPENDENCY_CHECK_TTL_MS);
111
+ expect((await monitoring.performHealthCheck()).status).toBe('unhealthy');
112
+ expect(prisma.$queryRaw).toHaveBeenCalledTimes(1);
113
+ expect(ping).toHaveBeenCalledTimes(1);
114
+
115
+ finish([{ 1: 1 }]);
116
+ await vi.advanceTimersByTimeAsync(0);
117
+ expect(await monitoring.checkReadiness()).toBe(true);
118
+ });
119
+
101
120
  it('/ready reuses the check /health just made, and a cached failure is not retried', async () => {
102
121
  vi.mocked(prisma.$queryRaw).mockRejectedValue(new Error('down'));
103
122
  expect((await monitoring.performHealthCheck()).status).toBe('unhealthy');
@@ -1,10 +1,6 @@
1
1
  /**
2
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.
3
+ * whole app): forgot-password acknowledges work before provider delivery.
8
4
  */
9
5
  import { afterAll, beforeAll, describe, expect, it } from 'vitest';
10
6
  import type { FastifyInstance } from 'fastify';
@@ -24,22 +20,23 @@ afterAll(async () => {
24
20
  });
25
21
 
26
22
  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 () => {
23
+ it('responds before the provider finishes delivery', async () => {
28
24
  const u = await registerUser(app, 'hung');
29
- mail.respond({ delayMs: 30_000 });
25
+ mail.respond({ delayMs: 5_000 });
30
26
  const started = Date.now();
31
27
  const r = await call(app, 'POST', '/auth/forgot-password', { payload: { email: u.email } });
32
28
  const seconds = (Date.now() - started) / 1000;
33
- mail.respond({});
34
29
  expect(r.status).toBe(200);
35
- expect(seconds).toBeGreaterThanOrEqual(9);
36
- expect(seconds).toBeLessThan(15);
30
+ expect(seconds).toBeLessThan(4);
31
+ await mail.waitFor(u.email);
32
+ mail.respond({});
37
33
  }, 30_000);
38
34
 
39
35
  it('a provider that answers an error: still 200, the same answer as for any address', async () => {
40
36
  const u = await registerUser(app, 'failing');
41
37
  mail.respond({ status: 500 });
42
38
  const failing = await call(app, 'POST', '/auth/forgot-password', { payload: { email: u.email } });
39
+ await mail.waitFor(u.email);
43
40
  mail.respond({});
44
41
  const unknown = await call(app, 'POST', '/auth/forgot-password', { payload: { email: `nobody-${Date.now()}@example.test` } });
45
42
  expect(failing.status).toBe(200);
@@ -8,16 +8,16 @@
8
8
  * address, and enough of them would block it automatically. The file deletes
9
9
  * its limiter keys at the end, and checks the address was never blocked.
10
10
  */
11
- import { afterAll, beforeAll, describe, expect, it } from 'vitest';
11
+ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
12
12
  import type { FastifyInstance } from 'fastify';
13
- import { buildTestApp, call, redis, startEmailStub, uniqueEmail, type EmailStub } from '@/test/integration-helpers.js';
13
+ import { buildTestApp, call, db, redis, registerAdmin, registerUser, startEmailStub, uniqueEmail, type EmailStub } from '@/test/integration-helpers.js';
14
14
 
15
15
  let app: FastifyInstance;
16
16
  let mail: EmailStub;
17
17
 
18
18
  beforeAll(async () => {
19
19
  process.env.RATE_LIMIT_ENABLED = 'true';
20
- process.env.RATE_LIMIT_OVERRIDES = 'DEFAULT=5/1m';
20
+ process.env.RATE_LIMIT_OVERRIDES = 'DEFAULT=5/1m,ADMIN_DEFAULT=2/1m';
21
21
  mail = await startEmailStub();
22
22
  app = await buildTestApp();
23
23
  });
@@ -31,6 +31,35 @@ afterAll(async () => {
31
31
  });
32
32
 
33
33
  describe('rate limits on', () => {
34
+ it('exempts a currently authorized admin after the anonymous quota is reached', async () => {
35
+ const admin = await registerAdmin(app, 'quota-admin');
36
+ const member = await registerUser(app, 'quota-member');
37
+ const url = '/admin/stats';
38
+ const unauthorized = [await call(app, 'GET', url), await call(app, 'GET', url, { jar: member.jar }), await call(app, 'GET', url)];
39
+ expect(unauthorized.map((result) => result.status)).toEqual([401, 403, 429]);
40
+ for (let request = 0; request < 3; request++) {
41
+ expect((await call(app, 'GET', url, { jar: admin.jar })).status).toBe(200);
42
+ }
43
+ });
44
+
45
+ it('refreshes permanent blocks without a separate deletion of the active cache', async () => {
46
+ const database = await db();
47
+ const connection = await redis();
48
+ const ip = '198.51.100.72';
49
+ const { syncBlockedIpsToRedis } = await import('@libs/ip-block.js');
50
+ await database.blockedIp.create({ data: { ip } });
51
+ const separateDeletion = vi.spyOn(connection, 'del');
52
+ try {
53
+ await syncBlockedIpsToRedis();
54
+ expect(await connection.sismember('blocked_ips', ip)).toBe(1);
55
+ expect(separateDeletion).not.toHaveBeenCalledWith('blocked_ips');
56
+ } finally {
57
+ separateDeletion.mockRestore();
58
+ await database.blockedIp.delete({ where: { ip } });
59
+ await syncBlockedIpsToRedis();
60
+ }
61
+ });
62
+
34
63
  it('the 4th forgot-password email to one address within the hour → 429', async () => {
35
64
  const email = uniqueEmail('cap');
36
65
  const statuses: number[] = [];
@@ -93,7 +93,7 @@ describe('the query never reaches a request log', () => {
93
93
 
94
94
  describe('logRequestLine', () => {
95
95
  const request = (url: string): FastifyRequest =>
96
- ({ method: 'GET', url, id: 'req-9', startTime: Date.now() - 5 }) as unknown as FastifyRequest;
96
+ ({ method: 'GET', url, routeOptions: { url: requestPath(url) }, id: 'req-9', startTime: Date.now() - 5 }) as unknown as FastifyRequest;
97
97
  const reply = (statusCode: number): FastifyReply =>
98
98
  ({ statusCode, raw: { statusMessage: 'Status' } }) as unknown as FastifyReply;
99
99
 
@@ -123,4 +123,12 @@ describe('logRequestLine', () => {
123
123
  logRequestLine(request('/api/v1/auth/me?x=1'), reply(200), { color: false, fields: false });
124
124
  expect(vi.mocked(logger.info).mock.calls[0]).toEqual([expect.stringMatching(/^GET {4}\/api\/v1\/auth\/me 200 /)]);
125
125
  });
126
+
127
+ it('logs a registered template without the submitted path segment', () => {
128
+ const matched = { ...request('/api/v1/users/fixture-private'), routeOptions: { url: '/api/v1/users/:id' } } as FastifyRequest;
129
+ logRequestLine(matched, reply(422), { color: false, fields: true });
130
+ const entry = vi.mocked(logger.warn).mock.calls[0];
131
+ expect(entry[0]).toMatchObject({ path: '/api/v1/users/:id' });
132
+ expect(JSON.stringify(entry)).not.toContain('fixture-private');
133
+ });
126
134
  });
@@ -7,6 +7,8 @@
7
7
  import http from 'node:http';
8
8
  import type { AddressInfo } from 'node:net';
9
9
  import type { LookupAddress } from 'node:dns';
10
+ import { buffer } from 'node:stream/consumers';
11
+ import { setTimeout as delay } from 'node:timers/promises';
10
12
  import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
11
13
  import { createSafeHttpClient, safeHttpClient } from '../safe-http.js';
12
14
  import { isForbiddenOutboundIp } from '../url-safety.js';
@@ -31,13 +33,17 @@ const server = http.createServer((req, res) => {
31
33
  res.writeHead(200, { 'content-type': 'application/octet-stream' });
32
34
  return res.end(Buffer.alloc(11 * 1024 * 1024, 1));
33
35
  }
36
+ if (url.pathname === '/headers') {
37
+ res.writeHead(200, { 'content-type': 'application/json' });
38
+ return res.end(JSON.stringify(req.headers));
39
+ }
34
40
  res.writeHead(200, { 'content-type': 'application/json' });
35
41
  res.end(JSON.stringify({ ok: true }));
36
42
  });
37
43
 
38
44
  /** Test DNS: public.test → the local server, internal.test → 10.0.0.5, mixed.test → both. */
39
45
  const resolve = async (hostname: string): Promise<LookupAddress[]> => {
40
- if (hostname === 'public.test') return [{ address: '127.0.0.1', family: 4 }];
46
+ if (hostname === 'public.test' || hostname === 'other.test') return [{ address: '127.0.0.1', family: 4 }];
41
47
  if (hostname === 'internal.test') return [{ address: '10.0.0.5', family: 4 }];
42
48
  if (hostname === 'mixed.test') return [{ address: '127.0.0.1', family: 4 }, { address: '169.254.169.254', family: 4 }];
43
49
  return [];
@@ -67,6 +73,13 @@ describe('safeHttpClient', () => {
67
73
  expect(res.data).toEqual({ ok: true });
68
74
  });
69
75
 
76
+ it('keeps the guarded adapter when a caller provides a different adapter', async () => {
77
+ const adapter = vi.fn().mockRejectedValue(new Error('fixture adapter should not run'));
78
+ const result = await client.get(`http://public.test:${port}/ok`, { adapter });
79
+ expect(result.data).toEqual({ ok: true });
80
+ expect(adapter).not.toHaveBeenCalled();
81
+ });
82
+
70
83
  it.each([
71
84
  ['a hostname resolving to a private address', 'http://internal.test/'],
72
85
  ['a hostname where ONE answer is internal', 'http://mixed.test:PORT/ok'],
@@ -102,16 +115,65 @@ describe('safeHttpClient', () => {
102
115
  expect(error).toBeInstanceOf(OutboundHttpError);
103
116
  });
104
117
 
118
+ it('strips caller headers when a public redirect changes origin', async () => {
119
+ const headers = { Authorization: 'fixture', Cookie: 'fixture=1', 'X-Custom': 'fixture' };
120
+ const first = await client.get(`http://public.test:${port}/headers`, { headers });
121
+ expect(first.data).toMatchObject({ authorization: 'fixture', cookie: 'fixture=1', 'x-custom': 'fixture' });
122
+ const location = encodeURIComponent(`http://other.test:${port}/headers`);
123
+ const redirected = await client.get(`http://public.test:${port}/redirect?to=${location}`, { headers });
124
+ expect(redirected.data.host).toBe(`other.test:${port}`);
125
+ for (const name of ['authorization', 'cookie', 'x-custom']) expect(redirected.data).not.toHaveProperty(name);
126
+ });
127
+
128
+ it('retains a custom header when a public redirect stays within its origin', async () => {
129
+ const redirected = await client.get(`http://public.test:${port}/redirect?to=/headers`, {
130
+ headers: { 'X-Custom': 'fixture-same-origin' },
131
+ });
132
+ expect(redirected.data['x-custom']).toBe('fixture-same-origin');
133
+ });
134
+
135
+ it('declines to forward a body to a different origin', async () => {
136
+ const location = encodeURIComponent(`http://other.test:${port}/headers`);
137
+ const before = hits.length;
138
+ const error = await failure(client.post(`http://public.test:${port}/redirect?to=${location}`, { file: 'fixture' }));
139
+ expect(error.kind).toBe('blocked');
140
+ expect(hits.length - before).toBe(1);
141
+ });
142
+
105
143
  it('follows at most 3 redirects', async () => {
106
144
  const before = hits.length;
107
- const error = await failure(client.get(`http://public.test:${port}/loop`));
145
+ const error = await failure(client.get(`http://public.test:${port}/loop`, { maxRedirects: 20 }));
108
146
  expect(error).toBeInstanceOf(OutboundHttpError);
109
147
  expect(hits.length - before).toBe(4); // the first request + 3 redirects
110
148
  });
111
149
 
112
150
  it('stops a response over 10 MB (kind too-large)', async () => {
113
- const error = await failure(client.get(`http://public.test:${port}/big`, { responseType: 'arraybuffer' }));
151
+ const error = await failure(client.get(`http://public.test:${port}/big`, { responseType: 'arraybuffer', maxContentLength: -1 }));
152
+ expect(error.kind).toBe('too-large');
153
+ });
154
+
155
+ it('reports a capped stream failure without exposing the transport request', async () => {
156
+ const response = await client.get(`http://public.test:${port}/big`, {
157
+ responseType: 'stream', maxContentLength: 128,
158
+ });
159
+ const error = await failure(buffer(response.data));
160
+ expect(error).toBeInstanceOf(OutboundHttpError);
114
161
  expect(error.kind).toBe('too-large');
162
+ for (const field of ['cause', 'request', 'config']) expect(error).not.toHaveProperty(field);
163
+ });
164
+
165
+ it('includes DNS resolution in the deadline', async () => {
166
+ const slow = createSafeHttpClient({
167
+ resolve: async (hostname) => {
168
+ await delay(250);
169
+ return resolve(hostname);
170
+ },
171
+ isForbidden: (ip) => ip !== '127.0.0.1',
172
+ });
173
+ const before = hits.length;
174
+ const error = await failure(slow.get(`http://public.test:${port}/ok`, { timeout: 50 }));
175
+ expect(error.kind).toBe('timeout');
176
+ expect(hits.length).toBe(before);
115
177
  });
116
178
 
117
179
  it('ignores an HTTP_PROXY from the environment (a proxy would fetch the target for us)', async () => {
@@ -36,8 +36,8 @@ describe('scrubSentryEvent', () => {
36
36
  expect(serialized).not.toContain('token=abc');
37
37
  // Useful, non-secret context survives
38
38
  expect(scrubbed.request?.method).toBe('POST');
39
- expect(scrubbed.request?.url).toBe('https://api.example.test/api/v1/auth/reset-password');
40
- expect(scrubbed.request?.headers?.['user-agent']).toBe('vitest');
39
+ expect(scrubbed.request?.url).toBe('https://api.example.test');
40
+ expect(scrubbed.request?.headers).toEqual({});
41
41
  });
42
42
 
43
43
  it('strips tokens from the Referer header, trace data, span attributes and the transaction name', () => {
@@ -72,11 +72,27 @@ describe('scrubSentryEvent', () => {
72
72
  for (const secret of ['txn-secret', 'referer-secret', 'trace-secret', 'trace-ref-secret', 'trace-query-secret', 'span-secret']) {
73
73
  expect(serialized).not.toContain(secret);
74
74
  }
75
- expect(serialized).toContain('https://app.example.test/reset-password');
75
+ expect(serialized).toContain('https://app.example.test');
76
76
  });
77
77
 
78
- it('leaves an event without request data untouched', () => {
79
- const event: Event = { message: 'boom' };
80
- expect(scrubSentryEvent(event)).toEqual({ message: 'boom' });
78
+ it('preserves event severity without forwarding a free-form message', () => {
79
+ const event: Event = { message: 'boom', level: 'error' };
80
+ expect(scrubSentryEvent(event)).toEqual({ level: 'error' });
81
+ });
82
+
83
+ it('keeps error structure and discards free-form private values', () => {
84
+ const secret = 'fixture-private-diagnostic-data';
85
+ const event: Event = {
86
+ request: { url: `https://api.example.test/files/${secret}`, headers: { 'X-Custom-Credential': secret } },
87
+ transaction: `GET /files/${secret}`,
88
+ extra: { result: { password: secret } },
89
+ user: { email: secret },
90
+ exception: { values: [{ type: 'TypeError', value: secret }] },
91
+ breadcrumbs: [{ category: 'console', message: secret, data: { payload: { token: secret } } }],
92
+ spans: [{ trace_id: 'trace', span_id: 'span', start_timestamp: 1, description: secret, data: { 'db.statement': secret } }],
93
+ };
94
+ expect(JSON.stringify(scrubSentryEvent(event))).not.toContain(secret);
95
+ expect(event.exception?.values?.[0]).toMatchObject({ type: 'TypeError' });
96
+ expect(event.spans?.[0]).toMatchObject({ trace_id: 'trace', span_id: 'span' });
81
97
  });
82
98
  });
@@ -27,6 +27,8 @@ describe('redactUrl', () => {
27
27
  it('strips credentials from the authority', () => {
28
28
  expect(redactUrl('https://user:pa55@api.example.com/v1/x')).toBe('https://api.example.com/v1/x');
29
29
  expect(redactUrl('http://token@example.com/')).toBe('http://example.com/');
30
+ expect(redactUrl('https://user:fake@password@api.example.com/x')).toBe('https://api.example.com/x');
31
+ expect(redactUrl('//user:fake@api.example.com/x')).toBe('//api.example.com/x');
30
32
  });
31
33
 
32
34
  it('leaves a normal URL unchanged', () => {
@@ -109,7 +111,7 @@ describe('isForbiddenOutboundIp — only public unicast is a valid destination',
109
111
  '2002:a00:5::1', // 6to4 embedding 10.0.0.5
110
112
  '224.0.0.1', '240.0.0.1', '255.255.255.255', '198.18.0.1', '192.0.0.1',
111
113
  '192.0.2.1', '198.51.100.1', '203.0.113.1', '2001:db8::1',
112
- 'ff02::1', 'fec0::1', '100::1', '2001::1',
114
+ 'ff02::1', 'fec0::1', '100::1', '2001::1', '3fff::1', '5f00::1',
113
115
  ])('forbids %s', (addr) => {
114
116
  expect(isForbiddenOutboundIp(addr)).toBe(true);
115
117
  });
@@ -0,0 +1,77 @@
1
+ import type { Prisma, User } from '@prisma/client';
2
+ import { env } from '@config/env.js';
3
+ import { assertAccountCanSignIn, needsEmailVerification } from '@libs/account-status.js';
4
+ import { isPrismaWriteConflict, prisma } from '@libs/prisma.js';
5
+ import { ConflictError, ForbiddenError, ServiceUnavailableError, UnauthorizedError } from '@shared/errors/errors.js';
6
+ import type { JwtPayload, UserRole } from '@shared/types/index.js';
7
+
8
+ export type MutationActor = Pick<JwtPayload, 'userId' | 'sessionId'>;
9
+ type AccountState = Pick<User, 'id' | 'role' | 'isActive' | 'deletedAt' | 'emailVerifiedAt'>;
10
+
11
+ /** A retry repeats every authorization and eligibility read before writing. */
12
+ export async function runAccountMutation<T>(write: (tx: Prisma.TransactionClient) => Promise<T>): Promise<T> {
13
+ for (let attempt = 1; ; attempt++) {
14
+ try {
15
+ return await prisma.$transaction(write, { isolationLevel: 'Serializable' });
16
+ } catch (error) {
17
+ if (!isPrismaWriteConflict(error)) throw error;
18
+ if (attempt === 3) {
19
+ throw new ServiceUnavailableError('Account changes are busy. Please try again.');
20
+ }
21
+ }
22
+ }
23
+ }
24
+
25
+ /** Lock reads inside the transaction keep an actor valid through the write. */
26
+ export async function assertMutationActor(
27
+ tx: Prisma.TransactionClient,
28
+ actor: MutationActor,
29
+ requiredRole?: UserRole,
30
+ ): Promise<void> {
31
+ const account = await tx.user.findUnique({
32
+ where: { id: actor.userId, deletedAt: null },
33
+ select: { role: true, isActive: true, emailVerifiedAt: true },
34
+ });
35
+ if (!account) throw new UnauthorizedError('Session ended', 'SESSION_EXPIRED');
36
+ assertAccountCanSignIn(account);
37
+ const session = await tx.session.findFirst({
38
+ where: { id: actor.sessionId, userId: actor.userId, expiresAt: { gt: new Date() } },
39
+ select: { id: true },
40
+ });
41
+ if (!session) throw new UnauthorizedError('Session ended', 'SESSION_EXPIRED');
42
+ if (requiredRole && account.role !== requiredRole) throw new ForbiddenError('Insufficient permissions');
43
+ }
44
+
45
+ /** Check only removals of eligible admins. Bootstrap and repair can add one. */
46
+ export async function assertAnotherSignInAdmin(tx: Prisma.TransactionClient, account: AccountState): Promise<void> {
47
+ if (account.role !== 'ADMIN' || !account.isActive || account.deletedAt || needsEmailVerification(account)) return;
48
+ // Serializable InnoDB reads protect the matching admin set until commit,
49
+ // including against writers on another API replica.
50
+ const others = await tx.user.count({
51
+ where: {
52
+ id: { not: account.id },
53
+ role: 'ADMIN',
54
+ isActive: true,
55
+ deletedAt: null,
56
+ ...(env.REQUIRE_USER_VERIFICATION ? { emailVerifiedAt: { not: null } } : {}),
57
+ },
58
+ });
59
+ if (others === 0) {
60
+ throw new ConflictError('Keep at least one admin who can sign in before making this change.', 'LAST_ADMIN');
61
+ }
62
+ }
63
+
64
+ /** Session-bound rows cascade. Legacy refresh credentials can have no session. */
65
+ export async function revokeAccountCredentials(
66
+ tx: Prisma.TransactionClient, userId: string, keepSessionId?: string,
67
+ ): Promise<number> {
68
+ const { count } = await tx.session.deleteMany({
69
+ where: keepSessionId ? { userId, id: { not: keepSessionId } } : { userId },
70
+ });
71
+ await tx.refreshToken.deleteMany({
72
+ where: keepSessionId
73
+ ? { userId, OR: [{ sessionId: null }, { sessionId: { not: keepSessionId } }] }
74
+ : { userId },
75
+ });
76
+ return count;
77
+ }