create-tigra 4.0.1 → 5.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 (166) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +21 -3
  3. package/bin/create-tigra.js +131 -65
  4. package/lib/installer-transaction.js +275 -0
  5. package/lib/patchers/diagnostics.patcher.js +123 -0
  6. package/lib/patchers/email-verification.patcher.js +86 -92
  7. package/lib/patchers/metrics.patcher.js +145 -0
  8. package/lib/project-files.js +99 -0
  9. package/modules/diagnostics/diagnostics.md +75 -0
  10. package/modules/diagnostics/prisma/diagnostic-bucket.prisma +22 -0
  11. package/modules/diagnostics/prisma/diagnostic-hourly-view.sql +24 -0
  12. package/modules/diagnostics/prisma/migration.sql +20 -0
  13. package/modules/diagnostics/server/__tests__/diagnostics.collector.test.ts +72 -0
  14. package/modules/diagnostics/server/__tests__/diagnostics.context.test.ts +51 -0
  15. package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +123 -0
  16. package/modules/diagnostics/server/__tests__/diagnostics.service.test.ts +31 -0
  17. package/modules/diagnostics/server/diagnostics.collector.ts +95 -0
  18. package/modules/diagnostics/server/diagnostics.context.ts +73 -0
  19. package/modules/diagnostics/server/diagnostics.repo.ts +79 -0
  20. package/modules/diagnostics/server/diagnostics.routes.ts +16 -0
  21. package/modules/diagnostics/server/diagnostics.sample.ts +92 -0
  22. package/modules/diagnostics/server/diagnostics.schemas.ts +33 -0
  23. package/modules/diagnostics/server/diagnostics.service.ts +44 -0
  24. package/modules/email-verification/client/hooks/useVerification.ts +4 -7
  25. package/modules/email-verification/server/__tests__/verification.integration.test.ts +17 -0
  26. package/modules/email-verification/server/__tests__/verification.service.test.ts +71 -0
  27. package/modules/email-verification/server/verification.service.ts +102 -157
  28. package/modules/metrics/client/WebVitalsReporter.tsx +37 -0
  29. package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +66 -0
  30. package/modules/metrics/client/metrics.pages.ts +5 -0
  31. package/modules/metrics/performance.md +56 -0
  32. package/modules/metrics/prisma/metric-bucket.prisma +18 -0
  33. package/modules/metrics/prisma/migration.sql +17 -0
  34. package/modules/metrics/server/__tests__/metrics.collector.test.ts +97 -0
  35. package/modules/metrics/server/__tests__/metrics.integration.test.ts +88 -0
  36. package/modules/metrics/server/__tests__/metrics.schemas.test.ts +36 -0
  37. package/modules/metrics/server/__tests__/metrics.service.test.ts +84 -0
  38. package/modules/metrics/server/metrics.collector.ts +133 -0
  39. package/modules/metrics/server/metrics.pages.ts +3 -0
  40. package/modules/metrics/server/metrics.repo.ts +45 -0
  41. package/modules/metrics/server/metrics.routes.ts +45 -0
  42. package/modules/metrics/server/metrics.schemas.ts +57 -0
  43. package/modules/metrics/server/metrics.service.ts +104 -0
  44. package/package.json +1 -1
  45. package/template/AGENTS.md +18 -10
  46. package/template/client/.dockerignore +2 -5
  47. package/template/client/gitignore +43 -0
  48. package/template/client/src/app/focus-rings.policy.test.ts +88 -0
  49. package/template/client/src/app/globals.css +46 -0
  50. package/template/client/src/app/layout.tsx +5 -0
  51. package/template/client/src/app/page.tsx +2 -2
  52. package/template/client/src/components/common/InputModalityTracker.tsx +12 -0
  53. package/template/client/src/components/ui/input.tsx +3 -2
  54. package/template/client/src/features/auth/components/AuthInitializer.tsx +45 -7
  55. package/template/client/src/features/auth/hooks/useAuth.ts +10 -33
  56. package/template/client/src/features/auth/hooks/useCurrentUser.ts +3 -3
  57. package/template/client/src/features/auth/hooks/useSessionTransition.ts +51 -0
  58. package/template/client/src/features/auth/services/auth.service.ts +3 -2
  59. package/template/client/src/features/auth/store/authSlice.ts +11 -8
  60. package/template/client/src/features/auth/types/auth.types.ts +1 -0
  61. package/template/client/src/lib/api/__tests__/axios.config.test.ts +17 -0
  62. package/template/client/src/lib/api/__tests__/session-events.test.ts +23 -0
  63. package/template/client/src/lib/api/axios.config.ts +24 -6
  64. package/template/client/src/lib/api/session-events.ts +54 -0
  65. package/template/client/src/lib/input-modality.test.ts +79 -0
  66. package/template/client/src/lib/input-modality.ts +52 -0
  67. package/template/client/src/lib/observability/sentry-scrub.ts +63 -46
  68. package/template/client/src/store/__tests__/store.test.ts +1 -0
  69. package/template/gitignore +3 -2
  70. package/template/server/.dockerignore +2 -5
  71. package/template/server/.env.example +1 -0
  72. package/template/server/.env.example.production +1 -0
  73. package/template/server/README.md +7 -2
  74. package/template/server/docs/deployment.md +66 -0
  75. package/template/server/docs/logging.md +9 -8
  76. package/template/server/docs/rate-limits.md +6 -4
  77. package/template/server/gitignore +33 -0
  78. package/template/server/prisma/migrations/0_init/migration.sql +25 -0
  79. package/template/server/prisma/retrofits/20261116000000_retired_refresh_tokens/migration.sql +13 -0
  80. package/template/server/prisma/retrofits/20261116000100_avatar_cleanup/migration.sql +9 -0
  81. package/template/server/prisma/retrofits/20261117000000_account_purge/migration.sql +1 -0
  82. package/template/server/prisma/schema.prisma +25 -1
  83. package/template/server/src/__tests__/routes.integration.test.ts +5 -2
  84. package/template/server/src/app.ts +14 -5
  85. package/template/server/src/config/env.ts +8 -0
  86. package/template/server/src/config/rate-limit.config.ts +1 -1
  87. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +26 -9
  88. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +2 -1
  89. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +51 -5
  90. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +30 -34
  91. package/template/server/src/jobs/cleanup-expired-auth.job.ts +2 -0
  92. package/template/server/src/jobs/index.ts +8 -2
  93. package/template/server/src/libs/__tests__/auth.test.ts +1 -1
  94. package/template/server/src/libs/__tests__/cookies.test.ts +16 -0
  95. package/template/server/src/libs/__tests__/error-handler.test.ts +20 -1
  96. package/template/server/src/libs/__tests__/http.test.ts +10 -10
  97. package/template/server/src/libs/__tests__/ip-block.test.ts +39 -7
  98. package/template/server/src/libs/__tests__/logger.test.ts +10 -1
  99. package/template/server/src/libs/__tests__/monitoring.test.ts +19 -0
  100. package/template/server/src/libs/__tests__/outbound.integration.test.ts +7 -10
  101. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +32 -3
  102. package/template/server/src/libs/__tests__/requestLogger.test.ts +9 -1
  103. package/template/server/src/libs/__tests__/safe-http.test.ts +65 -3
  104. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +22 -6
  105. package/template/server/src/libs/__tests__/url-safety.test.ts +3 -1
  106. package/template/server/src/libs/account-mutation.ts +77 -0
  107. package/template/server/src/libs/auth.ts +37 -3
  108. package/template/server/src/libs/cookies.ts +25 -13
  109. package/template/server/src/libs/email-quota.ts +11 -7
  110. package/template/server/src/libs/email.ts +11 -8
  111. package/template/server/src/libs/error-handler.ts +16 -12
  112. package/template/server/src/libs/http.ts +37 -13
  113. package/template/server/src/libs/ip-block.ts +56 -34
  114. package/template/server/src/libs/logger.ts +23 -8
  115. package/template/server/src/libs/monitoring.ts +57 -31
  116. package/template/server/src/libs/observability/sentry.ts +65 -49
  117. package/template/server/src/libs/prisma.ts +1 -1
  118. package/template/server/src/libs/private-cache.ts +6 -0
  119. package/template/server/src/libs/rate-limiting.ts +4 -0
  120. package/template/server/src/libs/requestLogger.ts +3 -3
  121. package/template/server/src/libs/safe-http.ts +58 -18
  122. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +15 -2
  123. package/template/server/src/libs/storage/file-storage.service.ts +59 -109
  124. package/template/server/src/libs/storage/file-validator.ts +2 -1
  125. package/template/server/src/libs/url-safety.ts +10 -2
  126. package/template/server/src/libs/validation-errors.ts +11 -8
  127. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +21 -4
  128. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +11 -0
  129. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +83 -40
  130. package/template/server/src/modules/admin/admin.controller.ts +4 -4
  131. package/template/server/src/modules/admin/admin.repo.ts +37 -54
  132. package/template/server/src/modules/admin/admin.routes.ts +3 -5
  133. package/template/server/src/modules/admin/admin.schemas.ts +3 -6
  134. package/template/server/src/modules/admin/admin.service.ts +61 -62
  135. package/template/server/src/modules/auth/__tests__/auth.schemas.test.ts +12 -0
  136. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +58 -295
  137. package/template/server/src/modules/auth/__tests__/recovery.integration.test.ts +177 -0
  138. package/template/server/src/modules/auth/__tests__/recovery.queue.test.ts +159 -0
  139. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +5 -10
  140. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +1 -1
  141. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +115 -44
  142. package/template/server/src/modules/auth/auth-link-store.ts +64 -0
  143. package/template/server/src/modules/auth/auth-mail-queue.ts +124 -0
  144. package/template/server/src/modules/auth/auth.controller.ts +16 -5
  145. package/template/server/src/modules/auth/auth.repo.ts +152 -61
  146. package/template/server/src/modules/auth/auth.routes.ts +4 -0
  147. package/template/server/src/modules/auth/auth.schemas.ts +7 -3
  148. package/template/server/src/modules/auth/auth.service.ts +33 -237
  149. package/template/server/src/modules/auth/recovery.queue.ts +44 -0
  150. package/template/server/src/modules/auth/recovery.store.ts +7 -0
  151. package/template/server/src/modules/auth/session.repo.ts +5 -4
  152. package/template/server/src/modules/files/__tests__/files.integration.test.ts +29 -1
  153. package/template/server/src/modules/files/files.controller.ts +2 -2
  154. package/template/server/src/modules/users/__tests__/avatar-cleanup.test.ts +49 -0
  155. package/template/server/src/modules/users/__tests__/avatar-controller.test.ts +50 -0
  156. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +56 -105
  157. package/template/server/src/modules/users/__tests__/users.integration.test.ts +2 -2
  158. package/template/server/src/modules/users/__tests__/users.repo.test.ts +8 -11
  159. package/template/server/src/modules/users/__tests__/users.service.test.ts +116 -44
  160. package/template/server/src/modules/users/avatar-cleanup.ts +70 -0
  161. package/template/server/src/modules/users/users.controller.ts +28 -25
  162. package/template/server/src/modules/users/users.repo.ts +12 -51
  163. package/template/server/src/modules/users/users.service.ts +109 -234
  164. package/template/server/src/shared/responses/paginatedResponse.ts +4 -1
  165. package/template/server/src/shared/schemas/pagination.schema.ts +5 -1
  166. package/template/server/src/test/setup.ts +4 -0
@@ -10,10 +10,9 @@
10
10
  * 2. Wrong input (route schema or ZodError): 422 VALIDATION_FAILED with the
11
11
  * field list, never the values (libs/validation-errors.ts).
12
12
  * 3. Other 4xx from Fastify or a plugin (malformed JSON, body too large,
13
- * rate limit, multipart limits): their status, a mapped code and a fixed or
14
- * Fastify message.
15
- * 4. Anything else: logged with its stack, sent to Sentry (a no-op unless
16
- * configured), and answered with a generic 500 that reveals nothing.
13
+ * rate limit, multipart limits): their status and an application-owned message.
14
+ * 4. Anything else: logged by route and request ID, captured by Sentry when
15
+ * configured, and answered with a generic 500.
17
16
  */
18
17
  import type { FastifyError, FastifyInstance } from 'fastify';
19
18
  import { logger } from '@libs/logger.js';
@@ -46,6 +45,9 @@ export function registerErrorHandler(app: FastifyInstance): void {
46
45
 
47
46
  // AppError — our typed errors (use duck-type check to avoid instanceof issues)
48
47
  if (isAppError(error)) {
48
+ if (error.statusCode >= 500) {
49
+ Sentry.captureException(error, { tags: { reqId: request.id, route: request.routeOptions.url ?? '(unmatched)' } });
50
+ }
49
51
  return reply
50
52
  .status(error.statusCode)
51
53
  .send(errorResponse(error.code, error.message, error.retryAfterSeconds, error.fields));
@@ -77,15 +79,17 @@ export function registerErrorHandler(app: FastifyInstance): void {
77
79
  .send(errorResponse('MULTIPART_LIMIT', 'Too many form fields or files in this upload'));
78
80
  }
79
81
 
80
- // Map common Fastify error codes to user-friendly messages
82
+ // Parser messages can quote input. Return a fixed message for each known
83
+ // category and a fixed fallback for other client errors from plugins.
81
84
  const errorCodeMap: Record<number, { code: string; message: string }> = {
82
85
  413: { code: 'FILE_TOO_LARGE', message: 'File size exceeds the maximum allowed limit' },
86
+ 415: { code: 'BAD_REQUEST', message: 'Unsupported media type' },
83
87
  429: { code: 'RATE_LIMIT_EXCEEDED', message: 'Too many requests. Please try again later' },
84
88
  };
85
89
 
86
- const errorInfo = errorCodeMap[error.statusCode] || {
90
+ const errorInfo = errorCodeMap[error.statusCode] ?? {
87
91
  code: 'BAD_REQUEST',
88
- message: error.message || 'Bad request',
92
+ message: 'Bad request',
89
93
  };
90
94
 
91
95
  return reply.status(error.statusCode).send(errorResponse(errorInfo.code, errorInfo.message));
@@ -94,16 +98,16 @@ export function registerErrorHandler(app: FastifyInstance): void {
94
98
  // Unexpected error — capture in Sentry (safe no-op when SDK uninitialized),
95
99
  // then log and return a generic 500. reqId ties the event to the log line.
96
100
  const requestId = request.id || 'unknown';
97
- Sentry.captureException(error, { extra: { reqId: requestId } });
101
+ const route = request.routeOptions.url ?? '(unmatched)';
102
+ Sentry.captureException(error, { tags: { reqId: requestId, route } });
98
103
  logger.error(
99
104
  {
100
105
  err: error,
101
- requestId,
102
- url: request.url,
106
+ reqId: requestId,
107
+ route,
103
108
  method: request.method,
104
- stack: error.stack,
105
109
  },
106
- `Unhandled error [${requestId}]: ${error.message}`,
110
+ 'Unhandled request error',
107
111
  );
108
112
 
109
113
  return reply.status(500).send(errorResponse('INTERNAL_ERROR', 'Internal server error'));
@@ -13,8 +13,9 @@
13
13
  * - one error type for every failure, OutboundHttpError: unhandled it is the
14
14
  * same generic 500 as before (code INTERNAL_ERROR, nothing upstream leaks),
15
15
  * while the caller can read `kind` and `status` to handle "not found" or retry
16
- * only timeouts.
16
+ * only timeouts. Raw transport errors remain local to the interceptor.
17
17
  */
18
+ import { Readable } from 'node:stream';
18
19
  import axios, {
19
20
  type AxiosError,
20
21
  type AxiosInstance,
@@ -39,20 +40,18 @@ export type OutboundFailureKind = 'http' | 'timeout' | 'network' | 'blocked' | '
39
40
  /**
40
41
  * Every outbound failure. Extends InternalError with the SAME code and message,
41
42
  * so an unhandled one answers the same generic 500 as before. `status` is the
42
- * upstream HTTP status when there was a response; `cause` keeps the original
43
- * error for the logs (pino logs only a cause's message and stack).
43
+ * upstream HTTP status when there was a response. Do not attach the original
44
+ * error: Axios keeps headers and payloads on it, and error serializers can
45
+ * follow even a non-enumerable cause.
44
46
  */
45
47
  export class OutboundHttpError extends InternalError {
46
48
  readonly kind: OutboundFailureKind;
47
49
  readonly status?: number;
48
50
 
49
- constructor(kind: OutboundFailureKind, options: { status?: number; cause?: unknown } = {}) {
51
+ constructor(kind: OutboundFailureKind, options: { status?: number } = {}) {
50
52
  super('Outbound HTTP request failed');
51
53
  this.kind = kind;
52
54
  this.status = options.status;
53
- if (options.cause !== undefined) {
54
- Object.defineProperty(this, 'cause', { value: options.cause, enumerable: false });
55
- }
56
55
  }
57
56
  }
58
57
 
@@ -70,11 +69,31 @@ function failureKind(error: AxiosError): OutboundFailureKind {
70
69
  if (wasBlocked(error)) return 'blocked';
71
70
  if (error.response) return 'http';
72
71
  if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') return 'timeout';
72
+ if (error.code === 'ERR_CANCELED' && error.config?.signal instanceof AbortSignal
73
+ && error.config.signal.reason?.name === 'TimeoutError') return 'timeout';
73
74
  if (typeof error.message === 'string' && error.message.includes('maxContentLength')) return 'too-large';
74
75
  if (typeof error.message === 'string' && error.message.includes('maxBodyLength')) return 'too-large';
75
76
  return 'network';
76
77
  }
77
78
 
79
+ /** Axios can fail a streaming body after the request promise has resolved. */
80
+ function safeResponseStream(source: Readable): Readable {
81
+ async function* readBody(): AsyncGenerator<Buffer> {
82
+ try {
83
+ yield* source;
84
+ } catch (error) {
85
+ const kind = isAxiosError(error) ? failureKind(error) : 'network';
86
+ throw new OutboundHttpError(kind);
87
+ }
88
+ }
89
+ const stream = Readable.from(readBody(), { objectMode: false });
90
+ // An aborted stream can fail before its caller starts reading. Preserve
91
+ // that failure for the iterator and release the source on early close.
92
+ source.on('error', () => {});
93
+ stream.once('close', () => source.destroy());
94
+ return stream;
95
+ }
96
+
78
97
  /** URLs as they may be logged. */
79
98
  const safeUrl = (url: string | undefined): string | undefined => (url === undefined ? undefined : redactUrl(url));
80
99
 
@@ -108,7 +127,7 @@ export function createHttpClient(config: CreateAxiosDefaults = {}): AxiosInstanc
108
127
  // A guard registered after this interceptor (it runs first) refused the
109
128
  // request: keep its typed error, do not turn it into a setup failure.
110
129
  if (error instanceof OutboundHttpError) throw error;
111
- logger.error({ err: error }, '[HTTP] Request setup failed');
130
+ logger.error('[HTTP] Request setup failed');
112
131
  throw new InternalError('Outbound HTTP request could not be constructed');
113
132
  },
114
133
  );
@@ -124,6 +143,9 @@ export function createHttpClient(config: CreateAxiosDefaults = {}): AxiosInstanc
124
143
  },
125
144
  '[HTTP] Outbound response',
126
145
  );
146
+ if (response.config.responseType === 'stream' && response.data instanceof Readable) {
147
+ response.data = safeResponseStream(response.data);
148
+ }
127
149
  return response;
128
150
  },
129
151
  (error: unknown): never => {
@@ -133,19 +155,21 @@ export function createHttpClient(config: CreateAxiosDefaults = {}): AxiosInstanc
133
155
  throw error;
134
156
  }
135
157
  if (isAxiosError(error)) {
158
+ const kind = failureKind(error);
159
+ const status = error.response?.status;
136
160
  logger.error(
137
161
  {
138
162
  method: error.config?.method?.toUpperCase(),
139
163
  url: safeUrl(error.config?.url),
140
- status: error.response?.status,
141
- message: error.message,
164
+ status,
165
+ kind,
142
166
  },
143
167
  '[HTTP] Outbound request failed',
144
168
  );
145
- throw new OutboundHttpError(failureKind(error), { status: error.response?.status, cause: error });
169
+ throw new OutboundHttpError(kind, { status });
146
170
  }
147
- logger.error({ err: error }, '[HTTP] Unexpected outbound error');
148
- throw new OutboundHttpError('network', { cause: error });
171
+ logger.error('[HTTP] Unexpected outbound error');
172
+ throw new OutboundHttpError('network');
149
173
  },
150
174
  );
151
175
 
@@ -8,7 +8,7 @@
8
8
  * Design decisions:
9
9
  * - DB is the source of truth for permanent blocks — survives Redis restarts
10
10
  * - Redis is the hot cache — all runtime checks hit Redis only (O(1))
11
- * - On server boot, syncBlockedIpsToRedis() loads all permanent blocks from DB into Redis
11
+ * - Boot, reconnect, and admin edits publish complete DB snapshots to Redis
12
12
  * - Fails open: if Redis is down, requests are NOT blocked (availability > security for rate limiting)
13
13
  * - Lazy cleanup: expired auto-blocks are removed on check, no separate cleanup job needed
14
14
  * - One spelling: every stored or removed block is the canonical form
@@ -19,6 +19,7 @@
19
19
  * private/reserved address (a proxy or Docker address would block everyone).
20
20
  */
21
21
 
22
+ import { randomUUID } from 'node:crypto';
22
23
  import { env } from '@config/env.js';
23
24
  import { prisma, isPrismaUniqueViolation } from '@libs/prisma.js';
24
25
  import { getRedis } from '@libs/redis.js';
@@ -29,8 +30,32 @@ import { normalizeIp } from '@libs/ip-address.js';
29
30
 
30
31
  // Redis keys
31
32
  const BLOCKED_IPS_KEY = 'blocked_ips';
33
+ const BLOCKED_IPS_REVISION = 'blocked_ips:revision';
32
34
  const AUTO_BLOCKED_KEY = 'auto_blocked_ips';
33
35
  const VIOLATION_PREFIX = 'rl_violations:';
36
+ const BLOCK_SYNC_ATTEMPTS = 3;
37
+
38
+ // An expiry observed before a concurrent renewal is stale. Recheck and
39
+ // remove in Redis together so cleaning one IP cannot drop its active block.
40
+ const REMOVE_EXPIRED_BLOCK = `
41
+ local expiry = redis.call('ZSCORE', KEYS[1], ARGV[1])
42
+ if not expiry then return false end
43
+ if tonumber(expiry) > tonumber(ARGV[2]) then return expiry end
44
+ redis.call('ZREM', KEYS[1], ARGV[1])
45
+ return false
46
+ `;
47
+
48
+ // The revision check and replacement are atomic. Batch SADD to stay within
49
+ // Lua's argument stack even when a project has a large block list.
50
+ const REPLACE_PERMANENT_BLOCKS = `
51
+ if (redis.call('GET', KEYS[2]) or '') ~= ARGV[1] then return 0 end
52
+ redis.call('DEL', KEYS[1])
53
+ for i = 3, #ARGV, 500 do
54
+ redis.call('SADD', KEYS[1], unpack(ARGV, i, math.min(i + 499, #ARGV)))
55
+ end
56
+ redis.call('SET', KEYS[2], ARGV[2])
57
+ return 1
58
+ `;
34
59
 
35
60
  // Auto-block thresholds — env-configurable (see .env.example).
36
61
  // The threshold default is deliberately high (20): auto-block must catch
@@ -43,25 +68,30 @@ const AUTO_BLOCK_WINDOW_SECONDS = env.IP_AUTO_BLOCK_WINDOW_SECONDS; // sli
43
68
  const AUTO_BLOCK_DURATION_SECONDS = env.IP_AUTO_BLOCK_DURATION_SECONDS; // block duration (default 3600 = 1 hour)
44
69
 
45
70
  /**
46
- * Sync all permanent blocked IPs from DB to Redis.
47
- * Called once during server startup.
71
+ * Publish the committed MySQL block list. Read the revision before fetching
72
+ * the rows so a concurrent publication forces a fresh snapshot. Admin edits
73
+ * use this same path after committing, even when two replicas edit one IP.
48
74
  */
49
75
  export async function syncBlockedIpsToRedis(): Promise<void> {
50
76
  try {
51
- const blockedIps = await prisma.blockedIp.findMany({ select: { ip: true } });
52
-
53
77
  const redis = getRedis();
54
-
55
- // Clear stale Redis state and repopulate from DB
56
- await redis.del(BLOCKED_IPS_KEY);
57
-
58
- if (blockedIps.length > 0) {
59
- await redis.sadd(BLOCKED_IPS_KEY, ...blockedIps.map((b) => b.ip));
78
+ for (let attempt = 0; attempt < BLOCK_SYNC_ATTEMPTS; attempt++) {
79
+ const revision = (await redis.get(BLOCKED_IPS_REVISION)) ?? '';
80
+ const blockedIps = await prisma.blockedIp.findMany({ select: { ip: true } });
81
+ const published = await redis.eval(
82
+ REPLACE_PERMANENT_BLOCKS, 2, BLOCKED_IPS_KEY, BLOCKED_IPS_REVISION,
83
+ revision, randomUUID(), ...blockedIps.map(({ ip }) => ip),
84
+ );
85
+ if (published === 1) {
86
+ logger.info(`[IP-BLOCK] Synced ${blockedIps.length} blocked IPs from DB to Redis`);
87
+ return;
88
+ }
60
89
  }
61
-
62
- logger.info(`[IP-BLOCK] Synced ${blockedIps.length} blocked IPs from DB to Redis`);
90
+ // After the first conflict, contenders on the new revision read their
91
+ // snapshots after this caller's DB edit committed.
92
+ logger.debug('[IP-BLOCK] Concurrent replicas published the permanent block list');
63
93
  } catch (error) {
64
- logger.warn('[IP-BLOCK] Failed to sync blocked IPs from DB to Redis — permanent blocks may not be enforced until next restart');
94
+ logger.warn('[IP-BLOCK] Failed to sync blocked IPs from DB to Redis — will retry on the next edit or reconnect');
65
95
  logger.debug(error);
66
96
  }
67
97
  }
@@ -93,14 +123,13 @@ export async function getIpBlock(ip: string): Promise<IpBlock> {
93
123
 
94
124
  // Check auto-block list (score = expiry Unix timestamp)
95
125
  const score = await redis.zscore(AUTO_BLOCKED_KEY, ip);
96
- if (score) {
97
- const secondsLeft = Number(score) - Date.now() / 1000;
98
- if (secondsLeft > 0) {
99
- return { blocked: true, permanent: false, retryAfterSeconds: Math.max(1, Math.ceil(secondsLeft)) };
100
- }
101
-
102
- // Expired — clean up lazily
103
- await redis.zrem(AUTO_BLOCKED_KEY, ip);
126
+ if (score === null) return { blocked: false };
127
+ const nowSeconds = Date.now() / 1000;
128
+ const expiry = Number(score) <= nowSeconds
129
+ ? await redis.eval(REMOVE_EXPIRED_BLOCK, 1, AUTO_BLOCKED_KEY, ip, nowSeconds)
130
+ : score;
131
+ if (typeof expiry === 'string') {
132
+ return { blocked: true, permanent: false, retryAfterSeconds: Math.max(1, Math.ceil(Number(expiry) - nowSeconds)) };
104
133
  }
105
134
 
106
135
  return { blocked: false };
@@ -157,13 +186,7 @@ export async function blockIp(
157
186
  throw error;
158
187
  }
159
188
 
160
- // Sync to Redis cache
161
- try {
162
- const redis = getRedis();
163
- await redis.sadd(BLOCKED_IPS_KEY, ip);
164
- } catch {
165
- logger.warn({ ip }, '[IP-BLOCK] Failed to sync block to Redis — will be synced on next restart');
166
- }
189
+ await syncBlockedIpsToRedis();
167
190
 
168
191
  logger.info({ ip, blockedBy, reason }, '[IP-BLOCK] IP permanently blocked');
169
192
  return blocked;
@@ -179,13 +202,12 @@ export async function unblockIp(rawIp: string): Promise<void> {
179
202
  // Remove from DB
180
203
  await prisma.blockedIp.deleteMany({ where: { ip } });
181
204
 
182
- // Remove from Redis (both permanent and auto-block)
205
+ // Publish the permanent list and clear any automatic block for this address.
206
+ await syncBlockedIpsToRedis();
183
207
  try {
184
- const redis = getRedis();
185
- await redis.srem(BLOCKED_IPS_KEY, ip);
186
- await redis.zrem(AUTO_BLOCKED_KEY, ip);
208
+ await getRedis().zrem(AUTO_BLOCKED_KEY, ip);
187
209
  } catch {
188
- logger.warn({ ip }, '[IP-BLOCK] Failed to sync unblock to Redis — will be synced on next restart');
210
+ logger.warn({ ip }, '[IP-BLOCK] Failed to clear automatic block — it will expire on schedule');
189
211
  }
190
212
 
191
213
  logger.info({ ip }, '[IP-BLOCK] IP unblocked');
@@ -39,6 +39,15 @@ export const REDACT_PATHS: string[] = [
39
39
  ...SECRET_KEYS.flatMap((k) => [k, `*.${k}`, `*.*.${k}`, `*.*.*.${k}`]),
40
40
  ];
41
41
 
42
+ /** Transport errors can hold request bodies, credentials and chained messages. */
43
+ function serializeError(error: unknown): { type: string; code?: string } {
44
+ if (!(error instanceof Error)) return { type: 'UnknownError' };
45
+ const type = /^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(error.name) ? error.name : 'Error';
46
+ const code = 'code' in error && typeof error.code === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(error.code)
47
+ ? error.code : undefined;
48
+ return { type, code };
49
+ }
50
+
42
51
  export const logger = pino({
43
52
  level: env.LOG_LEVEL,
44
53
  // Never let secrets reach the logs (REDACT_PATHS above). `remove: true` drops
@@ -47,6 +56,17 @@ export const logger = pino({
47
56
  paths: REDACT_PATHS,
48
57
  remove: true,
49
58
  },
59
+ hooks: {
60
+ logMethod(args, method): void {
61
+ // Pino otherwise promotes a bare Error's message to the log line.
62
+ if (args[0] instanceof Error) {
63
+ const [error, ...rest] = args;
64
+ method.apply(this, [{ err: error }, ...rest]);
65
+ } else {
66
+ method.apply(this, args);
67
+ }
68
+ },
69
+ },
50
70
  ...(env.NODE_ENV !== 'production' && {
51
71
  transport: {
52
72
  target: 'pino-pretty',
@@ -59,16 +79,11 @@ export const logger = pino({
59
79
  },
60
80
  }),
61
81
  serializers: {
82
+ err: serializeError,
62
83
  req: (req) => ({
63
84
  method: req.method,
64
- url: req.url,
65
- query: req.query,
66
- params: req.params,
67
- headers: {
68
- host: req.headers.host,
69
- 'user-agent': req.headers['user-agent'],
70
- 'content-type': req.headers['content-type'],
71
- },
85
+ route: req.routeOptions?.url ?? '(unmatched)',
86
+ id: req.id,
72
87
  }),
73
88
  res: (res) => ({
74
89
  statusCode: res.statusCode,
@@ -105,44 +105,67 @@ async function checkRedis(): Promise<CheckStatus> {
105
105
  * interval, so an outage still shows within one probe.
106
106
  */
107
107
  export const DEPENDENCY_CHECK_TTL_MS = 5_000;
108
+ const DEPENDENCY_CHECK_WAIT_MS = 1_000;
108
109
 
109
- interface DependencyChecks {
110
- database: CheckStatus;
111
- redis: CheckStatus;
110
+ interface CheckedDependency {
111
+ result: CheckStatus;
112
112
  checkedAt: number;
113
113
  }
114
114
 
115
- let cachedChecks: DependencyChecks | null = null;
116
- let checksInFlight: Promise<DependencyChecks> | null = null;
115
+ interface CachedDependency {
116
+ read(): Promise<CheckedDependency>;
117
+ reset(): void;
118
+ }
117
119
 
118
120
  /**
119
- * The database and Redis checks, cached for DEPENDENCY_CHECK_TTL_MS and
120
- * single-flight: callers arriving while a check runs share its promise
121
- * instead of starting another (a hung database would otherwise collect one
122
- * pending query per probe). Failures are cached too, so a down database is
123
- * not retried by every probe. checkDatabase/checkRedis never throw.
121
+ * Share one real query or ping per dependency. Answer callers at the deadline,
122
+ * but keep ownership of the underlying operation until it actually completes.
123
+ * A stalled Redis check cannot delay a fresh database result or readiness.
124
124
  */
125
- function checkDependencies(): Promise<DependencyChecks> {
126
- if (cachedChecks && Date.now() - cachedChecks.checkedAt < DEPENDENCY_CHECK_TTL_MS) {
127
- return Promise.resolve(cachedChecks);
128
- }
129
- if (!checksInFlight) {
130
- checksInFlight = Promise.all([checkDatabase(), checkRedis()])
131
- .then(([database, redis]) => {
132
- cachedChecks = { database, redis, checkedAt: Date.now() };
133
- return cachedChecks;
134
- })
135
- .finally(() => {
136
- checksInFlight = null;
125
+ function cacheDependency(name: string, check: () => Promise<CheckStatus>): CachedDependency {
126
+ let cached: CheckedDependency | undefined;
127
+ let inFlight: Promise<CheckedDependency> | undefined;
128
+ return {
129
+ read(): Promise<CheckedDependency> {
130
+ if (cached && Date.now() - cached.checkedAt < DEPENDENCY_CHECK_TTL_MS) return Promise.resolve(cached);
131
+ if (inFlight) return inFlight;
132
+
133
+ let timer: ReturnType<typeof setTimeout>;
134
+ const deadline = new Promise<CheckedDependency>((resolve) => {
135
+ timer = setTimeout(() => {
136
+ logger.warn({ dependency: name, timeoutMs: DEPENDENCY_CHECK_WAIT_MS }, 'Health check exceeded its deadline');
137
+ resolve({
138
+ result: { status: 'down', message: `${name} health check timed out`, responseTime: DEPENDENCY_CHECK_WAIT_MS },
139
+ checkedAt: Date.now(),
140
+ });
141
+ }, DEPENDENCY_CHECK_WAIT_MS);
142
+ timer.unref();
137
143
  });
138
- }
139
- return checksInFlight;
144
+ const actual = check().then((result) => ({ result, checkedAt: Date.now() }));
145
+ const pending = Promise.race([actual, deadline]);
146
+ inFlight = pending;
147
+ void actual.then((result) => {
148
+ clearTimeout(timer);
149
+ if (inFlight !== pending) return;
150
+ cached = result;
151
+ inFlight = undefined;
152
+ });
153
+ return pending;
154
+ },
155
+ reset(): void {
156
+ cached = undefined;
157
+ inFlight = undefined;
158
+ },
159
+ };
140
160
  }
141
161
 
162
+ const databaseCheck = cacheDependency('Database', checkDatabase);
163
+ const redisCheck = cacheDependency('Redis', checkRedis);
164
+
142
165
  /** Forget the cached checks, so each test starts with a real check. */
143
166
  export function resetHealthCacheForTests(): void {
144
- cachedChecks = null;
145
- checksInFlight = null;
167
+ databaseCheck.reset();
168
+ redisCheck.reset();
146
169
  }
147
170
 
148
171
  /** Heap use above this share of the heap LIMIT counts as degraded. */
@@ -235,11 +258,14 @@ export function shortCommit(raw: string | undefined): string | null {
235
258
  const APP_VERSION = readAppVersion();
236
259
 
237
260
  /**
238
- * Full health report (admins only). Database and Redis come from the shared 5 s cache
239
- * (checkDependencies); memory and uptime are read fresh, they cost nothing.
261
+ * Full health report (admins only). Database and Redis use their shared 5 s
262
+ * caches. Memory and uptime are read fresh.
240
263
  */
241
264
  export async function performHealthCheck(): Promise<HealthCheckResult> {
242
- const { database, redis, checkedAt } = await checkDependencies();
265
+ const [databaseStatus, redisStatus] = await Promise.all([databaseCheck.read(), redisCheck.read()]);
266
+ const database = databaseStatus.result;
267
+ const redis = redisStatus.result;
268
+ const checkedAt = Math.max(databaseStatus.checkedAt, redisStatus.checkedAt);
243
269
  const memory = checkMemory();
244
270
  const uptime = checkUptime();
245
271
 
@@ -281,8 +307,8 @@ export async function performHealthCheck(): Promise<HealthCheckResult> {
281
307
  * not. Shares the cached check with /health, so it adds no query of its own.
282
308
  */
283
309
  export async function checkReadiness(): Promise<boolean> {
284
- const { database } = await checkDependencies();
285
- return database.status !== 'down';
310
+ const { result } = await databaseCheck.read();
311
+ return result.status !== 'down';
286
312
  }
287
313
 
288
314
  /**
@@ -14,77 +14,88 @@ import { logger } from '@libs/logger.js';
14
14
 
15
15
  let initialized = false;
16
16
 
17
- /**
18
- * Privacy rule for error tracking: Sentry gets the error, never the secrets
19
- * around it. Same policy as the log redaction in libs/logger.ts — without it
20
- * a 500 during login/register/password change would ship the plaintext
21
- * password, the auth cookies and any token in the URL to a third party.
22
- *
23
- * Header names that must never leave the process (compared lowercase), and
24
- * headers whose value is a URL that may carry a token in its query string.
25
- * Keep in step with the client scrubber (client/src/lib/observability/sentry-scrub.ts).
26
- */
27
- const SECRET_HEADERS = new Set(['cookie', 'set-cookie', 'authorization', 'proxy-authorization', 'x-api-key', 'x-origin-verify']);
28
- const URL_HEADERS = new Set(['referer', 'referrer']);
17
+ const URL_FIELDS = new Set([
18
+ 'url', 'url.full', 'http.url', 'http.target', 'referer', 'referrer',
19
+ 'http.request.header.referer', 'http.request.header.referrer', 'from', 'to',
20
+ ]);
21
+ const HTTP_FIELDS = new Set(['http.request.method', 'http.method', 'http.response.status_code', 'http.status_code', 'status_code']);
22
+ const SAFE_REQUEST_HEADERS = new Set(['referer', 'referrer']);
29
23
 
30
- /** Drop the query string: reset/verify tokens and other secrets travel there. */
31
- function withoutQuery(url: string): string {
32
- const cut = url.search(/[?#]/);
33
- return cut === -1 ? url : url.slice(0, cut);
24
+ /** A raw URL can carry private path segments as well as query parameters. */
25
+ function safeUrl(url: string): string {
26
+ try {
27
+ const parsed = new URL(url);
28
+ if (parsed.protocol === 'http:' || parsed.protocol === 'https:') return parsed.origin;
29
+ } catch { /* Relative or malformed URL. */ }
30
+ return '(url omitted)';
34
31
  }
35
32
 
36
- /**
37
- * Clean a free-form attribute bag (breadcrumb data, span data, trace data):
38
- * strip queries from anything URL-like (url.full, http.target, referer
39
- * attributes, …) and drop query/cookie/auth attributes entirely.
40
- */
33
+ /** Keep HTTP dimensions and sanitized URLs. Arbitrary bags may hold bodies or SQL. */
41
34
  function scrubData(data: Record<string, unknown> | undefined): void {
42
35
  if (!data) return;
43
- for (const key of Object.keys(data)) {
36
+ for (const [key, value] of Object.entries(data)) {
44
37
  const lower = key.toLowerCase();
45
- if (lower.includes('query') || lower.includes('cookie') || lower.includes('authorization')) {
38
+ if (typeof value === 'string' && URL_FIELDS.has(lower)) {
39
+ data[key] = safeUrl(value);
40
+ } else if (!HTTP_FIELDS.has(lower) || (typeof value !== 'number' && typeof value !== 'string')) {
46
41
  delete data[key];
47
- continue;
48
- }
49
- const value = data[key];
50
- if (
51
- typeof value === 'string' &&
52
- (lower.includes('url') || lower.includes('referer') || lower.includes('target') || lower === 'from' || lower === 'to')
53
- ) {
54
- data[key] = withoutQuery(value);
55
42
  }
56
43
  }
57
44
  }
58
45
 
59
- /**
60
- * Remove request bodies, cookies, auth headers and query strings (including
61
- * inside the Referer header, span/trace attributes and the transaction name)
62
- * from an event before it is sent. Exported for tests.
63
- */
46
+ /** Shared privacy contract for the generated API server and Next.js app. */
64
47
  export function scrubSentryEvent<T extends Event>(event: T): T {
48
+ delete event.user;
49
+ delete event.extra;
50
+ delete event.message;
51
+ delete event.logentry;
52
+
65
53
  const request = event.request;
66
54
  if (request) {
67
55
  delete request.data;
68
56
  delete request.cookies;
69
57
  delete request.query_string;
70
- if (request.url) request.url = withoutQuery(request.url);
58
+ delete request.env;
59
+ if (request.url) request.url = safeUrl(request.url);
71
60
  if (request.headers) {
72
- for (const name of Object.keys(request.headers)) {
73
- const lower = name.toLowerCase();
74
- if (SECRET_HEADERS.has(lower)) delete request.headers[name];
75
- else if (URL_HEADERS.has(lower)) request.headers[name] = withoutQuery(request.headers[name]);
61
+ for (const [name, value] of Object.entries(request.headers)) {
62
+ if (SAFE_REQUEST_HEADERS.has(name.toLowerCase())) request.headers[name] = safeUrl(value);
63
+ else delete request.headers[name];
76
64
  }
77
65
  }
78
66
  }
79
67
 
80
- if (event.transaction) event.transaction = withoutQuery(event.transaction);
81
- for (const crumb of event.breadcrumbs ?? []) scrubData(crumb.data as Record<string, unknown> | undefined);
82
- for (const span of event.spans ?? []) scrubData(span.data as Record<string, unknown> | undefined);
83
- scrubData(event.contexts?.trace?.data as Record<string, unknown> | undefined);
84
-
68
+ if (event.tags) {
69
+ const { reqId, route } = event.tags;
70
+ event.tags = { reqId, route };
71
+ }
72
+ if (event.transaction && event.transaction_info?.source !== 'route') event.transaction = '(request)';
73
+ for (const exception of event.exception?.values ?? []) {
74
+ exception.value = 'Exception details omitted';
75
+ delete exception.mechanism?.data;
76
+ for (const frame of exception.stacktrace?.frames ?? []) {
77
+ delete frame.vars;
78
+ delete frame.abs_path;
79
+ delete frame.pre_context;
80
+ delete frame.context_line;
81
+ delete frame.post_context;
82
+ }
83
+ }
84
+ for (const crumb of event.breadcrumbs ?? []) {
85
+ delete crumb.message;
86
+ scrubData(crumb.data as Record<string, unknown> | undefined);
87
+ }
88
+ for (const span of event.spans ?? []) {
89
+ // Descriptions can hold SQL or a path assembled from customer data.
90
+ delete span.description;
91
+ scrubData(span.data as Record<string, unknown> | undefined);
92
+ }
93
+ const trace = event.contexts?.trace;
94
+ if (event.contexts) event.contexts = trace ? { trace } : undefined;
95
+ scrubData(trace?.data as Record<string, unknown> | undefined);
85
96
  return event;
86
- }
87
-
97
+ }
98
+
88
99
  /**
89
100
  * Initialize Sentry only when a DSN is configured.
90
101
  *
@@ -109,7 +120,12 @@ export function initSentry(): void {
109
120
  sendDefaultPii: false,
110
121
  // Don't even buffer incoming request bodies (default 'medium' = 10 KB,
111
122
  // which would include login/register/password-change payloads).
112
- integrations: [Sentry.httpIntegration({ maxIncomingRequestBodySize: 'none' })],
123
+ integrations: [
124
+ Sentry.httpIntegration({ maxIncomingRequestBodySize: 'none' }),
125
+ // Keep tracing, but let our handler capture the exception with the route
126
+ // and request ID. An automatic capture wins the SDK's deduplication race.
127
+ Sentry.fastifyIntegration({ shouldHandleError: () => false }),
128
+ ],
113
129
  // Last line of defence for anything another integration still attaches.
114
130
  beforeSend: (event) => scrubSentryEvent(event),
115
131
  beforeSendTransaction: (event) => scrubSentryEvent(event),