create-tigra 3.2.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (209) hide show
  1. package/README.md +81 -12
  2. package/bin/create-tigra.js +495 -472
  3. package/lib/patchers/email-verification.patcher.js +160 -44
  4. package/modules/email-verification/client/hooks/useVerification.ts +4 -1
  5. package/modules/email-verification/server/__tests__/verification.integration.test.ts +115 -0
  6. package/modules/email-verification/server/verification.controller.ts +3 -1
  7. package/modules/email-verification/server/verification.service.ts +81 -21
  8. package/package.json +3 -2
  9. package/template/.github/dependabot.yml +47 -0
  10. package/template/.github/workflows/audit.yml +36 -0
  11. package/template/.github/workflows/ci.yml +79 -0
  12. package/template/AGENTS.md +18 -9
  13. package/template/client/.dockerignore +1 -0
  14. package/template/client/.env.example.production +13 -2
  15. package/template/client/AGENTS.md +13 -5
  16. package/template/client/Dockerfile +186 -14
  17. package/template/client/next.config.ts +1 -1
  18. package/template/client/package-lock.json +15983 -14181
  19. package/template/client/package.json +56 -48
  20. package/template/client/scripts/check-sharp.mjs +53 -0
  21. package/template/client/scripts/next-dev.cjs +5 -1
  22. package/template/client/src/__tests__/proxy.test.ts +92 -0
  23. package/template/client/src/app/healthz/route.ts +16 -0
  24. package/template/client/src/app/layout.tsx +9 -3
  25. package/template/client/src/app/page.tsx +2 -2
  26. package/template/client/src/app/providers.tsx +23 -4
  27. package/template/client/src/components/layout/Header.tsx +7 -3
  28. package/template/client/src/features/admin/hooks/useAdminSessions.ts +2 -1
  29. package/template/client/src/features/admin/hooks/useAdminUsers.ts +3 -1
  30. package/template/client/src/features/admin/types/admin.types.ts +2 -3
  31. package/template/client/src/features/auth/components/AuthInitializer.tsx +38 -19
  32. package/template/client/src/features/auth/components/ForgotPasswordForm.tsx +107 -0
  33. package/template/client/src/features/auth/components/LimitNotice.tsx +28 -0
  34. package/template/client/src/features/auth/components/LoginForm.tsx +18 -4
  35. package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
  36. package/template/client/src/features/auth/hooks/useAuth.ts +27 -7
  37. package/template/client/src/features/auth/hooks/usePasswordReset.ts +7 -1
  38. package/template/client/src/features/auth/services/auth.service.ts +8 -3
  39. package/template/client/src/features/auth/store/authSlice.ts +7 -2
  40. package/template/client/src/features/auth/types/auth.types.ts +3 -0
  41. package/template/client/src/instrumentation-client.ts +9 -1
  42. package/template/client/src/instrumentation.ts +6 -0
  43. package/template/client/src/lib/api/__tests__/axios.config.test.ts +183 -0
  44. package/template/client/src/lib/api/api.types.ts +14 -0
  45. package/template/client/src/lib/api/axios.config.ts +101 -15
  46. package/template/client/src/lib/api/hard-redirect.ts +8 -0
  47. package/template/client/src/lib/api/session-events.ts +29 -0
  48. package/template/client/src/lib/constants/routes.ts +12 -0
  49. package/template/client/src/lib/observability/sentry-scrub.ts +71 -0
  50. package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
  51. package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
  52. package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
  53. package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
  54. package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
  55. package/template/client/src/lib/utils/error.ts +86 -1
  56. package/template/client/src/lib/utils/form.ts +31 -0
  57. package/template/client/src/lib/utils/paths.ts +18 -0
  58. package/template/client/src/lib/utils/security.ts +37 -0
  59. package/template/client/src/lib/utils/session-marker.ts +24 -0
  60. package/template/client/src/{middleware.ts → proxy.ts} +25 -11
  61. package/template/client/src/store/__tests__/store.test.ts +44 -0
  62. package/template/client/src/store/index.ts +26 -8
  63. package/template/client/vitest.config.mts +48 -0
  64. package/template/server/.env.example +280 -269
  65. package/template/server/.env.example.production +283 -236
  66. package/template/server/AGENTS.md +13 -4
  67. package/template/server/Dockerfile +181 -14
  68. package/template/server/docker-compose.yml +4 -2
  69. package/template/server/docs/deployment.md +63 -0
  70. package/template/server/docs/logging.md +52 -4
  71. package/template/server/docs/rate-limits.md +153 -0
  72. package/template/server/docs/testing.md +63 -0
  73. package/template/server/eslint.config.mjs +19 -0
  74. package/template/server/package-lock.json +8784 -8743
  75. package/template/server/package.json +79 -75
  76. package/template/server/prisma/migrations/0_init/migration.sql +82 -0
  77. package/template/server/prisma/migrations/migration_lock.toml +3 -0
  78. package/template/server/prisma/schema.prisma +19 -6
  79. package/template/server/prisma/seed.ts +13 -5
  80. package/template/server/scripts/check-heic.mjs +40 -0
  81. package/template/server/scripts/check-sharp.mjs +53 -0
  82. package/template/server/src/__tests__/routes.integration.test.ts +280 -0
  83. package/template/server/src/app.ts +248 -335
  84. package/template/server/src/config/__tests__/env.test.ts +219 -0
  85. package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
  86. package/template/server/src/config/env.ts +326 -171
  87. package/template/server/src/config/rate-limit.config.ts +157 -106
  88. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +110 -0
  89. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
  90. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
  91. package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
  92. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +81 -65
  93. package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
  94. package/template/server/src/jobs/index.ts +12 -2
  95. package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
  96. package/template/server/src/jobs/schedule.ts +50 -0
  97. package/template/server/src/libs/__tests__/auth.test.ts +168 -0
  98. package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
  99. package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
  100. package/template/server/src/libs/__tests__/cookies.test.ts +113 -0
  101. package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
  102. package/template/server/src/libs/__tests__/email.test.ts +68 -0
  103. package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
  104. package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
  105. package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
  106. package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
  107. package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
  108. package/template/server/src/libs/__tests__/http.test.ts +74 -2
  109. package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
  110. package/template/server/src/libs/__tests__/logger.test.ts +50 -0
  111. package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
  112. package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
  113. package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
  114. package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
  115. package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
  116. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
  117. package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
  118. package/template/server/src/libs/__tests__/redis.test.ts +59 -0
  119. package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
  120. package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
  121. package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
  122. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -0
  123. package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
  124. package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
  125. package/template/server/src/libs/account-status.ts +52 -0
  126. package/template/server/src/libs/auth.ts +51 -12
  127. package/template/server/src/libs/client-ip.ts +158 -77
  128. package/template/server/src/libs/cloudflare-ranges.ts +132 -0
  129. package/template/server/src/libs/cookies.ts +91 -24
  130. package/template/server/src/libs/email-quota.ts +74 -0
  131. package/template/server/src/libs/email.ts +46 -9
  132. package/template/server/src/libs/error-handler.ts +111 -0
  133. package/template/server/src/libs/health-routes.ts +53 -0
  134. package/template/server/src/libs/http.ts +139 -47
  135. package/template/server/src/libs/ip-address.ts +37 -0
  136. package/template/server/src/libs/ip-block.ts +284 -220
  137. package/template/server/src/libs/logger.ts +41 -12
  138. package/template/server/src/libs/monitoring.ts +131 -42
  139. package/template/server/src/libs/observability/sentry.ts +80 -0
  140. package/template/server/src/libs/origin-check.ts +9 -7
  141. package/template/server/src/libs/prisma.ts +47 -4
  142. package/template/server/src/libs/query-counter.ts +71 -59
  143. package/template/server/src/libs/rate-limiting.ts +110 -0
  144. package/template/server/src/libs/redis-required.ts +28 -0
  145. package/template/server/src/libs/redis.ts +108 -18
  146. package/template/server/src/libs/request-id.ts +18 -0
  147. package/template/server/src/libs/requestLogger.ts +112 -17
  148. package/template/server/src/libs/safe-http.ts +101 -0
  149. package/template/server/src/libs/shutdown.ts +87 -0
  150. package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
  151. package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +143 -0
  152. package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
  153. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
  154. package/template/server/src/libs/storage/file-storage.service.ts +104 -83
  155. package/template/server/src/libs/storage/file-validator.ts +48 -46
  156. package/template/server/src/libs/storage/image-optimizer.service.ts +78 -72
  157. package/template/server/src/libs/token-hash.ts +18 -0
  158. package/template/server/src/libs/url-safety.ts +127 -121
  159. package/template/server/src/libs/validation-errors.ts +86 -0
  160. package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
  161. package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
  162. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
  163. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
  164. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
  165. package/template/server/src/modules/admin/admin.controller.ts +66 -49
  166. package/template/server/src/modules/admin/admin.repo.ts +56 -13
  167. package/template/server/src/modules/admin/admin.routes.ts +48 -2
  168. package/template/server/src/modules/admin/admin.schemas.ts +18 -6
  169. package/template/server/src/modules/admin/admin.service.ts +73 -7
  170. package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
  171. package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
  172. package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
  173. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +332 -49
  174. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
  175. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
  176. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
  177. package/template/server/src/modules/auth/auth.controller.ts +133 -128
  178. package/template/server/src/modules/auth/auth.repo.ts +60 -42
  179. package/template/server/src/modules/auth/auth.schemas.ts +5 -2
  180. package/template/server/src/modules/auth/auth.service.ts +197 -109
  181. package/template/server/src/modules/auth/session.repo.ts +12 -12
  182. package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
  183. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
  184. package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
  185. package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
  186. package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
  187. package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
  188. package/template/server/src/modules/users/users.controller.ts +9 -38
  189. package/template/server/src/modules/users/users.repo.ts +25 -7
  190. package/template/server/src/modules/users/users.routes.ts +3 -22
  191. package/template/server/src/modules/users/users.schemas.ts +15 -9
  192. package/template/server/src/modules/users/users.service.ts +105 -93
  193. package/template/server/src/scripts/make-admin.ts +48 -0
  194. package/template/server/src/server.ts +48 -26
  195. package/template/server/src/shared/errors/AppError.ts +27 -1
  196. package/template/server/src/shared/errors/errors.ts +42 -5
  197. package/template/server/src/shared/responses/successResponse.ts +22 -3
  198. package/template/server/src/shared/types/index.ts +7 -0
  199. package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
  200. package/template/server/src/test/integration-helpers.ts +343 -0
  201. package/template/server/src/test/integration-services.ts +74 -0
  202. package/template/server/src/test/integration.global-setup.ts +144 -0
  203. package/template/server/src/test/integration.setup.ts +35 -158
  204. package/template/server/src/test/setup.ts +23 -8
  205. package/template/server/tsconfig.build.json +1 -1
  206. package/template/server/tsconfig.json +1 -0
  207. package/template/server/vitest.config.ts +17 -4
  208. package/template/server/vitest.integration.config.ts +18 -13
  209. package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Rate-limit wiring for the app (limits themselves: src/config/rate-limit.config.ts).
3
+ *
4
+ * - registerRateLimiting(): the onRoute hook that gives every route without its own
5
+ * limit DEFAULT_LIMIT (own counter per route), then @fastify/rate-limit keyed on the
6
+ * verified visitor IP. Over-limit requests on non-auth routes earn IP auto-block
7
+ * strikes; every 429 is a TooManyRequestsError carrying retryAfterSeconds.
8
+ * - registerNotFoundHandler(): unknown URLs answer in the error envelope and share one
9
+ * DEFAULT counter per IP (scanners get 429, then strikes).
10
+ *
11
+ * Never limited: MONITORING_PATHS (health probes come from infrastructure IPs), static
12
+ * /uploads/* (one page can load dozens of public files) and CORS preflights.
13
+ * Kept out of app.ts so tests can mount it on a bare Fastify with the in-memory store.
14
+ */
15
+ import rateLimit from '@fastify/rate-limit';
16
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
17
+ import type { Redis } from 'ioredis';
18
+ import { DEFAULT_LIMIT, RATE_LIMIT_ENABLED } from '@config/rate-limit.config.js';
19
+ import { getClientIp } from '@libs/client-ip.js';
20
+ import { isAuthPath } from '@libs/auth-path.js';
21
+ import { recordRateLimitViolation } from '@libs/ip-block.js';
22
+ import { logger } from '@libs/logger.js';
23
+ import { TooManyRequestsError, describeWait } from '@shared/errors/errors.js';
24
+ import { errorResponse } from '@shared/responses/successResponse.js';
25
+
26
+ /**
27
+ * Health endpoints: exempt from IP blocking, rate limiting and request logging. A blocked
28
+ * probe IP would mark a healthy container as dead and restart-loop it. Matched exactly on
29
+ * the path (query string stripped) so crafted URLs cannot widen the exemption. Must match
30
+ * the route registrations in app.ts.
31
+ */
32
+ export const MONITORING_PATHS = new Set(['/api/v1/health', '/api/v1/ready', '/api/v1/live']);
33
+
34
+ /** Public static files (avatars): cheap file reads, never rate limited. */
35
+ export function isUploadsPath(url: string): boolean {
36
+ return url.startsWith('/uploads/');
37
+ }
38
+
39
+ export interface RateLimitingOptions {
40
+ /** Shared counter store; omit for the in-memory store (tests, RATE_LIMIT_ENABLED=false). */
41
+ redis?: Redis;
42
+ }
43
+
44
+ /**
45
+ * Register the default-limit hook and the rate-limit plugin. Must run BEFORE any route is
46
+ * registered: both only see routes added after them.
47
+ */
48
+ export async function registerRateLimiting(app: FastifyInstance, options: RateLimitingOptions = {}): Promise<void> {
49
+ // @fastify/rate-limit only limits routes that carry config.rateLimit (global: false).
50
+ // This hook runs first for each new route and gives every other route DEFAULT_LIMIT
51
+ // with its OWN counter (the plugin's `global` mode would put them all in one shared
52
+ // counter). Health routes opt out with rateLimit: false.
53
+ app.addHook('onRoute', (routeOptions) => {
54
+ if (routeOptions.config?.rateLimit !== undefined) return; // own limit, or explicitly off
55
+ const methods = Array.isArray(routeOptions.method) ? routeOptions.method : [routeOptions.method];
56
+ if (methods.every((method) => method === 'OPTIONS')) return; // CORS preflight: no work done
57
+ if (isUploadsPath(routeOptions.url) || MONITORING_PATHS.has(routeOptions.url)) return;
58
+ routeOptions.config = { ...routeOptions.config, rateLimit: DEFAULT_LIMIT };
59
+ });
60
+
61
+ // Redis down → skipOnError lets requests through: limits are off until it is back
62
+ // (accepted; see docs/rate-limits.md).
63
+ await app.register(rateLimit, {
64
+ global: false,
65
+ max: DEFAULT_LIMIT.max,
66
+ timeWindow: DEFAULT_LIMIT.timeWindow,
67
+ ...(options.redis ? { redis: options.redis, nameSpace: 'rl:' } : {}),
68
+ skipOnError: true,
69
+ // Key on the verified visitor address (one counter per real visitor, and never an
70
+ // address the visitor wrote itself) — see src/libs/client-ip.ts.
71
+ keyGenerator: (request: FastifyRequest) => getClientIp(request),
72
+ onExceeded: (request: FastifyRequest) => {
73
+ // Auth routes keep their own per-route limit + account lockout; don't let a
74
+ // mistyped password arm the IP-wide auto-ban.
75
+ if (isAuthPath(request)) return;
76
+ void recordRateLimitViolation(getClientIp(request));
77
+ },
78
+ // Thrown, so it reaches the app's error handler like any AppError.
79
+ errorResponseBuilder: (_request, context) => {
80
+ const seconds = Math.max(1, Math.ceil(context.ttl / 1000));
81
+ return new TooManyRequestsError(
82
+ `Too many requests. Try again in ${describeWait(seconds)}.`,
83
+ 'RATE_LIMIT_EXCEEDED',
84
+ seconds,
85
+ );
86
+ },
87
+ });
88
+
89
+ if (!RATE_LIMIT_ENABLED) {
90
+ logger.warn('[RATE-LIMIT] Rate limiting is DISABLED (RATE_LIMIT_ENABLED=false)');
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Unknown URLs: 404 in the error envelope, counted under DEFAULT_LIMIT (one shared counter
96
+ * per IP). A missing file under /uploads/ also lands here and stays exempt, like the
97
+ * static files themselves. Call after registerRateLimiting().
98
+ */
99
+ export function registerNotFoundHandler(app: FastifyInstance): void {
100
+ const limiter = app.rateLimit(DEFAULT_LIMIT);
101
+ app.setNotFoundHandler(
102
+ {
103
+ preHandler: async (request: FastifyRequest, reply: FastifyReply) => {
104
+ if (isUploadsPath(request.url)) return;
105
+ await limiter.call(app, request, reply);
106
+ },
107
+ },
108
+ (_request, reply) => reply.status(404).send(errorResponse('NOT_FOUND', 'Route not found')),
109
+ );
110
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Guard for features that cannot work without Redis: password-reset and
3
+ * email-verification tokens live there, so while Redis is down those flows
4
+ * cannot succeed (rate limits, lockout and blocks merely switch off instead).
5
+ *
6
+ * Call it FIRST, before looking anything up, so every caller gets the same
7
+ * clear 503 SERVICE_UNAVAILABLE whatever the address. Failing later (after the
8
+ * account lookup) would answer 500 for real accounts and the generic success for
9
+ * unknown ones, which both looks broken and reveals who has an account.
10
+ *
11
+ * The check reads the client's connection state, no round trip: the client runs
12
+ * with the offline queue off, so "not ready" means every command would fail now.
13
+ */
14
+ import { getRedis } from '@libs/redis.js';
15
+ import { ServiceUnavailableError } from '@shared/errors/errors.js';
16
+
17
+ /** @param feature what the person asked for, e.g. "Password reset" (starts the message). */
18
+ export function assertRedisReady(feature: string): void {
19
+ let ready: boolean;
20
+ try {
21
+ ready = getRedis().status === 'ready';
22
+ } catch {
23
+ ready = false; // the client could not even be created
24
+ }
25
+ if (!ready) {
26
+ throw new ServiceUnavailableError(`${feature} is temporarily unavailable. Please try again in a few minutes.`);
27
+ }
28
+ }
@@ -2,38 +2,93 @@ import { Redis } from 'ioredis';
2
2
  import { env } from '@config/env.js';
3
3
  import { logger } from '@libs/logger.js';
4
4
 
5
+ /**
6
+ * Shared Redis client (rate limits, IP blocks, login lockout, reset tokens).
7
+ *
8
+ * Availability contract:
9
+ * - The connection reconnects FOREVER with capped backoff. It used to give up
10
+ * after REDIS_MAX_RETRIES attempts, which left a process permanently without
11
+ * rate limits, IP blocks and login lockout after any Redis blip longer than
12
+ * ~1 second, until someone restarted it.
13
+ * - While Redis is down, commands fail IMMEDIATELY (`enableOfflineQueue:
14
+ * false`) instead of queueing. Every caller already fails open on errors, so
15
+ * requests keep flowing without waiting ~10 s per command for a reconnect.
16
+ * - Logs say once when the connection is lost and once when it is back, not on
17
+ * every retry.
18
+ */
19
+
20
+ const RETRY_STEP_MS = 200;
21
+ const RETRY_MAX_DELAY_MS = 5000;
22
+
23
+ /** Backoff between reconnect attempts. Never returns null: we never give up. */
24
+ export function redisRetryDelay(attempt: number): number {
25
+ return Math.min(attempt * RETRY_STEP_MS, RETRY_MAX_DELAY_MS);
26
+ }
27
+
5
28
  let redis: Redis | null = null;
29
+ let connectionLost = false;
30
+ let closingOnPurpose = false;
31
+ const readyListeners = new Set<() => void>();
32
+
33
+ const LOST_MESSAGE =
34
+ '[REDIS] Connection lost — retrying in the background; rate limits, IP blocks and login lockout fail open until it is back';
35
+
36
+ /** Log the outage once, whichever event (error or close) reports it first. */
37
+ function markConnectionLost(error?: Error): void {
38
+ if (closingOnPurpose) return;
39
+ if (!connectionLost) {
40
+ connectionLost = true;
41
+ logger.warn(error ? { err: error } : {}, LOST_MESSAGE);
42
+ } else if (error) {
43
+ logger.debug({ err: error }, '[REDIS] Still unavailable');
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Run `listener` every time the client becomes ready again after a reconnect
49
+ * (e.g. to restore state a restarted Redis lost). Returns an unsubscribe fn.
50
+ */
51
+ export function onRedisReady(listener: () => void): () => void {
52
+ readyListeners.add(listener);
53
+ return () => readyListeners.delete(listener);
54
+ }
6
55
 
7
56
  export function getRedis(): Redis {
8
57
  if (!redis) {
58
+ closingOnPurpose = false;
9
59
  redis = new Redis(env.REDIS_URL, {
60
+ // Retries for a single command; the connection itself retries forever.
10
61
  maxRetriesPerRequest: env.REDIS_MAX_RETRIES,
11
62
  connectTimeout: env.REDIS_CONNECT_TIMEOUT,
12
63
  lazyConnect: true,
13
- retryStrategy: (times: number): number | null => {
14
- // Exponential backoff with max delay of 3 seconds
15
- if (times > env.REDIS_MAX_RETRIES) {
16
- // Stop retrying after max retries
17
- logger.error('[REDIS] Max retries reached, giving up');
18
- return null;
19
- }
20
- const delay = Math.min(times * 50, 3000);
64
+ enableOfflineQueue: false,
65
+ retryStrategy: (times: number): number => {
66
+ const delay = redisRetryDelay(times);
21
67
  logger.debug(`[REDIS] Retry attempt ${times}, waiting ${delay}ms`);
22
68
  return delay;
23
69
  },
24
70
  });
25
71
 
26
- redis.on('connect', () => {
27
- logger.info('[REDIS] Connection established');
72
+ redis.on('ready', () => {
73
+ if (connectionLost) {
74
+ connectionLost = false;
75
+ logger.info('[REDIS] Reconnected — Redis-backed protections are active again');
76
+ for (const listener of readyListeners) {
77
+ try {
78
+ listener();
79
+ } catch (error) {
80
+ logger.warn({ err: error }, '[REDIS] Ready listener failed');
81
+ }
82
+ }
83
+ } else {
84
+ logger.info('[REDIS] Connection established');
85
+ }
28
86
  });
29
87
 
30
- redis.on('error', (error: Error) => {
31
- logger.warn({ err: error }, '[REDIS] Connection error');
32
- });
88
+ redis.on('error', (error: Error) => markConnectionLost(error));
33
89
 
34
- redis.on('reconnecting', (delay: number) => {
35
- logger.info({ delay }, '[REDIS] Reconnecting');
36
- });
90
+ // A close without an error (e.g. Redis restarted cleanly) is also an outage.
91
+ redis.on('close', () => markConnectionLost());
37
92
  }
38
93
 
39
94
  return redis;
@@ -45,16 +100,51 @@ export async function connectRedis(): Promise<boolean> {
45
100
  await client.connect();
46
101
  return true;
47
102
  } catch (error) {
48
- logger.warn('[REDIS] Connection failed — server will start without Redis');
103
+ // What happens next is server.ts's call: production waits a little, then
104
+ // refuses to start; elsewhere the server starts without Redis.
105
+ logger.warn('[REDIS] Initial connection failed — retrying in the background');
49
106
  logger.debug(error);
50
107
  return false;
51
108
  }
52
109
  }
53
110
 
111
+ /**
112
+ * Resolves true as soon as the client is ready (connected and usable), or
113
+ * false once `timeoutMs` has passed without that. Never throws; the connection
114
+ * keeps retrying in the background either way (see getRedis). server.ts uses
115
+ * it at boot in production, where an unreachable Redis must stop the start.
116
+ */
117
+ export function waitForRedisReady(
118
+ timeoutMs: number,
119
+ client: Pick<Redis, 'status' | 'once' | 'off'> = getRedis(),
120
+ ): Promise<boolean> {
121
+ if (client.status === 'ready') return Promise.resolve(true);
122
+ return new Promise((resolve) => {
123
+ const onReady = (): void => {
124
+ clearTimeout(timer);
125
+ resolve(true);
126
+ };
127
+ const timer = setTimeout(() => {
128
+ client.off('ready', onReady);
129
+ resolve(false);
130
+ }, timeoutMs);
131
+ client.once('ready', onReady);
132
+ });
133
+ }
134
+
54
135
  export async function disconnectRedis(): Promise<void> {
55
136
  if (redis) {
56
- await redis.quit();
137
+ const client = redis;
57
138
  redis = null;
139
+ closingOnPurpose = true;
140
+ readyListeners.clear();
141
+ if (client.status === 'ready') {
142
+ await client.quit();
143
+ } else {
144
+ // Not connected (Redis down / still retrying): quit() would be rejected
145
+ // because the offline queue is off. disconnect() stops the retry loop.
146
+ client.disconnect();
147
+ }
58
148
  logger.info('[REDIS] Disconnected');
59
149
  }
60
150
  }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The id that ties one request's log lines, error report and response together
3
+ * (logged as reqId, echoed as the `x-request-id` response header).
4
+ *
5
+ * An inbound X-Request-Id is honoured so a proxy in front can pass its own id
6
+ * along, but only when it is short and plain: anyone can send that header, and
7
+ * the value lands in every log line of the request and in the response. A
8
+ * 16 KB id would bloat the logs; a reused one would make an attacker's requests
9
+ * look like part of someone else's trace. Anything else gets a fresh UUID.
10
+ */
11
+ import { randomUUID } from 'node:crypto';
12
+
13
+ /** Up to 128 letters, digits, dots, underscores or dashes (covers UUIDs and proxy ids). */
14
+ export const REQUEST_ID_PATTERN = /^[A-Za-z0-9._-]{1,128}$/;
15
+
16
+ export function requestIdFrom(header: string | string[] | undefined): string {
17
+ return typeof header === 'string' && REQUEST_ID_PATTERN.test(header) ? header : randomUUID();
18
+ }
@@ -1,4 +1,5 @@
1
1
  import type { FastifyRequest, FastifyReply } from 'fastify';
2
+ import { env } from '@config/env.js';
2
3
  import { logger } from '@libs/logger.js';
3
4
  import { getClientIp } from '@libs/client-ip.js';
4
5
 
@@ -22,6 +23,30 @@ const colors = {
22
23
  reset: '\x1b[0m',
23
24
  };
24
25
 
26
+ /**
27
+ * Whether request lines get terminal colours. Only for a developer watching a
28
+ * real terminal: in production pino writes JSON, where escape codes would end
29
+ * up as literal `\u001b[34m` junk inside `msg` (Coolify and log search show
30
+ * them verbatim). Production never gets colours, even if stdout is a TTY.
31
+ */
32
+ export function shouldColorize(isTty: boolean | undefined, nodeEnv: string): boolean {
33
+ return isTty === true && nodeEnv !== 'production';
34
+ }
35
+
36
+ /**
37
+ * Whether request lines carry their parts as separate JSON fields. Only where
38
+ * logs are JSON (production, the same switch as the pino-pretty transport in
39
+ * logger.ts): pino-pretty would print each field on its own line under every
40
+ * request, while a developer reads the one-line summary anyway.
41
+ */
42
+ export function shouldAttachFields(nodeEnv: string): boolean {
43
+ return nodeEnv === 'production';
44
+ }
45
+
46
+ // Decided once at startup: neither stdout nor NODE_ENV changes at runtime.
47
+ const useColor = shouldColorize(process.stdout.isTTY, env.NODE_ENV);
48
+ const attachFields = shouldAttachFields(env.NODE_ENV);
49
+
25
50
  function getStatusColor(statusCode: number): string {
26
51
  if (statusCode >= 500) return colors.serverError;
27
52
  if (statusCode >= 400) return colors.clientError;
@@ -35,6 +60,66 @@ function formatDuration(ms: number): string {
35
60
  return `${(ms / 1000).toFixed(2)}s`;
36
61
  }
37
62
 
63
+ export interface RequestLineParts {
64
+ method: string;
65
+ url: string;
66
+ statusCode: number;
67
+ statusMessage: string;
68
+ durationMs: number;
69
+ clientIp: string;
70
+ requestId: string;
71
+ }
72
+
73
+ /**
74
+ * The URL without its query string or fragment. Queries carry search terms,
75
+ * email addresses and the like (`/admin/users?search=jane@example.com`), and
76
+ * links in emails carry tokens, so no request log keeps them; route params
77
+ * stay (they are ids, not secrets).
78
+ */
79
+ export function requestPath(url: string): string {
80
+ const end = url.search(/[?#]/);
81
+ return end === -1 ? url : url.slice(0, end);
82
+ }
83
+
84
+ /** The request line's parts as JSON fields, for searching and alerting on production logs. */
85
+ export interface RequestLogFields {
86
+ reqId: string;
87
+ method: string;
88
+ path: string;
89
+ statusCode: number;
90
+ durationMs: number;
91
+ ip: string;
92
+ }
93
+
94
+ export function requestLogFields(parts: RequestLineParts): RequestLogFields {
95
+ return {
96
+ reqId: parts.requestId,
97
+ method: parts.method,
98
+ path: requestPath(parts.url),
99
+ statusCode: parts.statusCode,
100
+ durationMs: parts.durationMs,
101
+ ip: parts.clientIp,
102
+ };
103
+ }
104
+
105
+ /**
106
+ * Build the one-line summary. Pure (no I/O), so the colour rule is testable.
107
+ * With `color: false` the line contains no escape codes at all. The URL is
108
+ * printed without its query (requestPath).
109
+ */
110
+ export function formatRequestLine(parts: RequestLineParts, { color }: { color: boolean }): string {
111
+ const paint = (code: string, text: string): string => (color ? `${code}${text}${colors.reset}` : text);
112
+ const methodColor = colors[parts.method as keyof typeof colors] || colors.reset;
113
+
114
+ return [
115
+ paint(methodColor, parts.method.padEnd(7)),
116
+ `${requestPath(parts.url)} `,
117
+ paint(getStatusColor(parts.statusCode), `${parts.statusCode} ${parts.statusMessage}`),
118
+ ' ',
119
+ paint(colors.dim, `(${formatDuration(parts.durationMs)}) [ip=${parts.clientIp} reqId=${parts.requestId}]`),
120
+ ].join('');
121
+ }
122
+
38
123
  /**
39
124
  * Mark request start time (called in preHandler)
40
125
  */
@@ -46,27 +131,37 @@ export function markRequestStart(request: FastifyRequest): void {
46
131
  * Log a single-line request/response summary (called in onResponse)
47
132
  *
48
133
  * Format: GET /api/v1/auth/me 200 OK (12ms) [ip=203.0.113.7 reqId=<uuid>]
134
+ * In production the same parts also go out as JSON fields
135
+ * ({ reqId, method, path, statusCode, durationMs, ip }), so log search can
136
+ * filter on them instead of parsing the text. Neither keeps the query string.
49
137
  *
50
- * The IP is the Cloudflare-/proxy-aware resolved client IP (getClientIp), so
51
- * behind Cloudflare we log the CF-Connecting-IP, not the shared edge IP. reqId
52
- * is request.id (inbound X-Request-Id or the minted UUID) for log↔Sentry tie-up.
138
+ * The IP is the proxy-aware resolved client IP (getClientIp): the verified
139
+ * CF-Connecting-IP behind Cloudflare, otherwise the address our own proxy saw.
140
+ * reqId is request.id (inbound X-Request-Id or the minted UUID) for log↔Sentry
141
+ * tie-up. Colours follow shouldColorize(); production lines are plain text.
142
+ * `options` exists for tests; the app always uses the startup decision.
53
143
  */
54
- export function logRequestLine(request: FastifyRequest, reply: FastifyReply): void {
55
- const duration = request.startTime ? Date.now() - request.startTime : 0;
144
+ export function logRequestLine(
145
+ request: FastifyRequest,
146
+ reply: FastifyReply,
147
+ options: { color: boolean; fields: boolean } = { color: useColor, fields: attachFields },
148
+ ): void {
56
149
  const statusCode = reply.statusCode;
57
- const statusMessage = reply.raw.statusMessage || '';
58
- const clientIp = getClientIp(request);
59
-
60
- const methodColor = colors[request.method as keyof typeof colors] || colors.reset;
61
- const statusColor = getStatusColor(statusCode);
62
-
63
- const line = `${methodColor}${request.method.padEnd(7)}${colors.reset}${request.url} ${statusColor}${statusCode} ${statusMessage}${colors.reset} ${colors.dim}(${formatDuration(duration)}) [ip=${clientIp} reqId=${request.id}]${colors.reset}`;
150
+ const parts: RequestLineParts = {
151
+ method: request.method,
152
+ url: request.url,
153
+ statusCode,
154
+ statusMessage: reply.raw.statusMessage || '',
155
+ durationMs: request.startTime ? Date.now() - request.startTime : 0,
156
+ clientIp: getClientIp(request),
157
+ requestId: String(request.id),
158
+ };
159
+ const line = formatRequestLine(parts, { color: options.color });
160
+ const level = statusCode >= 500 ? 'error' : statusCode >= 400 ? 'warn' : 'info';
64
161
 
65
- if (statusCode >= 500) {
66
- logger.error(line);
67
- } else if (statusCode >= 400) {
68
- logger.warn(line);
162
+ if (options.fields) {
163
+ logger[level](requestLogFields(parts), line);
69
164
  } else {
70
- logger.info(line);
165
+ logger[level](line);
71
166
  }
72
167
  }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * The guarded outbound client for URLs that came from a user (an avatar or
3
+ * import "from a link", webhooks, link previews). A URL like that must never
4
+ * reach the database, Redis, Coolify's internal services or a cloud metadata
5
+ * endpoint (SSRF). Trusted, hard-coded URLs use httpClient (libs/http.ts).
6
+ *
7
+ * Every connection is checked, not just the URL as written:
8
+ * - http: and https: only (no file:, data:, ftp:, ...);
9
+ * - an IP literal in the URL (first hop, or any redirect hop) must be a public
10
+ * address (isForbiddenOutboundIp, libs/url-safety.ts);
11
+ * - a hostname is resolved by our own lookup, which refuses it when ANY answer
12
+ * is not public, and the socket then connects to exactly the addresses that
13
+ * were checked: a DNS answer cannot change between the check and the
14
+ * connection (DNS rebinding);
15
+ * - redirects: at most 3, each hop checked the same way;
16
+ * - environment proxies are ignored (with a proxy the lookup would check the
17
+ * proxy, and the proxy would fetch the internal target for us);
18
+ * - 10 s timeout, 10 MB body cap (createHttpClient).
19
+ *
20
+ * A refused request throws OutboundHttpError with kind 'blocked' (a generic 500
21
+ * unless the caller handles it, e.g. as "this link is not allowed").
22
+ */
23
+ import dns, { type LookupAddress } from 'node:dns';
24
+ import { isIP } from 'node:net';
25
+ import type { AxiosInstance, InternalAxiosRequestConfig } from 'axios';
26
+ import { createHttpClient, OutboundHttpError, OUTBOUND_BLOCKED } from '@libs/http.js';
27
+ import { isForbiddenOutboundIp } from '@libs/url-safety.js';
28
+
29
+ const SAFE_TIMEOUT_MS = 10_000;
30
+ const MAX_REDIRECTS = 3;
31
+
32
+ type Resolve = (hostname: string, options: { all: true; family?: number }) => Promise<LookupAddress[]>;
33
+
34
+ const systemResolve: Resolve = (hostname, options) => dns.promises.lookup(hostname, options);
35
+
36
+ /** The error our guards raise inside axios (recognised by libs/http.ts as kind 'blocked'). */
37
+ function blocked(): Error {
38
+ return Object.assign(new Error('Outbound request refused: the target is not a public address'), {
39
+ code: OUTBOUND_BLOCKED,
40
+ });
41
+ }
42
+
43
+ /** The hostname as an IP literal (brackets stripped), or null when it is a name. */
44
+ function literalIp(hostname: string): string | null {
45
+ const host = hostname.replace(/^\[|\]$/g, '');
46
+ return isIP(host) ? host : null;
47
+ }
48
+
49
+ /** Whether a target (protocol + hostname) may be connected to, before any DNS. */
50
+ function isAllowedTarget(protocol: string, hostname: string, isForbidden: (ip: string) => boolean): boolean {
51
+ if (protocol !== 'http:' && protocol !== 'https:') return false;
52
+ const ip = literalIp(hostname);
53
+ return ip === null || !isForbidden(ip);
54
+ }
55
+
56
+ export interface SafeHttpOptions {
57
+ /** DNS resolver (tests inject one). */
58
+ resolve?: Resolve;
59
+ /** Address policy (tests may loosen it for a local server; production never). */
60
+ isForbidden?: (ip: string) => boolean;
61
+ }
62
+
63
+ export function createSafeHttpClient({
64
+ resolve = systemResolve,
65
+ isForbidden = isForbiddenOutboundIp,
66
+ }: SafeHttpOptions = {}): AxiosInstance {
67
+ // Every hostname connection resolves here; the socket uses only checked addresses.
68
+ const lookup = async (hostname: string, options: { family?: number } = {}): Promise<LookupAddress[]> => {
69
+ const answers = await resolve(hostname, { all: true, family: options.family || undefined });
70
+ if (answers.length === 0 || answers.some((answer) => isForbidden(answer.address))) throw blocked();
71
+ return answers;
72
+ };
73
+
74
+ const client = createHttpClient({
75
+ timeout: SAFE_TIMEOUT_MS,
76
+ maxRedirects: MAX_REDIRECTS,
77
+ proxy: false,
78
+ lookup,
79
+ // Redirect hops: an IP literal skips the lookup, so check it (and the protocol) here.
80
+ beforeRedirect: (options) => {
81
+ if (!isAllowedTarget(String(options.protocol), String(options.hostname), isForbidden)) throw blocked();
82
+ },
83
+ });
84
+
85
+ // First hop: refuse before anything is sent (an IP literal never reaches the lookup).
86
+ client.interceptors.request.use((config: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
87
+ let target: URL;
88
+ try {
89
+ target = new URL(String(config.url), config.baseURL);
90
+ } catch {
91
+ throw new OutboundHttpError('blocked');
92
+ }
93
+ if (!isAllowedTarget(target.protocol, target.hostname, isForbidden)) throw new OutboundHttpError('blocked');
94
+ return config;
95
+ });
96
+
97
+ return client;
98
+ }
99
+
100
+ /** For URLs a user supplied. Trusted, hard-coded URLs: httpClient (libs/http.ts). */
101
+ export const safeHttpClient: AxiosInstance = createSafeHttpClient();
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Process shutdown with honest exit codes and a deadline (wired in server.ts).
3
+ *
4
+ * Exit codes are how Docker, Coolify and any restart policy tell a deploy or a
5
+ * stop from a crash:
6
+ * - SIGTERM / SIGINT (a deploy, `docker stop`, Ctrl+C): 0 once everything closed;
7
+ * - an uncaught exception, an unhandled rejection or a failed start: 1, even
8
+ * when the cleanup itself went fine (it used to be 0, so a crash or a server
9
+ * that never started looked like a clean stop);
10
+ * - a cleanup that throws: 1.
11
+ *
12
+ * The deadline: `docker stop` (and Coolify's rolling updates) wait 10 s after
13
+ * SIGTERM, then SIGKILL, which skips every log line. If closing hangs (a
14
+ * request that never ends, a database that does not answer), the process logs
15
+ * a fatal line and exits 1 at SHUTDOWN_DEADLINE_MS instead, inside that window.
16
+ */
17
+ import type { Logger } from 'pino';
18
+
19
+ export type ShutdownReason =
20
+ | 'SIGINT'
21
+ | 'SIGTERM'
22
+ | 'uncaughtException'
23
+ | 'unhandledRejection'
24
+ | 'startup-error';
25
+
26
+ /** Reasons that mean something went wrong: the process exits 1 whatever the cleanup does. */
27
+ const FAILURE_REASONS: ReadonlySet<ShutdownReason> = new Set([
28
+ 'uncaughtException',
29
+ 'unhandledRejection',
30
+ 'startup-error',
31
+ ]);
32
+
33
+ /** Below Docker's default 10 s stop timeout, so our own fatal line is written before SIGKILL. */
34
+ export const SHUTDOWN_DEADLINE_MS = 8_000;
35
+
36
+ export interface ShutdownOptions {
37
+ /** Closes the app, then Redis, then the database. */
38
+ close: () => Promise<void>;
39
+ /** process.exit in production; a spy in tests. */
40
+ exit: (code: number) => void;
41
+ logger: Pick<Logger, 'info' | 'error' | 'fatal'>;
42
+ deadlineMs?: number;
43
+ }
44
+
45
+ /**
46
+ * Returns the one shutdown function for the process. Only the first call
47
+ * closes anything; later calls (a second signal, an exception thrown while
48
+ * closing) start nothing new, but a failure reason arriving later still turns
49
+ * the final exit code into 1.
50
+ *
51
+ * The deadline timer is deliberately NOT unref'd: every path ends in exit(),
52
+ * so it never keeps a finished process alive, and if close() hung with nothing
53
+ * else holding the event loop, an unref'd timer would let Node end on its own
54
+ * with exit code 0.
55
+ */
56
+ export function createShutdown({
57
+ close,
58
+ exit,
59
+ logger,
60
+ deadlineMs = SHUTDOWN_DEADLINE_MS,
61
+ }: ShutdownOptions): (reason: ShutdownReason) => Promise<void> {
62
+ let started = false;
63
+ let failed = false;
64
+
65
+ return async function shutdown(reason: ShutdownReason): Promise<void> {
66
+ if (FAILURE_REASONS.has(reason)) failed = true;
67
+ if (started) return;
68
+ started = true;
69
+
70
+ logger.info(`[SERVER] Received ${reason} - shutting down gracefully`);
71
+ const deadline = setTimeout(() => {
72
+ logger.fatal(`[SERVER] Shutdown did not finish within ${deadlineMs / 1000}s; exiting`);
73
+ exit(1);
74
+ }, deadlineMs);
75
+
76
+ try {
77
+ await close();
78
+ clearTimeout(deadline);
79
+ logger.info('[SERVER] Shutdown complete');
80
+ exit(failed ? 1 : 0);
81
+ } catch (error) {
82
+ clearTimeout(deadline);
83
+ logger.error({ err: error }, '[SERVER] Error during shutdown');
84
+ exit(1);
85
+ }
86
+ };
87
+ }