create-tigra 4.1.0 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +4 -1
  3. package/bin/create-tigra.js +68 -73
  4. package/lib/installer-transaction.js +275 -0
  5. package/lib/patchers/diagnostics.patcher.js +33 -59
  6. package/lib/patchers/email-verification.patcher.js +86 -92
  7. package/lib/patchers/metrics.patcher.js +18 -18
  8. package/lib/project-files.js +99 -0
  9. package/modules/diagnostics/diagnostics.md +10 -0
  10. package/modules/diagnostics/prisma/diagnostic-hourly-view.sql +24 -0
  11. package/modules/diagnostics/prisma/migration.sql +1 -24
  12. package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +18 -2
  13. package/modules/diagnostics/server/diagnostics.repo.ts +12 -2
  14. package/modules/diagnostics/server/diagnostics.routes.ts +1 -2
  15. package/modules/email-verification/client/hooks/useVerification.ts +4 -7
  16. package/modules/email-verification/server/__tests__/verification.integration.test.ts +17 -0
  17. package/modules/email-verification/server/__tests__/verification.service.test.ts +71 -0
  18. package/modules/email-verification/server/verification.service.ts +102 -157
  19. package/modules/metrics/client/WebVitalsReporter.tsx +2 -0
  20. package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +1 -0
  21. package/modules/metrics/performance.md +2 -2
  22. package/modules/metrics/server/__tests__/metrics.collector.test.ts +22 -0
  23. package/modules/metrics/server/metrics.collector.ts +6 -3
  24. package/modules/metrics/server/metrics.routes.ts +1 -2
  25. package/modules/metrics/server/metrics.service.ts +6 -2
  26. package/package.json +1 -1
  27. package/template/AGENTS.md +4 -3
  28. package/template/client/.dockerignore +2 -5
  29. package/template/client/gitignore +43 -0
  30. package/template/client/package-lock.json +51 -51
  31. package/template/client/package.json +2 -2
  32. package/template/client/src/features/auth/components/AuthInitializer.tsx +45 -7
  33. package/template/client/src/features/auth/hooks/useAuth.ts +10 -33
  34. package/template/client/src/features/auth/hooks/useCurrentUser.ts +3 -3
  35. package/template/client/src/features/auth/hooks/useSessionTransition.ts +51 -0
  36. package/template/client/src/features/auth/services/auth.service.ts +3 -2
  37. package/template/client/src/features/auth/store/authSlice.ts +11 -8
  38. package/template/client/src/features/auth/types/auth.types.ts +1 -0
  39. package/template/client/src/lib/api/__tests__/axios.config.test.ts +17 -0
  40. package/template/client/src/lib/api/__tests__/session-events.test.ts +23 -0
  41. package/template/client/src/lib/api/axios.config.ts +24 -6
  42. package/template/client/src/lib/api/session-events.ts +54 -0
  43. package/template/client/src/lib/observability/sentry-scrub.ts +63 -46
  44. package/template/client/src/store/__tests__/store.test.ts +1 -0
  45. package/template/gitignore +3 -2
  46. package/template/server/.dockerignore +2 -5
  47. package/template/server/.env.example +1 -0
  48. package/template/server/.env.example.production +1 -0
  49. package/template/server/README.md +7 -2
  50. package/template/server/docs/deployment.md +66 -0
  51. package/template/server/docs/logging.md +9 -8
  52. package/template/server/docs/rate-limits.md +6 -4
  53. package/template/server/gitignore +33 -0
  54. package/template/server/prisma/migrations/0_init/migration.sql +25 -0
  55. package/template/server/prisma/retrofits/20261116000000_retired_refresh_tokens/migration.sql +13 -0
  56. package/template/server/prisma/retrofits/20261116000100_avatar_cleanup/migration.sql +9 -0
  57. package/template/server/prisma/retrofits/20261117000000_account_purge/migration.sql +1 -0
  58. package/template/server/prisma/schema.prisma +25 -1
  59. package/template/server/src/__tests__/routes.integration.test.ts +5 -2
  60. package/template/server/src/app.ts +14 -5
  61. package/template/server/src/config/env.ts +8 -0
  62. package/template/server/src/config/rate-limit.config.ts +1 -1
  63. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +26 -9
  64. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +2 -1
  65. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +51 -5
  66. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +30 -34
  67. package/template/server/src/jobs/cleanup-expired-auth.job.ts +2 -0
  68. package/template/server/src/jobs/index.ts +8 -2
  69. package/template/server/src/libs/__tests__/auth.test.ts +1 -1
  70. package/template/server/src/libs/__tests__/cookies.test.ts +16 -0
  71. package/template/server/src/libs/__tests__/error-handler.test.ts +20 -1
  72. package/template/server/src/libs/__tests__/http.test.ts +10 -10
  73. package/template/server/src/libs/__tests__/ip-block.test.ts +39 -7
  74. package/template/server/src/libs/__tests__/logger.test.ts +10 -1
  75. package/template/server/src/libs/__tests__/monitoring.test.ts +19 -0
  76. package/template/server/src/libs/__tests__/outbound.integration.test.ts +7 -10
  77. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +32 -3
  78. package/template/server/src/libs/__tests__/requestLogger.test.ts +9 -1
  79. package/template/server/src/libs/__tests__/safe-http.test.ts +65 -3
  80. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +22 -6
  81. package/template/server/src/libs/__tests__/url-safety.test.ts +3 -1
  82. package/template/server/src/libs/account-mutation.ts +77 -0
  83. package/template/server/src/libs/auth.ts +37 -3
  84. package/template/server/src/libs/cookies.ts +25 -13
  85. package/template/server/src/libs/email-quota.ts +11 -7
  86. package/template/server/src/libs/email.ts +11 -8
  87. package/template/server/src/libs/error-handler.ts +16 -12
  88. package/template/server/src/libs/http.ts +37 -13
  89. package/template/server/src/libs/ip-block.ts +56 -34
  90. package/template/server/src/libs/logger.ts +23 -8
  91. package/template/server/src/libs/monitoring.ts +57 -31
  92. package/template/server/src/libs/observability/sentry.ts +65 -49
  93. package/template/server/src/libs/prisma.ts +1 -1
  94. package/template/server/src/libs/private-cache.ts +6 -0
  95. package/template/server/src/libs/rate-limiting.ts +4 -0
  96. package/template/server/src/libs/requestLogger.ts +3 -3
  97. package/template/server/src/libs/safe-http.ts +58 -18
  98. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +15 -2
  99. package/template/server/src/libs/storage/file-storage.service.ts +59 -109
  100. package/template/server/src/libs/storage/file-validator.ts +2 -1
  101. package/template/server/src/libs/url-safety.ts +10 -2
  102. package/template/server/src/libs/validation-errors.ts +11 -8
  103. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +21 -4
  104. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +11 -0
  105. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +83 -40
  106. package/template/server/src/modules/admin/admin.controller.ts +4 -4
  107. package/template/server/src/modules/admin/admin.repo.ts +37 -54
  108. package/template/server/src/modules/admin/admin.routes.ts +3 -5
  109. package/template/server/src/modules/admin/admin.schemas.ts +3 -6
  110. package/template/server/src/modules/admin/admin.service.ts +61 -62
  111. package/template/server/src/modules/auth/__tests__/auth.schemas.test.ts +12 -0
  112. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +58 -295
  113. package/template/server/src/modules/auth/__tests__/recovery.integration.test.ts +177 -0
  114. package/template/server/src/modules/auth/__tests__/recovery.queue.test.ts +159 -0
  115. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +5 -10
  116. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +1 -1
  117. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +115 -44
  118. package/template/server/src/modules/auth/auth-link-store.ts +64 -0
  119. package/template/server/src/modules/auth/auth-mail-queue.ts +124 -0
  120. package/template/server/src/modules/auth/auth.controller.ts +16 -5
  121. package/template/server/src/modules/auth/auth.repo.ts +152 -61
  122. package/template/server/src/modules/auth/auth.routes.ts +4 -0
  123. package/template/server/src/modules/auth/auth.schemas.ts +7 -3
  124. package/template/server/src/modules/auth/auth.service.ts +33 -237
  125. package/template/server/src/modules/auth/recovery.queue.ts +44 -0
  126. package/template/server/src/modules/auth/recovery.store.ts +7 -0
  127. package/template/server/src/modules/auth/session.repo.ts +5 -4
  128. package/template/server/src/modules/files/__tests__/files.integration.test.ts +29 -1
  129. package/template/server/src/modules/files/files.controller.ts +2 -2
  130. package/template/server/src/modules/users/__tests__/avatar-cleanup.test.ts +49 -0
  131. package/template/server/src/modules/users/__tests__/avatar-controller.test.ts +50 -0
  132. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +56 -105
  133. package/template/server/src/modules/users/__tests__/users.integration.test.ts +2 -2
  134. package/template/server/src/modules/users/__tests__/users.repo.test.ts +8 -11
  135. package/template/server/src/modules/users/__tests__/users.service.test.ts +116 -44
  136. package/template/server/src/modules/users/avatar-cleanup.ts +70 -0
  137. package/template/server/src/modules/users/users.controller.ts +28 -25
  138. package/template/server/src/modules/users/users.repo.ts +12 -51
  139. package/template/server/src/modules/users/users.service.ts +109 -234
  140. package/template/server/src/shared/responses/paginatedResponse.ts +4 -1
  141. package/template/server/src/shared/schemas/pagination.schema.ts +5 -1
  142. package/template/server/src/test/setup.ts +4 -0
@@ -48,9 +48,26 @@ const count = (calls: string[], call: string): number => calls.filter((c) => c =
48
48
  beforeEach(() => {
49
49
  // Module mocks survive vi.resetModules(): forget the previous test's calls.
50
50
  vi.clearAllMocks();
51
+ localStorage.clear();
51
52
  document.cookie = 'auth_session=1; path=/';
52
53
  });
53
54
 
55
+ it('discards an old successful response after another tab changes session', async () => {
56
+ const t = await load(() => ({ status: 200 }));
57
+ let finish!: () => void;
58
+ let started!: () => void;
59
+ const sent = new Promise<void>(resolve => { started = resolve; });
60
+ t.apiClient.defaults.adapter = async config => {
61
+ await new Promise<void>(resolve => { finish = resolve; started(); });
62
+ return respond(config, 200, { profile: 'previous fixture account' });
63
+ };
64
+ const response = t.apiClient.get('/auth/me');
65
+ await sent;
66
+ localStorage.setItem('tigra:session-revision', 'next-session');
67
+ finish();
68
+ await expect(response).rejects.toMatchObject({ code: 'ERR_CANCELED' });
69
+ });
70
+
54
71
  describe('expired access token', () => {
55
72
  it('parallel 401s share ONE refresh, then every request is replayed', async () => {
56
73
  let refreshed = false;
@@ -0,0 +1,23 @@
1
+ // @vitest-environment jsdom
2
+ import { expect, it, vi } from 'vitest';
3
+
4
+ import { onPeerSessionChange, sessionRevision } from '../session-events';
5
+
6
+ it('detects peer changes and a missed revision when the tab returns', () => {
7
+ localStorage.clear();
8
+ const changed = vi.fn();
9
+ const stop = onPeerSessionChange(changed);
10
+ const key = 'tigra:session-revision';
11
+ localStorage.setItem(key, 'first-change');
12
+ window.dispatchEvent(new StorageEvent('storage', { key }));
13
+ window.dispatchEvent(new StorageEvent('storage', { key }));
14
+ expect(changed).toHaveBeenCalledTimes(1);
15
+ localStorage.setItem(key, 'missed-change');
16
+ window.dispatchEvent(new Event('pageshow'));
17
+ expect(changed).toHaveBeenCalledTimes(2);
18
+ expect(sessionRevision()).toBe('missed-change');
19
+ stop();
20
+ localStorage.setItem(key, 'after-cleanup');
21
+ window.dispatchEvent(new Event('focus'));
22
+ expect(changed).toHaveBeenCalledTimes(2);
23
+ });
@@ -1,10 +1,10 @@
1
- import axios from 'axios';
1
+ import axios, { CanceledError } from 'axios';
2
2
  import { toast } from 'sonner';
3
3
 
4
4
  import type { InternalAxiosRequestConfig } from 'axios';
5
5
 
6
6
  import { hardRedirect } from '@/lib/api/hard-redirect';
7
- import { emitSessionEnded } from '@/lib/api/session-events';
7
+ import { emitSessionEnded, sessionRevision } from '@/lib/api/session-events';
8
8
  import { API_ENDPOINTS } from '@/lib/constants/api-endpoints';
9
9
  import { ROUTES } from '@/lib/constants/routes';
10
10
  import { env } from '@/lib/env';
@@ -17,6 +17,8 @@ declare module 'axios' {
17
17
  * caller shows the message itself (the auth forms show it inline).
18
18
  */
19
19
  skipLimitToast?: boolean;
20
+ /** Session revision captured before the first send, including retries. */
21
+ sessionRevision?: string | null;
20
22
  }
21
23
  }
22
24
 
@@ -29,7 +31,12 @@ const apiClient = axios.create({
29
31
  withCredentials: true, // Send cookies with every request
30
32
  });
31
33
 
32
- // No request interceptor needed — cookies are sent automatically
34
+ apiClient.interceptors.request.use((config) => {
35
+ const revision = sessionRevision();
36
+ if (config.sessionRevision === undefined) config.sessionRevision = revision;
37
+ if (config.sessionRevision !== revision) throw new CanceledError('Session changed');
38
+ return config;
39
+ });
33
40
 
34
41
  let isRefreshing = false;
35
42
  let refreshTimestamp = 0;
@@ -83,6 +90,7 @@ let endingDeactivatedSession: Promise<void> | null = null;
83
90
  * Best effort: the user is signed out locally even if the logout call fails.
84
91
  */
85
92
  const endDeactivatedSession = (): Promise<void> => {
93
+ const revision = sessionRevision();
86
94
  endingDeactivatedSession ??= apiClient
87
95
  .post(API_ENDPOINTS.AUTH.LOGOUT)
88
96
  .then(
@@ -90,7 +98,7 @@ const endDeactivatedSession = (): Promise<void> => {
90
98
  () => undefined
91
99
  )
92
100
  .then(() => {
93
- emitSessionEnded('deactivated');
101
+ if (revision === sessionRevision()) emitSessionEnded('deactivated');
94
102
  })
95
103
  .finally(() => {
96
104
  endingDeactivatedSession = null;
@@ -99,9 +107,15 @@ const endDeactivatedSession = (): Promise<void> => {
99
107
  };
100
108
 
101
109
  apiClient.interceptors.response.use(
102
- (response) => response,
110
+ (response) => {
111
+ if (response.config.sessionRevision !== sessionRevision()) throw new CanceledError('Session changed');
112
+ return response;
113
+ },
103
114
  async (error) => {
104
115
  const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean };
116
+ if (originalRequest && originalRequest.sessionRevision !== sessionRevision()) {
117
+ throw new CanceledError('Session changed');
118
+ }
105
119
 
106
120
  // "Slow down" answers (429 rate limit / login lock / email cap, 403 IP_BLOCKED):
107
121
  // tell the person once, with the wait time, and never treat them as an auth
@@ -161,13 +175,17 @@ apiClient.interceptors.response.use(
161
175
 
162
176
  try {
163
177
  // Refresh — cookie is sent automatically
164
- await apiClient.post(API_ENDPOINTS.AUTH.REFRESH);
178
+ await apiClient.post(API_ENDPOINTS.AUTH.REFRESH, undefined, { sessionRevision: originalRequest.sessionRevision });
165
179
 
166
180
  processQueue(null);
167
181
 
168
182
  // Retry original request — new cookie is set automatically
169
183
  return apiClient(originalRequest);
170
184
  } catch (refreshError) {
185
+ if (originalRequest.sessionRevision !== sessionRevision()) {
186
+ processQueue(refreshError);
187
+ throw new CanceledError('Session changed');
188
+ }
171
189
  // Lost a race with another tab: both refreshed at once with the same
172
190
  // token, the other one won, and the server kept the cookies, so this
173
191
  // browser already holds the winner's fresh ones (401
@@ -16,6 +16,60 @@ type Listener = (reason: SessionEndReason) => void;
16
16
 
17
17
  const listeners = new Set<Listener>();
18
18
 
19
+ const REVISION_KEY = 'tigra:session-revision';
20
+ let inMemoryRevision: string | null = null;
21
+ let useMemoryRevision = false;
22
+
23
+ /** An opaque notification only. The API remains the source of identity. */
24
+ export function sessionRevision(): string | null {
25
+ if (typeof window === 'undefined') return null;
26
+ if (useMemoryRevision) return inMemoryRevision;
27
+ try {
28
+ return window.localStorage.getItem(REVISION_KEY) ?? inMemoryRevision;
29
+ } catch {
30
+ return inMemoryRevision;
31
+ }
32
+ }
33
+
34
+ /** Call after credentials have changed, before navigating away. */
35
+ export function publishSessionChange(): void {
36
+ const revision = crypto.randomUUID?.() ?? Date.now().toString(36) + Math.random().toString(36);
37
+ inMemoryRevision = revision;
38
+ try {
39
+ window.localStorage.setItem(REVISION_KEY, revision);
40
+ } catch {
41
+ // Same-tab response cancellation still works when storage is disabled.
42
+ useMemoryRevision = true;
43
+ }
44
+ }
45
+
46
+ /** Storage covers active tabs. Checking on return covers suspended tabs. */
47
+ export function onPeerSessionChange(listener: () => void): () => void {
48
+ let seen = sessionRevision();
49
+ const check = (): void => {
50
+ const current = sessionRevision();
51
+ if (current === seen) return;
52
+ seen = current;
53
+ listener();
54
+ };
55
+ const onStorage = (event: StorageEvent): void => {
56
+ if (event.key === REVISION_KEY) check();
57
+ };
58
+ const onVisible = (): void => {
59
+ if (document.visibilityState === 'visible') check();
60
+ };
61
+ window.addEventListener('storage', onStorage);
62
+ window.addEventListener('focus', check);
63
+ window.addEventListener('pageshow', check);
64
+ document.addEventListener('visibilitychange', onVisible);
65
+ return () => {
66
+ window.removeEventListener('storage', onStorage);
67
+ window.removeEventListener('focus', check);
68
+ window.removeEventListener('pageshow', check);
69
+ document.removeEventListener('visibilitychange', onVisible);
70
+ };
71
+ }
72
+
19
73
  /** Subscribe; returns the unsubscribe function (fits a useEffect cleanup). */
20
74
  export function onSessionEnded(listener: Listener): () => void {
21
75
  listeners.add(listener);
@@ -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