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
@@ -1,71 +1,88 @@
1
1
  /**
2
- * Privacy filter for Sentry events sent from the Next.js app (browser and the
3
- * Node/Edge server runtime). Mirrors the API server's scrubber
4
- * (server/src/libs/observability/sentry.ts) — keep the two in step.
5
- *
6
- * Why it exists: Next's `captureRequestError` attaches the incoming request's
7
- * headers (including the Cookie header), and the browser SDK attaches the page
8
- * URL and the Referer, both as request headers and as span/trace attributes.
9
- * Page URLs such as /reset-password?token=… and /verify-account?token=… carry
10
- * credentials, so every URL-like value loses its query string and fragment,
11
- * and cookie/auth headers are dropped, before anything is sent.
12
- *
13
- * Kept dependency-free (type-only import) so it never pulls @sentry/nextjs into
14
- * a bundle by itself.
2
+ * Privacy filter for browser and Next.js server Sentry events. Keep this
3
+ * contract in step with the API server under src/libs/observability/sentry.ts.
4
+ * The type-only import keeps the SDK out of this module's bundle.
15
5
  */
16
- import type { Event } from '@sentry/nextjs';
6
+ import type { Event } from '@sentry/nextjs';
7
+
8
+ const URL_FIELDS = new Set([
9
+ 'url', 'url.full', 'http.url', 'http.target', 'referer', 'referrer',
10
+ 'http.request.header.referer', 'http.request.header.referrer', 'from', 'to',
11
+ ]);
12
+ const HTTP_FIELDS = new Set(['http.request.method', 'http.method', 'http.response.status_code', 'http.status_code', 'status_code']);
13
+ const SAFE_REQUEST_HEADERS = new Set(['referer', 'referrer']);
17
14
 
18
- const SECRET_HEADERS = new Set(['cookie', 'set-cookie', 'authorization', 'proxy-authorization', 'x-api-key', 'x-origin-verify']);
19
- const URL_HEADERS = new Set(['referer', 'referrer']);
20
-
21
- /** Drop the query string and fragment: tokens travel there. */
22
- function withoutQuery(url: string): string {
23
- const cut = url.search(/[?#]/);
24
- return cut === -1 ? url : url.slice(0, cut);
15
+ /** A raw URL can carry private path segments as well as query parameters. */
16
+ function safeUrl(url: string): string {
17
+ try {
18
+ const parsed = new URL(url);
19
+ if (parsed.protocol === 'http:' || parsed.protocol === 'https:') return parsed.origin;
20
+ } catch { /* Relative or malformed URL. */ }
21
+ return '(url omitted)';
25
22
  }
26
23
 
27
- /**
28
- * Clean a free-form attribute bag (breadcrumb data, span data, trace data):
29
- * strip queries from anything URL-like, drop query/cookie/auth attributes.
30
- */
24
+ /** Keep HTTP dimensions and sanitized URLs. Arbitrary bags may hold bodies or SQL. */
31
25
  function scrubData(data: Record<string, unknown> | undefined): void {
32
26
  if (!data) return;
33
- for (const key of Object.keys(data)) {
27
+ for (const [key, value] of Object.entries(data)) {
34
28
  const lower = key.toLowerCase();
35
- if (lower.includes('query') || lower.includes('cookie') || lower.includes('authorization')) {
29
+ if (typeof value === 'string' && URL_FIELDS.has(lower)) {
30
+ data[key] = safeUrl(value);
31
+ } else if (!HTTP_FIELDS.has(lower) || (typeof value !== 'number' && typeof value !== 'string')) {
36
32
  delete data[key];
37
- continue;
38
- }
39
- const value = data[key];
40
- if (
41
- typeof value === 'string' &&
42
- (lower.includes('url') || lower.includes('referer') || lower.includes('target') || lower === 'from' || lower === 'to')
43
- ) {
44
- data[key] = withoutQuery(value);
45
33
  }
46
34
  }
47
35
  }
48
36
 
37
+ /** Shared privacy contract for the generated API server and Next.js app. */
49
38
  export function scrubSentryEvent<T extends Event>(event: T): T {
39
+ delete event.user;
40
+ delete event.extra;
41
+ delete event.message;
42
+ delete event.logentry;
43
+
50
44
  const request = event.request;
51
45
  if (request) {
52
46
  delete request.data;
53
47
  delete request.cookies;
54
48
  delete request.query_string;
55
- if (request.url) request.url = withoutQuery(request.url);
49
+ delete request.env;
50
+ if (request.url) request.url = safeUrl(request.url);
56
51
  if (request.headers) {
57
- for (const name of Object.keys(request.headers)) {
58
- const lower = name.toLowerCase();
59
- if (SECRET_HEADERS.has(lower)) delete request.headers[name];
60
- else if (URL_HEADERS.has(lower)) request.headers[name] = withoutQuery(request.headers[name]);
52
+ for (const [name, value] of Object.entries(request.headers)) {
53
+ if (SAFE_REQUEST_HEADERS.has(name.toLowerCase())) request.headers[name] = safeUrl(value);
54
+ else delete request.headers[name];
61
55
  }
62
56
  }
63
57
  }
64
58
 
65
- if (event.transaction) event.transaction = withoutQuery(event.transaction);
66
- for (const crumb of event.breadcrumbs ?? []) scrubData(crumb.data as Record<string, unknown> | undefined);
67
- for (const span of event.spans ?? []) scrubData(span.data as Record<string, unknown> | undefined);
68
- scrubData(event.contexts?.trace?.data as Record<string, unknown> | undefined);
69
-
59
+ if (event.tags) {
60
+ const { reqId, route } = event.tags;
61
+ event.tags = { reqId, route };
62
+ }
63
+ if (event.transaction && event.transaction_info?.source !== 'route') event.transaction = '(request)';
64
+ for (const exception of event.exception?.values ?? []) {
65
+ exception.value = 'Exception details omitted';
66
+ delete exception.mechanism?.data;
67
+ for (const frame of exception.stacktrace?.frames ?? []) {
68
+ delete frame.vars;
69
+ delete frame.abs_path;
70
+ delete frame.pre_context;
71
+ delete frame.context_line;
72
+ delete frame.post_context;
73
+ }
74
+ }
75
+ for (const crumb of event.breadcrumbs ?? []) {
76
+ delete crumb.message;
77
+ scrubData(crumb.data as Record<string, unknown> | undefined);
78
+ }
79
+ for (const span of event.spans ?? []) {
80
+ // Descriptions can hold SQL or a path assembled from customer data.
81
+ delete span.description;
82
+ scrubData(span.data as Record<string, unknown> | undefined);
83
+ }
84
+ const trace = event.contexts?.trace;
85
+ if (event.contexts) event.contexts = trace ? { trace } : undefined;
86
+ scrubData(trace?.data as Record<string, unknown> | undefined);
70
87
  return event;
71
- }
88
+ }
@@ -25,6 +25,7 @@ describe('makeStore', () => {
25
25
  isAuthenticated: false,
26
26
  isInitializing: false,
27
27
  isLoggingOut: false,
28
+ logoutFailed: false,
28
29
  });
29
30
  });
30
31
 
@@ -9,8 +9,9 @@ out/
9
9
 
10
10
  # Environment files
11
11
  .env
12
- .env.local
13
- .env.*.local
12
+ .env.*
13
+ !.env.example
14
+ !.env.example.production
14
15
 
15
16
  # OS files
16
17
  .DS_Store
@@ -11,11 +11,8 @@ build
11
11
  *.tsbuildinfo
12
12
 
13
13
  # Environment files (use Docker env vars instead)
14
- .env
15
- .env.local
16
- .env.*.local
17
- .env.development
18
- .env.test
14
+ **/.env
15
+ **/.env.*
19
16
 
20
17
  # Git
21
18
  .git
@@ -205,6 +205,7 @@ JWT_REFRESH_EXPIRY="7d"
205
205
  # middleware can see that a session exists. The access/refresh token cookies stay
206
206
  # host-only on the API (never shared with other subdomains).
207
207
  # COOKIE_DOMAIN=".example.com"
208
+ # COOKIE_LEGACY_DOMAINS="old.example.com"
208
209
 
209
210
  # ===================================================================
210
211
  # CORS (Cross-Origin Resource Sharing)
@@ -202,6 +202,7 @@ CORS_ORIGIN="https://yourdomain.com,https://app.yourdomain.com"
202
202
  # host-only on the API and are never sent to other subdomains.
203
203
  # Without it, the client keeps redirecting signed-in users to /login.
204
204
  COOKIE_DOMAIN=".yourdomain.com"
205
+ # COOKIE_LEGACY_DOMAINS="old.yourdomain.com"
205
206
 
206
207
  # ===================================================================
207
208
  # EMAIL (Resend)
@@ -83,11 +83,16 @@ Wrong input is always `422 VALIDATION_FAILED` with `fields`; "slow down" answers
83
83
  stops using it (`docs/deployment.md`).
84
84
  4. Tests: unit tests next to the code (`__tests__/`), and the route's contract (401/403, 422, success) in
85
85
  `src/__tests__/routes.integration.test.ts`. That file fails when a registered route is never called.
86
- 5. Fetching a URL a user gave you: `safeHttpClient` (`src/libs/safe-http.ts`), never `fetch`. Recurring work:
87
- `startRecurringJob` (`src/jobs/schedule.ts`), never `setInterval`.
86
+ 5. Use `safeHttpClient` (`src/libs/safe-http.ts`) for user-supplied URLs. It checks each destination, applies a
87
+ ten-second total deadline and ten MiB body limit, and follows up to three redirects. Cross-origin redirects
88
+ carry only bodyless GET or HEAD requests and drop caller-supplied headers. Use `startRecurringJob`
89
+ (`src/jobs/schedule.ts`) for recurring work.
88
90
 
89
91
  `AGENTS.md` in this folder has the full set of rules.
90
92
 
93
+ The admin user and session lists accept pages 1–1000 and at most 100 rows per page. The result count includes
94
+ every match. Use the existing filters to narrow large result sets.
95
+
91
96
  ## Configuration
92
97
 
93
98
  `src/config/env.ts` validates every setting at boot and stops with the reason when one is wrong. `.env.example`
@@ -61,3 +61,69 @@ but do not count on it.
61
61
 
62
62
  The fix for later: build the libvips stage once into a base image in a registry (it needs CI to publish it) and
63
63
  start both Dockerfiles from it. Until then, deploy when the server is quiet if its other apps are sensitive to load.
64
+
65
+ ## Password recovery
66
+
67
+ The API accepts recovery requests into Redis. API replicas share the stream and
68
+ resume pending jobs after a restart, provided Redis retains its data. Keep the
69
+ JWT secret and email configuration consistent across replicas so a retried job
70
+ uses the same link and delivery key. The worker discards jobs older than five
71
+ minutes and retries a failed or abandoned delivery once. Redis unavailability
72
+ or a full queue returns the same 503 for any address.
73
+
74
+ When adopting this change in an existing app, switch the recovery routes over
75
+ to the new version together. Existing unexpired links whose fingerprints still
76
+ match their current pointer remain usable.
77
+
78
+ ## Admin account changes
79
+
80
+ Upgrade all API replicas and the `make-admin` command in the same release.
81
+ They share a MySQL transaction policy for account changes. The last-admin
82
+ check counts only accounts that can sign in under the current verification
83
+ setting. A new installation can still bootstrap its first admin with
84
+ `make-admin`.
85
+
86
+ ## Session rotation and cookie scope
87
+
88
+ New projects create `retired_refresh_tokens` in their initial schema. For an existing
89
+ project, copy `prisma/retrofits/20261116000000_retired_refresh_tokens` into its
90
+ `prisma/migrations` directory and merge the Prisma model before generating the
91
+ client. Run `prisma migrate deploy` ahead of the server rollout. Keep the applied
92
+ initial migration from that project. The new table accepts the existing sessions
93
+ as they rotate. Finish the API rollout together so every replica records rotations.
94
+
95
+ When changing `COOKIE_DOMAIN`, set `COOKIE_LEGACY_DOMAINS` to the comma-separated
96
+ previous scopes. The API can clear a cookie from a scope that matches its own
97
+ hostname. For a move to an unrelated site, clear cookies from the former API
98
+ origin and revoke its server-side sessions during the cutover.
99
+
100
+ ## Authenticated API caching
101
+
102
+ Authenticated API responses and auth endpoints use `Cache-Control: private,
103
+ no-store`. Configure fronting caches to honor these headers and clear any
104
+ previously cached account responses during rollout.
105
+
106
+ ## Profile and avatar writes
107
+
108
+ API replicas serving the same avatars must share the public upload volume.
109
+ Avatar responses use `Cache-Control: no-store` so later requests see replacements
110
+ and deletions. Configure the CDN to honor this policy for the avatar path.
111
+ Serve avatars directly or use `unoptimized` on Next.js images for avatars to
112
+ bypass the image optimizer's cache. Shared caches holding copies from the
113
+ former one-year policy can be purged during rollout. Previously cached browser
114
+ copies can remain fresh until their original cache entry expires or is evicted.
115
+ For existing apps, copy `prisma/retrofits/20261116000100_avatar_cleanup`
116
+ into the project's `prisma/migrations` directory and merge the Prisma
117
+ model. Apply the forward migration before switching replicas together.
118
+ The new job retries detached avatar files when storage is temporarily
119
+ unavailable. Existing avatar URLs are kept.
120
+
121
+ ## Deleted account purge
122
+
123
+ Copy `prisma/retrofits/20261117000000_account_purge` into the migration history of
124
+ an existing app, add the Prisma field, and apply the migration before running
125
+ the new server. New scaffolds create the column in their initial migration.
126
+ Stop the old replicas before enabling the new purge and restore writers. They
127
+ must all honor the claim before a worker deletes retained media. A claimed
128
+ account stays eligible for purge retry when storage is unavailable, and its
129
+ restore endpoint returns `409 USER_PURGE_IN_PROGRESS` until removal.
@@ -14,9 +14,8 @@ GET /api/v1/auth/me 200 OK (12ms) [ip=203.0.113.7 reqId=<uuid>]
14
14
 
15
15
  Format: `METHOD PATH STATUS STATUS_MESSAGE (DURATION) [ip=CLIENT_IP reqId=REQUEST_ID]`
16
16
 
17
- `PATH` is the URL without its query string or fragment: queries carry search terms and email
18
- addresses (`/admin/users?search=jane@example.com`), and links from emails carry tokens, so no
19
- request log keeps them. Route params (ids) stay.
17
+ `PATH` is the registered route template, such as `/api/v1/admin/users/:userId`. Requests without
18
+ a route use `(unmatched)`. Query strings and submitted path segments stay out of request logs.
20
19
 
21
20
  In production (JSON logs) the same parts are also separate fields on the line, so log search can
22
21
  filter on them instead of parsing `msg`:
@@ -88,9 +87,9 @@ The public answer never says which check failed. Admins get the full report at
88
87
  uptime, `checkedAt`, `version` (from `package.json`) and `commit` (the first 12 characters of
89
88
  `SOURCE_COMMIT` when the environment provides it, otherwise `null`).
90
89
 
91
- The database and Redis are checked at most once per 5 s; every probe in between gets the same
92
- answer (`checkedAt` says when it was taken). A failing check logs the error at `error`
93
- (database) or `warn` (Redis).
90
+ The database and Redis each share a five-second cache and a single pending operation. A probe
91
+ reports a stalled dependency after one second. Further probes share that result until the pending
92
+ operation completes. Readiness consults MySQL, and liveness answers immediately.
94
93
 
95
94
  ## Secrets never reach the logs
96
95
 
@@ -103,8 +102,10 @@ keys password newPassword currentPassword passwordHash token accessToke
103
102
  headers authorization cookie set-cookie proxy-authorization x-api-key x-origin-verify
104
103
  ```
105
104
 
106
- Request lines never contain the query string, outbound request logs show URLs without keys or `user:password@`,
107
- and email addresses in email logs are masked. Logging a secret under another name is still on you: name it plainly.
105
+ Error records keep the exception type and a short machine code when present. Unexpected request errors also
106
+ keep the route and request ID. Sentry keeps correlation and stack locations while removing free-form error
107
+ messages and reducing raw URLs to their origins. Outbound request logs redact URL credentials and query
108
+ strings, and email logs mask recipient addresses.
108
109
 
109
110
  ## Configuration
110
111
 
@@ -30,12 +30,14 @@ Everything that slows down or stops a visitor, in one place. The limits themselv
30
30
  | `POST /users/avatar`, `POST /users/:userId/avatar` | 10 per minute | `USERS_UPLOAD_AVATAR` |
31
31
  | `DELETE /users/avatar`, `DELETE /users/:userId/avatar` | 30 per minute | `USERS_DELETE_AVATAR` |
32
32
  | `GET /files/:filename` | 100 per minute | `FILES_GET` |
33
- | every `/admin/*` route | 30 per minute | `ADMIN_DEFAULT` |
33
+ | `/admin/*` requests without admin authorization | 30 per minute | `ADMIN_DEFAULT` |
34
34
  | **any other route** (including routes you add) | 200 per minute | `DEFAULT` |
35
35
  | unknown URLs (404s) | 200 per minute, one shared counter | `DEFAULT` |
36
36
 
37
37
  All paths are under `/api/v1`. Password change checks the current password, so it stays low: someone holding a stolen session cannot guess that password. An avatar upload decodes an image of up to 50 MP, which is real CPU work.
38
38
 
39
+ The admin scope verifies the live session and current role before granting a quota exemption. Authorized admin requests skip the route quota and its IP-wide strikes. Admins use the same limits as other callers on ordinary routes. Active IP blocks still apply to admin traffic.
40
+
39
41
  **Never limited:**
40
42
  - `GET /api/v1/health`, `/api/v1/ready` and `/api/v1/live` (health probes come from infrastructure IPs);
41
43
  - static `/uploads/*` (one page can load dozens of avatars);
@@ -55,7 +57,7 @@ At most **3 emails per hour to one address**, on two separate counters so a stra
55
57
  - **Not counted at all:** the single verification email sent at register. An address can register only once, so it cannot flood anyone, and strangers who used up the public counter cannot stop it.
56
58
  - Why the sign-in re-send is still capped: whoever registered an address knows its password and could otherwise flood that inbox by signing in again and again.
57
59
  - Both counters are charged **before** looking the account up, so unknown addresses count exactly like real ones and the answer reveals nothing.
58
- - Redis keys are a SHA-256 of the address; raw emails are never stored there.
60
+ - Quota keys contain a SHA-256 fingerprint of the address. Recovery jobs retain the normalized address in the Redis stream until the worker finishes or discards the job. Never log stream contents.
59
61
 
60
62
  The IP limits alone cannot do this: someone with many IPs could flood one inbox and burn the sender's quota and reputation.
61
63
 
@@ -120,7 +122,7 @@ The app keeps serving, but while Redis is unreachable:
120
122
  - IP blocks are not enforced;
121
123
  - forgot-password, reset-password, send-verification and verify-account answer `503 SERVICE_UNAVAILABLE` ("Password reset is temporarily unavailable. Please try again in a few minutes."). Their tokens live in Redis, so they cannot work. The check runs before any account lookup, so the answer is the same for every address and reveals nothing (`src/libs/redis-required.ts`).
122
124
 
123
- `/api/v1/health` reports `degraded`; admins see that it is Redis at `/api/v1/admin/health`. Everything returns on its own when Redis is back; permanent blocks are re-loaded from the database on reconnect.
125
+ `/api/v1/health` reports `degraded`. The admin health report identifies Redis. On reconnect, boot, and admin edits, the API queries MySQL and atomically replaces the shared permanent block cache. Roll all replicas onto the new writer to keep the revision check effective.
124
126
 
125
127
  A missing or unreachable `REDIS_URL` at boot is different from an outage: in production the server refuses to start without it, and also when it cannot reach Redis within 10 s of starting (a wrong host or password), because it would otherwise run with every protection above switched off while its health check still passes. On Coolify that failed start never becomes healthy, so a rolling deploy keeps the old container serving. Outside production it defaults to `redis://localhost:6379` and starts without Redis.
126
128
 
@@ -135,7 +137,7 @@ On a correct setup this never happens. The server logs `[CLIENT-IP] Cloudflare r
135
137
  ## Known limits (read before relying on these)
136
138
 
137
139
  - **Anyone can use up an address's public email counter.** Three anonymous forgot-password or send-verification requests in an hour use up that address's public counter. For the rest of the hour nobody gets a reset link through that address. A determined stranger can keep doing this every hour, keeping one person from resetting a password by email. Verification is **not** blocked: the register email is not capped, and signing in with the right password re-sends the link on its own counter. A user who knows their password is not affected.
138
- - **Whether an email has an account can be found out.** Sign-up answers `409 EMAIL_ALREADY_EXISTS` for an existing account (and for one deleted recently, while its email stays reserved), and forgot-password gives the same answer for every address but takes noticeably longer for a real account, because it sends the email before replying. This is accepted on purpose (most apps do the same, and hiding it would make sign-up confusing). Sign-in and the lockout still reveal nothing: unknown emails cost the same time and lock the same way.
140
+ - **Sign-up discloses an existing registration.** It answers `409 EMAIL_ALREADY_EXISTS` for an existing account or a recently deleted account whose address is still reserved. Password recovery uses the same Redis admission path for all addresses. The worker looks up the account and delivers mail after admission.
139
141
  - **An unverified sign-up keeps its email.** With email verification on, someone can sign up with another person's address and never verify it. The real owner then gets `409 EMAIL_ALREADY_EXISTS` when signing up. They are not locked out: "forgot password" sends the reset link to their own inbox, and after resetting, signing in sends them the verification link. Accounts are never deleted automatically for staying unverified.
140
142
  - **Parallel sign-in attempts can get ahead of the lockout.** A burst of simultaneous failed sign-ins from one IP is checked before any of them is counted, so it can try more than 15 passwords. It is still capped by the login route limit (100 per 15 minutes per IP).
141
143
  - **`HEAD` requests count separately from `GET`.** Fastify adds a `HEAD` route for each `GET`, and it gets its own counter.
@@ -0,0 +1,33 @@
1
+ # Dependencies
2
+ node_modules/
3
+
4
+ # Build
5
+ dist/
6
+
7
+ # Local environment and installer recovery
8
+ .env
9
+ .env.*
10
+ !.env.example
11
+ !.env.example.production
12
+
13
+ # Prisma
14
+ .prisma/
15
+
16
+ # Test coverage
17
+ coverage/
18
+
19
+ # Logs
20
+ *.log
21
+ npm-debug.log*
22
+
23
+ # OS
24
+ .DS_Store
25
+ Thumbs.db
26
+
27
+ # IDE
28
+ .vscode/
29
+ .idea/
30
+
31
+ # Uploads (local development)
32
+ uploads/
33
+ !uploads/avatar/.gitkeep
@@ -10,6 +10,7 @@ CREATE TABLE `users` (
10
10
  `isActive` BOOLEAN NOT NULL DEFAULT true,
11
11
  `emailVerifiedAt` DATETIME(3) NULL,
12
12
  `deletedAt` DATETIME(3) NULL,
13
+ `purgeStartedAt` DATETIME(3) NULL,
13
14
  `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
14
15
  `updatedAt` DATETIME(3) NOT NULL,
15
16
 
@@ -55,6 +56,27 @@ CREATE TABLE `sessions` (
55
56
  PRIMARY KEY (`id`)
56
57
  ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
57
58
 
59
+ -- CreateTable
60
+ CREATE TABLE `retired_refresh_tokens` (
61
+ `fingerprint` CHAR(64) NOT NULL,
62
+ `sessionId` VARCHAR(191) NOT NULL,
63
+ `expiresAt` DATETIME(3) NOT NULL,
64
+
65
+ INDEX `retired_refresh_tokens_sessionId_idx`(`sessionId`),
66
+ INDEX `retired_refresh_tokens_expiresAt_idx`(`expiresAt`),
67
+ PRIMARY KEY (`fingerprint`)
68
+ ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
69
+
70
+ -- CreateTable
71
+ CREATE TABLE `avatar_cleanup` (
72
+ `userId` VARCHAR(191) NOT NULL,
73
+ `filename` VARCHAR(191) NOT NULL,
74
+ `dueAt` DATETIME(3) NOT NULL,
75
+
76
+ INDEX `avatar_cleanup_dueAt_idx`(`dueAt`),
77
+ PRIMARY KEY (`userId`, `filename`)
78
+ ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
79
+
58
80
  -- CreateTable
59
81
  CREATE TABLE `blocked_ips` (
60
82
  `id` VARCHAR(191) NOT NULL,
@@ -77,6 +99,9 @@ ALTER TABLE `refresh_tokens` ADD CONSTRAINT `refresh_tokens_sessionId_fkey` FORE
77
99
  -- AddForeignKey
78
100
  ALTER TABLE `sessions` ADD CONSTRAINT `sessions_userId_fkey` FOREIGN KEY (`userId`) REFERENCES `users`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
79
101
 
102
+ -- AddForeignKey
103
+ ALTER TABLE `retired_refresh_tokens` ADD CONSTRAINT `retired_refresh_tokens_sessionId_fkey` FOREIGN KEY (`sessionId`) REFERENCES `sessions`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
104
+
80
105
  -- AddForeignKey
81
106
  ALTER TABLE `blocked_ips` ADD CONSTRAINT `blocked_ips_blockedBy_fkey` FOREIGN KEY (`blockedBy`) REFERENCES `users`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
82
107
 
@@ -0,0 +1,13 @@
1
+ -- CreateTable
2
+ CREATE TABLE `retired_refresh_tokens` (
3
+ `fingerprint` CHAR(64) NOT NULL,
4
+ `sessionId` VARCHAR(191) NOT NULL,
5
+ `expiresAt` DATETIME(3) NOT NULL,
6
+
7
+ INDEX `retired_refresh_tokens_sessionId_idx`(`sessionId`),
8
+ INDEX `retired_refresh_tokens_expiresAt_idx`(`expiresAt`),
9
+ PRIMARY KEY (`fingerprint`)
10
+ ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
11
+
12
+ -- AddForeignKey
13
+ ALTER TABLE `retired_refresh_tokens` ADD CONSTRAINT `retired_refresh_tokens_sessionId_fkey` FOREIGN KEY (`sessionId`) REFERENCES `sessions`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,9 @@
1
+ -- CreateTable
2
+ CREATE TABLE `avatar_cleanup` (
3
+ `userId` VARCHAR(191) NOT NULL,
4
+ `filename` VARCHAR(191) NOT NULL,
5
+ `dueAt` DATETIME(3) NOT NULL,
6
+
7
+ INDEX `avatar_cleanup_dueAt_idx`(`dueAt`),
8
+ PRIMARY KEY (`userId`, `filename`)
9
+ ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
@@ -0,0 +1 @@
1
+ ALTER TABLE `users` ADD COLUMN `purgeStartedAt` DATETIME(3) NULL;
@@ -29,7 +29,9 @@ model User {
29
29
  // REQUIRE_USER_VERIFICATION is on.
30
30
  emailVerifiedAt DateTime?
31
31
  deletedAt DateTime?
32
-
32
+ // Set before deleting media. A claimed account can no longer be restored,
33
+ // and stays discoverable for retries until the permanent delete commits.
34
+ purgeStartedAt DateTime?
33
35
 
34
36
  createdAt DateTime @default(now())
35
37
  updatedAt DateTime @updatedAt
@@ -80,6 +82,7 @@ model Session {
80
82
 
81
83
  user User @relation(fields: [userId], references: [id], onDelete: Cascade)
82
84
  refreshTokens RefreshToken[]
85
+ retiredRefreshTokens RetiredRefreshToken[]
83
86
 
84
87
  // Performance indexes for session queries
85
88
  @@index([userId])
@@ -88,6 +91,27 @@ model Session {
88
91
  @@map("sessions")
89
92
  }
90
93
 
94
+ model RetiredRefreshToken {
95
+ fingerprint String @id @db.Char(64)
96
+ sessionId String
97
+ expiresAt DateTime
98
+ session Session @relation(fields: [sessionId], references: [id], onDelete: Cascade)
99
+
100
+ @@index([sessionId])
101
+ @@index([expiresAt])
102
+ @@map("retired_refresh_tokens")
103
+ }
104
+
105
+ model AvatarCleanup {
106
+ userId String
107
+ filename String
108
+ dueAt DateTime
109
+
110
+ @@id([userId, filename])
111
+ @@index([dueAt])
112
+ @@map("avatar_cleanup")
113
+ }
114
+
91
115
  model BlockedIp {
92
116
  id String @id @default(uuid())
93
117
  ip String @unique @db.VarChar(45)
@@ -162,7 +162,9 @@ describe('auth routes answer', () => {
162
162
  const reg = await call(app, 'POST', '/auth/register', { payload: { email, password: PASSWORD, firstName: 'Con', lastName: 'Tract' } });
163
163
  expect([reg.status, reg.body?.data?.user?.email]).toEqual([201, email]);
164
164
  const jar = await signIn(app, email);
165
- expect((await call(app, 'GET', '/auth/me', { jar })).body?.data?.email).toBe(email);
165
+ const me = await call(app, 'GET', '/auth/me', { jar });
166
+ expect(me.body?.data?.email).toBe(email);
167
+ expect(me.res.headers['cache-control']).toBe('private, no-store');
166
168
  const sessions = await call(app, 'GET', '/auth/sessions', { jar });
167
169
  expect([sessions.status, Array.isArray(sessions.body?.data) && sessions.body?.data.length >= 1]).toEqual([200, true]);
168
170
  expect((await call(app, 'POST', '/auth/refresh', { jar })).status).toBe(200);
@@ -180,7 +182,7 @@ describe('auth routes answer', () => {
180
182
  const u = await registerUser(app, 'contract-reset');
181
183
  expect((await call(app, 'POST', '/auth/forgot-password', { payload: { email: u.email } })).status).toBe(200);
182
184
  expect((await call(app, 'POST', '/auth/forgot-password', { payload: { email: uniqueEmail('nobody') } })).status).toBe(200);
183
- const token = tokenOf(mail.to(u.email).at(-1)?.link ?? null);
185
+ const token = tokenOf((await mail.waitFor(u.email, (e) => /reset-password/.test(e.link ?? ''))).at(-1)?.link ?? null);
184
186
  expect((await call(app, 'POST', '/auth/reset-password', { payload: { token, newPassword: 'Reset-Passw0rd-1' } })).status).toBe(200);
185
187
  const bad = await call(app, 'POST', '/auth/reset-password', { payload: { token: 'f'.repeat(64), newPassword: 'Reset-Passw0rd-1' } });
186
188
  expect([bad.status, bad.code]).toEqual([400, 'INVALID_RESET_TOKEN']);
@@ -228,6 +230,7 @@ describe('admin routes answer', () => {
228
230
  it('stats, health, client-ip and blocked-ips lists → 200 with their shapes', async () => {
229
231
  const stats = await call(app, 'GET', '/admin/stats', { jar: admin.jar });
230
232
  expect(stats.status).toBe(200);
233
+ expect(stats.res.headers['cache-control']).toBe('private, no-store');
231
234
  expect(stats.body?.data).toEqual(expect.objectContaining({ totalUsers: expect.any(Number) }));
232
235
  expect((await call(app, 'GET', '/admin/health', { jar: admin.jar })).status).toBe(200);
233
236
  expect(Object.keys((await call(app, 'GET', '/admin/client-ip', { jar: admin.jar })).body?.data ?? {}).sort()).toEqual(['ip', 'source']);
@@ -1,4 +1,5 @@
1
1
  import Fastify, { type FastifyInstance, type FastifyRequest, type RouteOptions } from 'fastify';
2
+ import { relative, sep } from 'node:path';
2
3
  import cors from '@fastify/cors';
3
4
  import helmet from '@fastify/helmet';
4
5
  import cookie from '@fastify/cookie';
@@ -143,15 +144,23 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
143
144
  // auth-gated, owner-scoped route GET /api/v1/files/:filename (filesRoutes).
144
145
  // Serving UPLOAD_PUBLIC_DIR at prefix '/uploads/' puts avatars at
145
146
  // /uploads/users/{id}/avatar/avatar-<hex>.webp.
146
- // Cached for a year, immutable: a public file never changes under its name
147
- // (every new avatar gets a new random name, see file-storage.service.ts), so
148
- // browsers and CDNs never need to re-check it. Anything else written to the
149
- // public tier must follow the same rule.
147
+ // Other public assets use immutable names. Avatars are user-removable, so
148
+ // browsers and CDNs must fetch them again each time they are requested.
149
+ const publicUploadDir = fileStorageService.getPublicDir();
150
150
  await app.register(fastifyStatic, {
151
- root: fileStorageService.getPublicDir(),
151
+ root: publicUploadDir,
152
152
  prefix: '/uploads/',
153
+ dotfiles: 'ignore', // Partially written avatar files stay behind a dot filename.
153
154
  maxAge: 365 * 24 * 60 * 60 * 1000, // ms
154
155
  immutable: true,
156
+ setHeaders(reply, servedPath): void {
157
+ // Match the directory so legacy filenames use the same policy. Windows
158
+ // can serve alternate casing for the same on-disk directory.
159
+ const parts = relative(publicUploadDir, servedPath).split(sep);
160
+ if (parts.length === 4 && parts[0]?.toLowerCase() === 'users' && parts[2]?.toLowerCase() === 'avatar') {
161
+ reply.header('Cache-Control', 'no-store');
162
+ }
163
+ },
155
164
  });
156
165
 
157
166
  // --- Sync permanent IP blocks from DB to Redis ---
@@ -147,6 +147,14 @@ const envSchema = z.object({
147
147
  // Applies only to the non-secret auth_session cookie; the token cookies are
148
148
  // always host-only on the API (see src/libs/cookies.ts).
149
149
  COOKIE_DOMAIN: optionalEnv(z.string().optional()),
150
+ COOKIE_LEGACY_DOMAINS: optionalEnv(z.string().optional())
151
+ .transform(value => [...new Set((value ?? '').split(',').map(domain =>
152
+ domain.trim().toLowerCase().replace(/^\./, ''),
153
+ ).filter(Boolean))])
154
+ .refine(domains => domains.every(domain =>
155
+ domain.length <= 253 && /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(domain)
156
+ && !/^\d+(?:\.\d+)+$/.test(domain),
157
+ ), 'Expected a comma-separated list of cookie domain names'),
150
158
 
151
159
  // --- Account Activation ---
152
160
  // When true, new users start with emailVerifiedAt = null and cannot sign in
@@ -165,7 +165,7 @@ export const RATE_LIMITS = {
165
165
  // Files — auth-gated private file streaming
166
166
  FILES_GET: routeLimit('FILES_GET', 100, '1m'),
167
167
 
168
- // Admin routes
168
+ // Admin routes use this quota until the request is authorized as staff.
169
169
  ADMIN_DEFAULT: routeLimit('ADMIN_DEFAULT', 30, '1m'),
170
170
  } as const;
171
171